Skip to main content

orch/cli/
notify.rs

1//! `orch notify` — send a Telegram message from the command line.
2//!
3//! Allows agents (and humans) to send Telegram messages directly by running:
4//!
5//! ```bash
6//! orch notify "Job completed successfully"
7//! orch notify --target 602365815 "Job failed: backup.sh exited with code 1"
8//! ```
9//!
10//! The `--target` flag overrides the `channels.telegram.chat_id` from config.
11//! If both are absent, the command returns an error.
12
13use crate::channels::telegram::TelegramChannel;
14use crate::channels::{Channel, OutgoingMessage};
15use crate::config;
16
17/// Send a Telegram notification message.
18///
19/// # Arguments
20///
21/// * `message` — the text to send
22/// * `target`  — optional chat_id override; falls back to `channels.telegram.chat_id`
23pub async fn send(message: &str, target: Option<&str>) -> anyhow::Result<()> {
24    // Resolve bot token
25    let token = config::get("channels.telegram.bot_token").map_err(|_| {
26        anyhow::anyhow!(
27            "Telegram bot token not configured.\n\
28             Set `channels.telegram.bot_token` in ~/.orch/config.yml"
29        )
30    })?;
31
32    // Resolve chat_id: --target arg → config default
33    let chat_id: Option<String> = target
34        .map(ToString::to_string)
35        .or_else(|| config::get("channels.telegram.chat_id").ok());
36
37    if chat_id.is_none() {
38        anyhow::bail!(
39            "No Telegram chat_id configured.\n\
40             Use --target <chat_id> or set `channels.telegram.chat_id` in ~/.orch/config.yml"
41        );
42    }
43
44    // Build the channel with the resolved chat_id
45    let channel = TelegramChannel::new(token, chat_id.clone())?;
46
47    // Build the outgoing message
48    let msg = OutgoingMessage {
49        thread_id: chat_id.unwrap_or_default(),
50        body: message.to_string(),
51        reply_to: None,
52        metadata: serde_json::Value::Null,
53        topic_id: None,
54    };
55
56    channel.send(&msg).await?;
57
58    println!("Telegram message sent.");
59    Ok(())
60}