wabot_addon_chat_controller_telegram/
lib.rs1use 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#[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 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
55pub struct TelegramChannel {
58 inner: Arc<Inner>,
59}
60
61struct Inner {
62 bot: Bot,
63 callback: Mutex<Option<MessageCallback>>,
64 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 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 *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 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(()); };
131
132 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
193impl 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}