Python Telegram BOT API中context.job_queue.run_once运行异常如何修复
Telegram Bot 代码修复方案
错误原因说明
- 错误1:
callback_search_msgs是Job队列的回调函数,收到的context仅携带job属性,不存在CommandHandler回调才有的args属性,你没有提前把用户输入的关键词传递到Job上下文 - 错误2:你在
callback_search_msgs中错误调用了search_msgs函数,把int类型的chat_id传给了search_msgs的context形参,调用时参数顺序完全错了,自然会报int没有job_queue属性的错误 - 额外问题:python-telegram-bot v13+开启
use_context=True后,不需要额外配置pass_job_queue、pass_user_data参数,context会默认携带这些属性
修复后完整代码
import telegram from telegram.ext import Updater, CommandHandler token = "你的Bot Token" bot = telegram.Bot(token=token) # 异步回调处理搜索逻辑 def callback_search_msgs(context): # 从Job上下文中取出提前存入的chat_id和搜索关键词 chat_id = context.job.context['chat_id'] userkey = context.job.context['userkey'] # 这里写你的数据库查询逻辑,用userkey查匹配文本 # 示例查询结果 result = f"你搜索的关键词是:{userkey}\n匹配结果:xxx" # 发送结果给用户 bot.send_message(chat_id=chat_id, text=result) # 接收/search_msgs命令的处理函数 def search_msgs(update, context): # 先判断用户有没有传关键词 if not context.args: update.message.reply_text("请携带搜索关键词,格式:/search_msgs 关键词") return userkey = context.args[0] chat_id = update.message.chat_id # 把需要的参数打包存入Job上下文,延时0秒立即执行异步任务 context.job_queue.run_once( callback_search_msgs, when=0, context={'chat_id': chat_id, 'userkey': userkey} ) def main(): updater = Updater(token, use_context=True) dp = updater.dispatcher # 注册命令处理器,不需要额外加pass_*参数 dp.add_handler(CommandHandler("search_msgs", search_msgs)) updater.start_polling() updater.idle() if __name__ == '__main__': main()
修改点说明
- 调整了任务传递逻辑:在命令处理函数中提前拿到用户输入的关键词,和chat_id一起打包存入Job的context,避免回调函数拿不到参数
- 删除了回调函数中对
search_msgs的错误调用,把搜索、发结果的逻辑直接放在回调函数中 - 增加了参数校验逻辑,用户没传关键词时返回提示
- 移除了CommandHandler中冗余的
pass_job_queue、pass_user_data配置
内容的提问来源于stack exchange,提问作者Vivek Singh
相关产品推荐
相关产品推荐

