Skip to content
↑ ↓ move↵ openEvery page also as Markdown: add .md

Guide

Commands

Commands

A command is message text that starts with /; #[derive(BotCommands)] turns an enum into a parser, a filter, a help text and the bot’s command menu.

Example

use vaegram::prelude::*;

#[derive(BotCommands, Debug, PartialEq)]
enum Cmd {
    /// Start the bot
    Start(Option<String>),
    /// Ban a user, with an optional reason
    #[command(alias = "b")]
    Ban { user_id: i64, #[command(rest)] reason: Option<String> },
}

let ban = Cmd::parse("/ban@MyBot 42 spam bot", Some("mybot")).unwrap();
assert_eq!(ban, Cmd::Ban { user_id: 42, reason: Some("spam bot".into()) });

assert_eq!(Cmd::descriptions().to_string(), "/start - Start the bot\n/ban, /b - Ban a user, with an optional reason");

How it works

Reading a command from a message

Text like /ban@MyBot 42 spam is read as the name ban, the bot MyBot and the rest 42 spam:

if let Some(command) = msg.command() {
    let _name = command.name;
    let _first_argument = command.arg(0);
    let _everything_after = command.rest();
}

command() returns None for text that is no command, and for a command that names another bot once the client knows its own username. A name is 1 to 32 letters, digits or underscores. command_with("/!") accepts any character of the given set as the prefix, and command_with_prefixes(&[".", "!x"]) any of several strings.

Command filters

filters::command("start") matches /start and /start@this_bot, in any letter case. filters::command(["ban", "kick"]) takes several names. filters::command_with("/!", names) lets any character of the first argument start the command, and filters::command_case_sensitive(prefixes, names) requires the typed case.

There is no command_with_args: arguments are read from the Message with command(), never from the filter. The filter only decides whether the handler runs.

The enum

#[derive(BotCommands)] writes the BotCommands trait for the enum:

  • A variant’s command is its name in snake_case: SetAge is /set_age.
  • Doc comment lines become its description. Only the first paragraph is used.
  • #[command(alias = "b")] adds another name; rename = "name" replaces it.
  • With one field, all the text after the command goes into it. With several, the text splits on spaces, one word per field; a last field marked #[command(rest)] takes everything left. An Option field may be missing.
use vaegram::prelude::*;

#[derive(BotCommands, Debug)]
enum Cmd {
    /// Start the bot
    Start(Option<String>),
    /// Ban a user, with an optional reason
    #[command(alias = "b")]
    Ban { user_id: i64, #[command(rest)] reason: Option<String> },
    /// Show this help
    #[command(allow_extra)]
    Help,
}

app.set_bot_commands(Cmd::bot_commands()).await?;

app.on_message(Cmd::filter::<Message>(), |msg: Message| async move {
    match msg.parse_command::<Cmd>()? {
        Cmd::Start(_) => {
            msg.answer("Hello!").await?;
        }
        Cmd::Ban { user_id, .. } => {
            msg.answer(format!("banning {user_id}")).await?;
        }
        Cmd::Help => {
            msg.answer(Cmd::descriptions().to_string()).await?;
        }
    }
    Ok(())
});

Cmd::filter() builds the filter from the enum’s names and aliases, so an update that cannot be one of its commands is dropped before parsing. msg.parse_command::<Cmd>() parses and checks the @mention against this bot’s username.

Help text and the menu

Cmd::descriptions() prints one line per command: /name, /alias - description. #[command(description = "Commands:")] on the enum puts a header above the list, and hide leaves a command out of both the help text and the menu while still parsing it.

A command set built at run time implements BotCommands by hand: CommandDescription::owned(prefix, command, description) and CommandDescriptions::owned(commands) take owned strings, so the help text needn’t be 'static. The derive keeps its literals static, with no allocation.

Cmd::bot_commands() is the menu for set_bot_commands. Telegram refuses the whole menu over one bad entry, so a name in it must be lowercase letters, digits or underscores and a description 3 to 256 characters long; the derive checks that when it builds.

Errors

parse returns CommandParseError: NotACommand, UnknownCommand, WrongBot, TooFewArguments, TooManyArguments, InvalidArgument, and Custom for a parse_with parser. An argument that doesn’t parse names the field and its position, as in invalid argument 1: invalid digit found in string. The error converts into Error, so ? works in a handler that returns Result.

Common mistakes

  • Reading arguments in the filter: use msg.command() or parse_command after the handler runs.
  • Leaving out allow_extra on a command with no fields that users may add words to: extra words are TooManyArguments.
  • Naming a menu command in uppercase or giving it a two-letter description: the derive refuses to build.
  • Comparing command.name case-sensitively: filters match any case, so /START arrives with "START" and must be compared without case.
  • Expecting filter() to keep hidden commands out: hide only affects the help text and the menu, not parsing.

See also