teloxide 0.11.0

An elegant Telegram bots framework for 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
//! Command parsers.
//!
//! You can either create an `enum` with derived [`BotCommands`], containing
//! commands of your bot, or use functions, which split input text into a string
//! command with its arguments.
//!
//! # Using BotCommands
//!
//! ```
//! # #[cfg(feature = "macros")] {
//! use teloxide::utils::command::BotCommands;
//!
//! type UnitOfTime = u8;
//!
//! #[derive(BotCommands, PartialEq, Debug)]
//! #[command(rename_rule = "lowercase", parse_with = "split")]
//! enum AdminCommand {
//!     Mute(UnitOfTime, char),
//!     Ban(UnitOfTime, char),
//! }
//!
//! let command = AdminCommand::parse("/ban 5 h", "bot_name").unwrap();
//! assert_eq!(command, AdminCommand::Ban(5, 'h'));
//! # }
//! ```
//!
//! # Using parse_command
//!
//! ```
//! use teloxide::utils::command::parse_command;
//!
//! let (command, args) = parse_command("/ban@MyBotName 3 hours", "MyBotName").unwrap();
//! assert_eq!(command, "ban");
//! assert_eq!(args, vec!["3", "hours"]);
//! ```
//!
//! # Using parse_command_with_prefix
//!
//! ```
//! use teloxide::utils::command::parse_command_with_prefix;
//!
//! let text = "!ban 3 hours";
//! let (command, args) = parse_command_with_prefix("!", text, "").unwrap();
//! assert_eq!(command, "ban");
//! assert_eq!(args, vec!["3", "hours"]);
//! ```
//!
//! See [examples/admin_bot] as a more complicated examples.
//!
//! [examples/admin_bot]: https://github.com/teloxide/teloxide/blob/master/examples/admin_bot/

use core::fmt;
use std::{
    error::Error,
    fmt::{Display, Formatter, Write},
};

use std::marker::PhantomData;
use teloxide_core::types::{BotCommand, Me};
#[cfg(feature = "macros")]
pub use teloxide_macros::BotCommands;

/// An enumeration of bot's commands.
///
/// # Example
/// ```
/// # #[cfg(feature = "macros")] {
/// use teloxide::utils::command::BotCommands;
///
/// type UnitOfTime = u8;
///
/// #[derive(BotCommands, PartialEq, Debug)]
/// #[command(rename_rule = "lowercase", parse_with = "split")]
/// enum AdminCommand {
///     Mute(UnitOfTime, char),
///     Ban(UnitOfTime, char),
/// }
///
/// let command = AdminCommand::parse("/ban 5 h", "bot_name").unwrap();
/// assert_eq!(command, AdminCommand::Ban(5, 'h'));
/// # }
/// ```
///
/// # Enum attributes
///  1. `#[command(rename_rule = "rule")]`
/// Rename all commands by `rule`. Allowed rules are `lowercase`, `UPPERCASE`,
/// `PascalCase`, `camelCase`, `snake_case`, `SCREAMING_SNAKE_CASE`,
/// `kebab-case`, and `SCREAMING-KEBAB-CASE`.
///
///  2. `#[command(prefix = "prefix")]`
/// Change a prefix for all commands (the default is `/`).
///
///  3. `#[command(description = "description")]`
/// Add a sumary description of commands before all commands.
///
///  4. `#[command(parse_with = "parser")]`
/// Change the parser of arguments. Possible values:
///    - `default` - the same as the unspecified parser. It only puts all text
///    after the first space into the first argument, which must implement
///    [`FromStr`].
///
/// ## Example
/// ```
/// # #[cfg(feature = "macros")] {
/// use teloxide::utils::command::BotCommands;
///
/// #[derive(BotCommands, PartialEq, Debug)]
/// #[command(rename_rule = "lowercase")]
/// enum Command {
///     Text(String),
/// }
///
/// let command = Command::parse("/text hello my dear friend!", "").unwrap();
/// assert_eq!(command, Command::Text("hello my dear friend!".to_string()));
/// # }
/// ```
///
///  - `split` - separates a messsage by a given separator (the default is the
///    space character) and parses each part into the corresponding arguments,
///    which must implement [`FromStr`].
///
/// ## Example
/// ```
/// # #[cfg(feature = "macros")] {
/// use teloxide::utils::command::BotCommands;
///
/// #[derive(BotCommands, PartialEq, Debug)]
/// #[command(rename_rule = "lowercase", parse_with = "split")]
/// enum Command {
///     Nums(u8, u16, i32),
/// }
///
/// let command = Command::parse("/nums 1 32 -5", "").unwrap();
/// assert_eq!(command, Command::Nums(1, 32, -5));
/// # }
/// ```
///
/// 5. `#[command(separator = "sep")]`
/// Specify separator used by the `split` parser. It will be ignored when
/// accompanied by another type of parsers.
///
/// ## Example
/// ```
/// # #[cfg(feature = "macros")] {
/// use teloxide::utils::command::BotCommands;
///
/// #[derive(BotCommands, PartialEq, Debug)]
/// #[command(rename_rule = "lowercase", parse_with = "split", separator = "|")]
/// enum Command {
///     Nums(u8, u16, i32),
/// }
///
/// let command = Command::parse("/nums 1|32|5", "").unwrap();
/// assert_eq!(command, Command::Nums(1, 32, 5));
/// # }
/// ```
///
/// # Variant attributes
/// All variant attributes override the corresponding `enum` attributes.
///
///  1. `#[command(rename_rule = "rule")]`
/// Rename one command by a rule. Allowed rules are `lowercase`, `UPPERCASE`,
/// `PascalCase`, `camelCase`, `snake_case`, `SCREAMING_SNAKE_CASE`,
/// `kebab-case`, `SCREAMING-KEBAB-CASE`.
///
///  2. `#[command(rename = "name")]`
/// Rename one command to `name` (literal renaming; do not confuse with
/// `rename_rule`).
///
///  3. `#[command(description = "description")]`
/// Give your command a description. Write `"off"` for `"description"` to hide a
/// command.
///
///  4. `#[command(parse_with = "parser")]`
/// Parse arguments of one command with a given parser. `parser` must be a
/// function of the signature `fn(String) -> Result<Tuple, ParseError>`, where
/// `Tuple` corresponds to the variant's arguments.
///
/// ## Example
/// ```
/// # #[cfg(feature = "macros")] {
/// use teloxide::utils::command::{BotCommands, ParseError};
///
/// fn accept_two_digits(input: String) -> Result<(u8,), ParseError> {
///     match input.len() {
///         2 => {
///             let num = input.parse::<u8>().map_err(|e| ParseError::IncorrectFormat(e.into()))?;
///             Ok((num,))
///         }
///         len => Err(ParseError::Custom(format!("Only 2 digits allowed, not {}", len).into())),
///     }
/// }
///
/// #[derive(BotCommands, PartialEq, Debug)]
/// #[command(rename_rule = "lowercase")]
/// enum Command {
///     #[command(parse_with = accept_two_digits)]
///     Num(u8),
/// }
///
/// let command = Command::parse("/num 12", "").unwrap();
/// assert_eq!(command, Command::Num(12));
/// let command = Command::parse("/num 333", "");
/// assert!(command.is_err());
/// # }
/// ```
///
///  5. `#[command(prefix = "prefix")]`
///  6. `#[command(separator = "sep")]`
///
/// These attributes just override the corresponding `enum` attributes for a
/// specific variant.
///
/// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
/// [`BotCommands`]: crate::utils::command::BotCommands
pub trait BotCommands: Sized {
    /// Parses a command.
    ///
    /// `bot_username` is required to parse commands like
    /// `/cmd@username_of_the_bot`.
    fn parse(s: &str, bot_username: &str) -> Result<Self, ParseError>;

    /// Returns descriptions of the commands suitable to be shown to the user
    /// (for example when `/help` command is used).
    fn descriptions() -> CommandDescriptions<'static>;

    /// Returns a vector of [`BotCommand`] that can be used with
    /// [`set_my_commands`].
    ///
    /// [`BotCommand`]: crate::types::BotCommand
    /// [`set_my_commands`]: crate::requests::Requester::set_my_commands
    fn bot_commands() -> Vec<BotCommand>;

    /// Returns `PhantomData<Self>` that is used as a param of [`commands_repl`]
    ///
    /// [`commands_repl`]: (crate::repls2::commands_repl)
    #[must_use]
    fn ty() -> PhantomData<Self> {
        PhantomData
    }
}

pub type PrefixedBotCommand = String;
pub type BotName = String;

/// Errors returned from [`BotCommands::parse`].
///
/// [`BotCommands::parse`]: BotCommands::parse
#[derive(Debug)]
pub enum ParseError {
    TooFewArguments {
        expected: usize,
        found: usize,
        message: String,
    },
    TooManyArguments {
        expected: usize,
        found: usize,
        message: String,
    },

    /// Redirected from [`FromStr::from_str`].
    ///
    /// [`FromStr::from_str`]: https://doc.rust-lang.org/std/str/trait.FromStr.html#tymethod.from_str
    IncorrectFormat(Box<dyn Error + Send + Sync + 'static>),

    UnknownCommand(PrefixedBotCommand),
    WrongBotName(BotName),

    /// A custom error which you can return from your custom parser.
    Custom(Box<dyn Error + Send + Sync + 'static>),
}

/// Command descriptions that can be shown to the user (e.g. as a part of
/// `/help` message)
///
/// Most of the time you don't need to create this struct yourself as it's
/// returned from [`BotCommands::descriptions`].
#[derive(Debug, Clone)]
pub struct CommandDescriptions<'a> {
    global_description: Option<&'a str>,
    descriptions: &'a [CommandDescription<'a>],
    bot_username: Option<&'a str>,
}

/// Description of a particular command, used in [`CommandDescriptions`].
#[derive(Debug, Clone)]
pub struct CommandDescription<'a> {
    /// Prefix of the command, usually `/`.
    pub prefix: &'a str,
    /// The command itself, e.g. `start`.
    pub command: &'a str,
    /// Human-readable description of the command.
    pub description: &'a str,
}

impl<'a> CommandDescriptions<'a> {
    /// Creates new [`CommandDescriptions`] from a list of command descriptions.
    #[must_use]
    pub fn new(descriptions: &'a [CommandDescription<'a>]) -> Self {
        Self { global_description: None, descriptions, bot_username: None }
    }

    /// Sets the global description of these commands.
    #[must_use]
    pub fn global_description(self, global_description: &'a str) -> Self {
        Self { global_description: Some(global_description), ..self }
    }

    /// Sets the username of the bot.
    ///
    /// After this method is called, returned instance of
    /// [`CommandDescriptions`] will append `@bot_username` to all commands.
    /// This is useful in groups, to disambiguate commands for different bots.
    ///
    /// ## Examples
    ///
    /// ```
    /// use teloxide::utils::command::{CommandDescription, CommandDescriptions};
    ///
    /// let descriptions = CommandDescriptions::new(&[
    ///     CommandDescription { prefix: "/", command: "start", description: "start this bot" },
    ///     CommandDescription { prefix: "/", command: "help", description: "show this message" },
    /// ]);
    ///
    /// assert_eq!(descriptions.to_string(), "/start — start this bot\n/help — show this message");
    /// assert_eq!(
    ///     descriptions.username("username_of_the_bot").to_string(),
    ///     "/start@username_of_the_bot — start this bot\n/help@username_of_the_bot — show this \
    ///      message"
    /// );
    /// ```
    #[must_use]
    pub fn username(self, bot_username: &'a str) -> Self {
        Self { bot_username: Some(bot_username), ..self }
    }

    /// Sets the username of the bot.
    ///
    /// This is the same as [`username`], but uses value returned from `get_me`
    /// method to get the username.
    ///
    /// [`username`]: self::CommandDescriptions::username
    #[must_use]
    pub fn username_from_me(self, me: &'a Me) -> CommandDescriptions<'a> {
        self.username(me.user.username.as_deref().expect("Bots must have usernames"))
    }
}

/// Parses a string into a command with args.
///
/// This function is just a shortcut for calling [`parse_command_with_prefix`]
/// with the default prefix `/`.
///
/// ## Example
/// ```
/// use teloxide::utils::command::parse_command;
///
/// let text = "/mute@my_admin_bot 5 hours";
/// let (command, args) = parse_command(text, "my_admin_bot").unwrap();
/// assert_eq!(command, "mute");
/// assert_eq!(args, vec!["5", "hours"]);
/// ```
///
/// If the name of a bot does not match, it will return `None`:
/// ```
/// use teloxide::utils::command::parse_command;
///
/// let result = parse_command("/ban@MyNameBot1 3 hours", "MyNameBot2");
/// assert!(result.is_none());
/// ```
///
/// [`parse_command_with_prefix`]:
/// crate::utils::command::parse_command_with_prefix
pub fn parse_command<N>(text: &str, bot_name: N) -> Option<(&str, Vec<&str>)>
where
    N: AsRef<str>,
{
    parse_command_with_prefix("/", text, bot_name)
}

/// Parses a string into a command with args (custom prefix).
///
/// `prefix`: symbols, which denote start of a command.
///
/// ## Example
/// ```
/// use teloxide::utils::command::parse_command_with_prefix;
///
/// let text = "!mute 5 hours";
/// let (command, args) = parse_command_with_prefix("!", text, "").unwrap();
/// assert_eq!(command, "mute");
/// assert_eq!(args, vec!["5", "hours"]);
/// ```
///
/// If the name of a bot does not match, it will return `None`:
/// ```
/// use teloxide::utils::command::parse_command_with_prefix;
///
/// let result = parse_command_with_prefix("!", "!ban@MyNameBot1 3 hours", "MyNameBot2");
/// assert!(result.is_none());
/// ```
pub fn parse_command_with_prefix<'a, N>(
    prefix: &str,
    text: &'a str,
    bot_name: N,
) -> Option<(&'a str, Vec<&'a str>)>
where
    N: AsRef<str>,
{
    if !text.starts_with(prefix) {
        return None;
    }
    let mut words = text.split_whitespace();
    let mut splited = words.next()?[prefix.len()..].split('@');
    let command = splited.next()?;
    let bot = splited.next();
    match bot {
        Some(name) if name.eq_ignore_ascii_case(bot_name.as_ref()) => {}
        None => {}
        _ => return None,
    }
    Some((command, words.collect()))
}

impl Display for ParseError {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        match self {
            ParseError::TooFewArguments { expected, found, message } => write!(
                f,
                "Too few arguments (expected {}, found {}, message = '{}')",
                expected, found, message
            ),
            ParseError::TooManyArguments { expected, found, message } => write!(
                f,
                "Too many arguments (expected {}, found {}, message = '{}')",
                expected, found, message
            ),
            ParseError::IncorrectFormat(e) => write!(f, "Incorrect format of command args: {}", e),
            ParseError::UnknownCommand(e) => write!(f, "Unknown command: {}", e),
            ParseError::WrongBotName(n) => write!(f, "Wrong bot name: {}", n),
            ParseError::Custom(e) => write!(f, "{}", e),
        }
    }
}

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

impl Display for CommandDescriptions<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(global_description) = self.global_description {
            f.write_str(global_description)?;
            f.write_str("\n\n")?;
        }

        let mut write = |&CommandDescription { prefix, command, description }, nls| {
            if nls {
                f.write_char('\n')?;
            }

            f.write_str(prefix)?;
            f.write_str(command)?;

            if let Some(username) = self.bot_username {
                f.write_char('@')?;
                f.write_str(username)?;
            }

            if !description.is_empty() {
                f.write_str("")?;
                f.write_str(description)?;
            }

            fmt::Result::Ok(())
        };

        if let Some(descr) = self.descriptions.first() {
            write(descr, false)?;
            for descr in &self.descriptions[1..] {
                write(descr, true)?;
            }
        }

        Ok(())
    }
}

// The rest of tests are integrational due to problems with macro expansion in
// unit tests.
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_command_with_args_() {
        let data = "/command arg1 arg2";
        let expected = Some(("command", vec!["arg1", "arg2"]));
        let actual = parse_command(data, "");
        assert_eq!(actual, expected)
    }

    #[test]
    fn parse_command_with_args_without_args() {
        let data = "/command";
        let expected = Some(("command", vec![]));
        let actual = parse_command(data, "");
        assert_eq!(actual, expected)
    }
}