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

如何用Python向Telegram频道自动上传最大2GB的文件?

解决方案:自动上传大文件到Telegram频道

核心问题拆解

  • Telegram官方Bot API单文件上传上限是50MB,直接用Bot传2GB文件根本行不通
  • 部分50MB以内的文件上传失败,大概率是网络波动、API调用频率超限,或是文件读取异常导致的

最优方案:Userbot + Bot 协作上传

方案逻辑

用普通用户账号(通过Userbot脚本控制)上传文件——普通用户支持最大2GB的文件上传权限,先让Userbot把文件发给你的Bot,再由Bot自动转发到目标频道,既实现自动化,又绕开Bot的大小限制。

具体实现步骤

  1. 搭建Userbot脚本
    用telethon或pyrogram这类支持Userbot的库,先去my.telegram.org申请普通用户账号的API密钥。示例代码(Telethon版):

    from telethon import TelegramClient
    import os
    import asyncio
    
    # 替换成你的账号信息
    API_ID = 你的API_ID
    API_HASH = "你的API_HASH"
    BOT_USERNAME = "@你的Bot用户名"
    FILE_DIR = "你的文件目录路径"
    
    client = TelegramClient("userbot_session", API_ID, API_HASH)
    
    async def send_files_to_bot():
        for file_name in os.listdir(FILE_DIR):
            file_path = os.path.join(FILE_DIR, file_name)
            try:
                # 发送文件给Bot
                await client.send_file(BOT_USERNAME, file_path)
                print(f"已推送文件:{file_name}")
                # 加个延迟,避免触发频率限制
                await asyncio.sleep(1)
            except Exception as e:
                with open("upload_fail.txt", "a", encoding="utf-8") as f:
                    f.write(f"{file_path} | 错误:{str(e)}\n")
                print(f"推送失败:{file_name}")
    
    with client:
        client.loop.run_until_complete(send_files_to_bot())
    
  2. 修改Bot代码实现自动转发
    更新你的Bot脚本,监听来自Userbot的文件消息,自动转发到目标频道:

    @dp.message_handler(content_types=['document'])
    async def forward_to_channel(message: types.Message):
        # 可选:验证发送者是你的Userbot,防止其他人滥用
        if message.from_user.id == 你的Userbot账号ID:
            try:
                await bot.forward_message(
                    chat_id=你的频道ID,
                    from_chat_id=message.chat.id,
                    message_id=message.message_id
                )
                print(f"已转发文件:{message.document.file_name}")
            except Exception as e:
                with open("forward_fail.txt", "a", encoding="utf-8") as f:
                    f.write(f"{message.document.file_name} | 错误:{str(e)}\n")
    

解决小文件上传失败的细节优化

  • 加重试机制:对上传失败的小文件,写个循环重试3-5次,减少网络波动的影响
  • 控制调用频率:每次上传/转发后加1-2秒延迟,避免触发Telegram的API频率限制
  • 前置文件检查:上传前先判断文件是否存在、是否能正常读取,排除损坏文件

备选方案:拆分大文件(不推荐)

如果不想用Userbot,可把50MB以上的文件拆成多个50MB以内的分卷,上传后在频道说明合并方法,但这种方法用户体验差,仅作为应急备选。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 01:47:05