You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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类,从而触发导入错误。

修复步骤

  1. 卸载冲突的telegram库
    打开命令提示符,执行以下命令:

    pip uninstall telegram
    

    执行pip list确认telegram库已被移除。

  2. 匹配python-telegram-bot版本
    你的代码基于python-telegram-bot v13.x版本编写(使用了Updater、use_context=True等特性),若安装的是v20+异步重构版本,代码会完全不兼容。建议安装v13.x稳定版:

    pip install python-telegram-bot==13.7
    
  3. 修正导入语句
    在v13.x版本中,Update类的正确导入路径是telegram.update,可以修改代码中的导入语句:

    from telegram.update import Update
    

    也可保留from telegram import Update(v13.x支持该方式,但必须确保无telegram库干扰)。

  4. 额外功能修复(可选)
    原代码中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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 10:01:08