// Minimal Telegram Bot API client. The base URL is configurable so tests can point it at // mock-telegram (packages/testkit). export interface TgUser { id: number; username?: string; first_name?: string; } export interface TgMessage { message_id: number; chat: { id: number; type: string; title?: string }; from?: TgUser; text?: string; /** PEP-62: a group became a supergroup (new chat id). */ migrate_to_chat_id?: number; reply_to_message?: TgMessage; /** PEP-45: voice notes and audio files become stories after transcription. */ voice?: TgFileRef; audio?: TgFileRef; /** PEP-143: a photo comes as several sizes (the last is the largest); its text is the caption. */ photo?: TgFileRef[]; /** An image sent «as a file». */ document?: TgFileRef & { file_name?: string }; caption?: string; /** Messages of one album share it. */ media_group_id?: string; } export interface TgFileRef { file_id: string; duration?: number; mime_type?: string; file_size?: number; } export interface TgCallbackQuery { id: string; from: TgUser; message?: TgMessage; data?: string; } export interface TgUpdate { update_id: number; message?: TgMessage; callback_query?: TgCallbackQuery; } export interface InlineButton { text: string; callback_data?: string; url?: string; } export class TelegramError extends Error { readonly method: string; readonly code: number; readonly description: string; readonly retryAfter?: number; constructor(method: string, code: number, description: string, retryAfter?: number) { super(`${method}: ${code} ${description}`); this.method = method; this.code = code; this.description = description; this.retryAfter = retryAfter; } } export class TelegramApi { private readonly token: string; private readonly baseUrl: string; constructor(token: string, baseUrl = "https://api.telegram.org") { this.token = token; this.baseUrl = baseUrl; } async call(method: string, params: Record = {}, timeoutMs = 15_000): Promise { let res: Response; try { res = await fetch(`${this.baseUrl}/bot${this.token}/${method}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(params), signal: AbortSignal.timeout(timeoutMs), }); } catch (e) { throw new TelegramError(method, 0, (e as Error).message); } const body = (await res.json().catch(() => ({}))) as { ok?: boolean; result?: T; description?: string; error_code?: number; parameters?: { retry_after?: number }; }; if (!body.ok) { throw new TelegramError(method, body.error_code ?? res.status, body.description ?? res.statusText, body.parameters?.retry_after); } return body.result as T; } getMe() { return this.call("getMe"); } getUpdates(offset: number, timeoutSec: number, signal?: AbortSignal) { return this.call( "getUpdates", { offset, timeout: timeoutSec, allowed_updates: ["message", "callback_query"] }, (timeoutSec + 10) * 1000, ).catch((e) => { if (signal?.aborted) return []; throw e; }); } answerCallbackQuery(id: string, text?: string) { return this.call("answerCallbackQuery", { callback_query_id: id, text }); } getFile(fileId: string) { return this.call<{ file_id: string; file_path?: string; file_size?: number }>("getFile", { file_id: fileId }); } /** Bytes of a file from getFile (Bot API: GET /file/bot/, up to 20 MB). */ async downloadFile(filePath: string): Promise { const res = await fetch(`${this.baseUrl}/file/bot${this.token}/${filePath}`, { signal: AbortSignal.timeout(60_000) }); if (!res.ok) throw new TelegramError("downloadFile", res.status, res.statusText); return Buffer.from(await res.arrayBuffer()); } /** PEP-143: a photo uploaded from memory (multipart/form-data, as the Bot API wants for new files). */ async sendPhoto(chatId: number, photo: { data: Uint8Array; filename: string; mime: string }, extra: Record = {}): Promise { const form = new FormData(); form.set("chat_id", String(chatId)); for (const [k, v] of Object.entries(extra)) if (v != null && k !== "chat_id") form.set(k, typeof v === "string" ? v : JSON.stringify(v)); form.set("photo", new Blob([photo.data as BlobPart], { type: photo.mime }), photo.filename); let res: Response; try { res = await fetch(`${this.baseUrl}/bot${this.token}/sendPhoto`, { method: "POST", body: form, signal: AbortSignal.timeout(60_000) }); } catch (e) { throw new TelegramError("sendPhoto", 0, (e as Error).message); } const body = (await res.json().catch(() => ({}))) as { ok?: boolean; result?: TgMessage; description?: string; error_code?: number; parameters?: { retry_after?: number } }; if (!body.ok) throw new TelegramError("sendPhoto", body.error_code ?? res.status, body.description ?? res.statusText, body.parameters?.retry_after); return body.result as TgMessage; } sendMessage(chatId: number, text: string, extra: Record = {}) { return this.call("sendMessage", { chat_id: chatId, text, parse_mode: "HTML", ...extra }); } }