export interface TelegramUpdateUser { id: number; username?: string; first_name: string; last_name?: string; } export interface TelegramUpdateMessage { message_id: number; text?: string; from?: TelegramUpdateUser; chat: { id: number; }; } export interface TelegramUpdate { update_id: number; message?: TelegramUpdateMessage; } export interface TelegramBotTransport { getUpdates(input: { offset?: number; timeoutSeconds: number; }): Promise; sendMessage(input: { chatId: number; text: string; }): Promise; } export function createTelegramBotApiTransport(botToken: string): TelegramBotTransport { const baseUrl = `https://api.telegram.org/bot${botToken}`; return { async getUpdates({ offset, timeoutSeconds }) { const response = await fetch(`${baseUrl}/getUpdates`, { method: "POST", headers: { "content-type": "application/json", }, body: JSON.stringify({ timeout: timeoutSeconds, ...(offset !== undefined ? { offset } : {}), }), }); const payload = (await response.json()) as { ok: boolean; result?: TelegramUpdate[]; description?: string; }; if (!response.ok || !payload.ok || !payload.result) { throw new Error( payload.description ?? `Telegram getUpdates failed with status ${response.status}.`, ); } return payload.result; }, async sendMessage({ chatId, text }) { const response = await fetch(`${baseUrl}/sendMessage`, { method: "POST", headers: { "content-type": "application/json", }, body: JSON.stringify({ chat_id: chatId, text, }), }); const payload = (await response.json()) as { ok: boolean; description?: string; }; if (!response.ok || !payload.ok) { throw new Error( payload.description ?? `Telegram sendMessage failed with status ${response.status}.`, ); } }, }; }