PyCharm中无法向Telegram发送文件:ImportError问题求助
无法从'telegram'模块导入'Bot'类的问题解决
环境配置
- Windows 11 操作系统
- PyCharm 作为开发IDE
- 已在PyCharm中安装 selenium 和 telegram 库
问题说明
尝试通过代码从本地目录向Telegram频道发送文件,运行时触发ImportError,无法从'telegram'模块导入'Bot'类。
用户代码
import os from telegram import Bot bot=Bot(token="xxxxxx") # Replace 'YOUR_TELEGRAM_TOKEN' with your actual Telegram bot token TOKEN='xxxx' # Replace 'YOUR_CHAT_ID' with your actual Telegram chat ID CHAT_ID='xxxx' # Directory path containing the files to upload DIRECTORY_PATH='E:\upload\2017' def upload_files_to_telegram(): bot=Bot(token=TOKEN) for filename in os.listdir(DIRECTORY_PATH): file_path=os.path.join(DIRECTORY_PATH,filename) if os.path.isfile(file_path): with open(file_path,'rb') as file: bot.send_document(chat_id=CHAT_ID,document=file) print(f"Uploaded {filename} successfully.")
报错信息
Traceback (most recent call last): File "E:\vss coding\Dayscoding100\venv\telegramupload.py", line 2, in <module> from telegram import Bot ImportError: cannot import name 'Bot' from 'telegram' (E:\vss coding\Dayscoding100\venv\lib\site-packages\telegram\__init__.py) Process finished with exit code 1
解决步骤
- 卸载错误的库
你安装的telegram包并非用于开发Telegram机器人的库,需先卸载:
pip uninstall telegram
- 安装正确的机器人库
安装官方推荐的python-telegram-bot库:
pip install python-telegram-bot
- 修正代码问题
- 路径转义:Windows路径需用双反斜杠
\\或原始字符串r'',避免转义字符解析错误 - 重复实例化Bot:代码开头无需提前创建Bot实例,函数内创建即可
- 调用上传函数:需在代码末尾调用
upload_files_to_telegram()才会执行上传逻辑
修正后的代码示例:
import os from telegram import Bot # 替换为你的Telegram机器人令牌 TOKEN='xxxx' # 替换为你的Telegram频道/聊天ID CHAT_ID='xxxx' # 本地文件目录(使用原始字符串避免转义问题) DIRECTORY_PATH=r'E:\upload\2017' def upload_files_to_telegram(): bot = Bot(token=TOKEN) for filename in os.listdir(DIRECTORY_PATH): file_path = os.path.join(DIRECTORY_PATH, filename) if os.path.isfile(file_path): with open(file_path, 'rb') as file: bot.send_document(chat_id=CHAT_ID, document=file) print(f"Uploaded {filename} successfully.") # 调用上传函数 upload_files_to_telegram()
内容的提问来源于stack exchange,提问作者vivek rajagopalan
相关产品推荐
相关产品推荐

