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

如何通过Telethon获取媒体下载URL而无需直接下载文件?

Telethon获取媒体临时下载URL的方法

核心结论

Telethon基于MTProto协议,本身没有提供永久公开的媒体下载URL,但可以通过调用Telegram内部API生成临时HTTP下载链接,无需直接下载文件。

实现步骤与代码示例

1. 针对文档/视频等文件类型

from telethon.tl.functions.messages import GetWebDocumentRequest
from telethon.tl.types import InputDocumentFileLocation

@client.on(events.NewMessage)
async def get_document_url(event):
    message = event.message
    # 判断消息是否包含文档类媒体
    if message.media and hasattr(message.media, 'document'):
        doc = message.media.document
        # 构造文件位置参数
        file_location = InputDocumentFileLocation(
            id=doc.id,
            access_hash=doc.access_hash,
            file_reference=doc.file_reference,
            thumb_size=''  # 留空获取原文件,需缩略图可填's'/'m'/'l'等尺寸标识
        )
        # 请求生成临时下载链接
        web_doc = await client(GetWebDocumentRequest(
            location=file_location,
            size=doc.size,
            mime_type=doc.mime_type,
            attributes=doc.attributes
        ))
        # 输出临时URL
        print(f"临时下载链接: {web_doc.url}")

2. 针对照片类型

from telethon.tl.functions.messages import GetWebDocumentRequest
from telethon.tl.types import InputPhotoFileLocation

@client.on(events.NewMessage)
async def get_photo_url(event):
    message = event.message
    # 判断消息是否包含照片
    if message.media and hasattr(message.media, 'photo'):
        photo = message.media.photo
        # 选取尺寸最大的照片
        largest_photo = photo.sizes[-1]
        # 构造照片位置参数
        file_location = InputPhotoFileLocation(
            id=photo.id,
            access_hash=photo.access_hash,
            file_reference=photo.file_reference,
            thumb_size=largest_photo.type
        )
        # 请求生成临时下载链接
        web_doc = await client(GetWebDocumentRequest(
            location=file_location,
            size=largest_photo.size,
            mime_type='image/jpeg',
            attributes=[]
        ))
        # 输出临时URL
        print(f"照片临时下载链接: {web_doc.url}")

注意事项

  • 生成的链接为临时有效,一般有效期几小时,过期后无法使用。
  • 该链接仅对应目标媒体文件,无法长期分享或存储复用。
  • 此方法不受Bot API的文件大小限制,支持MTProto协议允许的所有文件尺寸。

内容的提问来源于stack exchange,提问作者Mehrdad HMT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 15:02:20