Show strongly typed behaviour in examples/simple_commands_bot

This commit is contained in:
Temirkhan Myrzamadi 2020-07-07 01:20:09 +06:00
parent 9442ee5a7f
commit 31ac9bd984
2 changed files with 17 additions and 13 deletions

View file

@ -10,6 +10,5 @@ edition = "2018"
log = "0.4.8"
futures = "0.3.4"
tokio = "0.2.9"
rand = "0.7.3"
pretty_env_logger = "0.4.0"
teloxide = { path = "../../" }

View file

@ -1,20 +1,17 @@
use teloxide::{prelude::*, utils::command::BotCommand};
use rand::{thread_rng, Rng};
#[derive(BotCommand)]
#[command(rename = "lowercase", description = "These commands are supported:")]
enum Command {
#[command(description = "display this text.")]
Help,
#[command(description = "be a cat.")]
Meow,
#[command(description = "generate a random number within [0; 1).")]
Generate,
}
fn generate() -> String {
thread_rng().gen_range(0.0, 1.0).to_string()
#[command(description = "handle a username.")]
Username(String),
#[command(
description = "handle a username and an age.",
parse_with = "split"
)]
UsernameAndAge { username: String, age: u8 },
}
async fn answer(
@ -23,8 +20,16 @@ async fn answer(
) -> ResponseResult<()> {
match command {
Command::Help => cx.answer(Command::descriptions()).send().await?,
Command::Generate => cx.answer(generate()).send().await?,
Command::Meow => cx.answer("I am a cat! Meow!").send().await?,
Command::Username(username) => {
cx.answer_str(format!("Your username is @{}.", username)).await?
}
Command::UsernameAndAge { username, age } => {
cx.answer_str(format!(
"Your username is @{} and age is {}.",
username, age
))
.await?
}
};
Ok(())