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

aiogram使用BytesIO图片调用send_media_group发Telegram相册报错如何解决

问题原因

send_media_group 方法传入的媒体列表不能直接放BytesIO对象,每个元素必须是InputMedia子类的实例,发送图片对应使用InputMediaPhoto类型。另外现有代码里createimg()函数定义末尾漏了冒号,会先触发语法错误。

修正方案

  1. 从aiogram.types导入InputMediaPhoto
  2. 构造媒体列表时,把每个生成的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 10:57:01