Add Telegram and Pushover as notification channels
Both send to one fixed address each (api.telegram.org, api.pushover.net), take part in routing rules and the channel count, have a Send test that shows the service's own refusal, and keep their tokens and keys encrypted and out of errors and the audit log. A Telegram message carries one button, and a Pushover message one link, to the page where an alert can be acknowledged, silenced or snoozed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9f366c37de
commit
31f4debb9a
22 files changed
+670
-37
No files matched your search
@@ -63,6 +63,85 @@ async function sendNtfy(title: string, message: string, actions?: NotifyActions
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Telegram and Pushover ──────────────────────────────────────────────────
|
||||
//
|
||||
// Both are hosted services with one fixed address each (so nothing a person types decides where a request goes, as it does for a webhook). The addresses are kept here, in one object, so a test can
|
||||
// point them at a pretend server. Neither says why it refused in its HTTP status alone: Telegram answers { ok: false, description }, Pushover { status: 0, errors: [...] }, and that is what is shown.
|
||||
|
||||
export const CHANNEL_ENDPOINTS = { telegram: "https://api.telegram.org", pushover: "https://api.pushover.net" };
|
||||
|
||||
const clip = (text: string, max: number) => (text.length <= max ? text : `${text.slice(0, max - 1)}…`);
|
||||
|
||||
/** Telegram allows 4096 characters in a message. */
|
||||
export const TELEGRAM_MAX = 4000;
|
||||
/** Pushover allows 1024 in a message, 250 in a title, 512 in a link. */
|
||||
export const PUSHOVER_MESSAGE_MAX = 1024;
|
||||
export const PUSHOVER_TITLE_MAX = 250;
|
||||
export const PUSHOVER_URL_MAX = 512;
|
||||
const BUTTON_LABEL = "Acknowledge, silence or snooze";
|
||||
|
||||
/** Sends one message through a Telegram bot; throws what Telegram says when it refuses. The bot's token is in the address, so it is never put in an error. */
|
||||
export async function telegramSend(cfg: { token: string; chatId: string; silent?: boolean }, text: string, actions?: NotifyActions | null): Promise<void> {
|
||||
const post = async (body: Record<string, unknown>) => {
|
||||
const res = await fetch(`${CHANNEL_ENDPOINTS.telegram}/bot${cfg.token}/sendMessage`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
||||
const json = (await res.json().catch(() => null)) as { ok?: boolean; description?: string } | null;
|
||||
return { ok: res.ok && json?.ok !== false, status: res.status, description: json?.description ?? null };
|
||||
};
|
||||
const base = { chat_id: cfg.chatId, disable_web_page_preview: true, ...(cfg.silent ? { disable_notification: true } : {}) };
|
||||
// A button that opens the page where the alert can be dealt with — plain text for what is said, so nothing in it needs escaping.
|
||||
let result = await post({ ...base, text: clip(text, TELEGRAM_MAX), ...(actions ? { reply_markup: { inline_keyboard: [[{ text: BUTTON_LABEL, url: actions.pageUrl }]] } } : {}) });
|
||||
// Telegram refuses a button whose address it cannot open (an address on a private network, say): say it in the text instead.
|
||||
if (!result.ok && actions && result.status === 400) result = await post({ ...base, text: clip(text + footerText(actions), TELEGRAM_MAX) });
|
||||
if (!result.ok) throw new Error(`Telegram: ${result.description ?? `HTTP ${result.status}`}`);
|
||||
}
|
||||
|
||||
/** Sends one message through Pushover; throws what Pushover says when it refuses. */
|
||||
export async function pushoverSend(cfg: { appToken: string; userKey: string; device?: string; priority?: number }, title: string, message: string, actions?: NotifyActions | null): Promise<void> {
|
||||
const priority = Number.isInteger(cfg.priority) ? Math.min(2, Math.max(-2, cfg.priority as number)) : 0;
|
||||
const link = actions && actions.pageUrl.length <= PUSHOVER_URL_MAX ? actions.pageUrl : null;
|
||||
const body: Record<string, string | number> = {
|
||||
token: cfg.appToken,
|
||||
user: cfg.userKey,
|
||||
title: clip(title, PUSHOVER_TITLE_MAX),
|
||||
// A link too long for Pushover goes in the text instead.
|
||||
message: clip(actions && !link ? message + footerText(actions) : message, PUSHOVER_MESSAGE_MAX),
|
||||
priority,
|
||||
};
|
||||
if (cfg.device?.trim()) body.device = cfg.device.trim();
|
||||
// An emergency message repeats until someone acknowledges it: Pushover wants to be told how often (every minute) and for how long (an hour).
|
||||
if (priority === 2) {
|
||||
body.retry = 60;
|
||||
body.expire = 3600;
|
||||
}
|
||||
if (link) {
|
||||
body.url = link;
|
||||
body.url_title = BUTTON_LABEL;
|
||||
}
|
||||
const res = await fetch(`${CHANNEL_ENDPOINTS.pushover}/1/messages.json`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
||||
const json = (await res.json().catch(() => null)) as { status?: number; errors?: string[] } | null;
|
||||
if (!res.ok || json?.status !== 1) throw new Error(`Pushover: ${json?.errors?.length ? json.errors.join(", ") : `HTTP ${res.status}`}`);
|
||||
}
|
||||
|
||||
async function sendTelegram(title: string, message: string, actions?: NotifyActions | null) {
|
||||
const { telegram } = await getSettings();
|
||||
if (!telegram.enabled || !telegram.token || !telegram.chatId) return;
|
||||
try {
|
||||
await telegramSend(telegram, `${title}\n\n${message}`, actions);
|
||||
} catch (err) {
|
||||
console.error("[notify]", err instanceof Error ? err.message : "Telegram failed");
|
||||
}
|
||||
}
|
||||
|
||||
async function sendPushover(title: string, message: string, actions?: NotifyActions | null) {
|
||||
const { pushover } = await getSettings();
|
||||
if (!pushover.enabled || !pushover.appToken || !pushover.userKey) return;
|
||||
try {
|
||||
await pushoverSend(pushover, title, message, actions);
|
||||
} catch (err) {
|
||||
console.error("[notify]", err instanceof Error ? err.message : "Pushover failed");
|
||||
}
|
||||
}
|
||||
|
||||
async function sendSmtp(title: string, message: string, actions?: NotifyActions | null) {
|
||||
const { smtp } = await getSettings();
|
||||
if (!smtp.enabled || !smtp.host || !smtp.to || !smtp.from) return;
|
||||
@@ -175,6 +254,8 @@ async function sendToChannels(title: string, message: string, audience: Audience
|
||||
await Promise.all([
|
||||
to("gotify") ? sendGotify(title, message, actions) : undefined,
|
||||
to("ntfy") ? sendNtfy(title, message, actions) : undefined,
|
||||
to("telegram") ? sendTelegram(title, message, actions) : undefined,
|
||||
to("pushover") ? sendPushover(title, message, actions) : undefined,
|
||||
to("smtp") ? sendSmtp(title, message, actions) : undefined,
|
||||
to("webhook") ? sendWebhook(title, message, actions) : undefined,
|
||||
to("webPush") ? sendWebPush(title, message, audience.pushIds, actions) : undefined,
|
||||
@@ -221,11 +302,13 @@ export async function notifyNow(title: string, message: string): Promise<void> {
|
||||
|
||||
/** How many channels are switched on and filled in enough to send, so a "send it now" can say when there is nowhere to send to. */
|
||||
export async function enabledChannelCount(): Promise<number> {
|
||||
const { gotify, ntfy, smtp, webhook, webPush } = await getSettings();
|
||||
const { gotify, ntfy, telegram, pushover, smtp, webhook, webPush } = await getSettings();
|
||||
return [
|
||||
webPush.enabled && (await subscriptionCount()) > 0,
|
||||
gotify.enabled && gotify.url && gotify.token,
|
||||
ntfy.enabled && ntfy.url && ntfy.topic,
|
||||
telegram.enabled && telegram.token && telegram.chatId,
|
||||
pushover.enabled && pushover.appToken && pushover.userKey,
|
||||
smtp.enabled && smtp.host && smtp.to && smtp.from,
|
||||
webhook.enabled && webhook.url,
|
||||
].filter(Boolean).length;
|
||||
@@ -298,6 +381,14 @@ export async function testNtfy(cfg: { url: string; topic: string; token?: string
|
||||
if (!res.ok) throw new Error(`ntfy returned ${res.status}: ${await res.text().catch(() => "")}`);
|
||||
}
|
||||
|
||||
export async function testTelegram(cfg: { token: string; chatId: string; silent?: boolean }): Promise<void> {
|
||||
await telegramSend(cfg, "Homelab Manager — Test\n\nTelegram notifications are working correctly.");
|
||||
}
|
||||
|
||||
export async function testPushover(cfg: { appToken: string; userKey: string; device?: string; priority?: number }): Promise<void> {
|
||||
await pushoverSend(cfg, "Homelab Manager — Test", "Pushover notifications are working correctly.");
|
||||
}
|
||||
|
||||
export async function testSmtp(cfg: {
|
||||
host: string;
|
||||
port?: number;
|
||||
|
||||
Reference in new issue
Block a user