Telegram Bot开发报错:Updater类不存在dispatcher属性
解决python-telegram-bot中Updater无dispatcher属性的问题
问题出在python-telegram-bot版本差异:v20及以上版本彻底重构了API,移除了Updater类的dispatcher属性,改用updater.application来获取处理逻辑的核心实例。
修复步骤
1. 确认版本
执行命令查看当前安装的版本:
pip show python-telegram-bot
如果版本是20.x或更高,按以下方式修改代码。
2. 修改代码(适配v20+)
把原来的updater.dispatcher.add_handler()替换为updater.application.add_handler(),同时v20+中use_context=True是默认设置,无需手动传入。修改后的代码如下:
import logging from multiprocessing import Queue from telegram import InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import Updater, CommandHandler, CallbackQueryHandler def start(update, context): # 补充你的start命令逻辑 pass def button(update, context): # 补充你的按钮回调逻辑 pass def main(): update_queue = Queue() # v20+无需传use_context=True,默认启用 updater = Updater("API KEY", update_queue=update_queue) # 替换dispatcher为application updater.application.add_handler(CommandHandler('start', start)) updater.application.add_handler(CallbackQueryHandler(button)) updater.start_polling() updater.idle() if __name__ == '__main__': main()
3. 更推荐的v20+写法(直接用Application类)
v20+官方更推荐直接使用Application类构建Bot,替代Updater的旧模式,代码结构更清晰:
import logging from multiprocessing import Queue from telegram import InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import Application, CommandHandler, CallbackQueryHandler def start(update, context): pass def button(update, context): pass def main(): update_queue = Queue() application = Application.builder().token("API KEY").update_queue(update_queue).build() application.add_handler(CommandHandler('start', start)) application.add_handler(CallbackQueryHandler(button)) application.run_polling() if __name__ == '__main__': main()
注意事项
- 若坚持使用旧版API(v13-v19),可指定安装对应版本:
但不推荐,旧版已停止维护。pip install python-telegram-bot==13.7
内容的提问来源于stack exchange,提问作者AdriI Gofman
相关产品推荐
相关产品推荐

