/** Минимальный клиент Telegram Bot API. Токен не попадает в ошибки и логи. */ export interface TelegramClient { sendMessage(chatId: number, text: string): Promise; setWebhook(url: string, secretToken: string): Promise; } export class TelegramError extends Error { constructor(method: string, status: number) { super(`telegram ${method} failed: ${status}`); this.name = "TelegramError"; } } export const TELEGRAM_TEXT_LIMIT = 4096; export interface TelegramOptions { token: string; fetch?: typeof fetch; timeoutMs?: number; } export function createTelegramClient(opts: TelegramOptions): TelegramClient { const doFetch = opts.fetch ?? fetch; async function call(method: string, payload: Record): Promise { let res: Response; try { res = await doFetch(`https://api.telegram.org/bot${opts.token}/${method}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(payload), signal: AbortSignal.timeout(opts.timeoutMs ?? 10_000), }); } catch { throw new TelegramError(method, 0); } if (!res.ok) throw new TelegramError(method, res.status); } return { // Без parse_mode: текст выводится как есть, разметка не интерпретируется. sendMessage: (chatId, text) => call("sendMessage", { chat_id: chatId, text: text.slice(0, TELEGRAM_TEXT_LIMIT) }), setWebhook: (url, secretToken) => call("setWebhook", { url, secret_token: secretToken, allowed_updates: ["message"] }), }; }