From 08fe1ad4dcd5e573446febad9ef41012ab3d669b Mon Sep 17 00:00:00 2001 From: Kyle Fang Date: Tue, 6 Jun 2023 09:52:30 +0800 Subject: [PATCH] feat: add ability to upload file --- src/index.ts | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/src/index.ts b/src/index.ts index 0fc1304..903a3d1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -44,6 +44,20 @@ router.post("/t/:webhookId/raw", async (context) => { context.res.body = { ok: true }; }); +router.post("/t/:webhookId/file", async (context) => { + const chat = await TG_GROUPS.get( + `webhook-chat:${context.req.params.webhookId}` + ); + if (chat == null) { + context.res.body = { ok: false, error: "chatId not found" }; + context.res.status = 404; + return; + } + const result = await context.req.body.json(); + await uploadFileToChat(JSON.parse(chat), result.fileName, result.content); + context.res.body = { ok: true }; +}); + router.post("/t/:webhookId", async (context) => { const chat = await TG_GROUPS.get( `webhook-chat:${context.req.params.webhookId}` @@ -139,3 +153,39 @@ async function sendToChat( }), }); } + +export async function uploadFileToChat( + chat: { + chatId: number; + messageThreadId?: number; + }, + fileName: string, + content: string +) { + await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendDocument`, { + method: "POST", + headers: { + "Content-Type": "multipart/form-data; boundary=WebAppBoundary", + }, + body: `--WebAppBoundary +Content-Disposition: form-data; name="chat_id" +Content-Type: text/plain + +${chat.chatId} +${ + chat.messageThreadId != null + ? `--WebAppBoundary +Content-Disposition: form-data; name="message_thread_id" +Content-Type: text/plain + +${chat.messageThreadId} +` + : "" +}--WebAppBoundary +Content-Disposition: form-data; name="document"; filename="${fileName}" +Content-Type: application/octet-stream + +${content} +--WebAppBoundary--`.replace(/\n/g, "\r\n"), + }).then((a) => a.json()); +}