使用MTProto/js调用upload.getFile遇FILE_REFERENCE_EXPIRED错误求助
解决MTProto调用upload.getFile触发FILE_REFERENCE_EXPIRED异常的方案
问题场景
在JavaScript环境下使用MTProto客户端调用upload.getFile方法,传入inputPhotoFileLocation获取消息中的图片数据时,触发FILE_REFERENCE_EXPIRED异常。原调用代码如下:
await TelegramAPI.call("upload.getFile", { location: { _: "inputPhotoFileLocation", id: Image[0].media.photo.id, access_hash: Image[0].media.photo.access_hash, file_reference: Image[0].media.photo.file_reference, thumb_size: Image[0].media.photo.sizes.find( (size: any) => size._ == "photoSizeProgressive" ).type, }, offset: 0, limit: 1024 * 1024, })
核心原因与解决方法
FILE_REFERENCE_EXPIRED是Telegram的机制:file_reference字段会定期失效,必须获取最新值才能正常调用接口。具体解决步骤如下:
1. 重新拉取最新的消息实体
调用messages.getMessages或messages.getHistory接口,传入目标消息ID,从返回的最新消息数据中提取photo.file_reference,替换原过期值。
2. 校验参数合理性
- 确保
thumb_size对应的类型是Telegram支持的有效值(如"s"、"m"、"w"等),若找不到photoSizeProgressive类型的尺寸,设置默认值避免报错。 - 确认
access_hash和id与最新消息实体中的值一致,避免参数不匹配。
3. 优化后的示例代码
// 第一步:重新获取目标消息的最新数据 const latestMsgResp = await TelegramAPI.call("messages.getMessages", { id: [Image[0].id] // 传入需要更新的消息ID }); const latestPhoto = latestMsgResp.messages[0].media.photo; // 第二步:使用最新参数调用upload.getFile await TelegramAPI.call("upload.getFile", { location: { _: "inputPhotoFileLocation", id: latestPhoto.id, access_hash: latestPhoto.access_hash, file_reference: latestPhoto.file_reference, // 用最新的file_reference thumb_size: latestPhoto.sizes.find(size => size._ === "photoSizeProgressive")?.type || "s" }, offset: 0, limit: 1024 * 1024, });
额外注意事项
- 不要长期缓存
file_reference,每次获取文件前建议重新拉取消息数据更新该字段。 - 若批量处理图片,建议先批量更新所有目标消息的
file_reference,再统一调用upload.getFile。 - 可添加最多2-3次的重试逻辑,规避临时网络波动导致的异常。
内容的提问来源于stack exchange,提问作者sagarbhusal01
相关产品推荐
相关产品推荐

