telers 1.0.0-beta.8

An asynchronous framework for Telegram Bot API written in Rust
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
use super::{formatter::split_by_entity, Formatter as TextFormatter, FormatterErrorKind};
use crate::types::{
    MessageEntity, MessageEntityCustomEmoji, MessageEntityDateTime, MessageEntityPre,
    MessageEntityTextLink, MessageEntityTextMention,
};

use std::fmt::Display;

const BOLD_TAG: &str = "b";
const ITALIC_TAG: &str = "i";
const UNDERLINE_TAG: &str = "u";
const STRIKETHROUGH_TAG: &str = "s";
const SPOILER_TAG: &str = "tg-spoiler";
const EMOJI_TAG: &str = "tg-emoji";

/// To use this mode, pass `HTML` in the `parse_mode` field
/// # Documentation
/// <https://core.telegram.org/bots/api#html-style>
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Formatter {
    bold: &'static str,
    italic: &'static str,
    underline: &'static str,
    strikethrough: &'static str,
    spoiler: &'static str,
    emoji: &'static str,
}

impl Formatter {
    /// Create a new instance of [`Formatter`] with custom tags
    /// # Notes
    /// If you want to use the default tags, use `Formatter::default` instead.
    #[inline]
    #[must_use]
    pub const fn new_with_tags(
        bold: &'static str,
        italic: &'static str,
        underline: &'static str,
        strikethrough: &'static str,
        spoiler: &'static str,
        emoji: &'static str,
    ) -> Self {
        Self {
            bold,
            italic,
            underline,
            strikethrough,
            spoiler,
            emoji,
        }
    }

    /// Create a new instance of [`Formatter`]
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        Self::new_with_tags(
            BOLD_TAG,
            ITALIC_TAG,
            UNDERLINE_TAG,
            STRIKETHROUGH_TAG,
            SPOILER_TAG,
            EMOJI_TAG,
        )
    }
}

impl Default for Formatter {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl TextFormatter for Formatter {
    fn bold<T>(&self, text: T) -> String
    where
        T: Display,
    {
        format!("<{tag}>{text}</{tag}>", tag = self.bold)
    }

    fn italic<T>(&self, text: T) -> String
    where
        T: Display,
    {
        format!("<{tag}>{text}</{tag}>", tag = self.italic)
    }

    fn underline<T>(&self, text: T) -> String
    where
        T: Display,
    {
        format!("<{tag}>{text}</{tag}>", tag = self.underline)
    }

    fn strikethrough<T>(&self, text: T) -> String
    where
        T: Display,
    {
        format!("<{tag}>{text}</{tag}>", tag = self.strikethrough)
    }

    fn spoiler<T>(&self, text: T) -> String
    where
        T: Display,
    {
        format!("<{tag}>{text}</{tag}>", tag = self.spoiler)
    }

    fn blockquote<T>(&self, text: T) -> String
    where
        T: Display,
    {
        format!("<blockquote>{text}</blockquote>")
    }

    fn expandable_blockquote<T>(&self, text: T) -> String
    where
        T: Display,
    {
        format!("<blockquote expandable>{text}</blockquote>")
    }

    fn text_link<T, U>(&self, text: T, url: U) -> String
    where
        T: Display,
        U: Display,
    {
        format!("<a href=\"{url}\">{text}</a>")
    }

    fn text_mention<T>(&self, text: T, user_id: i64) -> String
    where
        T: Display,
    {
        format!("<a href=\"tg://user?id={user_id}\">{text}</a>")
    }

    fn custom_emoji<T, E>(&self, text: T, emoji_id: E) -> String
    where
        T: Display,
        E: Display,
    {
        format!(
            "<{tag} emoji-id=\"{emoji_id}\">{text}</{tag}>",
            tag = self.emoji
        )
    }

    fn code<T>(&self, text: T) -> String
    where
        T: Display,
    {
        format!("<code>{text}</code>")
    }

    fn pre<T>(&self, text: T) -> String
    where
        T: Display,
    {
        format!("<pre>{text}</pre>")
    }

    fn pre_language<T, L>(&self, text: T, language: L) -> String
    where
        T: Display,
        L: Display,
    {
        format!("<pre><code class=\"language-{language}\">{text}</code></pre>")
    }

    fn date_time<T>(&self, text: T, unix_time: i64) -> String
    where
        T: Display,
    {
        format!("<tg-time unix=\"{unix_time}\">{text}</tg-time>")
    }

    fn date_time_with_format<T, F>(&self, text: T, unix_time: i64, date_time_format: F) -> String
    where
        T: Display,
        F: Display,
    {
        format!("<tg-time unix=\"{unix_time}\" format=\"{date_time_format}\">{text}</tg-time>")
    }

    fn quote<T>(&self, text: T) -> String
    where
        T: Display,
    {
        let text = text.to_string();

        text.chars()
            .fold(String::with_capacity(text.len()), |mut string, ch| {
                match ch {
                    '&' => string.push_str("&amp;"),
                    '<' => string.push_str("&lt;"),
                    '>' => string.push_str("&gt;"),
                    _ => string.push(ch),
                }
                string
            })
    }

    fn apply_entity<T>(&self, text: T, entity: &MessageEntity) -> Result<String, FormatterErrorKind>
    where
        T: Display,
    {
        let text = text.to_string();

        if text.is_empty() {
            return Err(FormatterErrorKind::EmptyText);
        }

        let (previous_text, editable_text, next_text) = split_by_entity(&text, entity)?;

        let edited_text = match entity {
            // Auto-detected entities (their prefix `@`/`#`/`$`/`/` is already part of the
            // entity span, and Telegram re-detects them) must be returned untouched.
            MessageEntity::Mention(_)
            | MessageEntity::Hashtag(_)
            | MessageEntity::Cashtag(_)
            | MessageEntity::BotCommand(_)
            | MessageEntity::Url(_)
            | MessageEntity::Email(_)
            // Entity types unknown to the library can't be re-formatted either, so their
            // span is also kept as is.
            | MessageEntity::PhoneNumber(_)
            | MessageEntity::Unknown(_) => editable_text.clone(),
            MessageEntity::Bold(_) => self.bold(self.quote(editable_text)),
            MessageEntity::Italic(_) => self.italic(self.quote(editable_text)),
            MessageEntity::Underline(_) => self.underline(self.quote(editable_text)),
            MessageEntity::Strikethrough(_) => self.strikethrough(self.quote(editable_text)),
            MessageEntity::Spoiler(_) => self.spoiler(self.quote(editable_text)),
            MessageEntity::Blockquote(_) => self.blockquote(self.quote(editable_text)),
            MessageEntity::ExpandableBlockquote(_) => {
                self.expandable_blockquote(self.quote(editable_text))
            }
            MessageEntity::Code(_) => self.code(self.quote(editable_text)),
            MessageEntity::Pre(MessageEntityPre {
                language, ..
            }) => match language {
                Some(language) => self.pre_language(self.quote(editable_text), language),
                None => self.pre(self.quote(editable_text)),
            },
            MessageEntity::TextLink(MessageEntityTextLink {
                url, ..
            }) => self.text_link(self.quote(editable_text), url),
            MessageEntity::TextMention(MessageEntityTextMention {
                user, ..
            }) => self.text_mention(self.quote(editable_text), user.id),
            MessageEntity::CustomEmoji(MessageEntityCustomEmoji {
                custom_emoji_id, ..
            }) => self.custom_emoji(self.quote(editable_text), custom_emoji_id),
            MessageEntity::DateTime(MessageEntityDateTime {
                unix_time,
                date_time_format,
                ..
            }) => match date_time_format {
                Some(date_time_format) => self.date_time_with_format(
                    self.quote(editable_text),
                    *unix_time,
                    date_time_format,
                ),
                None => self.date_time(self.quote(editable_text), *unix_time),
            },
        };

        Ok(format!(
            "{}{edited_text}{}",
            self.quote(previous_text),
            self.quote(next_text)
        ))
    }
}

pub const FORMATTER: Formatter = Formatter::new();

#[inline]
pub fn bold(text: impl Display) -> String {
    FORMATTER.bold(text)
}

#[inline]
pub fn italic(text: impl Display) -> String {
    FORMATTER.italic(text)
}

#[inline]
pub fn underline(text: impl Display) -> String {
    FORMATTER.underline(text)
}

#[inline]
pub fn strikethrough(text: impl Display) -> String {
    FORMATTER.strikethrough(text)
}

#[inline]
pub fn spoiler(text: impl Display) -> String {
    FORMATTER.spoiler(text)
}

#[inline]
pub fn blockquote(text: impl Display) -> String {
    FORMATTER.blockquote(text)
}

#[inline]
pub fn expandable_blockquote(text: impl Display) -> String {
    FORMATTER.expandable_blockquote(text)
}

#[inline]
pub fn text_link(text: impl Display, url: impl Display) -> String {
    FORMATTER.text_link(text, url)
}

#[inline]
pub fn text_mention(text: impl Display, user_id: i64) -> String {
    FORMATTER.text_mention(text, user_id)
}

#[inline]
pub fn custom_emoji(text: impl Display, emoji_id: impl Display) -> String {
    FORMATTER.custom_emoji(text, emoji_id)
}

#[inline]
pub fn code(text: impl Display) -> String {
    FORMATTER.code(text)
}

#[inline]
pub fn pre(text: impl Display) -> String {
    FORMATTER.pre(text)
}

#[inline]
pub fn pre_language(text: impl Display, language: impl Display) -> String {
    FORMATTER.pre_language(text, language)
}

#[inline]
pub fn quote(text: impl Display) -> String {
    FORMATTER.quote(text)
}

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

    #[test]
    fn test_bold() {
        let formatter = Formatter::default();
        assert_eq!(formatter.bold("text"), "<b>text</b>");
    }

    #[test]
    fn test_italic() {
        let formatter = Formatter::default();
        assert_eq!(formatter.italic("text"), "<i>text</i>");
    }

    #[test]
    fn test_underline() {
        let formatter = Formatter::default();
        assert_eq!(formatter.underline("text"), "<u>text</u>");
    }

    #[test]
    fn test_strikethrough() {
        let formatter = Formatter::default();
        assert_eq!(formatter.strikethrough("text"), "<s>text</s>");
    }

    #[test]
    fn test_spoiler() {
        let formatter = Formatter::default();
        assert_eq!(formatter.spoiler("text"), "<tg-spoiler>text</tg-spoiler>");
    }

    #[test]
    fn test_blockquote() {
        let formatter = Formatter::default();
        assert_eq!(
            formatter.blockquote("text"),
            "<blockquote>text</blockquote>"
        );
    }

    #[test]
    fn test_expandable_blockquote() {
        let formatter = Formatter::default();
        assert_eq!(
            formatter.expandable_blockquote("text"),
            "<blockquote expandable>text</blockquote>"
        );
    }

    #[test]
    fn test_text_link() {
        let formatter = Formatter::default();
        assert_eq!(
            formatter.text_link("text", "http://example.com"),
            "<a href=\"http://example.com\">text</a>"
        );
    }

    #[test]
    fn test_text_mention() {
        let formatter = Formatter::default();
        assert_eq!(
            formatter.text_mention("text", 1),
            "<a href=\"tg://user?id=1\">text</a>"
        );
    }

    #[test]
    fn test_code() {
        let formatter = Formatter::default();
        assert_eq!(formatter.code("text"), "<code>text</code>");
    }

    #[test]
    fn test_pre() {
        let formatter = Formatter::default();
        assert_eq!(formatter.pre("text"), "<pre>text</pre>");
    }

    #[test]
    fn test_pre_language() {
        let formatter = Formatter::default();
        assert_eq!(
            formatter.pre_language("text", "python"),
            "<pre><code class=\"language-python\">text</code></pre>"
        );
    }

    #[test]
    fn test_custom_emoji() {
        let formatter = Formatter::default();
        assert_eq!(
            formatter.custom_emoji("text", "emoji_id"),
            "<tg-emoji emoji-id=\"emoji_id\">text</tg-emoji>"
        );
    }

    #[test]
    fn test_date_time() {
        let formatter = Formatter::default();
        assert_eq!(
            formatter.date_time("text", 1),
            "<tg-time unix=\"1\">text</tg-time>"
        );
        assert_eq!(
            formatter.date_time_with_format("text", 1, "test"),
            "<tg-time unix=\"1\" format=\"test\">text</tg-time>"
        );
    }

    #[test]
    fn test_quote() {
        let formatter = Formatter::default();
        assert_eq!(formatter.quote("text"), "text");
        assert_eq!(formatter.quote("<text>"), "&lt;text&gt;");
        assert_eq!(formatter.quote("&text"), "&amp;text");
    }

    #[test]
    fn test_apply_entity_keeps_auto_detected_entities_untouched() {
        use crate::types::{
            MessageEntityBotCommand, MessageEntityCashtag, MessageEntityHashtag,
            MessageEntityMention,
        };

        let formatter = Formatter::default();
        // Each entity span already includes its prefix char, so applying it must not add
        // a second one (no `@@user`, `##tag`, ...).
        let text = "@user #tag $CASH /cmd";
        for entity in [
            MessageEntity::Mention(MessageEntityMention::new(0, 5)),
            MessageEntity::Hashtag(MessageEntityHashtag::new(6, 4)),
            MessageEntity::Cashtag(MessageEntityCashtag::new(11, 5)),
            MessageEntity::BotCommand(MessageEntityBotCommand::new(17, 4)),
        ] {
            assert_eq!(formatter.apply_entity(text, &entity).unwrap(), text);
        }
    }

    #[test]
    fn formatting_methods_compose_without_escaping() {
        let formatter = Formatter::default();

        // Formatting methods wrap the text as is, so their results can be nested ("tag in
        // tag") and HTML entities pass through. Plain text is escaped explicitly with
        // `quote` instead.
        assert_eq!(formatter.italic(formatter.bold("0_0")), "<i><b>0_0</b></i>");
        assert_eq!(
            formatter.text_link("&#8203;&#8203;", "http://x"),
            "<a href=\"http://x\">&#8203;&#8203;</a>"
        );
        assert_eq!(
            formatter.bold(formatter.quote("a<b>&c")),
            "<b>a&lt;b&gt;&amp;c</b>"
        );
    }

    #[test]
    fn test_apply_entity_escapes_entity_span() {
        use crate::types::MessageEntityBold;

        let formatter = Formatter::default();

        // `apply_entity` receives plain text, so the entity span itself is escaped before
        // the formatting is applied.
        let entity = MessageEntity::Bold(MessageEntityBold::new(0, 3));
        assert_eq!(
            formatter.apply_entity("a<b", &entity).unwrap(),
            "<b>a&lt;b</b>"
        );
    }

    #[test]
    fn test_apply_entity_escapes_surrounding_text() {
        use crate::types::MessageEntityBold;

        let formatter = Formatter::default();

        // The literal text around the entity span must be escaped too, otherwise `<`/`>`/`&`
        // in it would break the HTML markup.
        let entity = MessageEntity::Bold(MessageEntityBold::new(0, 1));
        assert_eq!(
            formatter.apply_entity("a<b>&c", &entity).unwrap(),
            "<b>a</b>&lt;b&gt;&amp;c"
        );
    }

    #[test]
    fn apply_entity_bold_over_cyrillic_covers_whole_word() {
        use crate::types::MessageEntityBold;

        let formatter = Formatter::default();
        // "Привет" is 6 UTF-16 code units (and 6 chars) but 12 UTF-8 bytes. A byte-based slice would
        // bold only "При" and yield "<b>При</b>вет".
        let entity = MessageEntity::Bold(MessageEntityBold::new(0, 6));

        assert_eq!(
            formatter.apply_entity("Привет", &entity).unwrap(),
            "<b>Привет</b>"
        );
    }

    #[test]
    fn apply_entity_bold_after_emoji_uses_utf16_offsets() {
        use crate::types::MessageEntityBold;

        let formatter = Formatter::default();
        // "😀X": the emoji is a non-BMP scalar = 2 UTF-16 code units (4 UTF-8 bytes); "X" starts at
        // UTF-16 offset 2. A byte-based slice at offset 2 would land inside the emoji and panic.
        let entity = MessageEntity::Bold(MessageEntityBold::new(2, 1));

        assert_eq!(
            formatter.apply_entity("😀X", &entity).unwrap(),
            "😀<b>X</b>"
        );
    }
}