如何用Gramjs与Telegram API下载媒体文件?参数问题咨询
使用GramJS和Telegram API下载媒体文件的问题解决
问题1:bigint类型不兼容BigInteger的错误处理
GramJS依赖big-integer库的BigInteger类型,而非JavaScript原生bigint,需按以下步骤处理:
- 安装依赖:
npm install big-integer - 导入并转换类型:
直接将字符串或原生bigint传入import BigInteger from 'big-integer'; // 转换示例 const targetId = BigInteger("-4156887774564"); const targetOffset = BigInteger(0);BigInteger构造函数,即可解决TS类型错误。
问题2:参数的正确设置(结合你提供的聊天记录media数据)
注意:你提供的媒体是MessageMediaDocument类型(视频文件),应使用InputDocumentFileLocation而非示例中的InputFileLocation,后者多用于照片类媒体。以下是对应参数的填写方式:
1. location参数(InputDocumentFileLocation)
从media.document字段中提取对应值:
id:取media.document.id,转换为BigInteger:BigInteger("5381878726680130068")accessHash:取media.document.accessHash,转换为BigInteger:BigInteger("-5928175209338587382")fileReference:将media.document.fileReference.data转为Buffer:Buffer.from([2, 82, 208, ...])(直接使用你拿到的数组即可)thumbSize:下载原文件填空字符串"";下载缩略图则填对应尺寸标识(比如你media里的"m")
2. 其他参数
offset:初始下载填BigInteger(0),续传时填已下载的字节数(如已下载1MB则填BigInteger(1048576))limit:单次请求下载的字节数,建议设为1048576(1MB),避免因请求过大失败precise:保持true,确保偏移量精确cdnSupported:保持true,允许使用CDN加速下载
完整示例代码
import BigInteger from 'big-integer'; import { Api, TelegramClient } from 'telegram'; // 假设已完成client初始化 const downloadMedia = async (media: any) => { const document = media.document; const data = await client.invoke( new Api.upload.GetFile({ location: new Api.InputDocumentFileLocation({ id: BigInteger(document.id), accessHash: BigInteger(document.accessHash), fileReference: Buffer.from(document.fileReference.data), thumbSize: "", // 下载原文件 }), offset: BigInteger(0), // 从文件开头下载 limit: 1048576, // 每次下载1MB precise: true, cdnSupported: true, }) ); // 处理返回的文件数据,比如写入本地文件 // data为upload.File类型,包含bytes字段 };
补充说明
- 若为照片类媒体,才需要使用
InputFileLocation,此时volumeId、localId、secret从照片的Photo对象的尺寸字段中提取(如photo.sizes[0].location) - 大文件需分多次请求
upload.GetFile,每次更新offset为已下载字节数,直到返回的data.bytes长度小于limit,表示文件下载完成
内容的提问来源于stack exchange,提问作者user11553898
相关产品推荐
相关产品推荐

