import { readFile } from "node:fs/promises"; import { basename } from "node:path"; // Тонкий клиент Telegram Bot API. fetchImpl подменяется в тестах. export class Telegram { constructor(token, fetchImpl = fetch) { this.base = `https://api.telegram.org/bot${token}`; this.fetch = fetchImpl; } async call(method, params = {}) { const res = await this.fetch(`${this.base}/${method}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(params), }); const body = await res.json(); if (!body.ok) throw new Error(`Telegram ${method}: ${body.description}`); return body.result; } sendMessage(chatId, text, extra = {}) { return this.call("sendMessage", { chat_id: chatId, text, ...extra }); } answerCallbackQuery(id, text) { return this.call("answerCallbackQuery", { callback_query_id: id, text }); } async sendDocument(chatId, path, caption) { const form = new FormData(); form.set("chat_id", String(chatId)); if (caption) form.set("caption", caption); form.set("document", new Blob([await readFile(path)]), basename(path)); const res = await this.fetch(`${this.base}/sendDocument`, { method: "POST", body: form }); const body = await res.json(); if (!body.ok) throw new Error(`Telegram sendDocument: ${body.description}`); return body.result; } getUpdates(offset, timeout = 30) { return this.call("getUpdates", { offset, timeout, allowed_updates: ["message", "callback_query"] }); } }