send repeated messages with apscheduler - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: send repeated messages with apscheduler (/thread-23537.html) |
send repeated messages with apscheduler - pylab - Jan-04-2020 Hey there, I've been working on my code, a bit, and i want to make it work more efficient. I want to make a program that sends a random photo from a certain folder to a certain user every X hours/days. User ids, folders and frequency may vary. I want to make a scalable solution to make it easy to add new users. I want to make a function that can be called easily which has all the arguments (folder_name, user_id, frequency). I know the attached code is not working properly, but this is where i got stuck. Help is much appreciated. import fbchat from fbchat.models import * import random,os from apscheduler.schedulers.blocking import BlockingScheduler import docs import lista_prieteni client = fbchat.Client(docs.username, docs.password) friend = client.searchForUsers(lista_prieteni.lista) id1 = friend[0].uid path1 = r"D:\Downloads\poze test\masini" def mesaj_fb(path,id): random_filename = random.choice([ x for x in os.listdir(path) if os.path.isfile(os.path.join(path, x))]) print(random_filename) client.sendLocalImage(os.path.join(path, random_filename),message=Message(text="Doza ta zilnica de..."),thread_id=id) def main(): sched = BlockingScheduler() sched.add_job(mesaj_fb(path1,id1), 'interval', minutes=10) sched.start() main()i would like to create a function that looks like : mesaj_fb (folder_name, user_id, frequency) - and to be able to call it easily in the main function everytime i want to add a new user. I don't want to add 10 new lines of code everytime i add a new user. RE: send repeated messages with apscheduler - snippsat - Jan-04-2020 When you use fbchat i don't think is running a loop(maybe in bots mode) and just do API call to the chat. Then you need to make a running loop. Use BackgroundScheduler so it don't block fbchat calls and your function call is wrong.Here is a working example. from apscheduler.schedulers.background import BackgroundScheduler from datetime import datetime import time, random def mesaj_fb(path,my_id): print(f'Tick! The time is: {datetime.now()} {random.choice(path), my_id}') if __name__ == '__main__': scheduler = BackgroundScheduler() scheduler.add_job(mesaj_fb, 'interval', args=[('image_1.png','image_2.png','image_3.png'), 10], seconds=5) scheduler.start() print('Press Ctrl+C to exit') try: while True: time.sleep(2) except (KeyboardInterrupt, SystemExit): scheduler.shutdown()
|