Personal Telegram developer console for GitHub

feat: download bounded UTF-8 Telegram documents

davoodmehraban89 committed Oct 3, 2026 at 14:34 UTC c1a4695ee93a5af22036be87e8b579b67ae87abe
1 file changed +38 -1
src/telegram.js
+38 -1
@@ -2,6 +2,7 @@ export class TelegramClient {
2 constructor(botToken, options = {}) {
3 this.botToken = botToken;
4 this.baseUrl = options.baseUrl || `https://api.telegram.org/bot${botToken}`;
5 + this.fileBaseUrl = options.fileBaseUrl || `https://api.telegram.org/file/bot${botToken}`;
6 this.fetchFn = options.fetch || ((...args) => fetch(...args));
7 }
8
@@ -41,6 +42,42 @@ export class TelegramClient {
42 return body;
43 }
44
45 + async downloadTextFile(fileId, { maxBytes = 12000 } = {}) {
46 + if (!this.botToken) throw new Error('TELEGRAM_BOT_TOKEN is not configured');
47 + const id = String(fileId || '');
48 + if (!id) throw new Error('Telegram file_id is required');
49 + const limit = Number(maxBytes);
50 + if (!Number.isFinite(limit) || limit <= 0) throw new Error('Telegram file size limit is invalid');
51 +
52 + const metadata = await this.callApi('getFile', { file_id: id });
53 + const filePath = String(metadata?.result?.file_path || '');
54 + if (!filePath) throw new Error('Telegram getFile did not return file_path');
55 + const announcedSize = Number(metadata?.result?.file_size);
56 + if (Number.isFinite(announcedSize) && announcedSize > limit) {
57 + throw new Error(`Telegram file exceeds ${limit} byte size limit`);
58 + }
59 +
60 + const safePath = filePath.split('/').map(segment => encodeURIComponent(segment)).join('/');
61 + let response;
62 + try {
63 + response = await this.fetchFn(`${this.fileBaseUrl}/${safePath}`, { method: 'GET' });
64 + } catch (err) {
65 + throw new Error(`Telegram file download network failure: ${err.message}`);
66 + }
67 + if (!response.ok) throw new Error(`Telegram file download failed: ${response.status}`);
68 +
69 + const bytes = await response.arrayBuffer();
70 + if (bytes.byteLength > limit) throw new Error(`Telegram file exceeds ${limit} byte size limit`);
71 +
72 + let text;
73 + try {
74 + text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
75 + } catch {
76 + throw new Error('Telegram file is not valid UTF-8 text');
77 + }
78 + return { text, byteLength: bytes.byteLength, filePath };
79 + }
80 +
81 async sendMessage(chatId, text, replyMarkup = null, parseMode = 'HTML') {
82 const payload = {
83 chat_id: chatId,
@@ -68,4 +105,4 @@ export class TelegramClient {
105 if (showAlert) payload.show_alert = showAlert;
106 return this.callApi('answerCallbackQuery', payload);
107 }
71 -}
108 +}
\ No newline at end of file