teloxide/utils/command.rs
1//! Command parsers.
2//!
3//! You can either create an `enum` with derived [`BotCommands`], containing
4//! commands of your bot, or use functions, which split input text into a string
5//! command with its arguments.
6//!
7//! # Using BotCommands
8//!
9//! ```
10//! # #[cfg(feature = "macros")] {
11//! use teloxide::utils::command::BotCommands;
12//!
13//! type UnitOfTime = u8;
14//!
15//! #[derive(BotCommands, PartialEq, Debug)]
16//! #[command(rename_rule = "lowercase", parse_with = "split")]
17//! enum AdminCommand {
18//! Mute(UnitOfTime, char),
19//! Ban(UnitOfTime, char),
20//! }
21//!
22//! let command = AdminCommand::parse("/ban 5 h", "bot_name").unwrap();
23//! assert_eq!(command, AdminCommand::Ban(5, 'h'));
24//! # }
25//! ```
26//!
27//! # Using parse_command
28//!
29//! ```
30//! use teloxide::utils::command::parse_command;
31//!
32//! let (command, args) = parse_command("/ban@MyBotName 3 hours", "MyBotName").unwrap();
33//! assert_eq!(command, "ban");
34//! assert_eq!(args, vec!["3", "hours"]);
35//! ```
36//!
37//! # Using parse_command_with_prefix
38//!
39//! ```
40//! use teloxide::utils::command::parse_command_with_prefix;
41//!
42//! let text = "!ban 3 hours";
43//! let (command, args) = parse_command_with_prefix("!", text, "").unwrap();
44//! assert_eq!(command, "ban");
45//! assert_eq!(args, vec!["3", "hours"]);
46//! ```
47//!
48//! See [examples/admin] as a more complicated examples.
49//!
50//! [examples/admin]: https://github.com/teloxide/teloxide/blob/master/crates/teloxide/examples/admin.rs
51
52use core::fmt;
53use std::{
54 error::Error,
55 fmt::{Display, Formatter, Write},
56};
57
58use teloxide_core::types::{BotCommand, BotFullInfo};
59#[cfg(feature = "macros")]
60pub use teloxide_macros::BotCommands;
61
62/// An enumeration of bot's commands.
63///
64/// # Example
65/// ```
66/// # #[cfg(feature = "macros")] {
67/// use teloxide::utils::command::BotCommands;
68///
69/// type UnitOfTime = u8;
70///
71/// #[derive(BotCommands, PartialEq, Debug)]
72/// #[command(rename_rule = "lowercase", parse_with = "split")]
73/// enum AdminCommand {
74/// Mute(UnitOfTime, char),
75/// Ban(UnitOfTime, char),
76/// }
77///
78/// let command = AdminCommand::parse("/ban 5 h", "bot_name").unwrap();
79/// assert_eq!(command, AdminCommand::Ban(5, 'h'));
80/// # }
81/// ```
82///
83/// # Enum attributes
84/// 1. `#[command(rename_rule = "rule")]` Rename all commands by `rule`.
85/// Allowed rules are `lowercase`, `UPPERCASE`, `PascalCase`, `camelCase`,
86/// `snake_case`, `SCREAMING_SNAKE_CASE`, `kebab-case`, and
87/// `SCREAMING-KEBAB-CASE`.
88///
89/// 2. `#[command(prefix = "prefix")]` Change a prefix for all commands (the
90/// default is `/`).
91///
92/// 3. `#[command(description = "description")]` and `/// description` Add a
93/// summary description of commands before all commands.
94///
95/// 4. `#[command(parse_with = "parser")]` Change the parser of arguments.
96/// Possible values:
97/// - `default` - the same as the unspecified parser. It only puts all
98/// text after the first space into the first argument, which must
99/// implement [`FromStr`].
100///
101/// ## Example
102/// ```
103/// # #[cfg(feature = "macros")] {
104/// use teloxide::utils::command::BotCommands;
105///
106/// #[derive(BotCommands, PartialEq, Debug)]
107/// #[command(rename_rule = "lowercase")]
108/// enum Command {
109/// Text(String),
110/// }
111///
112/// let command = Command::parse("/text hello my dear friend!", "").unwrap();
113/// assert_eq!(command, Command::Text("hello my dear friend!".to_string()));
114/// # }
115/// ```
116///
117/// - `split` - separates a message by a given separator (the default is the
118/// space character) and parses each part into the corresponding arguments,
119/// which must implement [`FromStr`].
120///
121/// ## Example
122/// ```
123/// # #[cfg(feature = "macros")] {
124/// use teloxide::utils::command::BotCommands;
125///
126/// #[derive(BotCommands, PartialEq, Debug)]
127/// #[command(rename_rule = "lowercase", parse_with = "split")]
128/// enum Command {
129/// Nums(u8, u16, i32),
130/// }
131///
132/// let command = Command::parse("/nums 1 32 -5", "").unwrap();
133/// assert_eq!(command, Command::Nums(1, 32, -5));
134/// # }
135/// ```
136///
137/// 5. `#[command(separator = "sep")]` Specify separator used by the `split`
138/// parser. It will be ignored when accompanied by another type of parsers.
139///
140/// ## Example
141/// ```
142/// # #[cfg(feature = "macros")] {
143/// use teloxide::utils::command::BotCommands;
144///
145/// #[derive(BotCommands, PartialEq, Debug)]
146/// #[command(rename_rule = "lowercase", parse_with = "split", separator = "|")]
147/// enum Command {
148/// Nums(u8, u16, i32),
149/// }
150///
151/// let command = Command::parse("/nums 1|32|5", "").unwrap();
152/// assert_eq!(command, Command::Nums(1, 32, 5));
153/// # }
154/// ```
155///
156/// 6. `#[command(command_separator = "sep")]` Specify separator between command
157/// and args. Default is a space character.
158///
159/// ## Example
160/// ```
161/// # #[cfg(feature = "macros")] {
162/// use teloxide::utils::command::BotCommands;
163///
164/// #[derive(BotCommands, PartialEq, Debug)]
165/// #[command(
166/// rename_rule = "lowercase",
167/// parse_with = "split",
168/// separator = "_",
169/// command_separator = "_"
170/// )]
171/// enum Command {
172/// Nums(u8, u16, i32),
173/// }
174///
175/// let command = Command::parse("/nums_1_32_5", "").unwrap();
176/// assert_eq!(command, Command::Nums(1, 32, 5));
177/// # }
178/// ```
179///
180/// # Variant attributes
181/// All variant attributes override the corresponding `enum` attributes.
182///
183/// 1. `#[command(rename_rule = "rule")]` Rename one command by a rule. Allowed
184/// rules are `lowercase`, `UPPERCASE`, `PascalCase`, `camelCase`,
185/// `snake_case`, `SCREAMING_SNAKE_CASE`, `kebab-case`,
186/// `SCREAMING-KEBAB-CASE`.
187///
188/// 2. `#[command(rename = "name")]` Rename one command to `name` (literal
189/// renaming; do not confuse with `rename_rule`).
190///
191/// 3. `#[command(description = "description")]` and `/// description` Give
192/// your command a description. It will be shown in the help message.
193///
194/// 4. `#[command(parse_with = "parser")]` Parse arguments of one command with
195/// a given parser. `parser` must be a function of the signature `fn(String)
196/// -> Result<Tuple, ParseError>`, where `Tuple` corresponds to the
197/// variant's arguments.
198///
199/// 5. `#[command(hide)]` Hide a command from the help message. It will still
200/// be parsed.
201///
202/// 6. `#[command(alias = "alias")]` Add an alias to a command. It will be shown
203/// in the help message.
204///
205/// 7. `#[command(aliases = ["alias1", "alias2"])]` Add multiple aliases to a
206/// command. They will be shown in the help message.
207///
208/// 8. `#[command(hide_aliases)]` Hide all aliases of a command from the help
209/// message.
210///
211/// ## Example
212/// ```
213/// # #[cfg(feature = "macros")] {
214/// use teloxide::utils::command::{BotCommands, ParseError};
215///
216/// fn accept_two_digits(input: String) -> Result<(u8,), ParseError> {
217/// match input.len() {
218/// 2 => {
219/// let num = input.parse::<u8>().map_err(|e| ParseError::IncorrectFormat(e.into()))?;
220/// Ok((num,))
221/// }
222/// len => Err(ParseError::Custom(format!("Only 2 digits allowed, not {}", len).into())),
223/// }
224/// }
225///
226/// #[derive(BotCommands, PartialEq, Debug)]
227/// #[command(rename_rule = "lowercase")]
228/// enum Command {
229/// #[command(parse_with = accept_two_digits)]
230/// Num(u8),
231/// }
232///
233/// let command = Command::parse("/num 12", "").unwrap();
234/// assert_eq!(command, Command::Num(12));
235/// let command = Command::parse("/num 333", "");
236/// assert!(command.is_err());
237/// # }
238/// ```
239///
240/// 5. `#[command(prefix = "prefix")]`
241/// 6. `#[command(separator = "sep")]`
242///
243/// These attributes just override the corresponding `enum` attributes for a
244/// specific variant.
245///
246/// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
247/// [`BotCommands`]: crate::utils::command::BotCommands
248pub trait BotCommands: Sized {
249 /// Parses a command.
250 ///
251 /// `bot_username` is required to parse commands like
252 /// `/cmd@username_of_the_bot`.
253 fn parse(s: &str, bot_username: &str) -> Result<Self, ParseError>;
254
255 /// Returns descriptions of the commands suitable to be shown to the user
256 /// (for example when `/help` command is used).
257 fn descriptions() -> CommandDescriptions<'static>;
258
259 /// Returns a vector of [`BotCommand`] that can be used with
260 /// [`set_my_commands`].
261 ///
262 /// The derived implementation uses unprefixed names, omits hidden commands
263 /// and names outside `[a-z0-9_]{1,32}`, and does not register aliases.
264 /// Descriptions are trimmed and limited to 256 characters. If a description
265 /// has fewer than three characters, it uses the command name (or `Run NAME`
266 /// for names shorter than three characters). This does not affect parsing
267 /// or [`descriptions`](Self::descriptions). Telegram's command menu
268 /// sends commands with `/`, regardless of any custom parsing prefix.
269 ///
270 /// [`BotCommand`]: crate::types::BotCommand
271 /// [`set_my_commands`]: crate::requests::Requester::set_my_commands
272 fn bot_commands() -> Vec<BotCommand>;
273}
274
275pub type PrefixedBotCommand = String;
276pub type BotName = String;
277
278/// Errors returned from [`BotCommands::parse`].
279///
280/// [`BotCommands::parse`]: BotCommands::parse
281#[derive(Debug)]
282pub enum ParseError {
283 TooFewArguments {
284 expected: usize,
285 found: usize,
286 message: String,
287 },
288 TooManyArguments {
289 expected: usize,
290 found: usize,
291 message: String,
292 },
293
294 /// Redirected from [`FromStr::from_str`].
295 ///
296 /// [`FromStr::from_str`]: https://doc.rust-lang.org/std/str/trait.FromStr.html#tymethod.from_str
297 IncorrectFormat(Box<dyn Error + Send + Sync + 'static>),
298
299 UnknownCommand(PrefixedBotCommand),
300 WrongBotName(BotName),
301
302 /// A custom error which you can return from your custom parser.
303 Custom(Box<dyn Error + Send + Sync + 'static>),
304}
305
306/// Command descriptions that can be shown to the user (e.g. as a part of
307/// `/help` message)
308///
309/// Most of the time you don't need to create this struct yourself as it's
310/// returned from [`BotCommands::descriptions`].
311#[derive(Debug, Clone)]
312pub struct CommandDescriptions<'a> {
313 global_description: Option<&'a str>,
314 descriptions: &'a [CommandDescription<'a>],
315 bot_username: Option<&'a str>,
316}
317
318/// Description of a particular command, used in [`CommandDescriptions`].
319#[derive(Debug, Clone)]
320pub struct CommandDescription<'a> {
321 /// Prefix of the command, usually `/`.
322 pub prefix: &'a str,
323 /// The command itself, e.g. `start`.
324 pub command: &'a str,
325 /// The command aliases, e.g. `["help", "h"]`.
326 pub aliases: &'a [&'a str],
327 /// Human-readable description of the command.
328 pub description: &'a str,
329}
330
331impl<'a> CommandDescriptions<'a> {
332 /// Creates new [`CommandDescriptions`] from a list of command descriptions.
333 #[must_use]
334 pub const fn new(descriptions: &'a [CommandDescription<'a>]) -> Self {
335 Self { global_description: None, descriptions, bot_username: None }
336 }
337
338 /// Sets the global description of these commands.
339 #[must_use]
340 pub fn global_description(self, global_description: &'a str) -> Self {
341 Self { global_description: Some(global_description), ..self }
342 }
343
344 /// Sets the username of the bot.
345 ///
346 /// After this method is called, returned instance of
347 /// [`CommandDescriptions`] will append `@bot_username` to all commands.
348 /// This is useful in groups, to disambiguate commands for different bots.
349 ///
350 /// ## Examples
351 ///
352 /// ```
353 /// use teloxide::utils::command::{CommandDescription, CommandDescriptions};
354 ///
355 /// let descriptions = CommandDescriptions::new(&[
356 /// CommandDescription {
357 /// prefix: "/",
358 /// command: "start",
359 /// description: "start this bot",
360 /// aliases: &[],
361 /// },
362 /// CommandDescription {
363 /// prefix: "/",
364 /// command: "help",
365 /// description: "show this message",
366 /// aliases: &[],
367 /// },
368 /// ]);
369 ///
370 /// assert_eq!(descriptions.to_string(), "/start — start this bot\n/help — show this message");
371 /// assert_eq!(
372 /// descriptions.username("username_of_the_bot").to_string(),
373 /// "/start@username_of_the_bot — start this bot\n/help@username_of_the_bot — show this \
374 /// message"
375 /// );
376 /// ```
377 #[must_use]
378 pub fn username(self, bot_username: &'a str) -> Self {
379 Self { bot_username: Some(bot_username), ..self }
380 }
381
382 /// Sets the username of the bot.
383 ///
384 /// This is the same as [`username`], but uses value returned from `get_me`
385 /// method to get the username.
386 ///
387 /// [`username`]: self::CommandDescriptions::username
388 #[must_use]
389 pub fn username_from_me(self, me: &'a BotFullInfo) -> CommandDescriptions<'a> {
390 match me.username() {
391 Some(username) => self.username(username),
392 None => self,
393 }
394 }
395}
396
397/// Parses a string into a command with args.
398///
399/// This function is just a shortcut for calling [`parse_command_with_prefix`]
400/// with the default prefix `/`.
401///
402/// ## Example
403/// ```
404/// use teloxide::utils::command::parse_command;
405///
406/// let text = "/mute@my_admin_bot 5 hours";
407/// let (command, args) = parse_command(text, "my_admin_bot").unwrap();
408/// assert_eq!(command, "mute");
409/// assert_eq!(args, vec!["5", "hours"]);
410/// ```
411///
412/// If the name of a bot does not match, it will return `None`:
413/// ```
414/// use teloxide::utils::command::parse_command;
415///
416/// let result = parse_command("/ban@MyNameBot1 3 hours", "MyNameBot2");
417/// assert!(result.is_none());
418/// ```
419///
420/// [`parse_command_with_prefix`]:
421/// crate::utils::command::parse_command_with_prefix
422pub fn parse_command<N>(text: &str, bot_name: N) -> Option<(&str, Vec<&str>)>
423where
424 N: AsRef<str>,
425{
426 parse_command_with_prefix("/", text, bot_name)
427}
428
429/// Parses a string into a command with args (custom prefix).
430///
431/// `prefix`: symbols, which denote start of a command.
432///
433/// ## Example
434/// ```
435/// use teloxide::utils::command::parse_command_with_prefix;
436///
437/// let text = "!mute 5 hours";
438/// let (command, args) = parse_command_with_prefix("!", text, "").unwrap();
439/// assert_eq!(command, "mute");
440/// assert_eq!(args, vec!["5", "hours"]);
441/// ```
442///
443/// If the name of a bot does not match, it will return `None`:
444/// ```
445/// use teloxide::utils::command::parse_command_with_prefix;
446///
447/// let result = parse_command_with_prefix("!", "!ban@MyNameBot1 3 hours", "MyNameBot2");
448/// assert!(result.is_none());
449/// ```
450pub fn parse_command_with_prefix<'a, N>(
451 prefix: &str,
452 text: &'a str,
453 bot_name: N,
454) -> Option<(&'a str, Vec<&'a str>)>
455where
456 N: AsRef<str>,
457{
458 if !text.starts_with(prefix) {
459 return None;
460 }
461 let mut words = text.split_whitespace();
462 let mut split = words.next()?[prefix.len()..].split('@');
463 let command = split.next()?;
464 let bot = split.next();
465 match bot {
466 Some(name) if name.eq_ignore_ascii_case(bot_name.as_ref()) => {}
467 None => {}
468 _ => return None,
469 }
470 Some((command, words.collect()))
471}
472
473impl Display for ParseError {
474 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
475 match self {
476 ParseError::TooFewArguments { expected, found, message } => write!(
477 f,
478 "Too few arguments (expected {expected}, found {found}, message = '{message}')"
479 ),
480 ParseError::TooManyArguments { expected, found, message } => write!(
481 f,
482 "Too many arguments (expected {expected}, found {found}, message = '{message}')"
483 ),
484 ParseError::IncorrectFormat(e) => write!(f, "Incorrect format of command args: {e}"),
485 ParseError::UnknownCommand(e) => write!(f, "Unknown command: {e}"),
486 ParseError::WrongBotName(n) => write!(f, "Wrong bot name: {n}"),
487 ParseError::Custom(e) => write!(f, "{e}"),
488 }
489 }
490}
491
492impl std::error::Error for ParseError {}
493
494impl Display for CommandDescriptions<'_> {
495 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
496 if let Some(global_description) = self.global_description {
497 f.write_str(global_description)?;
498 f.write_str("\n\n")?;
499 }
500
501 let format_command = |command: &str, prefix: &str, formater: &mut fmt::Formatter<'_>| {
502 formater.write_str(prefix)?;
503 formater.write_str(command)?;
504 if let Some(username) = self.bot_username {
505 formater.write_char('@')?;
506 formater.write_str(username)?;
507 }
508 fmt::Result::Ok(())
509 };
510
511 let mut write = |&CommandDescription { prefix, command, aliases, description }, nls| {
512 if nls {
513 f.write_char('\n')?;
514 }
515
516 format_command(command, prefix, f)?;
517 for alias in aliases {
518 f.write_str(", ")?;
519 format_command(alias, prefix, f)?;
520 }
521
522 if !description.is_empty() {
523 f.write_str(" — ")?;
524 f.write_str(description)?;
525 }
526
527 fmt::Result::Ok(())
528 };
529
530 if let Some(descr) = self.descriptions.first() {
531 write(descr, false)?;
532 for descr in &self.descriptions[1..] {
533 write(descr, true)?;
534 }
535 }
536
537 Ok(())
538 }
539}
540
541// The rest of tests are integration due to problems with macro expansion in
542// unit tests.
543#[cfg(test)]
544mod tests {
545 use super::*;
546
547 #[cfg(feature = "macros")]
548 #[test]
549 fn derived_registration_uses_bot_api_names_and_descriptions() {
550 use crate as teloxide;
551
552 #[derive(BotCommands, Debug, PartialEq)]
553 #[command(rename_rule = "lowercase")]
554 enum Command {
555 #[command(prefix = "!", description = " Start here ", alias = "s")]
556 Start,
557 Help,
558 #[command(description = " ")]
559 A,
560 #[command(rename = "_1")]
561 Numeric,
562 #[command(hide)]
563 Hidden,
564 #[command(rename = "Not-Valid")]
565 Custom,
566 #[command(rename = "")]
567 Empty,
568 #[command(rename = "abcdefghijklmnopqrstuvwxyz0123456")]
569 Oversize,
570 }
571
572 assert_eq!(
573 Command::bot_commands(),
574 [
575 BotCommand::new("start", "Start here"),
576 BotCommand::new("help", "help"),
577 BotCommand::new("a", "Run a"),
578 BotCommand::new("_1", "Run _1"),
579 ]
580 );
581 assert_eq!(Command::parse("!start", "").unwrap(), Command::Start);
582 assert_eq!(Command::parse("/Not-Valid", "").unwrap(), Command::Custom);
583 }
584
585 #[test]
586 fn parse_command_with_args_() {
587 let data = "/command arg1 arg2";
588 let expected = Some(("command", vec!["arg1", "arg2"]));
589 let actual = parse_command(data, "");
590 assert_eq!(actual, expected)
591 }
592
593 #[test]
594 fn parse_command_with_args_without_args() {
595 let data = "/command";
596 let expected = Some(("command", vec![]));
597 let actual = parse_command(data, "");
598 assert_eq!(actual, expected)
599 }
600}