teloxide/examples/sqlite_remember_bot/src/main.rs

56 lines
1.4 KiB
Rust
Raw Normal View History

2020-10-24 18:57:51 +02:00
#[macro_use]
extern crate derive_more;
mod states;
mod transitions;
use states::*;
use teloxide::{
dispatching::dialogue::{serializer::Json, SqliteStorage, Storage},
2020-10-24 18:57:51 +02:00
prelude::*,
2021-03-15 04:22:10 +01:00
RequestError,
2020-10-24 18:57:51 +02:00
};
use thiserror::Error;
type StorageError = <SqliteStorage<Json> as Storage<Dialogue>>::Error;
2020-10-24 18:57:51 +02:00
#[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-10-24 18:57:51 +02:00
2021-03-05 22:24:10 +01:00
async fn handle_message(
cx: UpdateWithCx<AutoSend<Bot>, Message>,
dialogue: Dialogue,
) -> TransitionOut<Dialogue> {
match cx.update.text().map(ToOwned::to_owned) {
2020-10-24 18:57:51 +02:00
None => {
2021-03-05 22:24:10 +01:00
cx.answer("Send me a text message.").await?;
2020-10-24 18:57:51 +02:00
next(dialogue)
}
Some(ans) => dialogue.react(cx, ans).await,
}
}
#[tokio::main]
async fn main() {
2021-03-05 22:24:10 +01:00
let bot = Bot::from_env().auto_send();
2020-10-24 18:57:51 +02:00
Dispatcher::new(bot)
.messages_handler(DialogueDispatcher::with_storage(
|DialogueWithCx { cx, dialogue }: In| async move {
let dialogue = dialogue.expect("std::convert::Infallible");
handle_message(cx, dialogue).await.expect("Something wrong with the bot!")
},
SqliteStorage::open("db.sqlite", Json).await.unwrap(),
2020-10-24 18:57:51 +02:00
))
.dispatch()
.await;
}