teloxide/examples/redis_remember_bot/src/main.rs

59 lines
1.7 KiB
Rust
Raw Normal View History

2020-07-01 15:25:10 +02:00
#[macro_use]
extern crate derive_more;
mod states;
mod transitions;
use states::*;
2020-04-19 19:47:12 +02:00
use teloxide::{
dispatching::dialogue::{serializer::Bincode, RedisStorage, Storage},
prelude::*,
2021-03-15 04:22:10 +01:00
RequestError,
2020-04-19 19:47:12 +02:00
};
use thiserror::Error;
type StorageError = <RedisStorage<Bincode> as Storage<Dialogue>>::Error;
#[derive(Debug, Error)]
enum Error {
#[error("error from Telegram: {0}")]
TelegramError(#[from] RequestError),
#[error("error from storage: {0}")]
StorageError(#[from] StorageError),
}
2021-03-05 22:24:10 +01:00
type In = DialogueWithCx<AutoSend<Bot>, Message, Dialogue, StorageError>;
2020-04-19 19:47:12 +02:00
#[tokio::main]
async fn main() {
2021-03-05 22:24:10 +01:00
let bot = Bot::from_env().auto_send();
2020-04-19 19:47:12 +02:00
Dispatcher::new(bot)
.messages_handler(DialogueDispatcher::with_storage(
2020-07-26 09:46:43 +02:00
|DialogueWithCx { cx, dialogue }: In| async move {
let dialogue = dialogue.expect("std::convert::Infallible");
handle_message(cx, dialogue).await.expect("Something wrong with the bot!")
2020-04-19 19:47:12 +02:00
},
2020-07-04 17:02:07 +02:00
// You can also choose serializer::JSON or serializer::CBOR
// All serializers but JSON require enabling feature
// "serializer-<name>", e. g. "serializer-cbor"
// or "serializer-bincode"
RedisStorage::open("redis://127.0.0.1:6379", Bincode).await.unwrap(),
2020-04-19 19:47:12 +02:00
))
.dispatch()
.await;
}
2021-03-05 22:24:10 +01:00
async fn handle_message(
cx: UpdateWithCx<AutoSend<Bot>, Message>,
dialogue: Dialogue,
) -> TransitionOut<Dialogue> {
2021-03-17 20:50:48 +01:00
match cx.update.text().map(ToOwned::to_owned) {
None => {
2021-03-05 22:24:10 +01:00
cx.answer("Send me a text message.").await?;
next(dialogue)
}
Some(ans) => dialogue.react(cx, ans).await,
}
}