Macro teloxide::handler

source ·
macro_rules! handler {
    ($($variant:ident)::+) => { ... };
    ($($variant:ident)::+ ($param:ident)) => { ... };
    ($($variant:ident)::+ ($($param:ident),+ $(,)?)) => { ... };
    ($($variant:ident)::+ {$param:ident}) => { ... };
    ($($variant:ident)::+ {$($param:ident),+ $(,)?}) => { ... };
}
Expand description

Filters an enumeration, passing its payload forwards.

This macro expands to a crate::Handler that acts on your enumeration type: if the enumeration is of a certain variant, the execution continues; otherwise, dptree will try the next branch. This is very useful for dialogue FSM transitions and incoming command filtering; for a real-world example, please see teloxide’s examples/purchase.rs.

Variants can take the following forms:

  • Enum::MyVariant for empty variants;
  • Enum::MyVariant(param1, ..., paramN) for function-like variants;
  • Enum::MyVariant { param1, ..., paramN } for struct-like variants.

In the first case, this macro results in a simple crate::filter; in the second and third cases, this macro results in crate::filter_map that passes the payload of MyVariant to the next handler if the match occurs. (This next handler can be an endpoint or a more complex one.) The payload format depend on the form of MyVariant:

  • For Enum::MyVariant(param) and Enum::MyVariant { param }, the payload is param.
  • For Enum::MyVariant(param,) and Enum::MyVariant { param, }, the payload is (param,).
  • For Enum::MyVariant(param1, ..., paramN) and Enum::MyVariant { param1, ..., paramN }, the payload is (param1, ..., paramN) (where N>1).

Dependency requirements

  • Your enumeration Enum.

Examples

use dptree::prelude::*;

#[derive(Clone)]
enum Command {
    Meow,
    Add(i32, i32),
}

let h: crate::Handler<_, _> = dptree::entry()
    .branch(dptree::case![Command::Meow].endpoint(|| async move { format!("Meow!") }))
    .branch(
        dptree::case![Command::Add(x, y)]
            .endpoint(|(x, y): (i32, i32)| async move { format!("{}", x + y) }),
    );

assert_eq!(
    h.dispatch(dptree::deps![Command::Meow]).await,
    ControlFlow::Break("Meow!".to_owned())
);
assert_eq!(
    h.dispatch(dptree::deps![Command::Add(1, 2)]).await,
    ControlFlow::Break("3".to_owned())
);