拓冰建站拓冰建站
首页 / 资讯中心 / 正文

mtproto-core 高级实战:文件上传、媒体消息发送与下载完整教程

mtproto-core 高级实战文件上传、媒体消息发送与下载完整教程【免费下载链接】mtproto-coreTelegram API JS (MTProto) client library for Node.js and browser项目地址: https://gitcode.com/gh_mirrors/mt/mtproto-coremtproto-core 是一款基于 Telegram API JS (MTProto) 协议的客户端库同时支持 Node.js 与浏览器环境。很多初学者学会了发送文本消息却卡在了媒体能力上如何在 mtproto-core 中完成文件上传如何发送图片、视频和文档又如何把文件下载回来本文用最少的代码带你走通「分片上传 → 构造 inputFile → sendMedia 发送 → upload.getFile 下载」的完整链路一份真正可落地的 mtproto-core 文件上传教程。为什么选 mtproto-core 处理媒体消息在动手之前先了解这个库的几个关键特性API 层新内置 158 层的 API scheme支持messages.sendMedia、upload.getFile等最新方法全自动加密MTProto 的 DH 密钥协商、AES-IGE 加密、消息序号全部封装在内部你只需关注业务双端通用Node.js 走 TCP浏览器走 WebSocket同一套调用代码所有 API 方法都通过client.call(method, params)调用入口在 src/index.js。而 RPC 的加密、序列化、ack 处理都在 src/rpc/index.js 中完成看不懂也不影响使用。准备工作安装与初始化客户端一键安装步骤npm install mtproto/core # 或从仓库克隆 git clone https://gitcode.com/gh_mirrors/mt/mtproto-core最快初始化方法在 Node.js 环境直接引入即可入口文件是 envs/node/index.jsconst MTProto require(mtproto/core); const client new MTProto({ api_id: 你的 api_id, // 在 my.telegram.org 申请 api_hash: 你的 api_hash, });浏览器环境则引入 envs/browser/index.js它会自动使用window.crypto和 WebSocket。别忘了先完成用户授权auth.sendCode→auth.signIn本仓库的 docs/authentication.md 有指引。文件上传三步走分片、构造、发送Telegram 的文件上传流程是固定的先把文件切成小块逐片上传得到file_id再把它包装成inputFile最后在发送媒体消息时引用。mtproto-core 全部通过client.call完成逻辑清晰。第一步分片上传upload.saveFilePart每个分片建议 512KB小于 10MB 的文件用upload.saveFilePart更大的文件用upload.saveBigFilePartconst CHUNK_SIZE 512 * 1024; async function uploadFile(buffer, fileName) { const fileId Math.floor(Math.random() * 2 ** 53); // 随机 64 位 ID const parts Math.ceil(buffer.length / CHUNK_SIZE); const method buffer.length 10 * 1024 * 1024 ? upload.saveBigFilePart : upload.saveFilePart; for (let i 0; i parts; i) { await client.call(method, { file_id: fileId, file_part: i, file_total_parts: parts, bytes: buffer.slice(i * CHUNK_SIZE, (i 1) * CHUNK_SIZE), }); console.log(上传进度 ${i 1}/${parts}); } return { _: buffer.length 10 * 1024 * 1024 ? inputFileBig : inputFile, id: fileId, parts, name: fileName, }; } 建议在循环里维护进度并做错误重试upload.saveFilePart返回boolTrue即表示该分片上传成功。第二步构造媒体描述inputMediaUploaded*拿到inputFile后根据类型选择构造器图片 →inputMediaUploadedPhoto文档/视频/音频 →inputMediaUploadedDocument需附带mime_type和文件属性这些构造器都定义在 scheme/api.json 中158 层 API 全量可用。第三步发送媒体消息messages.sendMedia// 发送图片 await client.call(messages.sendMedia, { peer: { _: inputPeerUser, user_id, access_hash }, media: { _: inputMediaUploadedPhoto, file: uploadedFile, // 第一步的返回值 }, message: 这张照片不错吧 , random_id: Date.now(), }); // 发送 PDF 文档 await client.call(messages.sendMedia, { peer: { _: inputPeerUser, user_id, access_hash }, media: { _: inputMediaUploadedDocument, file: uploadedFile, mime_type: application/pdf, attributes: [{ _: documentAttributeFilename, file_name: report.pdf }], }, message: 月度报告 , random_id: Date.now(), });注意peer里的user_id与access_hash必须来自contacts.resolveUsername或messages.getDialogs的返回结果不能凭空构造。进阶技巧群发与多文件消息批量发送messages.sendMultiMedia可以在一条消息里携带最多 10 个媒体直播相册、图集场景非常实用先传后发messages.uploadMedia可先把文件上传成photo/document之后反复用inputMediaPhoto/inputMediaDocument引用避免重复上传适合做素材库上传进度分片循环本身就是天然进度条结合sendMessageUploadPhotoAction等动作状态还能在聊天界面显示「正在上传」下载文件upload.getFile 实战下载本质是反方向分片拉取。先通过messages.getDocumentByHash或消息体拿到文件的id、access_hash、file_reference再循环调用upload.getFileasync function downloadFile(location, totalSize) { const chunks []; let offset 0; while (offset totalSize) { const res await client.call(upload.getFile, { location: { _: inputFileLocation, id: location.id, access_hash: location.access_hash, file_reference: location.file_reference, }, offset, limit: 1024 * 1024, // 每次 1MB }); chunks.push(res.bytes); offset res.bytes.length; } return Buffer.concat(chunks); }大文件可能触发 CDN 重定向返回upload.fileCdnRedirect此时需改用upload.getCdnFile系列方法处理逻辑同样在 scheme/api.json 中可查。常见错误与排查报错类型原因解决办法FILE_PART_X_MISSING分片未按顺序上传严格按file_part递增上传FILE_PARTS_INVALID分片大小或数量不对统一 512KB保持file_total_parts正确PEER_ID_INVALIDpeer 缺少 access_hash先解析用户名再构造 peerFILE_REFERENCE_EXPIREDfile_reference 过期重新获取消息体再下载更多错误语义可参考 docs/handling-common-errors.md。源码速查这些文件值得一看src/index.js — MTProto 主类call()方法入口src/rpc/index.js — RPC 调用、加解密与消息确认src/tl/serializer/index.js — TL 序列化src/tl/deserializer/index.js — TL 反序列化src/storage/index.js — 会话与 authKey 存储envs/node/index.js 与 envs/browser/index.js — 双端环境适配结语mtproto-core 把 Telegram 最复杂的 MTProto 协议细节全部封装掉文件上传与媒体消息发送只需要「分片 → inputFile → sendMedia」三步即可完成。希望这份 mtproto-core 高级实战教程能帮你快速搞定图片、文档的上传与下载。动手跑通一个发送图片的小 demo比读十遍文档更有效快去试试吧【免费下载链接】mtproto-coreTelegram API JS (MTProto) client library for Node.js and browser项目地址: https://gitcode.com/gh_mirrors/mt/mtproto-core创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门