blazegram 0.4.2

Telegram bot framework: clean chats, zero garbage, declarative screens, pure Rust MTProto.
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
use crate::keyboard::{InlineKeyboard, KeyboardBuilder};
use crate::types::*;

/// A screen — the atomic unit of UI. What the user sees right now.
#[derive(Debug, Clone)]
pub struct Screen {
    /// Unique identifier for this screen (used by the differ and nav stack).
    pub id: ScreenId,
    /// The messages that make up this screen (usually one, but multi-message screens are supported).
    pub messages: Vec<ScreenMessage>,
    /// If set, the screen expects user input of this kind.
    pub input: Option<InputSpec>,
    /// Show a "typing…" (or similar) indicator before sending.
    pub typing_action: Option<ChatAction>,
    /// Protect content from forwarding/saving.
    pub protect_content: bool,
    /// Reply keyboard (bottom keyboard). `None` = don’t change, `Some(Remove)` = remove.
    pub reply_keyboard: Option<ReplyKeyboardAction>,
    /// Reply to a specific message.
    pub reply_to: Option<MessageId>,
}

/// What to do with the reply (bottom) keyboard.
#[derive(Debug, Clone)]
pub enum ReplyKeyboardAction {
    /// Show a reply keyboard with these buttons.
    Show {
        /// Button rows (outer = rows, inner = buttons in a row).
        rows: Vec<Vec<ReplyButton>>,
        /// Resize the keyboard to fit the buttons (instead of full width).
        resize: bool,
        /// Hide the keyboard after the user presses a button.
        one_time: bool,
        /// Placeholder text shown in the input field while the keyboard is active.
        placeholder: Option<String>,
    },
    /// Remove the reply keyboard.
    Remove,
}

/// A single button on the reply (bottom) keyboard.
#[derive(Debug, Clone)]
pub struct ReplyButton {
    /// Button label.
    pub text: String,
    /// Pressing the button shares the user’s phone number.
    pub request_contact: bool,
    /// Pressing the button shares the user’s current location.
    pub request_location: bool,
}

/// A single message within a [`Screen`].
///
/// Multi-message screens contain multiple `ScreenMessage` entries.
#[derive(Debug, Clone)]
pub struct ScreenMessage {
    /// The content to be sent (text, photo, video, etc.).
    pub content: MessageContent,
}

impl Screen {
    /// Create a screen builder with the given ID.
    pub fn builder(id: impl Into<ScreenId>) -> ScreenBuilder {
        ScreenBuilder {
            id: id.into(),
            messages: Vec::new(),
            input: None,
            typing_action: None,
            protect_content: false,
            reply_keyboard: None,
            reply_to: None,
            lang: None,
        }
    }

    /// Shortcut: single text message screen.
    pub fn text(id: impl Into<ScreenId>, text: impl Into<String>) -> ScreenTextBuilder {
        Self::builder(id).text(text)
    }

    /// Quick text screen with auto-generated ID. Ideal for `ctx.reply()`.
    pub fn reply_text(text: impl Into<String>) -> Screen {
        Self::builder("__reply__").text(text).build()
    }
}

// ─── Screen Builder ───

/// Step-by-step builder for assembling a [`Screen`].
///
/// Start with [`Screen::builder`] or [`Screen::text`], chain messages and
/// options, then call [`.build()`](Self::build).
pub struct ScreenBuilder {
    id: ScreenId,
    messages: Vec<ScreenMessage>,
    input: Option<InputSpec>,
    typing_action: Option<ChatAction>,
    protect_content: bool,
    reply_keyboard: Option<ReplyKeyboardAction>,
    reply_to: Option<MessageId>,
    /// Language code for framework-generated labels (pagination, nav_back, etc).
    lang: Option<String>,
}

impl ScreenBuilder {
    /// Add a text message to the screen.
    pub fn text(self, text: impl Into<String>) -> ScreenTextBuilder {
        ScreenTextBuilder {
            parent: self,
            text: text.into(),
            parse_mode: ParseMode::Html,
            keyboard: None,
            link_preview: LinkPreview::Disabled,
        }
    }

    /// Add a text message processed through the [`markup`](crate::markup) shorthand engine.
    pub fn markup(self, text: impl Into<String>) -> ScreenTextBuilder {
        let processed = crate::markup::render(&text.into());
        ScreenTextBuilder {
            parent: self,
            text: processed,
            parse_mode: ParseMode::Html,
            keyboard: None,
            link_preview: LinkPreview::Disabled,
        }
    }

    /// Add a photo message to the screen.
    pub fn photo(self, source: impl Into<FileSource>) -> ScreenMediaBuilder {
        ScreenMediaBuilder {
            parent: self,
            media_type: ContentType::Photo,
            source: source.into(),
            caption: None,
            parse_mode: ParseMode::Html,
            keyboard: None,
            spoiler: false,
        }
    }

    /// Add a video message to the screen.
    pub fn video(self, source: impl Into<FileSource>) -> ScreenMediaBuilder {
        ScreenMediaBuilder {
            parent: self,
            media_type: ContentType::Video,
            source: source.into(),
            caption: None,
            parse_mode: ParseMode::Html,
            keyboard: None,
            spoiler: false,
        }
    }

    /// Add a document message to the screen.
    pub fn document(self, source: impl Into<FileSource>) -> ScreenMediaBuilder {
        ScreenMediaBuilder {
            parent: self,
            media_type: ContentType::Document,
            source: source.into(),
            caption: None,
            parse_mode: ParseMode::Html,
            keyboard: None,
            spoiler: false,
        }
    }

    /// Expect free-form text input from the user.
    pub fn expect_text(self) -> ScreenInputBuilder {
        ScreenInputBuilder {
            parent: self,
            validator: None,
            placeholder: None,
        }
    }

    /// Expect a photo from the user.
    pub fn expect_photo(mut self) -> Self {
        self.input = Some(InputSpec::Photo);
        self
    }

    /// Expect a choice from a fixed list of options (shown as a reply keyboard).
    pub fn expect_choice(mut self, options: Vec<String>) -> Self {
        self.input = Some(InputSpec::Choice { options });
        self
    }

    /// Set the language code for framework-generated labels.
    /// Propagated to `KeyboardBuilder` in `.keyboard()` closures.
    pub fn lang(mut self, lang: impl Into<String>) -> Self {
        self.lang = Some(lang.into());
        self
    }

    /// Show a “typing…” indicator before sending this screen.
    pub fn typing(mut self) -> Self {
        self.typing_action = Some(ChatAction::Typing);
        self
    }

    /// Prevent the user from forwarding or saving the content.
    pub fn protect_content(mut self) -> Self {
        self.protect_content = true;
        self
    }

    /// Set a reply (bottom) keyboard.
    pub fn reply_keyboard(mut self, rows: Vec<Vec<&str>>) -> Self {
        self.reply_keyboard = Some(ReplyKeyboardAction::Show {
            rows: rows
                .into_iter()
                .map(|row| {
                    row.into_iter()
                        .map(|t| ReplyButton {
                            text: t.to_string(),
                            request_contact: false,
                            request_location: false,
                        })
                        .collect()
                })
                .collect(),
            resize: true,
            one_time: false,
            placeholder: None,
        });
        self
    }

    /// Remove the reply keyboard.
    pub fn remove_reply_keyboard(mut self) -> Self {
        self.reply_keyboard = Some(ReplyKeyboardAction::Remove);
        self
    }

    /// Reply to a specific message when sending.
    pub fn reply_to(mut self, message_id: MessageId) -> Self {
        self.reply_to = Some(message_id);
        self
    }

    /// Finalize the builder and produce a [`Screen`].
    pub fn build(self) -> Screen {
        if self.messages.is_empty() {
            tracing::warn!(
                screen_id = %self.id,
                "Screen::build() called with no messages — this screen will be a no-op. \
                 Did you forget to call .text() or .photo()?"
            );
        }
        Screen {
            id: self.id,
            messages: self.messages,
            input: self.input,
            typing_action: self.typing_action,
            protect_content: self.protect_content,
            reply_keyboard: self.reply_keyboard,
            reply_to: self.reply_to,
        }
    }
}

// ─── Text sub-builder ───

/// Sub-builder for a text message within a screen.
#[must_use = "builder does nothing until .build() or .done() is called"]
pub struct ScreenTextBuilder {
    parent: ScreenBuilder,
    text: String,
    parse_mode: ParseMode,
    keyboard: Option<InlineKeyboard>,
    link_preview: LinkPreview,
}

impl ScreenTextBuilder {
    /// Set the parse mode (default: HTML).
    pub fn parse_mode(mut self, pm: ParseMode) -> Self {
        self.parse_mode = pm;
        self
    }

    /// Enable or disable URL link previews.
    pub fn link_preview(mut self, lp: LinkPreview) -> Self {
        self.link_preview = lp;
        self
    }

    /// Attach an inline keyboard via a builder closure.
    pub fn keyboard(mut self, f: impl FnOnce(KeyboardBuilder) -> KeyboardBuilder) -> Self {
        let kb_builder = match &self.parent.lang {
            Some(lang) => KeyboardBuilder::with_lang(lang.clone()),
            None => KeyboardBuilder::new(),
        };
        let kb = f(kb_builder);
        self.keyboard = Some(kb.build());
        self
    }

    /// Finish this text message, return to ScreenBuilder.
    pub fn done(mut self) -> ScreenBuilder {
        self.parent.messages.push(ScreenMessage {
            content: MessageContent::Text {
                text: self.text,
                parse_mode: self.parse_mode,
                keyboard: self.keyboard,
                link_preview: self.link_preview,
            },
        });
        self.parent
    }

    /// Finalize this text message and produce a [`Screen`].
    pub fn build(self) -> Screen {
        self.done().build()
    }

    /// Finalize this message and return to ScreenBuilder for adding more.
    pub fn build_msg(self) -> ScreenBuilder {
        self.done()
    }

    /// Prevent forwarding / saving content.
    pub fn protect_content(mut self) -> Self {
        self.parent.protect_content = true;
        self
    }

    /// Set a reply keyboard (delegates to parent builder).
    pub fn reply_keyboard(mut self, rows: Vec<Vec<&str>>) -> Self {
        self.parent = self.parent.reply_keyboard(rows);
        self
    }

    /// Remove the reply keyboard (delegates to parent builder).
    pub fn remove_reply_keyboard(mut self) -> Self {
        self.parent = self.parent.remove_reply_keyboard();
        self
    }

    /// Chain: add another text message.
    pub fn text(self, text: impl Into<String>) -> ScreenTextBuilder {
        self.done().text(text)
    }

    /// Chain: add photo message.
    pub fn photo(self, source: impl Into<FileSource>) -> ScreenMediaBuilder {
        self.done().photo(source)
    }

    /// Chain: expect text input.
    pub fn expect_text(self) -> ScreenInputBuilder {
        self.done().expect_text()
    }

    /// Chain: expect photo input.
    pub fn expect_photo(self) -> ScreenBuilder {
        self.done().expect_photo()
    }
}

// ─── Media sub-builder ───

/// Sub-builder for a media (photo / video / document) message within a screen.
#[must_use = "builder does nothing until .build() or .done() is called"]
pub struct ScreenMediaBuilder {
    parent: ScreenBuilder,
    media_type: ContentType,
    source: FileSource,
    caption: Option<String>,
    parse_mode: ParseMode,
    keyboard: Option<InlineKeyboard>,
    spoiler: bool,
}

impl ScreenMediaBuilder {
    /// Set the media caption.
    pub fn caption(mut self, cap: impl Into<String>) -> Self {
        self.caption = Some(cap.into());
        self
    }

    /// Mark the media as a spoiler (click to reveal).
    pub fn spoiler(mut self) -> Self {
        self.spoiler = true;
        self
    }

    /// Attach an inline keyboard via a builder closure.
    pub fn keyboard(mut self, f: impl FnOnce(KeyboardBuilder) -> KeyboardBuilder) -> Self {
        let kb_builder = match &self.parent.lang {
            Some(lang) => KeyboardBuilder::with_lang(lang.clone()),
            None => KeyboardBuilder::new(),
        };
        let kb = f(kb_builder);
        self.keyboard = Some(kb.build());
        self
    }

    /// Finish this media message and return to the parent [`ScreenBuilder`].
    pub fn done(mut self) -> ScreenBuilder {
        let content = match self.media_type {
            ContentType::Photo => MessageContent::Photo {
                source: self.source,
                caption: self.caption,
                parse_mode: self.parse_mode,
                keyboard: self.keyboard,
                spoiler: self.spoiler,
            },
            ContentType::Video => MessageContent::Video {
                source: self.source,
                caption: self.caption,
                parse_mode: self.parse_mode,
                keyboard: self.keyboard,
                spoiler: self.spoiler,
            },
            ContentType::Document => MessageContent::Document {
                source: self.source,
                caption: self.caption,
                parse_mode: self.parse_mode,
                keyboard: self.keyboard,
                filename: None,
            },
            _ => unreachable!("ScreenMediaBuilder only supports Photo/Video/Document"),
        };
        self.parent.messages.push(ScreenMessage { content });
        self.parent
    }

    /// Finish this media message and produce a [`Screen`].
    pub fn build(self) -> Screen {
        self.done().build()
    }

    /// Chain: add a text message after this media message.
    pub fn text(self, text: impl Into<String>) -> ScreenTextBuilder {
        self.done().text(text)
    }
}

// ─── Input sub-builder ───

/// Sub-builder for configuring expected text input on a screen.
pub struct ScreenInputBuilder {
    parent: ScreenBuilder,
    validator: Option<ValidatorFn>,
    placeholder: Option<String>,
}

impl ScreenInputBuilder {
    /// Set a validation function that rejects bad input with an error message.
    pub fn validator(
        mut self,
        f: impl Fn(&str) -> Result<(), String> + Send + Sync + 'static,
    ) -> Self {
        self.validator = Some(std::sync::Arc::new(f));
        self
    }

    /// Set placeholder text shown in the input field.
    pub fn placeholder(mut self, p: impl Into<String>) -> Self {
        self.placeholder = Some(p.into());
        self
    }

    /// Finalize and produce a [`Screen`] expecting text input.
    pub fn build(mut self) -> Screen {
        self.parent.input = Some(InputSpec::Text {
            validator: self.validator,
            placeholder: self.placeholder,
        });
        self.parent.build()
    }

    /// Finish configuring input and return to the parent [`ScreenBuilder`].
    pub fn done(mut self) -> ScreenBuilder {
        self.parent.input = Some(InputSpec::Text {
            validator: self.validator,
            placeholder: self.placeholder,
        });
        self.parent
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn screen_text_basic() {
        let s = Screen::text("home", "Hello").build();
        assert_eq!(s.id, ScreenId::from("home"));
        assert_eq!(s.messages.len(), 1);
        assert!(matches!(
            &s.messages[0].content,
            MessageContent::Text { text, parse_mode: ParseMode::Html, .. } if text == "Hello"
        ));
    }

    #[test]
    fn screen_reply_text() {
        let s = Screen::reply_text("Hi");
        assert_eq!(s.id, ScreenId::from("__reply__"));
    }

    #[test]
    fn screen_photo_with_caption_and_spoiler() {
        let s = Screen::builder("gallery")
            .photo("https://example.com/pic.jpg")
            .caption("Nice")
            .spoiler()
            .build();
        assert_eq!(s.messages.len(), 1);
        match &s.messages[0].content {
            MessageContent::Photo {
                caption, spoiler, ..
            } => {
                assert_eq!(caption.as_deref(), Some("Nice"));
                assert!(spoiler);
            }
            _ => panic!("expected Photo"),
        }
    }

    #[test]
    fn screen_multi_message() {
        let s = Screen::builder("multi")
            .text("First")
            .done()
            .text("Second")
            .done()
            .build();
        assert_eq!(s.messages.len(), 2);
    }

    #[test]
    fn screen_expect_text_with_placeholder() {
        let s = Screen::builder("input")
            .text("Enter name:")
            .done()
            .expect_text()
            .placeholder("Your name")
            .build();
        assert!(s.input.is_some());
        match &s.input {
            Some(InputSpec::Text { placeholder, .. }) => {
                assert_eq!(placeholder.as_deref(), Some("Your name"));
            }
            _ => panic!("expected Text input"),
        }
    }

    #[test]
    fn screen_expect_choice() {
        let s = Screen::builder("choose")
            .text("Pick one")
            .done()
            .expect_choice(vec!["A".into(), "B".into()])
            .build();
        match &s.input {
            Some(InputSpec::Choice { options }) => {
                assert_eq!(options.len(), 2);
            }
            _ => panic!("expected Choice input"),
        }
    }

    #[test]
    fn screen_typing_and_protect() {
        let s = Screen::builder("sec")
            .typing()
            .protect_content()
            .text("Secret")
            .build();
        assert!(s.typing_action.is_some());
        assert!(s.protect_content);
    }

    #[test]
    fn screen_reply_keyboard() {
        let s = Screen::builder("kb")
            .text("Choose")
            .reply_keyboard(vec![vec!["A", "B"]])
            .build();
        assert!(s.reply_keyboard.is_some());
        match &s.reply_keyboard {
            Some(ReplyKeyboardAction::Show { rows, .. }) => {
                assert_eq!(rows.len(), 1);
                assert_eq!(rows[0].len(), 2);
            }
            _ => panic!("expected Show"),
        }
    }

    #[test]
    fn screen_remove_reply_keyboard() {
        let s = Screen::builder("rm")
            .remove_reply_keyboard()
            .text("Done")
            .build();
        assert!(matches!(
            s.reply_keyboard,
            Some(ReplyKeyboardAction::Remove)
        ));
    }

    #[test]
    fn screen_document() {
        let s = Screen::builder("doc")
            .document("https://example.com/file.pdf")
            .caption("PDF")
            .build();
        assert!(matches!(
            &s.messages[0].content,
            MessageContent::Document { .. }
        ));
    }

    #[test]
    fn screen_video() {
        let s = Screen::builder("vid")
            .video("https://example.com/v.mp4")
            .build();
        assert!(matches!(
            &s.messages[0].content,
            MessageContent::Video { .. }
        ));
    }

    #[test]
    fn screen_link_preview() {
        let s = Screen::text("lp", "Check https://example.com")
            .link_preview(LinkPreview::Enabled)
            .build();
        match &s.messages[0].content {
            MessageContent::Text { link_preview, .. } => {
                assert_eq!(*link_preview, LinkPreview::Enabled);
            }
            _ => panic!("expected Text"),
        }
    }

    #[test]
    fn screen_text_chain() {
        let s = Screen::builder("chain")
            .text("A")
            .text("B")
            .text("C")
            .build();
        assert_eq!(s.messages.len(), 3);
    }

    #[test]
    fn screen_empty_builds() {
        let s = Screen::builder("empty").build();
        assert!(s.messages.is_empty());
    }
}