skip to Main Content

Let’s say there’s an infinity loop inside the start function. while it’s running… I need another command to run in the background. another function. (a stop command for an example) I tried putting it after "updater.start_polling()" but it didn’t work because of a few reasons. I couldn’t set up a scheduler for that.

def start(update: Update, context: CallbackContext) -> None:
    while true:
        context.bot.send_message(chat_id=update.effective_chat.id, text= "Choose an option. ('/option1' , '/option 2', '/...')")


def main():

    updater = Updater("<MY-BOT-TOKEN>", use_context=True)

    updater.dispatcher.add_handler(CommandHandler('start', start))

    updater.start_polling()
    updater.idle()


if __name__ == '__main__':
    main()

2

Answers


  1. Chosen as BEST ANSWER

    okay, I found a way... set up a while true after start polling and make it wait for a flag to come true. when the user sends an update it triggers the function and makes the flag True. that triggers the code after "start Polling()". with a time.sleep(1) I can run both multiple commands at once


  2. Utilize threading

    from time import sleep
    from threading import Thread    
    
    def start(update: Update, context: CallbackContext) -> None:
       while true:
          context.bot.send_message(chat_id=update.effective_chat.id, text= "Choose an option. ('/option1' , '/option 2', '/...')")
          sleep(.1)
    
    def stop():
       pass # some code here
    
    def main():
    
       updater = Updater("<MY-BOT-TOKEN>", use_context=True)
    
       updater.dispatcher.add_handler(CommandHandler('start', start))
    
       t1 = Thread(target=updater.start_polling)
       t2 = Thread(target=stop)
       t1.start()
       t2.start()
       updater.idle()
    
    
    if __name__ == '__main__':
       main()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search