teloxide/examples/db_remember.rs

104 lines
2.9 KiB
Rust
Raw Normal View History

// Set the `DB_REMEMBER_REDIS` environmental variable if you want to use Redis.
// Otherwise, the default is Sqlite.
2020-10-24 18:57:51 +02:00
use teloxide::{
2022-03-24 12:25:42 +01:00
dispatching::dialogue::{
serializer::{Bincode, Json},
ErasedStorage, RedisStorage, SqliteStorage, Storage,
},
2022-03-24 12:25:42 +01:00
prelude::*,
utils::command::BotCommands,
};
2020-10-24 18:57:51 +02:00
type MyDialogue = Dialogue<State, ErasedStorage<State>>;
type MyStorage = std::sync::Arc<ErasedStorage<State>>;
type HandlerResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;
2020-10-24 18:57:51 +02:00
#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
pub enum State {
#[default]
Start,
GotNumber(i32),
}
2022-04-02 17:41:04 +02:00
#[derive(Clone, BotCommands)]
#[command(rename = "lowercase", description = "These commands are supported:")]
pub enum Command {
#[command(description = "get your number.")]
Get,
#[command(description = "reset your number.")]
Reset,
}
2020-10-24 18:57:51 +02:00
#[tokio::main]
async fn main() {
pretty_env_logger::init();
2022-04-26 21:00:08 +02:00
log::info!("Starting DB remember bot...");
let bot = Bot::from_env().auto_send();
2021-03-05 22:24:10 +01:00
let storage: MyStorage = if std::env::var("DB_REMEMBER_REDIS").is_ok() {
RedisStorage::open("redis://127.0.0.1:6379", Bincode).await.unwrap().erase()
} else {
SqliteStorage::open("db.sqlite", Json).await.unwrap().erase()
};
2022-02-02 21:36:36 +01:00
let handler = Update::filter_message()
.enter_dialogue::<Message, ErasedStorage<State>, State>()
.branch(dptree::case![State::Start].endpoint(start))
.branch(
dptree::case![State::GotNumber(n)]
.branch(dptree::entry().filter_command::<Command>().endpoint(got_number))
.branch(dptree::endpoint(invalid_command)),
);
2022-01-26 10:51:51 +01:00
Dispatcher::builder(bot, handler)
.dependencies(dptree::deps![storage])
.build()
.setup_ctrlc_handler()
.dispatch()
.await;
2020-10-24 18:57:51 +02:00
}
async fn start(bot: AutoSend<Bot>, msg: Message, dialogue: MyDialogue) -> HandlerResult {
match msg.text().map(|text| text.parse::<i32>()) {
Some(Ok(n)) => {
dialogue.update(State::GotNumber(n)).await?;
bot.send_message(
msg.chat.id,
format!("Remembered number {n}. Now use /get or /reset."),
)
.await?;
}
_ => {
bot.send_message(msg.chat.id, "Please, send me a number.").await?;
}
}
Ok(())
}
async fn got_number(
bot: AutoSend<Bot>,
msg: Message,
dialogue: MyDialogue,
num: i32,
cmd: Command,
) -> HandlerResult {
match cmd {
Command::Get => {
bot.send_message(msg.chat.id, format!("Here is your number: {num}.")).await?;
}
Command::Reset => {
dialogue.reset().await?;
bot.send_message(msg.chat.id, "Number resetted.").await?;
}
}
Ok(())
}
async fn invalid_command(bot: AutoSend<Bot>, msg: Message) -> HandlerResult {
bot.send_message(msg.chat.id, "Please, send /get or /reset.").await?;
Ok(())
}