使用Aiogram开发Telegram Bot无法发送本地图片问题求助
解决Aiogram发送本地图片的报错问题
核心问题分析
- 直接传本地路径报错:Telegram API会将字符串默认当作网络URL解析,本地路径不符合HTTP URL格式,因此触发端口错误。
types.InputFile实例化报错:InputFile是抽象基类,不能直接创建实例,必须使用其具体实现类或正确的文件对象包装方式。
正确解决方案
方法1:使用FileInputFile(Aiogram 3.x推荐)
Aiogram 3.x专门提供FileInputFile类处理本地文件,直接传入路径即可:
from aiogram.types import FileInputFile # 替换为你的本地图片路径 photo = FileInputFile("./test.jpg") await bot.send_photo(chat_id=你的聊天ID, photo=photo)
方法2:用BufferedInputFile包装文件内容
如果需要手动读取文件内容,用BufferedInputFile封装后发送:
from aiogram.types import BufferedInputFile with open("./test.jpg", "rb") as f: photo = BufferedInputFile(f.read(), filename="test.jpg") await bot.send_photo(chat_id=你的聊天ID, photo=photo)
方法3:直接传入二进制文件对象
以二进制模式打开文件,直接传入send_photo方法:
with open("./test.jpg", "rb") as f: await bot.send_photo(chat_id=你的聊天ID, photo=f)
版本兼容提示
如果使用Aiogram 2.x,无需额外封装类,直接传入二进制文件对象即可:
# Aiogram 2.x写法 await bot.send_photo(chat_id=你的聊天ID, photo=open("./test.jpg", "rb"))
内容的提问来源于stack exchange,提问作者sleepylore
相关产品推荐
相关产品推荐

