python-telegram-bot 13.7版本导入Update、Filters报错求助
问题描述
此前在Replit上编写的基础Telegram机器人Python代码,执行pip install python-telegram-bot==13.7后可正常运行,但现在出现以下问题:
- IDE提示“Update是未知导入符号”“Filters是未知导入符号”
- 运行时抛出核心报错:
Traceback (most recent call last): File "/home/runner/PeachpuffSquareTraining/main.py", line 1, in <module> from telegram import Update ImportError: cannot import name 'Update' from 'telegram' (/home/runner/PeachpuffSquareTraining/.pythonlibs/lib/python3.10/site-packages/telegram/__init__.py)
此前正常运行的代码如下:
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext # Replace 'YOUR_BOT_TOKEN' with the actual token you obtained from BotFather TOKEN = 'the token is secret' def start(update: Update, context: CallbackContext) -> None: update.message.reply_text('Hello! I am your bot.') def echo(update: Update, context: CallbackContext) -> None: update.message.reply_text(update.message.text) def main() -> None: updater = Updater(TOKEN) dp = updater.dispatcher # Command handlers dp.add_handler(CommandHandler("start", start)) # Message handler for echoing messages dp.add_handler(MessageHandler(Filters.text & ~Filters.command, echo)) # Start the Bot updater.start_polling() # Run the bot until you send a signal to stop it updater.idle() if __name__ == '__main__': main()
问题原因与解决方法
原因1:代码缺少必要的导入语句
在python-telegram-bot 13.x版本中,Update类属于telegram核心模块,而非telegram.ext子模块。当前代码仅导入了telegram.ext下的类,未导入Update,导致IDE无法识别类型注解中的Update符号,这是IDE提示错误的直接原因。
原因2:环境依赖版本异常
运行时的ImportError大概率是因为当前环境中的python-telegram-bot版本已不再是13.7——可能是Replit自动更新了依赖,或后续误操作安装了更高版本。该库在v20+版本中完全重构了模块结构,Update的导入路径、Updater及Filters的实现都发生了根本性变化,直接导致旧代码无法兼容。
解决步骤
- 强制重装指定版本依赖
执行以下命令,确保环境中安装的是兼容的13.7版本:
pip install --force-reinstall python-telegram-bot==13.7
- 修正代码导入语句
在现有导入代码前添加Update的导入,修改后的导入部分如下:
from telegram import Update from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
完成以上两步后,重新运行代码即可恢复正常。
内容的提问来源于stack exchange,提问作者Post
相关产品推荐
相关产品推荐

