botkit-telegram 0.2.0

Telegram implementation for botkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;

use botkit_core::{
    Bot, BotBuilder, BotError, Context, ContextData, Event, IntoHandler, Response, Shutdown,
};
use executor_core::spawn;
use http_kit::{Body, Endpoint, HttpError, Request, Response as HttpResponse, StatusCode};
use tracing::{error, warn};

use crate::client::TelegramClient;
use crate::event::TelegramContextData;
use crate::types::{
    BotCommand, InlineKeyboardButton, InlineKeyboardMarkup, ReplyMarkup, Update, UpdateKind,
};

/// How long Telegram holds a long-poll open before returning empty.
const POLL_TIMEOUT_SECS: u32 = 30;
/// First wait after a failed `getUpdates`; doubles up to the max.
const INITIAL_POLL_BACKOFF: Duration = Duration::from_secs(1);
/// Longest wait between failed `getUpdates` attempts.
const MAX_POLL_BACKOFF: Duration = Duration::from_secs(60);

/// Error type for the Telegram webhook endpoint
#[derive(Debug)]
pub struct WebhookError(BotError);

impl WebhookError {
    /// The underlying bot error
    pub fn into_inner(self) -> BotError {
        self.0
    }
}

impl std::fmt::Display for WebhookError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::error::Error for WebhookError {}

impl HttpError for WebhookError {
    fn status(&self) -> StatusCode {
        StatusCode::INTERNAL_SERVER_ERROR
    }
}

/// Telegram bot builder
///
/// Create a bot with command and button handlers, then either call `build()`
/// for a webhook endpoint or `run()` for long polling.
///
/// # Example
/// ```ignore
/// use botkit_core::User;
/// use botkit_telegram::{TelegramBot, TelegramWebhook};
///
/// // Simple handler - no Context needed!
/// async fn ping() -> &'static str {
///     "Pong!"
/// }
///
/// // With extractors
/// async fn greet(user: User) -> String {
///     format!("Hello, {}!", user.name)
/// }
///
/// // Return TelegramWebhook directly - it implements Endpoint
/// #[skyzen::main]
/// fn main() -> TelegramWebhook {
///     TelegramBot::new(token)
///         .command("ping", ping)
///         .command("greet", greet)
///         .build()
/// }
/// ```
pub struct TelegramBot {
    token: String,
    builder: BotBuilder,
    register_commands: bool,
}

impl TelegramBot {
    /// Create a new Telegram bot
    pub fn new(token: impl Into<String>) -> Self {
        Self {
            token: token.into(),
            builder: BotBuilder::new(),
            register_commands: true,
        }
    }

    /// Register a command handler (e.g., /start, /help)
    pub fn command<H, Args>(mut self, name: impl Into<String>, handler: H) -> Self
    where
        H: IntoHandler<Args>,
    {
        self.builder = self.builder.command(name, handler);
        self
    }

    /// Register a command handler with description
    ///
    /// The description appears in Telegram's command menu (slash command suggestions).
    pub fn command_with_description<H, Args>(
        mut self,
        name: impl Into<String>,
        description: impl Into<String>,
        handler: H,
    ) -> Self
    where
        H: IntoHandler<Args>,
    {
        self.builder = self
            .builder
            .command_with_description(name, description, handler);
        self
    }

    /// Register a button handler (callback query data pattern)
    ///
    /// Pattern can end with `*` for prefix matching (e.g., "confirm_*")
    pub fn button<H, Args>(mut self, pattern: impl Into<String>, handler: H) -> Self
    where
        H: IntoHandler<Args>,
    {
        self.builder = self.builder.button(pattern, handler);
        self
    }

    /// Register a message handler
    pub fn message<H, Args>(mut self, handler: H) -> Self
    where
        H: IntoHandler<Args>,
    {
        self.builder = self.builder.message(handler);
        self
    }

    /// Register a handler for events nothing else claimed
    ///
    /// Unregistered commands and unmatched callbacks reach the fallback
    /// rather than being dropped. See [`BotBuilder::fallback`].
    pub fn fallback<H, Args>(mut self, handler: H) -> Self
    where
        H: IntoHandler<Args>,
    {
        self.builder = self.builder.fallback(handler);
        self
    }

    /// Stop publishing the registered commands to Telegram on startup
    ///
    /// On by default for [`TelegramBot::run`]; webhook mode never registers
    /// commands, since `build()` does no I/O.
    pub fn skip_command_registration(mut self) -> Self {
        self.register_commands = false;
        self
    }

    /// Build the webhook handler (for use with skyzen's Endpoint)
    ///
    /// Registering the command menu is a network call, so webhook deployments
    /// should call [`TelegramClient::set_my_commands`] themselves at startup;
    /// [`TelegramBot::commands`] renders the list to pass it.
    pub fn build(self) -> TelegramWebhook {
        TelegramWebhook {
            dispatcher: Arc::new(Dispatcher {
                client: TelegramClient::new(&self.token),
                builder: self.builder,
            }),
        }
    }

    /// The command menu entries implied by the registered handlers
    pub fn commands(&self) -> Vec<BotCommand> {
        self.builder
            .commands()
            .map(|command| {
                // Telegram rejects an empty description, so fall back to the name.
                let description = if command.description.is_empty() {
                    command.name
                } else {
                    command.description
                };
                BotCommand::new(command.name, description)
            })
            .collect()
    }
}

impl Bot for TelegramBot {
    async fn run_until(self, shutdown: Shutdown) -> Result<(), BotError> {
        let client = TelegramClient::new(&self.token);

        if self.register_commands {
            let commands = self.commands();
            if !commands.is_empty()
                && let Err(e) = client.set_my_commands(&commands).await
            {
                warn!("Failed to register commands: {e}");
            }
        }

        // Long polling and webhooks are mutually exclusive on Telegram's side.
        client.delete_webhook().await?;

        let dispatcher = Arc::new(Dispatcher {
            client,
            builder: self.builder,
        });

        poll_updates(dispatcher, shutdown).await
    }
}

async fn poll_updates(dispatcher: Arc<Dispatcher>, shutdown: Shutdown) -> Result<(), BotError> {
    let mut offset: Option<i64> = None;
    let mut backoff = INITIAL_POLL_BACKOFF;

    loop {
        if shutdown.is_shutdown() {
            return Ok(());
        }

        let poll = dispatcher
            .client
            .get_updates(offset, Some(POLL_TIMEOUT_SECS));

        let updates = match race_shutdown(poll, &shutdown).await {
            None => return Ok(()),
            Some(Ok(updates)) => {
                backoff = INITIAL_POLL_BACKOFF;
                updates
            }
            Some(Err(e)) => {
                // Without a backoff a persistent failure (revoked token,
                // network outage) becomes a hot loop against Telegram's API.
                error!("Error fetching updates: {e}");
                if race_shutdown(sleep(backoff), &shutdown).await.is_none() {
                    return Ok(());
                }
                backoff = (backoff * 2).min(MAX_POLL_BACKOFF);
                continue;
            }
        };

        for update in updates {
            // Acknowledge before handling: an update that panics a handler must
            // not be redelivered forever.
            offset = Some(update.update_id + 1);

            if let Err(e) = dispatcher.dispatch(update).await {
                error!("Error handling update: {e}");
            }
        }
    }
}

/// Routes updates to handlers and sends whatever they return.
///
/// Shared by webhook and polling mode so both behave identically.
struct Dispatcher {
    client: TelegramClient,
    builder: BotBuilder,
}

impl Dispatcher {
    /// Handle one update to completion.
    async fn dispatch(&self, update: Update) -> Result<(), BotError> {
        let Some((data, handler)) = self.prepare(update).await? else {
            return Ok(());
        };

        let chat_id = data.chat_id();
        let thread_id = data.thread_id();
        let response = handler.call(Context::new(data)).await;
        send_response(&self.client, chat_id, thread_id, response).await
    }

    /// Handle one update in the background, so a webhook can reply immediately.
    async fn dispatch_detached(self: &Arc<Self>, update: Update) -> Result<(), BotError> {
        let Some((data, handler)) = self.prepare(update).await? else {
            return Ok(());
        };

        let this = Arc::clone(self);
        spawn(async move {
            let chat_id = data.chat_id();
            let thread_id = data.thread_id();
            let response = handler.call(Context::new(data)).await;
            if let Err(e) = send_response(&this.client, chat_id, thread_id, response).await {
                error!("Telegram response error: {e}");
            }
        })
        .detach();

        Ok(())
    }

    /// Acknowledge the update and resolve it to a handler, building the context
    /// exactly once.
    async fn prepare(
        &self,
        update: Update,
    ) -> Result<Option<(TelegramContextData, botkit_core::AnyHandler)>, BotError> {
        // Telegram spins the button until the query is answered, so do it
        // before the handler runs rather than after. A failure here is cosmetic
        // - it must not cost the user their button press.
        if let UpdateKind::CallbackQuery(callback_query) = &update.kind
            && let Err(e) = self
                .client
                .answer_callback_query(&callback_query.id, None, false)
                .await
        {
            warn!("Failed to answer callback query: {e}");
        }

        // Edits and reactions route as messages: they only arrive when the
        // bot opted into them via `allowed_updates`, and the message handler
        // is where a bot would observe them. The handler can tell them apart
        // through `UpdateKind`.
        if !matches!(
            update.kind,
            UpdateKind::Message(_)
                | UpdateKind::EditedMessage(_)
                | UpdateKind::CallbackQuery(_)
                | UpdateKind::MessageReaction(_)
        ) {
            return Ok(None);
        }

        let is_callback = matches!(update.kind, UpdateKind::CallbackQuery(_));
        let data = TelegramContextData::new(update, self.client.clone());

        let event = match (is_callback, data.command_name(), data.button_id()) {
            // A callback carries a button id or nothing we can route on; it is
            // never a message, so don't let it fall through to the catch-all.
            (true, _, Some(button)) => Event::Button(button),
            (true, _, None) => return Ok(None),
            (false, Some(command), _) => Event::Command(command),
            (false, None, _) => Event::Message,
        };

        Ok(self
            .builder
            .route(event)
            .cloned()
            .map(|handler| (data, handler)))
    }
}

/// Telegram webhook handler
///
/// Handles incoming webhook updates from Telegram. Use with a skyzen router.
#[derive(Clone)]
pub struct TelegramWebhook {
    dispatcher: Arc<Dispatcher>,
}

impl TelegramWebhook {
    /// Get the client for making API calls
    pub fn client(&self) -> &TelegramClient {
        &self.dispatcher.client
    }

    /// Handle a webhook update
    ///
    /// Returns as soon as the update is routed; the handler runs in the
    /// background so Telegram isn't kept waiting on slow work.
    pub async fn handle(&self, update: Update) -> Result<(), BotError> {
        self.dispatcher.dispatch_detached(update).await
    }
}

impl Endpoint for TelegramWebhook {
    type Error = WebhookError;

    async fn respond(&mut self, request: &mut Request) -> Result<HttpResponse, Self::Error> {
        let update: Update = request
            .body_mut()
            .into_json()
            .await
            .map_err(|e| WebhookError(BotError::Other(e.to_string())))?;

        self.handle(update).await.map_err(WebhookError)?;

        Ok(HttpResponse::new(Body::from_bytes("OK")))
    }
}

async fn send_response(
    client: &TelegramClient,
    chat_id: Option<i64>,
    thread_id: Option<i64>,
    mut response: Response,
) -> Result<(), BotError> {
    if response.is_empty() || response.is_acknowledge() {
        return Ok(());
    }

    // Callback queries from inline messages carry no chat to reply in.
    let Some(chat_id) = chat_id else {
        return Ok(());
    };

    if let Some(file) = response.take_file() {
        let _ = client
            .send_chat_action(chat_id, "upload_document", thread_id)
            .await;

        return client
            .send_document(
                chat_id,
                file.file,
                file.filename.as_deref(),
                file.caption.as_deref(),
                thread_id,
            )
            .await
            .map(|_| ());
    }

    let content = response.content().unwrap_or("");
    if content.is_empty() {
        return Ok(());
    }

    client
        .send_message(chat_id, content, thread_id, build_reply_markup(&response))
        .await?;
    Ok(())
}

/// Flatten unified components into Telegram's inline keyboard rows.
///
/// A bare button becomes a row of its own; select menus have no Telegram
/// equivalent and are skipped.
fn build_reply_markup(response: &Response) -> Option<ReplyMarkup> {
    use botkit_core::types::component::{Button, Component};

    fn to_button(button: &Button) -> Option<InlineKeyboardButton> {
        match (&button.url, &button.custom_id) {
            (Some(url), _) => Some(InlineKeyboardButton::url(&button.label, url)),
            (None, Some(custom_id)) => {
                Some(InlineKeyboardButton::callback(&button.label, custom_id))
            }
            (None, None) => None,
        }
    }

    let mut rows: Vec<Vec<InlineKeyboardButton>> = Vec::new();

    for component in response.components() {
        match component {
            Component::ActionRow(action_row) => {
                let row: Vec<_> = action_row
                    .components
                    .iter()
                    .filter_map(|c| match c {
                        Component::Button(button) => to_button(button),
                        _ => None,
                    })
                    .collect();

                if !row.is_empty() {
                    rows.push(row);
                }
            }
            Component::Button(button) => rows.extend(to_button(button).map(|b| vec![b])),
            Component::SelectMenu(_) => {}
        }
    }

    (!rows.is_empty()).then_some(ReplyMarkup::InlineKeyboard(InlineKeyboardMarkup {
        inline_keyboard: rows,
    }))
}

/// Await `future`, giving up early if shutdown is requested.
async fn race_shutdown<F: Future>(future: F, shutdown: &Shutdown) -> Option<F::Output> {
    futures_lite::future::or(async { Some(future.await) }, async {
        shutdown.wait().await;
        None
    })
    .await
}

async fn sleep(duration: Duration) {
    async_io::Timer::after(duration).await;
}

#[cfg(test)]
mod tests {
    use super::*;
    use botkit_core::types::component::{ActionRow, Button, Component, SelectMenu, SelectOption};

    /// The event an update routes to, without performing any network calls.
    fn routed_event(update: &Update) -> Option<&'static str> {
        if !matches!(
            update.kind,
            UpdateKind::Message(_)
                | UpdateKind::EditedMessage(_)
                | UpdateKind::CallbackQuery(_)
                | UpdateKind::MessageReaction(_)
        ) {
            return None;
        }

        let is_callback = matches!(update.kind, UpdateKind::CallbackQuery(_));
        let data = TelegramContextData::new(update.clone(), TelegramClient::new("t"));

        match (is_callback, data.command_name(), data.button_id()) {
            (true, _, Some(_)) => Some("button"),
            (true, _, None) => None,
            (false, Some(_), _) => Some("command"),
            (false, None, _) => Some("message"),
        }
    }

    fn update(json: serde_json::Value) -> Update {
        serde_json::from_value(json).expect("update parses")
    }

    #[test]
    fn commands_messages_and_buttons_route_to_distinct_events() {
        let command = update(serde_json::json!({
            "update_id": 1,
            "message": {
                "message_id": 1, "date": 0,
                "chat": { "id": 1, "type": "private" },
                "text": "/ping",
                "entities": [{ "type": "bot_command", "offset": 0, "length": 5 }]
            }
        }));
        assert_eq!(routed_event(&command), Some("command"));

        let message = update(serde_json::json!({
            "update_id": 2,
            "message": {
                "message_id": 1, "date": 0,
                "chat": { "id": 1, "type": "private" },
                "text": "just chatting"
            }
        }));
        assert_eq!(routed_event(&message), Some("message"));

        let button = update(serde_json::json!({
            "update_id": 3,
            "callback_query": {
                "id": "cb", "chat_instance": "x", "data": "confirm",
                "from": { "id": 1, "is_bot": false, "first_name": "Ada" }
            }
        }));
        assert_eq!(routed_event(&button), Some("button"));
    }

    #[test]
    fn reaction_updates_route_to_the_message_handler() {
        let reaction = update(serde_json::json!({
            "update_id": 7,
            "message_reaction": {
                "message_id": 9,
                "chat": { "id": 42, "type": "private" },
                "user": { "id": 1, "is_bot": false, "first_name": "Ada" },
                "date": 0,
                "old_reaction": [],
                "new_reaction": [{ "type": "emoji", "emoji": "👍" }]
            }
        }));
        assert_eq!(routed_event(&reaction), Some("message"));

        let data = TelegramContextData::new(reaction, TelegramClient::new("t"));
        assert_eq!(data.chat_id(), Some(42));
        assert_eq!(data.user_name(), "Ada");
        let UpdateKind::MessageReaction(r) = &data.update.kind else {
            panic!("expected a reaction update");
        };
        assert_eq!(r.message_id, 9);
        assert!(matches!(
            r.new_reaction.as_slice(),
            [crate::types::ReactionType::Emoji { .. }]
        ));
    }

    #[test]
    fn a_callback_without_data_does_not_fall_through_to_the_message_handler() {
        let update = update(serde_json::json!({
            "update_id": 4,
            "callback_query": {
                "id": "cb", "chat_instance": "x",
                "from": { "id": 1, "is_bot": false, "first_name": "Ada" }
            }
        }));
        assert_eq!(routed_event(&update), None);
    }

    #[test]
    fn edits_route_to_the_message_handler_but_unmodelled_kinds_do_not() {
        let edit = update(serde_json::json!({
            "update_id": 5,
            "edited_message": {
                "message_id": 1, "date": 0,
                "chat": { "id": 1, "type": "private" },
                "text": "reworded"
            }
        }));
        assert_eq!(routed_event(&edit), Some("message"));

        let poll = update(serde_json::json!({ "update_id": 6, "poll": { "id": "p" } }));
        assert_eq!(routed_event(&poll), None);
    }

    fn markup(response: &Response) -> Option<Vec<Vec<InlineKeyboardButton>>> {
        build_reply_markup(response).map(|ReplyMarkup::InlineKeyboard(m)| m.inline_keyboard)
    }

    #[test]
    fn no_components_means_no_markup() {
        assert!(markup(&Response::text("hi")).is_none());
    }

    #[test]
    fn action_rows_become_keyboard_rows() {
        let response = Response::text("hi").with_components(vec![Component::ActionRow(
            ActionRow::buttons(vec![
                Button::primary("a", "A"),
                Button::link("https://example.com", "Link"),
            ]),
        )]);

        let rows = markup(&response).expect("one row");
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0][0].callback_data.as_deref(), Some("a"));
        assert_eq!(rows[0][1].url.as_deref(), Some("https://example.com"));
        assert!(rows[0][1].callback_data.is_none());
    }

    #[test]
    fn bare_buttons_get_their_own_row() {
        let response = Response::text("hi").with_components(vec![
            Component::Button(Button::primary("a", "A")),
            Component::Button(Button::secondary("b", "B")),
        ]);

        let rows = markup(&response).expect("two rows");
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0][0].text, "A");
        assert_eq!(rows[1][0].text, "B");
    }

    #[test]
    fn components_without_a_telegram_equivalent_are_skipped() {
        let response = Response::text("hi").with_components(vec![
            Component::SelectMenu(SelectMenu::new("menu", vec![SelectOption::new("l", "v")])),
            Component::ActionRow(ActionRow::new(vec![])),
        ]);
        assert!(markup(&response).is_none());
    }
}