aiogram使用BytesIO图片调用send_media_group发Telegram相册报错如何解决
问题原因
send_media_group 方法传入的媒体列表不能直接放BytesIO对象,每个元素必须是InputMedia子类的实例,发送图片对应使用InputMediaPhoto类型。另外现有代码里createimg()函数定义末尾漏了冒号,会先触发语法错误。
修正方案
- 从
aiogram.types导入InputMediaPhoto - 构造媒体列表时,把每个生成的
BytesIO对象封装为InputMediaPhoto实例
修正后完整代码:
from PIL import Image, ImageDraw, ImageFont from io import BytesIO from aiogram import Bot, Dispatcher, executor, types # 导入需要的InputMediaPhoto from aiogram.types import InputMediaPhoto import logging API_TOKEN = 'xxxxxx' logging.basicConfig(level=logging.INFO) bot = Bot(token=API_TOKEN) dp = Dispatcher(bot) # 补全函数定义的冒号 def createimg(): im = Image.new('RGB', (256, 256), color='black') bio = BytesIO() bio.name = 'res.png' im.save(bio, 'PNG') bio.seek(0) return bio @dp.message_handler(commands=['start']) async def send_welcome(message: types.Message): # 把每个BytesIO封装为InputMediaPhoto实例 media_list = [ InputMediaPhoto(createimg()), InputMediaPhoto(createimg()) ] await bot.send_media_group(message.from_user.id, media=media_list)
如果需要给单张图片加配文,在构造InputMediaPhoto时传入caption参数即可:
InputMediaPhoto(createimg(), caption="第一张测试图片")
内容的提问来源于stack exchange,提问作者Juls Winfield
相关产品推荐
相关产品推荐

