无法运行Python Telegram Bot包:ModuleNotFoundError报错求助
Telegram机器人运行报错:ModuleNotFoundError: No module named 'telegram.ext.updater'
问题详情
在Windows 11 Pro(Python 3.9.15)上运行Telegram机器人脚本时出现以下报错:
(stockAlert) PS D:\Development\StockAlert> python .\stockAlertBot.py Traceback (most recent call last): File "D:\Development\StockAlert\stockAlertBot.py", line 1, in <module> from telegram.ext.updater import Updater ModuleNotFoundError: No module named 'telegram.ext.updater'
同一脚本在Mac设备上可正常运行,已尝试以下操作但未解决:
- 卸载并重新安装相关包
- 创建新虚拟环境并安装包
- 重启系统
解决方案
1. 修正导入语句
telegram.ext.updater不是正确的导入路径,需根据python-telegram-bot版本调整:
- 若使用v12.x 或 v13.x:将导入语句改为:
from telegram.ext import Updater - 若使用v20.x 及以上:该版本已移除
Updater类,需改用Application重构代码,示例: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!') if __name__ == '__main__': application = ApplicationBuilder().token('YOUR_TOKEN').build() start_handler = CommandHandler('start', start) application.add_handler(start_handler) application.run_polling()
2. 同步Mac与Windows的包版本
Mac上能正常运行说明其python-telegram-bot版本与代码兼容,可同步版本解决问题:
- 在Mac上导出包列表:
pip freeze > requirements.txt - 将
requirements.txt复制到Windows项目目录,激活虚拟环境后执行:pip install -r requirements.txt
3. 确认虚拟环境激活状态
确保运行脚本时,你创建的stockAlert虚拟环境处于激活状态,避免系统全局Python环境的包干扰。
内容的提问来源于stack exchange,提问作者user20969617
相关产品推荐
相关产品推荐

