Telethon Userbot实现带Spoiler转发图片:无需重新上传的方案问询
解决方案:复用已有媒体添加Spoiler遮罩无需下载重传
你不需要下载重传文件,Telethon支持直接复用Telegram服务器上已存在的媒体资源,通过构造InputMediaPhoto或InputMediaDocument对象并设置spoiler=True即可实现需求,完全不会消耗额外带宽。
核心原理
InputMediaUploadedPhoto是用于上传本地文件的类型,而你需要的是引用已存在于Telegram服务器的媒体,对应的类型是InputMediaPhoto(针对照片)和InputMediaDocument(针对文档类媒体,比如动图、贴纸)。通过从原消息的媒体对象中提取id、access_hash和file_reference,就能构造出可直接使用的输入媒体对象。
代码实现
处理照片类媒体
from telethon import events from telethon.tl.types import InputMediaPhoto, InputPhoto, MessageMediaPhoto @bot.on(events.NewMessage(chats=你的频道ID列表)) async def forward_with_spoiler(event): # 判断是否为照片媒体 if isinstance(event.message.media, MessageMediaPhoto): # 从原消息照片构造InputPhoto(复用服务器上的文件) input_photo = InputPhoto( id=event.message.media.photo.id, access_hash=event.message.media.photo.access_hash, file_reference=event.message.media.photo.file_reference ) # 构造带spoiler遮罩的媒体对象 spoiler_media = InputMediaPhoto(input_photo, spoiler=True) # 发送到目标聊天群 await bot.send_file(你的目标群ID, spoiler_media, caption=event.message.text) # 其他媒体类型可参考下面的文档处理逻辑
处理文档类媒体(如动图、贴纸)
from telethon.tl.types import InputMediaDocument, InputDocument, MessageMediaDocument # 在上述事件处理函数中添加: elif isinstance(event.message.media, MessageMediaDocument): input_doc = InputDocument( id=event.message.media.document.id, access_hash=event.message.media.document.access_hash, file_reference=event.message.media.document.file_reference ) spoiler_media = InputMediaDocument(input_doc, spoiler=True) await bot.send_file(你的目标群ID, spoiler_media, caption=event.message.text)
为什么之前的尝试失败?
你提到的types.MessageMediaDocument是消息中的媒体类型,而send_file需要的是输入媒体类型(InputMedia*系列),两者类型不匹配,因此会触发错误。必须使用InputMediaPhoto/InputMediaDocument这类专门用于发送的输入媒体类型,才能正确设置spoiler属性。
内容的提问来源于stack exchange,提问作者NikGovn
相关产品推荐
相关产品推荐

