UNPKG

@jackdbd/notifications

Version:

Functions used to send notifications to various channels (Telegram, email, etc)

77 lines 2.59 kB
import { debuglog } from 'node:util'; import phin from 'phin'; const debug = debuglog('notifications/telegram'); /** * https://core.telegram.org/bots/api#making-requests */ const errorMessageFromTelegramApi = ({ chat_id, description, error_code }) => { switch (error_code) { case 400: { return description; } case 404: { return `Telegram chat id ${chat_id} not found`; } default: { return description; } } }; /** * Send a text message to a Telegram chat, using the Telegram API. * * https://core.telegram.org/bots/api#sendmessage */ export const send = async ({ chat_id, text, token }, options) => { if (!chat_id) { throw new Error('chat_id not set'); } if (!token) { throw new Error('token not set'); } debug(`send Telegram message to chat id ${chat_id}`); const data = { chat_id, disable_notification: options?.disable_notification || true, disable_web_page_preview: options?.disable_web_page_preview || false, parse_mode: options?.parse_mode || 'HTML', text }; try { const res = await phin({ data, headers: { 'Content-Type': 'application/json' }, method: 'POST', parse: 'json', url: `https://api.telegram.org/bot${token}/sendMessage` }); if (!res.body.ok) { const b = res.body; debug(`Telegram message was NOT delivered to chat id ${chat_id}. Original Telegram API response: %O`, b); return { delivered: false, message: errorMessageFromTelegramApi({ chat_id, description: b.description, error_code: b.error_code }) }; } else { const b = res.body; debug(`Telegram message delivered to chat id ${chat_id}. Original Telegram API response: %O`, b); const r = b.result; const delivered_at = new Date(r.date * 1000).toISOString(); return { delivered: true, delivered_at, message: `message id ${r.message_id} delivered to chat id ${r.chat.id} (username ${r.chat.username}) by bot ${r.from.first_name}` }; } } catch (err) { debug(`Telegram API could not respond. Original error: %O`, err); throw new Error(`Telegram API could not respond: ${err.message}`); } }; //# sourceMappingURL=telegram.js.map