Skip to main content

rustango_cms/notify/channels/
telegram.rs

1//! Telegram — Bot API `sendMessage`.
2
3use crate::notify::{ConfigField, DeliverError, Delivery, Notification, NotificationChannel};
4use serde_json::json;
5
6/// Sends via a bot to one chat.
7///
8/// Unlike the webhook channels the destination is two parts — the bot
9/// token (secret) and the chat id (not) — because one bot serves many
10/// chats and only the token is a credential.
11#[derive(Default)]
12pub struct TelegramChannel;
13
14#[async_trait::async_trait]
15impl NotificationChannel for TelegramChannel {
16    fn kind(&self) -> &'static str {
17        "telegram"
18    }
19    fn label(&self) -> &'static str {
20        "Telegram"
21    }
22    fn help(&self) -> &'static str {
23        "Create a bot with @BotFather for the token, then add it to the chat and use that chat's id."
24    }
25    fn config_fields(&self) -> Vec<ConfigField> {
26        vec![
27            ConfigField {
28                name: "chat_id",
29                label: "Chat ID",
30                help: "e.g. -1001234567890 for a group, or a numeric user id.",
31                secret: false,
32                required: true,
33            },
34            ConfigField {
35                name: "bot_token",
36                label: "Bot token",
37                help: "From @BotFather, e.g. 123456:ABC-DEF…",
38                secret: true,
39                required: true,
40            },
41        ]
42    }
43
44    async fn deliver(&self, d: &Delivery<'_>, msg: &Notification) -> Result<(), DeliverError> {
45        if d.secret.is_empty() {
46            return Err(DeliverError::Permanent("no bot token set".to_owned()));
47        }
48        let Some(chat_id) = d.config.get("chat_id").filter(|s| !s.trim().is_empty()) else {
49            return Err(DeliverError::Permanent("no chat id set".to_owned()));
50        };
51        // HTML rather than MarkdownV2: Markdown requires escaping some
52        // eighteen characters, and unescaped user content in a form answer
53        // would make the API reject the whole message. HTML needs three.
54        let mut text = format!("<b>{}</b>\n", esc(&msg.title));
55        if !msg.summary.is_empty() {
56            text.push_str(&format!("{}\n", esc(&msg.summary)));
57        }
58        for (k, v) in &msg.fields {
59            text.push_str(&format!("\n<b>{}</b>: {}", esc(k), esc(v)));
60        }
61        if !msg.url.is_empty() {
62            text.push_str(&format!("\n\n{}", esc(&msg.url)));
63        }
64        // Telegram rejects anything over 4096 characters outright.
65        let text = super::slack::truncate(&text, 4000);
66        let url = format!("https://api.telegram.org/bot{}/sendMessage", d.secret);
67        let payload = json!({ "chat_id": chat_id, "text": text, "parse_mode": "HTML",
68                              "disable_web_page_preview": true });
69        super::slack::post_json(&url, &payload).await
70    }
71}
72
73fn esc(s: &str) -> String {
74    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
75}
76
77crate::register_notification_channel!(TelegramChannel);