44 lines
1.8 KiB
JavaScript
44 lines
1.8 KiB
JavaScript
// Telegram Bot API: sendMessage. Токен и chat id — только из env.
|
||
export function createTelegram({ token = process.env.TELEGRAM_BOT_TOKEN, chatId = process.env.TELEGRAM_CHAT_ID, fetchImpl = fetch } = {}) {
|
||
return {
|
||
channel: "telegram",
|
||
secrets: () => [token].filter(Boolean),
|
||
connected: () => Boolean(token && chatId),
|
||
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;
|
||
},
|
||
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;
|
||
},
|
||
};
|
||
}
|