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

Telegram Bot Updater模块导入失败问题求助

问题根源

你安装的是python-telegram-bot v20及以上版本,该版本彻底移除了Updater、Dispatcher等旧API,改用基于asyncio的Application架构,因此旧代码会出现导入错误。


两种解决方案

方案一:降级到兼容旧代码的版本

如果想继续使用你原来的代码结构,可降级到最后一个支持Updater的稳定版本:

  1. 卸载当前版本:
pip uninstall python-telegram-bot -y
  1. 安装v13.7版本:
pip install python-telegram-bot==13.7
  1. 补全旧代码的缺失导入:
    • 第一段代码需添加:from telegram.ext import CommandHandler
    • 第二段代码需添加:from telegram.ext import MessageHandler, Filters,并将bot.send_message改为context.bot.send_message(原代码中bot未在处理函数内定义)

方案二:改用v20+的新API写法(推荐,旧版本已停止维护)

以下是适配新版本的完整代码,同时优化了Yahoo Finance的价格获取逻辑(避免依赖动态的data-reactid):

import requests
from bs4 import BeautifulSoup
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes

def get_price(symbol):
    url = f"https://finance.yahoo.com/quote/{symbol}"
    # 添加请求头,避免被Yahoo拦截
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
    }
    page = requests.get(url, headers=headers)
    soup = BeautifulSoup(page.content, "html.parser")
    
    # 优先使用Yahoo官方的实时价格标签
    price_element = soup.find("fin-streamer", {"class": "Fw(b) Fz(36px) Mb(-4px) D(ib)"})
    if price_element:
        return price_element.get_text()
    
    # 备用选择器,防止页面结构变更
    price_element = soup.find("span", {"data-test": "qsp-price"})
    return price_element.get_text() if price_element else "无法获取价格"

async def check_price(update: Update, context: ContextTypes.DEFAULT_TYPE):
    symbols = ["^DJI", "^GSPC"]
    prices = [get_price(symbol) for symbol in symbols]
    message = f"DJI: {prices[0]}\nGSPC: {prices[1]}"
    await context.bot.send_message(chat_id=update.effective_chat.id, text=message)

async def handle_text_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    dji_price = get_price("^DJI")
    sp_price = get_price("^GSPC")
    message = f"DJI Price: {dji_price}\nSP Price: {sp_price}"
    await context.bot.send_message(chat_id=update.effective_chat.id, text=message)

def main():
    token = "你的Bot Token"
    # 初始化Application替代原Updater
    application = ApplicationBuilder().token(token).build()
    
    # 添加命令处理器
    price_handler = CommandHandler("price", check_price)
    application.add_handler(price_handler)
    
    # 添加文本消息处理器(排除命令消息)
    text_handler = MessageHandler(filters.TEXT & ~filters.COMMAND, handle_text_message)
    application.add_handler(text_handler)
    
    # 启动Bot
    application.run_polling()

if __name__ == '__main__':
    main()

新代码核心变化:

  • 用ApplicationBuilder替代Updater,采用异步架构
  • 所有消息处理函数需定义为async,发送消息需用await
  • 用filters.TEXT替代旧版Filters.text(v20+命名规范调整)
  • 优化价格获取逻辑,避免依赖动态属性,提升稳定性

内容的提问来源于stack exchange,提问作者VanderNight

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:31:00