【问题标题】:Is there any way to run a command while another command is already running in python-telegram-bot?当另一个命令已经在 python-telegram-bot 中运行时,有什么方法可以运行一个命令?
【发布时间】:2021-04-03 20:22:33
【问题描述】:

假设在 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()

【问题讨论】:

  • 你应该在你在 start 中拥有的单独的线程代码中
  • @furas 我试过这样做,这是我能看到的最好的方式。但是当它提供更新时我无法触发代码。就像...我需要一个听众。 (我确定有办法做到这一点,但我不确定如何)

标签: python telegram telegram-bot python-telegram-bot py-telegram-bot-api


【解决方案1】:

利用线程

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

【讨论】:

    【解决方案2】:

    好的,我找到了一种方法...在开始轮询后设置一段时间为真,并使其等待标志变为真。当用户发送更新时,它会触发该功能并使标志为 True。在“开始轮询()”之后触发代码。使用 time.sleep(1) 我可以同时运行多个命令

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 2013-08-13
      • 2012-04-10
      相关资源
      最近更新 更多