From 91986d1d51c2411f144696fa016a0ec50507c872 Mon Sep 17 00:00:00 2001 From: MythEclipse Date: Mon, 18 May 2026 08:18:55 +0700 Subject: [PATCH] fix: upload binary files to Telegram with source payload --- src/utils/telegram.ts | 14 +++++++------- test/telegram.test.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/src/utils/telegram.ts b/src/utils/telegram.ts index f1fec49..3380f30 100644 --- a/src/utils/telegram.ts +++ b/src/utils/telegram.ts @@ -24,17 +24,17 @@ export const forwardToStorage = async ( ): Promise => { try { const caption = forceDocument ? `📁 ${fileName}` : fileName; - const input: any = forceDocument - ? { document: fileChunk, caption } - : { photo: [fileChunk], caption }; - - const result = await bot.telegram.sendPhoto(config.storageChatId, input); + const filePayload = { source: fileChunk, filename: fileName }; + const result: any = forceDocument + ? await bot.telegram.sendDocument(config.storageChatId, filePayload, { caption }) + : await bot.telegram.sendPhoto(config.storageChatId, filePayload, { caption }); + const uploadedFile = forceDocument ? result.document : result.photo?.slice(-1)[0]; logger.info('File forwarded to storage', { fileName, message: result.message_id }); return { - telegramFileId: result.photo?.slice(-1)[0]?.file_id || '', - telegramFileUniqueId: result.photo?.slice(-1)[0]?.file_unique_id || '', + telegramFileId: uploadedFile?.file_id || '', + telegramFileUniqueId: uploadedFile?.file_unique_id || '', storageMessageId: result.message_id, }; } catch (error: any) { diff --git a/test/telegram.test.ts b/test/telegram.test.ts index f6d3e8f..48b4680 100644 --- a/test/telegram.test.ts +++ b/test/telegram.test.ts @@ -18,6 +18,15 @@ mock.module('telegraf', () => { ], }), ), + sendDocument: mock(() => + Promise.resolve({ + message_id: 54321, + document: { + file_id: 'document_id', + file_unique_id: 'document_unique_id', + }, + }), + ), }; } }, @@ -71,6 +80,25 @@ describe('Telegram API Utilities', () => { }); }); + it('should forward documents with source and filename payload', async () => { + const bot = getBot(); + const chunk = Buffer.from('fake document data'); + const fileName = 'document.pdf'; + + const result = await forwardToStorage(chunk, fileName, true); + + expect(bot.telegram.sendDocument).toHaveBeenCalledWith( + -1003996572954, + { source: chunk, filename: fileName }, + { caption: `📁 ${fileName}` }, + ); + expect(result).toEqual({ + telegramFileId: 'document_id', + telegramFileUniqueId: 'document_unique_id', + storageMessageId: 54321, + }); + }); + it('should handle error when forwarding fails', async () => { const bot = getBot(); bot.telegram.sendPhoto = mock(() => Promise.reject(new Error('Telegram send failed')));