当另一个命令已经在 python-telegram-bot 中运行时,有什么方法可以运行命令吗?

问题描述

假设在 start 函数中有一个无限循环。当它正在运行时......我需要另一个命令在后台运行。另一个功能。 (以停止命令为例)我尝试将它放在“updater.start_polling()”之后,但由于一些原因它不起作用。我无法为此设置调度程序。

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()

解决方法

利用线程

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()