telers 1.0.0-beta.7

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
use std::fmt::Display;

use crate::types::MessageEntity;

#[derive(Debug, thiserror::Error)]
pub enum ErrorKind {
    #[error("The text is empty")]
    EmptyText,
    #[error("Index out of bounds")]
    IndexOutOfBounds,
}

/// Splits `text` into the `(before, inside, after)` parts delimited by a Telegram
/// [`MessageEntity`]'s `offset`/`length`.
///
/// Telegram entity offsets and lengths are measured in **UTF-16 code units** (not bytes or
/// `char`s), so the text is decoded to UTF-16, sliced in that domain, and re-encoded.
///
/// # Errors
/// Returns [`ErrorKind::IndexOutOfBounds`] if the offset/length are negative, their sum overflows,
/// they extend past the end of `text`, or a boundary splits a surrogate pair. It never panics, even
/// on attacker-controlled entities.
pub(crate) fn split_by_entity(
    text: &str,
    entity: &MessageEntity,
) -> Result<(String, String, String), ErrorKind> {
    let offset = usize::try_from(entity.offset()).map_err(|_| ErrorKind::IndexOutOfBounds)?;
    let length = usize::try_from(entity.length()).map_err(|_| ErrorKind::IndexOutOfBounds)?;
    let end = offset
        .checked_add(length)
        .ok_or(ErrorKind::IndexOutOfBounds)?;

    let units: Vec<u16> = text.encode_utf16().collect();
    if end > units.len() {
        return Err(ErrorKind::IndexOutOfBounds);
    }

    let decode = |slice: &[u16]| String::from_utf16(slice).map_err(|_| ErrorKind::IndexOutOfBounds);

    Ok((
        decode(&units[..offset])?,
        decode(&units[offset..end])?,
        decode(&units[end..])?,
    ))
}

/// The Bot API supports basic formatting for messages. You can use bold, italic, underlined, strikethrough, and spoiler text, as well as inline links and pre-formatted code in your bots' messages. Telegram clients will render them accordingly. You can specify text entities directly, or use markdown-style or HTML-style formatting.
///
/// Note that Telegram clients will display an **alert** to the user before opening an inline link ('Open this link?' together with the full URL).
///
/// Message entities can be nested, providing following restrictions are met:
/// - If two entities have common characters, then one of them is fully contained inside another.
/// - `bold`, `italic`, `underline`, `strikethrough`, and spoiler entities can contain and can be part of any other entities, except `pre` and `code`.
/// - All other entities can't contain each other.
///
/// Links `tg://user?id=<user_id>` can be used to mention a user by their ID without using a username. Please note:
/// - These links will work **only** if they are used inside an inline link or in an inline keyboard button. For example, they will not work, when used in a message text.
/// - Unless the user is a member in the chat where they were mentioned, these mentions are only guaranteed to work if the user has contacted the bot in private in the past or has sent a callback query to the bot via an inline button and doesn't have Forwarded Messages privacy enabled for the bot.
///
/// # Escaping
///
/// The formatting methods escape the given text for the target parse mode, so any user-provided
/// content can be passed to them safely: special characters can't break out of the markup.
/// `code`/`pre` and link URLs use the smaller escape sets those positions require.
///
/// # Examples
/// ```rust
/// use telers::utils::text::{Formatter as _, MarkdownFormatter};
///
/// let formatter = MarkdownFormatter::default();
///
/// // `_` is special in MarkdownV2, so it is escaped inside the formatted span
/// assert_eq!(formatter.bold("hello_world"), "*hello\\_world*");
/// assert_eq!(
///     formatter.text_link("docs", "https://core.telegram.org/bots/api"),
///     "[docs](https://core.telegram.org/bots/api)"
/// );
/// ```
pub trait Formatter {
    #[must_use]
    fn bold<T>(&self, text: T) -> String
    where
        T: Display;

    #[must_use]
    fn italic<T>(&self, text: T) -> String
    where
        T: Display;

    #[must_use]
    fn code<C>(&self, code: C) -> String
    where
        C: Display;

    #[must_use]
    fn underline<T>(&self, text: T) -> String
    where
        T: Display;

    #[must_use]
    fn strikethrough<T>(&self, text: T) -> String
    where
        T: Display;

    #[must_use]
    fn spoiler<T>(&self, text: T) -> String
    where
        T: Display;

    #[must_use]
    fn blockquote<T>(&self, text: T) -> String
    where
        T: Display;

    #[must_use]
    fn expandable_blockquote<T>(&self, text: T) -> String
    where
        T: Display;

    #[must_use]
    fn text_link<T, U>(&self, text: T, url: U) -> String
    where
        T: Display,
        U: Display;

    #[must_use]
    fn text_mention<T>(&self, text: T, user_id: i64) -> String
    where
        T: Display;

    #[must_use]
    fn custom_emoji<T, E>(&self, emoji: T, emoji_id: E) -> String
    where
        T: Display,
        E: Display;

    #[must_use]
    fn pre<C>(&self, code: C) -> String
    where
        C: Display;

    #[must_use]
    fn pre_language<C, L>(&self, code: C, language: L) -> String
    where
        C: Display,
        L: Display;

    #[must_use]
    fn date_time<T>(&self, text: T, unix_time: i64) -> String
    where
        T: Display;

    #[must_use]
    fn date_time_with_format<T, F>(&self, text: T, unix_time: i64, date_time_format: F) -> String
    where
        T: Display,
        F: Display;

    #[must_use]
    fn quote<T>(&self, text: T) -> String
    where
        T: Display;

    /// Apply the [`MessageEntity`] to the given text with offset and length.
    /// # Errors
    /// - If the given text is empty, then the [`ErrorKind::EmptyText`] will be returned.
    /// - If the given entity offset+length is out of bounds, then the [`ErrorKind::IndexOutOfBounds`] will be returned.
    fn apply_entity<T>(&self, text: T, entity: &MessageEntity) -> Result<String, ErrorKind>
    where
        T: Display;
}

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

    struct TestFormatter;

    impl Formatter for TestFormatter {
        fn bold<T>(&self, text: T) -> String
        where
            T: Display,
        {
            format!("**{text}**")
        }

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

            if text_len == 0 {
                return Err(ErrorKind::EmptyText);
            }

            let offset = entity.offset() as usize;
            let length = entity.length() as usize;

            if offset + length > text_len {
                return Err(ErrorKind::IndexOutOfBounds);
            }

            let editable_text = &text[offset..offset + length];

            if let MessageEntity::Bold(_) = entity {
            } else {
                unimplemented!();
            }

            let edited_text = self.bold(editable_text);

            let mut text = text.to_owned();
            text.replace_range(offset..offset + length, &edited_text);

            Ok(text)
        }

        fn italic<T>(&self, _text: T) -> String
        where
            T: Display,
        {
            todo!()
        }

        fn code<C>(&self, _code: C) -> String
        where
            C: Display,
        {
            todo!()
        }

        fn underline<T>(&self, _text: T) -> String
        where
            T: Display,
        {
            todo!()
        }

        fn strikethrough<T>(&self, _text: T) -> String
        where
            T: Display,
        {
            todo!()
        }

        fn spoiler<T>(&self, _text: T) -> String
        where
            T: Display,
        {
            todo!()
        }

        fn blockquote<T>(&self, _text: T) -> String
        where
            T: Display,
        {
            todo!()
        }

        fn expandable_blockquote<T>(&self, _text: T) -> String
        where
            T: Display,
        {
            todo!()
        }

        fn text_link<T, U>(&self, _text: T, _url: U) -> String
        where
            T: Display,
            U: Display,
        {
            todo!()
        }

        fn text_mention<T>(&self, _text: T, _user_id: i64) -> String
        where
            T: Display,
        {
            todo!()
        }

        fn custom_emoji<T, E>(&self, _emoji: T, _emoji_id: E) -> String
        where
            T: Display,
            E: Display,
        {
            todo!()
        }

        fn pre<C>(&self, _code: C) -> String
        where
            C: Display,
        {
            todo!()
        }

        fn pre_language<C, L>(&self, _code: C, _language: L) -> String
        where
            C: Display,
            L: Display,
        {
            todo!()
        }

        fn date_time<T>(&self, _text: T, _unix_time: i64) -> String
        where
            T: Display,
        {
            todo!()
        }

        fn date_time_with_format<T, F>(
            &self,
            _text: T,
            _unix_time: i64,
            _date_time_format: F,
        ) -> String
        where
            T: Display,
            F: Display,
        {
            todo!()
        }

        fn quote<T>(&self, _text: T) -> String
        where
            T: Display,
        {
            todo!()
        }
    }

    #[test]
    fn test_apply_entity() {
        let formatter = TestFormatter;
        let text = "Hello, world!";

        let entity = MessageEntity::Bold(MessageEntityBold::new(0, 5));

        assert_eq!(
            formatter.apply_entity(text, &entity).unwrap(),
            "**Hello**, world!"
        );

        let entity = MessageEntity::Bold(MessageEntityBold::new(7, 5));

        assert_eq!(
            formatter.apply_entity(text, &entity).unwrap(),
            "Hello, **world**!"
        );

        let entity = MessageEntity::Bold(MessageEntityBold::new(0, text.len() as i64));

        assert_eq!(
            formatter.apply_entity(text, &entity).unwrap(),
            "**Hello, world!**"
        );
    }

    #[test]
    #[should_panic]
    fn test_apply_entity_panic() {
        let formatter = TestFormatter;
        let text = "Hello, world!";
        let entity = MessageEntity::Bold(MessageEntityBold::new(0, 15));

        formatter.apply_entity(text, &entity).unwrap();

        let entity = MessageEntity::Bold(MessageEntityBold::new(7, 9));

        formatter.apply_entity(text, &entity).unwrap();

        let entity = MessageEntity::Bold(MessageEntityBold::new(0, text.len() as i64 + 1));

        formatter.apply_entity(text, &entity).unwrap();

        let text = "";

        formatter.apply_entity(text, &entity).unwrap();
    }

    #[test]
    fn split_by_entity_uses_utf16_and_rejects_invalid_offsets() {
        // "a😀b": 'a' = unit 0, '😀' = units 1..3 (a surrogate pair), 'b' = unit 3 — 4 units total.
        let text = "a😀b";

        // Bolding "b" at UTF-16 offset 3, length 1 splits into ("a😀", "b", "").
        let entity = MessageEntity::Bold(MessageEntityBold::new(3, 1));
        assert_eq!(
            split_by_entity(text, &entity).unwrap(),
            ("a😀".to_owned(), "b".to_owned(), String::new())
        );

        // A negative offset returns an error instead of panicking on `usize::try_from`.
        let entity = MessageEntity::Bold(MessageEntityBold::new(-1, 1));
        assert!(matches!(
            split_by_entity(text, &entity),
            Err(ErrorKind::IndexOutOfBounds)
        ));

        // `offset + length` past the end (the text is 4 UTF-16 units) returns an error.
        let entity = MessageEntity::Bold(MessageEntityBold::new(0, 10));
        assert!(matches!(
            split_by_entity(text, &entity),
            Err(ErrorKind::IndexOutOfBounds)
        ));

        // An offset that falls between the surrogate halves of '😀' (unit 2) splits the pair, which
        // `String::from_utf16` rejects — so we return an error instead of producing garbage.
        let entity = MessageEntity::Bold(MessageEntityBold::new(2, 1));
        assert!(matches!(
            split_by_entity(text, &entity),
            Err(ErrorKind::IndexOutOfBounds)
        ));
    }
}