Add examples/simple_commands_bot

This commit is contained in:
Temirkhan Myrzamadi 2020-02-14 03:23:41 +06:00
parent 027b80f19b
commit 2147ba2048
4 changed files with 72 additions and 3 deletions

3
.gitignore vendored
View file

@ -7,4 +7,5 @@ examples/ping_pong_bot/target
examples/dialogue_bot/target
examples/multiple_handlers_bot/target
examples/admin_bot/target
examples/guess_a_number_bot/target
examples/guess_a_number_bot/target
examples/simple_commands_bot/target

View file

@ -1,8 +1,9 @@
# Examples
Just enter the directory (for example, `cd dialogue_bot`) and execute `cargo run` to run an example. Don't forget to initialise the `TELOXIDE_TOKEN` environmental variable.
- [ping_pong_bot](ping_pong_bot) - Just answers "pong" to each incoming message.
- [ping_pong_bot](ping_pong_bot) - Answers "pong" to each incoming message.
- [simple_commands_bot](simple_commands_bot) - Shows how to deal with bot's commands.
- [guess_a_number_bot](guess_a_number_bot) - The "guess a number" game.
- [dialogue_bot](dialogue_bot) - Drive a dialogue with a user using a type-safe finite automaton.
- [admin_bot](admin_bot) - Shows how to deal with bot's commands.
- [admin_bot](admin_bot) - A bot, which can ban, kick, and mute on a command.
- [multiple_handlers_bot](multiple_handlers_bot) - Shows how multiple dispatcher's handlers relate to each other.

View file

@ -0,0 +1,13 @@
[package]
name = "simple_commands_bot"
version = "0.1.0"
authors = ["Temirkhan Myrzamadi <hirrolot@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
log = "0.4.8"
tokio = "0.2.9"
pretty_env_logger = "0.4.0"
teloxide = { path = "../../" }

View file

@ -0,0 +1,54 @@
use teloxide::{prelude::*, utils::command::BotCommand};
#[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 = "be a dog.")]
Woof,
#[command(description = "be a cow.")]
Moo,
}
async fn handle_command(
ctx: DispatcherHandlerCtx<Message>,
) -> Result<(), RequestError> {
let text = match ctx.update.text() {
Some(text) => text,
None => return Ok(()),
};
let command = match Command::parse(text) {
Some((command, _)) => command,
None => return Ok(()),
};
match command {
Command::Help => ctx.answer(Command::descriptions()).send().await?,
Command::Meow => ctx.answer("I am a cat! Meow!").send().await?,
Command::Woof => ctx.answer("I am a dog! Woof!").send().await?,
Command::Moo => ctx.answer("I am a cow! Moo!").send().await?,
};
Ok(())
}
#[tokio::main]
async fn main() {
run().await;
}
async fn run() {
teloxide::enable_logging!();
log::info!("Starting ping_pong_bot!");
let bot = Bot::from_env();
Dispatcher::<RequestError>::new(bot)
.message_handler(&handle_command)
.dispatch()
.await;
}