【问题标题】:how to stop a while loop in python-telegram from client side如何从客户端停止python-telegram中的while循环
【发布时间】:2021-04-06 16:06:29
【问题描述】:

如何使用来自客户端的命令或文本来停止作为参数传递给电报机器人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循环是合乎逻辑的,那么有什么方法可以在循环中侦听新命令吗?

【问题讨论】:

    标签: python while-loop telegram python-telegram-bot


    【解决方案1】:

    我看到两个选项:

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

    【讨论】:

    • 第一个选项就像一个魅力。谢谢。
    • 甜蜜。请记住,只要循环正在运行,这仍然会阻塞worker 线程之一;)
    猜你喜欢
    • 1970-01-01
    • 2018-10-14
    • 2010-09-26
    • 2013-09-11
    • 2023-01-10
    • 1970-01-01
    • 2018-08-15
    • 2015-12-30
    • 2015-10-04
    相关资源
    最近更新 更多