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

如何用Telethon实现Telegram Bot突破20MB文件下载限制?

实现大文件下载的思路与代码建议

核心原理

Telethon基于Telegram原生MTProto API开发,完全不受Bot API的20MB文件下载限制,原生支持最大2GB左右的文件下载(取决于Telegram官方当前限制)。你提到的GetPublicLinkBot本质也是利用MTProto的能力绕开Bot API限制,而非依赖getFile接口。

基础准备

  • 已获取有效的api_id和api_hash(从Telegram官方开发者平台获取)
  • 安装Telethon:pip install telethon

具体实现步骤

1. 初始化Telethon客户端

from telethon import TelegramClient

# 替换为你的信息
api_id = 123456
api_hash = "your_api_hash_here"
session_name = "large_file_download_session"

# 首次运行会要求输入手机号和验证码,后续会自动保存会话
client = TelegramClient(session_name, api_id, api_hash)

2. 定位目标文件消息

要下载文件,首先需要获取包含该文件的消息对象,可通过对话ID、用户名或搜索消息实现:

async def get_target_file_message(chat_identifier):
    # chat_identifier 可以是对话ID、用户名(如@some_channel)或直接的实体对象
    chat = await client.get_entity(chat_identifier)
    # 示例:获取对话中最新的10条消息,筛选带文件的消息
    messages = await client.get_messages(chat, limit=10)
    return next((msg for msg in messages if msg.document), None)

3. 直接下载大文件

使用Telethon原生的download_media方法,支持断点续传,无需依赖Bot API的file_id:

async def download_large_file():
    # 替换为目标对话的标识
    file_msg = await get_target_file_message("@your_target_chat")
    if file_msg:
        # 下载到指定路径,不指定则默认保存在当前目录
        await client.download_media(file_msg, file="./downloaded_large_file.ext")
        print("大文件下载完成")
    else:
        print("未找到可下载的文件消息")

# 运行客户端执行下载
with client:
    client.loop.run_until_complete(download_large_file())

4. 可选:生成公开下载链接(类似GetPublicLinkBot)

如果需要生成公开分享链接,可将文件转发到你控制的公开频道,再提取消息链接:

async def generate_public_download_link(file_msg):
    # 替换为你的公开频道用户名
    public_channel = await client.get_entity("@your_public_channel")
    forwarded_msg = await client.forward_messages(public_channel, file_msg)
    # 生成公开可访问的链接
    return f"https://t.me/{public_channel.username}/{forwarded_msg.id}"

注意事项

  • 避免频繁批量下载大文件,防止触发Telegram账号风控限制
  • 大文件下载可通过download_media的timeout参数调整超时时间,避免中断
  • 下载私有对话/频道的文件时,确保你的账号拥有对应访问权限

内容的提问来源于stack exchange,提问作者Lansen Portan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 17:05:04