首页 > 解决方案 > 当另一个命令已经在 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()

标签: pythontelegramtelegram-botpython-telegram-botpy-telegram-bot-api

解决方案


利用线程

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

推荐阅读