brendmanager/src/telegram.js

100 lines
5.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Telegram Bot API: sendMessage. Токен и chat id — только из env.
// BRM-143: ключ — только отдельного бота Татьяны (BRAND_BOT_TOKEN). TELEGRAM_BOT_TOKEN — бот стажировок,
// PM запретил его подключать (вопрос #1686), поэтому приложение его не читает.
export function createTelegram({ token = process.env.BRAND_BOT_TOKEN, chatId = process.env.TELEGRAM_CHAT_ID, fetchImpl = fetch } = {}) {
return {
channel: "telegram",
secrets: () => [token].filter(Boolean),
connected: () => Boolean(token && chatId),
// BRM-78: чего не хватает для отправки — ключа бота или чата.
missing: () => (!token ? "key" : !chatId ? "chat" : null),
async call(method, payload) {
if (!token) return null; // отправка выключена, пока нет ключа бота
const r = await fetchImpl(`https://api.telegram.org/bot${token}/${method}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(payload) });
return (await r.json()).result ?? null;
},
// BRM-143: полный ответ Bot API ({ ok, result, description }) — чтобы назвать точную причину сбоя.
async api(method, payload = {}, file) {
if (!token) return { ok: false, error_code: 0, description: "no-token" };
let init;
if (file) { // файл материала: multipart, поле file.field
const fd = new FormData();
for (const [k, v] of Object.entries(payload)) fd.append(k, typeof v === "object" ? JSON.stringify(v) : String(v));
fd.append(file.field, new Blob([file.buf], { type: file.mime }), file.name);
init = { method: "POST", body: fd };
} else init = { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(payload) };
try { return await (await fetchImpl(`https://api.telegram.org/bot${token}/${method}`, init)).json(); }
catch (e) { return { ok: false, error_code: -1, description: String(e.message ?? e).split(token).join("***") }; }
},
async send(text) {
if (!token || !chatId) throw new Error("нет доступов к Telegram");
const r = await fetchImpl(`https://api.telegram.org/bot${token}/sendMessage`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ chat_id: chatId, text }),
});
const j = await r.json();
if (!j.ok) throw new Error(j.description ?? "ошибка Telegram");
return j.result;
},
};
}
// Мок с контрактом Bot API; заменить createTelegram() при появлении доступов Татьяны.
export function mockTelegram({ fail } = {}) {
const sent = [];
return {
channel: "telegram",
sent,
secrets: () => ["MOCK_TOKEN"],
connected: () => true,
calls: [],
async call(method, payload) { this.calls.push({ method, ...payload }); return { message_id: this.calls.length }; },
async send(text) {
if (fail) throw new Error(fail);
const m = { message_id: sent.length + 1, text };
sent.push(m);
return m;
},
};
}
// BRM-143: мок Bot API с тем же контрактом, что api() настоящего бота: getMe, getChat, getChatMember,
// sendMessage, sendPhoto; ошибки — { ok: false, error_code, description }. Заменяется createTelegram().
export function mockTelegramApi({ token = "MOCK_TELEGRAM_TOKEN", me = { id: 900, is_bot: true, username: "mock_brm_bot" }, chats = {}, members = {}, failSend, webhook = { url: "https://mock-brm.example/api/telegram/webhook", allowed_updates: [] } } = {}) {
const calls = [];
const posts = {};
const err = (code, description) => ({ ok: false, error_code: code, description });
return {
channel: "telegram", calls, posts, chats, members,
secrets: () => [token].filter(Boolean),
connected: () => Boolean(token),
missing: () => (token ? null : "key"),
async call(method, payload) { const r = await this.api(method, payload); return r.ok ? r.result : null; },
async send(text) { throw new Error("mockTelegramApi: send без чата не используется"); },
async api(method, payload = {}, file) {
calls.push({ method, ...payload, ...(file ? { file: file.name } : {}) });
if (!token) return err(0, "no-token");
if (token.startsWith("bad-")) return err(401, "Unauthorized"); // мок неверного ключа
if (method === "getMe") return { ok: true, result: me };
if (method === "getWebhookInfo") return { ok: true, result: { pending_update_count: 0, ...webhook } };
if (method === "setWebhook") { Object.assign(webhook, { url: payload.url, allowed_updates: payload.allowed_updates ?? [] }); return { ok: true, result: true }; }
const id = String(payload.chat_id);
if (method === "getChat") return chats[id] ? { ok: true, result: chats[id] } : err(400, "Bad Request: chat not found");
if (method === "getChatMember") {
if (!chats[id]) return err(400, "Bad Request: chat not found");
return { ok: true, result: members[id] ?? { status: "left", user: me } };
}
if (method === "sendMessage" || method === "sendPhoto") {
if (failSend) return err(400, failSend);
posts[id] ??= [];
const m = { message_id: posts[id].length + 1, chat: { id: Number(id) }, date: 0, text: payload.text ?? payload.caption ?? "", reply_markup: payload.reply_markup };
posts[id].push(m);
return { ok: true, result: m };
}
if (method === "answerCallbackQuery") return { ok: true, result: true };
return err(404, "Not Found: method " + method);
},
};
}