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

无需虚拟机或服务器,如何修改Telegram Bot代码发送大文件?

解决方案思路
  • 放弃Telegram Bot API,改用MTProto客户端协议库(如Pyrogram/Telethon),直接模拟桌面客户端行为,原生支持大文件分片上传
  • 实现本地桌面文件的按需检索,根据用户请求匹配对应文件
  • 依赖库自动处理大文件分片,避免内存占用过高问题
具体实现步骤(以Pyrogram为例)

1. 环境准备

  • 安装依赖库:pip install pyrogram tgcrypto
  • 获取API密钥:前往my.telegram.org注册个人应用,获取api_id和api_hash(注意不是Bot Token)

2. 核心代码实现

以下脚本实现监听用户私信请求,自动从本地桌面查找并发送大文件:

from pyrogram import Client, filters
import os

# 替换为你的API信息和会话名称
app = Client(
    "local_file_sender",
    api_id=123456,
    api_hash="your_api_hash_here"
)

# 替换为你的本地桌面路径(Windows用户可改为os.path.expanduser("%USERPROFILE%\\Desktop"))
DESKTOP_DIR = os.path.expanduser("~/Desktop")

@app.on_message(filters.text & filters.private)
async def send_requested_file(client, message):
    requested_filename = message.text.strip()
    full_file_path = os.path.join(DESKTOP_DIR, requested_filename)

    if not os.path.exists(full_file_path):
        await message.reply(f"桌面未找到文件:{requested_filename}")
        return

    file_size_mb = os.path.getsize(full_file_path) / 1024 / 1024
    await message.reply(f"开始发送:{requested_filename}(大小:{file_size_mb:.2f}MB)")

    # 自动处理大文件分片上传,无需额外配置
    await client.send_document(
        chat_id=message.chat.id,
        document=full_file_path,
        progress=upload_progress
    )

async def upload_progress(current, total):
    print(f"上传进度:{current/1024/1024:.2f}MB / {total/1024/1024:.2f}MB")

if __name__ == "__main__":
    app.run()

3. 关键细节说明

  • MTProto协议优势:相比Bot API,客户端协议支持最大4GB文件上传,分片逻辑由库自动处理,无需手动拆分文件
  • 本地文件读取:直接访问桌面路径,无需虚拟机或中转服务器,所有操作在本地完成
  • 按需触发:用户发送文件名即可触发文件查找与发送,无需提前上传文件到云端
注意事项
  • 首次运行脚本需输入个人Telegram账号的手机号与验证码,相当于登录自己的客户端账号
  • 确保桌面路径配置正确,避免文件查找失败
  • 大文件上传依赖稳定网络,分片上传失败会自动重试
  • 严格遵守Telegram服务条款,禁止传输违规内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 10:33:19