python-telegram-bot 20.2版本无法导入Dispatcher模块求助
解决python-telegram-bot v20.2导入Dispatcher报错的问题
问题原因
python-telegram-bot从v20版本开始进行了重大架构重构,Dispatcher类已被彻底移除,这就是你找不到该模块、导入时触发ImportError的核心原因。多数在线教程基于旧版本(v13及更早版本)编写,所以仍在使用Dispatcher相关代码,和当前新版本的API不兼容。
解决方案
方案1:使用v20+的新架构(推荐)
新版本用Application替代了原来的Updater+Dispatcher组合,同时处理函数需要改为异步形式。示例代码如下:
from telegram import Update from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes # 异步处理函数 async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text('Hello!') def main(): # 创建Application实例 application = ApplicationBuilder().token("你的机器人TOKEN").build() # 添加命令处理器 application.add_handler(CommandHandler("start", start)) # 启动轮询 application.run_polling() if __name__ == '__main__': main()
关键变化点:
- 用
ApplicationBuilder构建应用,替代原Updater - 所有消息/命令处理函数必须定义为异步函数(添加
async关键字,调用Telegram API方法时加await) - 使用
ContextTypes.DEFAULT_TYPE作为上下文类型注解
方案2:降级到旧版本(不推荐)
如果暂时不想适配新架构,可以安装兼容Dispatcher的旧版本(比如v13.7,这是旧架构的最后一个稳定版本):
pip uninstall python-telegram-bot pip install python-telegram-bot==13.7
但注意旧版本已停止官方维护,后续不会有功能更新和安全修复,长期来看建议使用新版本。
内容的提问来源于stack exchange,提问作者Akshay Patil
相关产品推荐
相关产品推荐

