Telegram提及Python机器人脚本ImportError:无法导入Update类的解决方法
解决Telegram机器人ImportError: cannot import name 'Update' from 'telegram'问题
问题场景
在Windows 8.1 32位系统中安装最新版Python,搭建Telegram提及机器人并编写了脚本,已安装pip、telegram、python-telegram-bot等依赖。运行脚本时出现导入错误。
机器人代码
import logging from telegram import Update # from telegram.update import Update from telegram.ext import Updater, CommandHandler, MessageHandler, CallbackContext, Filters logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) TOKEN = 'I removed it for now' # Initialize the Updater updater = Updater(token=TOKEN, use_context=True) dispatcher = updater.dispatcher # Command handler def start(update: Update, context: CallbackContext) -> None: update.message.reply_text("Hello! I am your mention bot. Use @everyone to mention all members.") start_handler = CommandHandler('start', start) dispatcher.add_handler(start_handler) # Mention handler def handle_mentions(update: Update, context: CallbackContext) -> None: message_text = update.message.text if "@everyone" in message_text: chat_id = update.message.chat_id # Get the list of all members in the group all_members = context.bot.get_chat_members(chat_id) # Prepare the mention message mention_message = " ".join([f"@{member.user.username}" for member in all_members if member.user.username]) if mention_message: mention_message = f"Mentioning all members: {mention_message}" else: mention_message = "No active members to mention." # Send the mention message context.bot.send_message(chat_id, mention_message, reply_to_message_id=update.message.message_id) mention_handler = MessageHandler(Filters.text & ~Filters.command, handle_mentions) dispatcher.add_handler(mention_handler) # Start the bot updater.start_polling() # Run the bot until you press Ctrl-C updater.idle()
报错信息
C:\Python\bot>python mention_bot.py Traceback (most recent call last): File "C:\Python\bot\mention_bot.py", line 2, in <module> from telegram import Update ImportError: cannot import name 'Update' from 'telegram' (C:\Python\Lib\site-packages\telegram\__init__.py>
解决方案
核心问题
你同时安装了telegram和python-telegram-bot两个库,前者是过时的轻量库,后者是官方推荐的Telegram机器人开发主流库,两者命名空间完全重叠,导致Python优先加载了telegram库,而该库中没有Update类,从而触发导入错误。
修复步骤
卸载冲突的
telegram库
打开命令提示符,执行以下命令:pip uninstall telegram执行
pip list确认telegram库已被移除。匹配
python-telegram-bot版本
你的代码基于python-telegram-botv13.x版本编写(使用了Updater、use_context=True等特性),若安装的是v20+异步重构版本,代码会完全不兼容。建议安装v13.x稳定版:pip install python-telegram-bot==13.7修正导入语句
在v13.x版本中,Update类的正确导入路径是telegram.update,可以修改代码中的导入语句:from telegram.update import Update也可保留
from telegram import Update(v13.x支持该方式,但必须确保无telegram库干扰)。额外功能修复(可选)
原代码中context.bot.get_chat_members(chat_id)无法直接获取所有群成员,单次调用最多返回100个成员,需通过分页循环获取:all_members = [] offset = 0 while True: members = context.bot.get_chat_members(chat_id, offset=offset, limit=100) if not members: break all_members.extend(members) offset += 100
内容的提问来源于stack exchange,提问作者Adorian Vinfo
相关产品推荐
相关产品推荐

