Python Telegram Bot JobQueue中daily_routine回调未触发的解决方法
解决Telegram Bot定时任务不触发的问题
核心问题分析
你的代码存在两个关键问题,导致定时任务无法正常触发或执行:
- JobQueue未启动:仅创建并关联了JobQueue实例,但未启动任务调度,定时任务不会开始运行。
- 缺少目标聊天ID参数:调用
run_daily时未传入chat_id,执行daily_routine时会因无法获取有效聊天ID而报错(即便任务触发也无法发送消息)。
修复步骤
1. 启动JobQueue
在初始化Bot类时,创建JobQueue后必须调用start()方法启动任务队列:
self.job_queue = JobQueue() self.job_queue.set_application(self.application) self.job_queue.start() # 新增启动代码
2. 为定时任务传入聊天ID
修改run_daily调用,添加chat_id参数(替换为实际目标聊天ID,可从用户交互中获取或硬编码测试):
for routine in daily_routines: self.job_queue.run_daily( routine, time=datetime.time(hour=15, minute=49, tzinfo=pytz.timezone('Asia/Jerusalem')), chat_id=123456789 # 替换为实际聊天ID )
3. (可选)验证时区同步
确保服务器系统时间与Asia/Jerusalem时区一致,避免时间偏差导致任务触发时间错误。
完整修复后的Bot类代码
class Bot: def __init__(self, handlers: list[BaseHandler], daily_routines, target_chat_id): self.application = Application.builder().token(BOT_TOKEN).build() for handler in handlers: self.application.add_handler(handler) self.job_queue = JobQueue() self.job_queue.set_application(self.application) self.job_queue.start() # 启动任务队列 for routine in daily_routines: self.job_queue.run_daily( routine, time=datetime.time(hour=15, minute=49, tzinfo=pytz.timezone('Asia/Jerusalem')), chat_id=target_chat_id # 传入目标聊天ID ) def __call__(self, *args, **kwargs): self.application.run_polling() if __name__ == "__main__": _handlers = [ ... ] TARGET_CHAT_ID = 123456789 # 替换为实际聊天ID bot = Bot(_handlers, [daily_routine], TARGET_CHAT_ID) bot()
额外注意
- 若需给多个用户发送定时消息,可在任务中遍历用户ID列表逐个发送,或为每个用户单独创建定时任务。
- 确保Bot已加入目标聊天,且拥有发送消息的权限。
内容的提问来源于stack exchange,提问作者Eliran Turgeman
相关产品推荐
相关产品推荐

