如何从客户端停止 python-telegram 中的 while 循环

how to stop a while loop in python-telegram from client side

如何使用来自客户端的命令或文本停止作为参数传递给电报机器人 CommandHandler 的函数内的 while 循环?

我有这个机器人:

from telegram import *
from datetime import datetime
import time
from telegram.ext import *
import ast #ignore this. i'll use it later

RUN_FUNC = True
def func_starter(update: Update, context):
    update.effective_chat.send_message('Function innitiated.')
    counter = 0
    RUN_FUNC = True
    while RUN_FUNC:
        print(f'function running for {counter} seconds.')
        counter += 1
        time.sleep(1)


def func_stopper(update: Update, context):
    update.effective_chat.send_message('function stopped')
    RUN_FUNC = False


def main():
    updater = Updater('*********:***********************************', use_context=True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler("stop", func_stopper))
    dp.add_handler(CommandHandler("start", func_starter))

    updater.start_polling(0)
    updater.idle()

main()

因此机器人从客户端获取 /start 命令并启动 func_starter 函数,其中包含条件 while 循环。但是因为程序永远不会通过 while 循环,来自客户端的任何其他命令/文本永远不会被 python 代码注册,因此循环永远持续下去。我希望能够使用来自客户端的命令停止 func_starter 函数。 我什至做了一个全局变量,但显然无济于事大声笑。我认为程序永远不会通过 while 循环是合乎逻辑的,那么有什么方法可以在循环中侦听新命令吗?

我看到两个选项:

  1. run_async=True 传递给 CommandHandler("start", …),这将使 func_starter 运行 在其自己的线程中。
  2. 不要在回调中使用 while 循环,而是使用 JobQueue 安排后续步骤