Telethon转发Telegram图片组时拆分为多条消息的修复方案咨询
Telethon转发Telegram图片组时拆分为多条消息的修复方案咨询
嘿,我来帮你搞定这个图片组转发被拆分的问题!你现在的代码之所以会把图片组拆成多条消息,是因为处理多媒体的方式搞错了——你把第一张图单独作为主文件,剩下的用file参数传,但这并不是Telethon发送媒体组的正确姿势。
问题出在哪儿?
看你这段代码:
await client.send_file(Id_bot, media[0], caption=event.message.message, file=media[1:])
这里的file参数是用来附加额外文件的,不是用来构建媒体组的。这样写会导致第一张图单独发一条消息,剩下的图片会作为后续的附件消息发出去,自然就拆分了。
修复方案
其实Telethon的send_file本身就支持直接接收媒体列表,自动打包成单条消息里的媒体组。我们只需要调整代码逻辑就行:
简化版(直接复用原媒体对象,无需重新上传)
如果不需要修改媒体内容,直接用event.media就行,不用重新上传:
from telethon import TelegramClient, events import asyncio Id_bot = # 填入你的机器人ID Id_Group2 = # 填入对应群组ID Id_Group3 = Id_Group4 = Id_Group5 = api_id = '' # 填入你的api_id api_hash = '' # 填入你的api_hash client = TelegramClient('none', api_id, api_hash) @client.on(events.NewMessage) async def handler(event): chat_id = event.chat_id print(chat_id) # 避免循环转发,排除目标群组 if chat_id not in [Id_Group2, Id_Group3, Id_Group4, Id_Group5]: if event.media: # 统一处理caption,空的话就传None caption = event.message.message or None # 直接传递整个媒体列表,自动作为媒体组发送 await client.send_file(Id_bot, event.media, caption=caption) elif event.message.message: await client.send_message(Id_bot, event.message.message) client.start() client.run_until_disconnected()
进阶版(需要重新上传媒体的场景)
如果你的业务场景必须重新上传媒体(比如要修改媒体),那也要把所有上传后的媒体对象放在一个列表里,直接传给send_file:
# 仅修改handler里的媒体处理部分 if event.media: caption = event.message.message or None if isinstance(event.media, list): # 收集所有上传后的媒体对象 media_group = [] for media_item in event.media: media_group.append(await client.upload_file(media_item)) # 传递整个媒体组列表 await client.send_file(Id_bot, media_group, caption=caption) else: # 单媒体处理 await client.send_file(Id_bot, event.media, caption=caption)
核心逻辑说明
send_file函数接收单个媒体对象或媒体列表时,会自动判断:列表就发成一个媒体组,单个就发单条媒体消息。- 不要拆分媒体列表,直接把整个列表传给
send_file的第一个参数,这才是构建媒体组的正确方式。
备注:内容来源于stack exchange,提问作者Денис Жгута




