如何在Python Telegram Bot中通过用户输入动态更新run_daily执行时间
解决Python Telegram Bot动态更新run_daily任务时间的问题
先修正原代码的关键错误
原代码中job.run_daily(send_message_to_the_user(), time=ALARM)存在严重问题:你直接调用了send_message_to_the_user()并将返回值(默认是None)传给了run_daily,这会导致任务无法正常执行。正确写法是传递函数引用,不带括号:
job.run_daily(send_message_to_the_user, time=ALARM)
动态更新任务时间的可行方案
无法直接修改已创建的run_daily任务的time参数——因为任务初始化时就固定了执行时间规则。最优方案是:保存任务实例,用户更新时间时先停止旧任务,再创建新的每日任务。
具体实现步骤
- 用全局变量存储任务实例,方便后续操作
- 在
set_timer处理器中解析用户提供的新时间,停止旧任务后创建新任务
修改后的完整代码示例:
import datetime from telegram.ext import Updater, MessageHandler, Filters API_KEY = "你的API密钥" CHAT_ID = "目标聊天ID" ALARM = datetime.time(hour=8, minute=0) # 初始执行时间 daily_job = None # 全局变量存储每日任务实例 def send_message_to_the_user(context): context.bot.send_message(chat_id=CHAT_ID, text="Example of the message") def set_timer(update, context): global daily_job, ALARM try: # 解析用户发送的时间(支持格式如"09:30") new_time = datetime.time.fromisoformat(update.message.text.strip()) except ValueError: update.message.reply_text("时间格式错误,请发送如'09:30'的格式") return # 停止并移除旧任务 if daily_job: daily_job.schedule_removal() # 更新全局时间变量并创建新任务 ALARM = new_time daily_job = context.job_queue.run_daily(send_message_to_the_user, time=ALARM) update.message.reply_text(f"每日任务时间已更新为{new_time.strftime('%H:%M')}") def main(): global daily_job updater = Updater(API_KEY, use_context=True) dp = updater.dispatcher job_queue = updater.job_queue daily_job = job_queue.run_daily(send_message_to_the_user, time=ALARM) dp.add_handler(MessageHandler(Filters.text, set_timer)) updater.start_polling() updater.idle() if __name__ == "__main__": main()
关键说明
schedule_removal()方法会将旧任务从JobQueue中彻底移除,避免旧任务继续执行- 每次更新时间都重新调用
run_daily创建新任务,这是官方文档推荐的动态调整定时任务的标准方式
内容的提问来源于stack exchange,提问作者storeboughtruler
相关产品推荐
相关产品推荐

