Skip to main content

wabot_addon_chat_controller_telegram/
lib.rs

1//! Telegram chat channel — port of wabot-ts
2//! `addon/chat-controller/telegram/TelegramChannel.ts`. Built on
3//! [`teloxide`].
4//!
5//! Configuration is runtime-only: register a [`TelegramChannelConfig`]
6//! singleton with a bot token (typically read from `BOT_TOKEN`) and
7//! the channel will pick it up. The `#[telegram]` marker on a
8//! controller method takes no arguments — the framework resolves the
9//! channel and config from the container.
10//!
11//! Why no inline-token decorator: the Rust macro can't read environment
12//! state at compile time, and embedding tokens in source defeats secret
13//! hygiene. The runtime-config approach mirrors how the rest of
14//! wabot-rust handles per-channel state.
15
16use std::sync::Arc;
17
18use async_trait::async_trait;
19use parking_lot::Mutex;
20use teloxide::dispatching::ShutdownToken;
21use teloxide::prelude::*;
22use teloxide::types::{ChatKind, MessageKind};
23
24use wabot_feature_chat_controller::{
25    ChannelError, ChannelMessage, ChatChannel, ChatConnection, ChatMessage, ChatType,
26    MessageCallback, ReplyResult,
27};
28
29pub const TELEGRAM_CHANNEL_NAME: &str = "TelegramChannel";
30
31/// Bot token + any future Telegram-specific knobs (admin chat ids,
32/// webhook URL, polling interval, etc.).
33#[derive(Debug, Clone)]
34pub struct TelegramChannelConfig {
35    pub bot_token: String,
36}
37
38impl TelegramChannelConfig {
39    pub fn new(bot_token: impl Into<String>) -> Self {
40        Self {
41            bot_token: bot_token.into(),
42        }
43    }
44
45    /// Read the bot token from the named environment variable. Panics
46    /// if the var is missing — by design: a misconfigured Telegram
47    /// channel should fail loudly at startup, not silently no-op.
48    pub fn from_env(var: &str) -> Self {
49        let bot_token = std::env::var(var)
50            .unwrap_or_else(|_| panic!("missing telegram bot token env var: {var}"));
51        Self { bot_token }
52    }
53}
54
55/// Telegram channel. Cheap to clone (`Arc`-internal). Construct one
56/// per process and register as a singleton.
57pub struct TelegramChannel {
58    inner: Arc<Inner>,
59}
60
61struct Inner {
62    bot: Bot,
63    callback: Mutex<Option<MessageCallback>>,
64    /// Set on `connect()`; used by `disconnect()` to stop the dispatcher.
65    shutdown: Mutex<Option<ShutdownToken>>,
66}
67
68impl TelegramChannel {
69    pub fn new(config: TelegramChannelConfig) -> Self {
70        Self {
71            inner: Arc::new(Inner {
72                bot: Bot::new(config.bot_token),
73                callback: Mutex::new(None),
74                shutdown: Mutex::new(None),
75            }),
76        }
77    }
78}
79
80#[async_trait]
81impl ChatChannel for TelegramChannel {
82    fn listen(&self, callback: MessageCallback) {
83        *self.inner.callback.lock() = Some(callback);
84    }
85
86    async fn connect(&self) -> Result<(), ChannelError> {
87        let inner = self.inner.clone();
88        let bot = inner.bot.clone();
89
90        // Per-update handler. Captures the channel's `Inner` so it can
91        // grab the latest callback on every message.
92        let handler = Update::filter_message().endpoint(move |bot: Bot, msg: Message| {
93            let inner = inner.clone();
94            async move { handle_message(inner, bot, msg).await }
95        });
96
97        let mut dispatcher = Dispatcher::builder(bot, handler)
98            .enable_ctrlc_handler()
99            .build();
100
101        // Stash the shutdown token so `disconnect()` can flip it.
102        *self.inner.shutdown.lock() = Some(dispatcher.shutdown_token());
103
104        dispatcher.dispatch().await;
105        Ok(())
106    }
107
108    async fn disconnect(&self) -> Result<(), ChannelError> {
109        *self.inner.callback.lock() = None;
110        let token = self.inner.shutdown.lock().take();
111        if let Some(t) = token {
112            // shutdown() returns a future that resolves once the
113            // dispatcher loop exits — but we don't await it here to
114            // avoid blocking on slow in-flight handlers; `connect()`
115            // returns after dispatch() finishes.
116            let _ = t.shutdown();
117        }
118        Ok(())
119    }
120}
121
122async fn handle_message(
123    inner: Arc<Inner>,
124    bot: Bot,
125    msg: Message,
126) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
127    let cb_opt = { inner.callback.lock().clone() };
128    let Some(cb) = cb_opt else {
129        return Ok(()); // no listener wired yet — drop silently
130    };
131
132    // Pull the user-visible text. We currently support text-only
133    // updates; media handling is left to a follow-up.
134    let text = match &msg.kind {
135        MessageKind::Common(common) => match &common.media_kind {
136            teloxide::types::MediaKind::Text(t) => Some(t.text.clone()),
137            _ => None,
138        },
139        _ => None,
140    };
141
142    let chat_type = match msg.chat.kind {
143        ChatKind::Private(_) => ChatType::Private,
144        _ => ChatType::Group,
145    };
146
147    let chat_connection = ChatConnection {
148        id: msg.chat.id.0.to_string(),
149        chat_type,
150        channel_name: TELEGRAM_CHANNEL_NAME.into(),
151    };
152
153    let (sender_id, sender_name) = match &msg.from {
154        Some(u) => (Some(u.id.0.to_string()), Some(u.first_name.clone())),
155        None => (None, None),
156    };
157
158    let bot_for_reply = bot.clone();
159    let chat_id_for_reply = msg.chat.id;
160
161    let channel_msg = ChannelMessage {
162        channel_name: TELEGRAM_CHANNEL_NAME,
163        chat_connection,
164        message: ChatMessage {
165            sender_id,
166            sender_name,
167            text,
168            ..Default::default()
169        },
170        reply: build_reply(bot_for_reply, chat_id_for_reply),
171        inject_instances: Vec::new(),
172    };
173
174    cb(channel_msg).await;
175    Ok(())
176}
177
178fn build_reply(bot: Bot, chat_id: ChatId) -> wabot_feature_chat_controller::ReplyFn {
179    Box::new(move |reply: ChatMessage| {
180        let bot = bot.clone();
181        Box::pin(async move {
182            let Some(text) = reply.text else {
183                return Ok::<(), ChannelError>(());
184            };
185            bot.send_message(chat_id, text)
186                .await
187                .map_err(|e| ChannelError::SendFailed(e.to_string()))?;
188            Ok(())
189        }) as std::pin::Pin<Box<dyn std::future::Future<Output = ReplyResult> + Send>>
190    })
191}
192
193/// DI helper — pair with `register_singletons!(&c, TelegramChannel)`.
194///
195/// Requires `Arc<TelegramChannelConfig>` to already be registered
196/// (typically `c.register_instance(Arc::new(TelegramChannelConfig::from_env("BOT_TOKEN")))`).
197impl wabot_core::injection::IsSingleton for TelegramChannel {
198    fn register_in(c: &wabot_core::injection::Container) {
199        c.register_singleton_factory::<TelegramChannel, _>(|c2| {
200            let cfg: Arc<TelegramChannelConfig> = c2.resolve::<TelegramChannelConfig>();
201            Arc::new(TelegramChannel::new((*cfg).clone()))
202        });
203    }
204}