【发布时间】: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