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

如何通过GramJS使用file_id/file_unique_id发送Telegram媒体(避免重传)

解决GramJS通过file_id发送已有媒体无需重新上传的问题

直接将file_id字符串传给sendFile的file参数会被GramJS当作本地文件路径处理,必须通过Telegram API定义的输入媒体对象来指定云端已存在的媒体,具体实现步骤如下:

1. 解析file_id获取媒体参数

GramJS提供了decodeFileId工具函数,可将file_id解码为构造输入对象所需的核心参数:

import { decodeFileId } from '@gramjs/telegram'

const mediaId = 'AgACAgIAAx0CT3U93QAAAAAAAAAAAAAA-AAAAAAAAAAAAAA-AAAAAAAAAA'
const decoded = decodeFileId(mediaId)

2. 构造对应类型的InputMedia对象

根据媒体实际类型(照片/文档/音频等),选择匹配的InputMedia和Input类:

示例1:发送照片(file_id对应照片类型)

const inputMedia = new Api.InputMediaPhoto({
  id: new Api.InputPhoto({
    id: BigInt(decoded.id),
    accessHash: BigInt(decoded.accessHash),
    fileReference: decoded.fileReference
  })
})

示例2:发送文档(file_id对应视频、音频、普通文件等)

const inputMedia = new Api.InputMediaDocument({
  id: new Api.InputDocument({
    id: BigInt(decoded.id),
    accessHash: BigInt(decoded.accessHash),
    fileReference: decoded.fileReference
  })
})

3. 调用sendFile发送媒体

将构造好的inputMedia传入file参数即可触发云端媒体复用,无需重新上传:

await userbot.sendFile(-100123123123, {
  file: inputMedia,
  message: "Hello there!",
  randomId: BigInt("-4156887774564")
})

补充:使用file_unique_id发送媒体

file_unique_id无法直接构造输入对象,需先通过getMediaByUniqueId获取媒体元数据,再生成对应InputMedia:

const fileUniqueId = '你的file_unique_id'
const media = await userbot.getMediaByUniqueId(fileUniqueId)

// 根据媒体类型自动匹配InputMedia
const inputMedia = media instanceof Api.Photo 
  ? new Api.InputMediaPhoto({ id: media }) 
  : new Api.InputMediaDocument({ id: media })

await userbot.sendFile(-100123123123, {
  file: inputMedia,
  message: "Hello there!",
  randomId: BigInt("-4156887774564")
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:46:08