You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python Telegram Bot从磁盘发送图片报错问题排查

解决Telegram Bot发送本地图片报错的问题

先梳理下你给出的操作代码和报错片段:

你的执行代码

from telegram import Bot
bot = Bot(token)
update = bot.get_updates()[0]
chat_id = update["message"]["chat"]["id"]
bot.send_photo(chat_id=chat_id, photo=open("test.jpg", "rb"))

报错回溯片段

Traceback (most recent call last):
File "", line 1, in
bot.send_photo(chat_id=chat_id, photo=open("test.jpg", "rb"))...

针对这个发送图片失败的问题,我整理了几个高频排查方向,你可以逐个尝试:

  • 检查文件路径是否正确
    你用的是相对路径"test.jpg",得确保这个图片和你的脚本/Notebook在同一个工作目录里。拿不准的话,直接用绝对路径更稳妥:

    import os
    # 获取当前脚本所在目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    # 拼接图片绝对路径
    photo_full_path = os.path.join(current_dir, "test.jpg")
    bot.send_photo(chat_id=chat_id, photo=open(photo_full_path, "rb"))
    

    如果是在Jupyter环境里,先执行!pwd(Linux/macOS)或!cd(Windows)查看当前工作目录,确认图片是否在该目录下。

  • 确认文件读取权限
    确保你的Python进程有权限读取这张图片。Linux/macOS可以执行chmod +r test.jpg赋予读取权限;Windows右键图片→属性→安全,检查当前用户是否有读取权限。

  • 适配python-telegram-bot版本差异
    不同版本的库API有差异:

    • 如果你用的是v13及以上版本,推荐用InputFile包装文件对象:
      from telegram import InputFile
      with open("test.jpg", "rb") as photo_file:
          bot.send_photo(chat_id=chat_id, photo=InputFile(photo_file))
      
    • 如果你用的是v20+的最新版本,需要用异步写法:
      import asyncio
      from telegram import Bot, InputFile
      
      async def send_local_photo():
          bot = Bot(token)
          updates = await bot.get_updates()
          chat_id = updates[0].message.chat.id
          with open("test.jpg", "rb") as photo_file:
              await bot.send_photo(chat_id=chat_id, photo=InputFile(photo_file))
      
      asyncio.run(send_local_photo())
      
  • 验证图片文件有效性
    有时候图片文件损坏也会导致发送失败。先尝试用系统自带的图片查看器打开test.jpg,确认它是正常可读取的图片;如果损坏,换一张正常的图片测试。

如果以上方法都没解决,建议贴出完整的报错信息,这样能更精准定位问题~

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

火山引擎 最新活动