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

Python中ModuleNotFoundError求助:找不到'telegram'模块

ModuleNotFoundError: No module named 'telegram' 解决方案

问题重现

运行以下代码时持续报错 ModuleNotFoundError: No module named 'telegram':

import telegram

api_key = "api_key"
user_id = "id"

class NotificationManager:
    #This class is responsible for sending notifications with the deal flight details.

    def __init__(self):
        self.bot = telegram.Bot(token=api_key)
        pass

    def sendMessage(self, contents):
        self.bot.send_message(chat_id=user_id, text=contents)
    pass

已尝试的无效操作:

  • 执行以下安装命令均无效果:
    pip3 install telegram
    pip3 install python-telegram
    pip3 install python-telegram-bot
    
  • 更新Python和Pip至最新版本
  • 卸载并重新安装相关包

核心原因

问题出在python-telegram-bot版本迭代导致的导入路径变更:

  • 旧版本(v13及以下)支持直接import telegram
  • 新版本(v14+,尤其是v20+)重构了模块结构,不再兼容旧的导入方式
  • 额外注意:pip3 install telegram安装的是一个无关第三方包,并非官方Telegram Bot开发工具包,完全无法满足需求

解决方案

方案1:保留原代码,安装兼容版本

如果不想修改代码,安装最后一个支持import telegram的稳定分支版本:

pip3 install python-telegram-bot==13.7

安装完成后直接运行原代码即可。

方案2:适配最新版本(推荐)

若想使用最新功能,修改代码的导入逻辑适配新版本:

from telegram import Bot

api_key = "api_key"
user_id = "id"

class NotificationManager:
    def __init__(self):
        self.bot = Bot(token=api_key)

    def sendMessage(self, contents):
        self.bot.send_message(chat_id=user_id, text=contents)

然后确保安装最新版本:

pip3 install python-telegram-bot --upgrade

额外排查步骤

  1. 确认Python与Pip环境匹配:
    运行which python3和which pip3,确保两者路径一致,避免包安装到了其他Python环境。
  2. 清理无效包:
    运行pip3 list | grep telegram,若存在telegram或python-telegram无关包,先卸载:
    pip3 uninstall telegram python-telegram -y
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 18:57:08