Skip to main content

orch/channels/
telegram.rs

1//! Telegram channel — receives commands and streams agent output.
2//!
3//! Uses the Telegram Bot API to receive commands and stream agent output.
4
5use super::{Channel, IncomingMessage, OutgoingMessage, html_escape};
6use anyhow::Context;
7use async_trait::async_trait;
8use chrono::{DateTime, Utc};
9use reqwest::Client;
10use serde::Deserialize;
11use sha2::{Digest, Sha256};
12use std::fmt;
13use std::fmt::Debug;
14use std::fmt::Formatter;
15use std::fmt::Write as _;
16use std::mem;
17use std::sync::Arc;
18use std::time::Duration;
19use tokio::sync::Mutex;
20use tokio::sync::mpsc;
21use tokio::sync::mpsc::Receiver;
22use tokio::time;
23
24const TELEGRAM_LONG_POLL_TIMEOUT_SECS: u64 = 30;
25const TELEGRAM_HTTP_TIMEOUT_SECS: u64 = TELEGRAM_LONG_POLL_TIMEOUT_SECS + 15;
26const TELEGRAM_MAX_RETRIES: u32 = 3;
27const _: () = assert!(
28    TELEGRAM_HTTP_TIMEOUT_SECS > TELEGRAM_LONG_POLL_TIMEOUT_SECS,
29    "the HTTP timeout must outlast the long poll"
30);
31
32/// Escape text for Telegram HTML parse_mode.
33///
34/// Telegram's HTML parser is strict: bare `<`, `>`, or `&` cause
35/// "can't parse entities" errors. This function escapes those characters.
36// Telegram refuses a message over 4096 characters, so parts stay below it with room to spare
37const MAX_MESSAGE_CHARS: usize = 4000;
38
39/* Split plain text into parts whose escaped form fits one message. It breaks at line ends, and
40hard-splits only a line too long by itself. Splitting before escaping means no part can cut an
41entity such as `&amp;` in half */
42fn split_for_telegram(text: &str, max: usize) -> Vec<String> {
43    let size = |s: &str| html_escape(s).chars().count();
44    let mut parts = Vec::new();
45    let mut current = String::new();
46    for line in text.split_inclusive('\n') {
47        if !current.is_empty() && size(&current) + size(line) > max {
48            parts.push(mem::take(&mut current));
49        }
50        if size(line) <= max {
51            current.push_str(line);
52            continue;
53        }
54
55        for c in line.chars() {
56            let mut buf = [0u8; 4];
57            let c = c.encode_utf8(&mut buf);
58            if size(&current) + size(c) > max {
59                parts.push(mem::take(&mut current));
60            }
61            current.push_str(c);
62        }
63    }
64    if !current.is_empty() || parts.is_empty() {
65        parts.push(current);
66    }
67    parts
68}
69
70fn is_preformatted_html(msg: &OutgoingMessage) -> bool {
71    msg.metadata
72        .get("preformatted_html")
73        .and_then(serde_json::Value::as_bool)
74        .unwrap_or(false)
75}
76
77pub struct TelegramChannel {
78    pub token: String,
79    pub client: Client,
80    pub chat_id: Option<String>,
81    pub offset: Arc<Mutex<i64>>,
82}
83
84impl Debug for TelegramChannel {
85    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
86        f.debug_struct("TelegramChannel")
87            .field("chat_id", &self.chat_id)
88            .finish_non_exhaustive()
89    }
90}
91
92#[derive(Deserialize)]
93struct TelegramUser {
94    first_name: String,
95    #[serde(default)]
96    username: Option<String>,
97}
98
99#[derive(Deserialize)]
100struct TelegramMessage {
101    message_id: i64,
102    from: Option<TelegramUser>,
103    chat: TelegramChat,
104    text: Option<String>,
105    date: i64,
106    #[serde(default)]
107    message_thread_id: Option<i64>,
108}
109
110#[derive(Deserialize)]
111struct TelegramChat {
112    id: i64,
113}
114
115#[derive(Deserialize)]
116struct CallbackQuery {
117    id: String,
118    from: TelegramUser,
119    message: Option<TelegramMessage>,
120    data: Option<String>,
121}
122
123#[derive(Deserialize)]
124struct Update {
125    #[serde(rename = "update_id")]
126    id: i64,
127    message: Option<TelegramMessage>,
128    callback_query: Option<CallbackQuery>,
129}
130
131#[derive(Deserialize)]
132struct GetUpdatesResponse {
133    ok: bool,
134    result: Vec<Update>,
135}
136
137impl TelegramChannel {
138    pub fn new(token: String, chat_id: Option<String>) -> anyhow::Result<Self> {
139        let client = Client::builder()
140            .timeout(Duration::from_secs(TELEGRAM_HTTP_TIMEOUT_SECS))
141            .build()
142            .context("failed to build HTTP client")?;
143
144        Ok(Self {
145            token,
146            client,
147            chat_id,
148            offset: Arc::new(Mutex::new(0)),
149        })
150    }
151
152    fn api_url(&self, method: &str) -> String {
153        format!("https://api.telegram.org/bot{}/{}", self.token, method)
154    }
155
156    async fn get_updates(&self, offset: i64) -> anyhow::Result<Vec<Update>> {
157        let url = self.api_url("getUpdates");
158
159        let params = serde_json::json!({
160            "offset": offset,
161            "timeout": TELEGRAM_LONG_POLL_TIMEOUT_SECS,
162            "allowed_updates": ["message", "callback_query"]
163        });
164
165        for attempt in 0..TELEGRAM_MAX_RETRIES {
166            let response = match self
167                .client
168                .post(&url)
169                .json(&params)
170                .send()
171                .await
172                .map_err(reqwest::Error::without_url)
173            {
174                Ok(r) => r,
175                Err(e) => {
176                    if attempt + 1 < TELEGRAM_MAX_RETRIES {
177                        time::sleep(Duration::from_secs(2)).await;
178                        continue;
179                    }
180                    anyhow::bail!(
181                        "telegram getUpdates failed after {TELEGRAM_MAX_RETRIES} attempts: {e}",
182                    );
183                }
184            };
185
186            if !response.status().is_success() {
187                let body = response.text().await.unwrap_or_default();
188                anyhow::bail!("telegram API error: {body}");
189            }
190
191            let updates: GetUpdatesResponse =
192                response.json().await.map_err(reqwest::Error::without_url)?;
193
194            if !updates.ok {
195                anyhow::bail!("telegram API returned ok=false");
196            }
197
198            return Ok(updates.result);
199        }
200
201        anyhow::bail!("telegram getUpdates failed after {TELEGRAM_MAX_RETRIES} attempts");
202    }
203
204    async fn send_message(
205        &self,
206        chat_id: i64,
207        text: &str,
208        topic_id: Option<i64>,
209    ) -> anyhow::Result<()> {
210        for part in split_for_telegram(text, MAX_MESSAGE_CHARS) {
211            self.send_formatted_message(chat_id, &html_escape(&part), topic_id)
212                .await?;
213        }
214        Ok(())
215    }
216
217    async fn send_formatted_message(
218        &self,
219        chat_id: i64,
220        text: &str,
221        topic_id: Option<i64>,
222    ) -> anyhow::Result<()> {
223        let url = self.api_url("sendMessage");
224
225        // Use HTML parse mode. Callers must ensure text is properly escaped
226        // (send_message escapes automatically; send_formatted_message expects
227        // pre-escaped/pre-formatted input from TaskNotification::format_telegram).
228        let mut params = serde_json::json!({
229            "chat_id": chat_id,
230            "text": text,
231            "parse_mode": "HTML"
232        });
233        if let Some(tid) = topic_id {
234            params["message_thread_id"] = serde_json::json!(tid);
235        }
236
237        let response = self
238            .client
239            .post(&url)
240            .json(&params)
241            .send()
242            .await
243            .map_err(reqwest::Error::without_url)?;
244
245        if !response.status().is_success() {
246            let body = response.text().await.unwrap_or_default();
247            anyhow::bail!("telegram API error: {body}");
248        }
249
250        Ok(())
251    }
252
253    pub async fn send_inline_keyboard(
254        &self,
255        chat_id: i64,
256        topic_id: Option<i64>,
257        text: &str,
258        buttons: &[(String, String)], // (label, callback_data)
259    ) -> anyhow::Result<i64> {
260        let keyboard: Vec<Vec<serde_json::Value>> = buttons
261            .iter()
262            .map(|(label, data)| {
263                vec![serde_json::json!({
264                    "text": label,
265                    "callback_data": data
266                })]
267            })
268            .collect();
269
270        let mut params = serde_json::json!({
271            "chat_id": chat_id,
272            "text": text,
273            "reply_markup": { "inline_keyboard": keyboard }
274        });
275        if let Some(tid) = topic_id {
276            params["message_thread_id"] = serde_json::json!(tid);
277        }
278
279        let url = self.api_url("sendMessage");
280        let response = self
281            .client
282            .post(&url)
283            .json(&params)
284            .send()
285            .await
286            .map_err(reqwest::Error::without_url)?;
287        if !response.status().is_success() {
288            let body = response.text().await.unwrap_or_default();
289            anyhow::bail!("telegram API error: {body}");
290        }
291        let result: serde_json::Value =
292            response.json().await.map_err(reqwest::Error::without_url)?;
293        let message_id = result["result"]["message_id"].as_i64().unwrap_or(0);
294        Ok(message_id)
295    }
296
297    pub async fn answer_callback_query(
298        &self,
299        callback_query_id: &str,
300        text: &str,
301    ) -> anyhow::Result<()> {
302        let url = self.api_url("answerCallbackQuery");
303        let params = serde_json::json!({
304            "callback_query_id": callback_query_id,
305            "text": text
306        });
307        let response = self
308            .client
309            .post(&url)
310            .json(&params)
311            .send()
312            .await
313            .map_err(reqwest::Error::without_url)?;
314        if !response.status().is_success() {
315            let body = response.text().await.unwrap_or_default();
316            anyhow::bail!("telegram API error: {body}");
317        }
318        Ok(())
319    }
320}
321
322#[async_trait]
323impl Channel for TelegramChannel {
324    fn name(&self) -> &'static str {
325        "telegram"
326    }
327
328    async fn start(&self) -> anyhow::Result<Receiver<IncomingMessage>> {
329        let (tx, rx) = mpsc::channel(64);
330        let token = self.token.clone();
331        let client = self.client.clone();
332        let chat_id = self.chat_id.clone();
333        let offset = Arc::clone(&self.offset);
334
335        let token_fingerprint = {
336            let mut hasher = Sha256::new();
337            hasher.update(token.as_bytes());
338            let hash = hasher.finalize();
339            let hex = hash[..8].iter().fold(String::new(), |mut hex, b| {
340                let _ = write!(hex, "{b:02x}");
341                hex
342            });
343            format!("sha256:{hex}")
344        };
345
346        tracing::info!(token_fingerprint = %token_fingerprint, "telegram channel started");
347
348        // Create a single TelegramChannel instance to reuse for all API calls
349        let channel = TelegramChannel {
350            token,
351            client,
352            chat_id,
353            offset: Arc::clone(&offset),
354        };
355
356        tokio::spawn(async move {
357            const POLL_BACKOFF_BASE: Duration = Duration::from_secs(5);
358            const POLL_BACKOFF_CAP: Duration = Duration::from_secs(60);
359            let mut backoff = POLL_BACKOFF_BASE;
360
361            loop {
362                let current_offset = {
363                    let off = offset.lock().await;
364                    *off
365                };
366
367                let updates = match channel.get_updates(current_offset).await {
368                    Ok(u) => u,
369                    Err(e) => {
370                        tracing::warn!(
371                            ?e,
372                            backoff_secs = backoff.as_secs(),
373                            "failed to get telegram updates"
374                        );
375                        time::sleep(backoff).await;
376                        backoff = (backoff * 2).min(POLL_BACKOFF_CAP);
377                        continue;
378                    }
379                };
380                backoff = POLL_BACKOFF_BASE;
381
382                let has_updates = !updates.is_empty();
383
384                for update in updates {
385                    // Update offset
386                    {
387                        let mut off = offset.lock().await;
388                        if update.id + 1 > *off {
389                            *off = update.id + 1;
390                        }
391                    }
392
393                    // Handle callback queries
394                    if let Some(cb) = update.callback_query {
395                        let chat_id_val = cb
396                            .message
397                            .as_ref()
398                            .map(|m| m.chat.id.to_string())
399                            .unwrap_or_default();
400                        let topic_id = cb
401                            .message
402                            .as_ref()
403                            .and_then(|m| m.message_thread_id)
404                            .map(|id| id.to_string());
405                        let author = cb
406                            .from
407                            .username
408                            .clone()
409                            .unwrap_or(cb.from.first_name.clone());
410                        let body = cb.data.clone().unwrap_or_default();
411                        let msg_id = cb
412                            .message
413                            .as_ref()
414                            .map(|m| m.message_id.to_string())
415                            .unwrap_or_default();
416                        let msg_date = cb.message.as_ref().map_or(0, |m| m.date);
417
418                        let incoming = IncomingMessage {
419                            channel: "telegram".to_string(),
420                            id: msg_id,
421                            thread_id: chat_id_val,
422                            author,
423                            body,
424                            timestamp: DateTime::from_timestamp(msg_date, 0)
425                                .unwrap_or_else(Utc::now),
426                            metadata: serde_json::json!({
427                                "callback_query_id": cb.id,
428                                "callback_data": cb.data
429                            }),
430                            topic_id,
431                        };
432
433                        if tx.send(incoming).await.is_err() {
434                            tracing::debug!("telegram channel receiver dropped");
435                            return;
436                        }
437                        continue;
438                    }
439
440                    // Handle regular messages
441                    let Some(msg) = update.message else { continue };
442
443                    let author = msg.from.as_ref().map_or_else(
444                        || "unknown".to_string(),
445                        |u| u.username.clone().unwrap_or(u.first_name.clone()),
446                    );
447
448                    let body = msg.text.unwrap_or_default();
449
450                    // Skip empty messages or non-command messages unless we have a specific chat_id
451                    if body.is_empty() {
452                        continue;
453                    }
454
455                    let topic_id = msg.message_thread_id.map(|id| id.to_string());
456
457                    let incoming = IncomingMessage {
458                        channel: "telegram".to_string(),
459                        id: msg.message_id.to_string(),
460                        thread_id: msg.chat.id.to_string(),
461                        author,
462                        body,
463                        timestamp: DateTime::from_timestamp(msg.date, 0).unwrap_or_else(Utc::now),
464                        metadata: serde_json::json!({ "chat_id": msg.chat.id }),
465                        topic_id,
466                    };
467
468                    if tx.send(incoming).await.is_err() {
469                        tracing::debug!("telegram channel receiver dropped");
470                        return;
471                    }
472                }
473
474                // If no updates, sleep briefly to avoid busy looping
475                if !has_updates {
476                    time::sleep(Duration::from_secs(1)).await;
477                }
478            }
479        });
480
481        Ok(rx)
482    }
483
484    async fn send(&self, msg: &OutgoingMessage) -> anyhow::Result<()> {
485        // Resolve chat_id: metadata override → configured default.
486        let chat_id = if let Some(override_val) = msg.metadata.get("chat_id_override") {
487            override_val
488                .as_str()
489                .ok_or_else(|| anyhow::anyhow!("chat_id_override is not a string"))?
490                .parse::<i64>()
491                .map_err(|_| anyhow::anyhow!("invalid chat_id_override"))?
492        } else {
493            self.chat_id
494                .as_ref()
495                .ok_or_else(|| anyhow::anyhow!("telegram chat_id not configured"))?
496                .parse::<i64>()
497                .map_err(|_| anyhow::anyhow!("invalid chat_id"))?
498        };
499
500        let topic_id = msg.topic_id.as_ref().and_then(|t| t.parse::<i64>().ok());
501
502        // If metadata carries inline keyboard buttons, send as interactive message.
503        if let Some(buttons_val) = msg.metadata.get("buttons")
504            && let Some(buttons_arr) = buttons_val.as_array()
505        {
506            let buttons: Vec<(String, String)> = buttons_arr
507                .iter()
508                .filter_map(|b| {
509                    let text = b["text"].as_str()?.to_string();
510                    let callback_data = b["callback_data"].as_str()?.to_string();
511                    Some((text, callback_data))
512                })
513                .collect();
514            if !buttons.is_empty() {
515                self.send_inline_keyboard(chat_id, topic_id, &msg.body, &buttons)
516                    .await?;
517                return Ok(());
518            }
519        }
520
521        // Check if body is already pre-formatted HTML (e.g. TaskNotification::format_telegram)
522        // or raw text that needs escaping (e.g. streamed agent output).
523        let preformatted = is_preformatted_html(msg);
524
525        if preformatted {
526            self.send_formatted_message(chat_id, &msg.body, topic_id)
527                .await
528        } else {
529            self.send_message(chat_id, &msg.body, topic_id).await
530        }
531    }
532
533    async fn ack_interaction(&self, callback_query_id: &str) -> anyhow::Result<()> {
534        self.answer_callback_query(callback_query_id, "").await
535    }
536
537    async fn health_check(&self) -> anyhow::Result<()> {
538        let url = self.api_url("getMe");
539
540        let response = self
541            .client
542            .get(&url)
543            .send()
544            .await
545            .map_err(reqwest::Error::without_url)?;
546
547        if !response.status().is_success() {
548            let body = response.text().await.unwrap_or_default();
549            anyhow::bail!("telegram health check failed: {body}");
550        }
551
552        tracing::info!("telegram bot health check passed");
553        Ok(())
554    }
555}
556
557#[cfg(test)]
558mod tests {
559
560    use super::*;
561    use serde_json::json;
562
563    #[tokio::test]
564    async fn request_errors_do_not_contain_the_token_url() {
565        let token = "123456:FAKE-TOKEN";
566        let url = format!("http://127.0.0.1:1/bot{token}/getUpdates");
567        let err = Client::new()
568            .post(&url)
569            .send()
570            .await
571            .expect_err("port 1 refuses connections");
572        assert!(err.to_string().contains(token));
573
574        let err = reqwest::Error::without_url(err);
575        assert!(!err.to_string().contains(token));
576        assert!(!format!("{err:?}").contains(token));
577    }
578
579    #[test]
580    fn a_short_message_is_one_part() {
581        assert_eq!(split_for_telegram("hello\nworld", 4000), ["hello\nworld"]);
582        assert_eq!(split_for_telegram("", 4000), [""]);
583    }
584
585    #[test]
586    fn a_long_message_splits_at_line_ends_and_loses_nothing() {
587        let text = (0..400).fold(String::new(), |mut text, i| {
588            let _ = writeln!(text, "line {i} with some text");
589            text
590        });
591        let parts = split_for_telegram(&text, 4000);
592        assert!(parts.len() > 1);
593        assert_eq!(parts.concat(), text);
594        for part in &parts {
595            assert!(html_escape(part).chars().count() <= 4000);
596            assert!(part.ends_with('\n'), "a part ended mid line");
597        }
598    }
599
600    #[test]
601    fn escaping_counts_toward_the_limit_and_an_entity_is_never_cut() {
602        let text = "&".repeat(3000);
603        let parts = split_for_telegram(&text, 4000);
604        assert_eq!(parts.concat(), text);
605        for part in &parts {
606            let escaped = html_escape(part);
607            assert!(escaped.chars().count() <= 4000);
608            assert_eq!(escaped.matches("&amp;").count(), part.len());
609        }
610    }
611
612    #[test]
613    fn a_line_longer_than_the_limit_is_hard_split_on_char_boundaries() {
614        let text = "é".repeat(9000);
615        let parts = split_for_telegram(&text, 4000);
616        assert_eq!(parts.len(), 3);
617        assert_eq!(parts.concat(), text);
618    }
619
620    #[test]
621    fn html_escape_escapes_telegram_html_entities() {
622        assert_eq!(
623            html_escape("a < b && c > d"),
624            "a &lt; b &amp;&amp; c &gt; d"
625        );
626    }
627
628    #[test]
629    fn preformatted_html_defaults_to_false() {
630        let msg = OutgoingMessage {
631            thread_id: "thread".to_string(),
632            body: "raw <text>".to_string(),
633            reply_to: None,
634            metadata: serde_json::Value::Null,
635            topic_id: None,
636        };
637
638        assert!(!is_preformatted_html(&msg));
639    }
640
641    #[test]
642    fn preformatted_html_honors_metadata_flag() {
643        let msg = OutgoingMessage {
644            thread_id: "thread".to_string(),
645            body: "<b>formatted</b>".to_string(),
646            reply_to: None,
647            metadata: json!({ "preformatted_html": true }),
648            topic_id: None,
649        };
650
651        assert!(is_preformatted_html(&msg));
652    }
653}