teloxide/examples/shared_state.rs

35 lines
1,003 B
Rust
Raw Normal View History

2020-03-04 09:15:23 +01:00
// This bot answers how many messages it received in total on every message.
use std::sync::{
atomic::{AtomicU64, Ordering},
Arc,
};
2020-03-04 09:15:23 +01:00
2022-03-24 12:25:42 +01:00
use teloxide::prelude::*;
2020-03-04 09:15:23 +01:00
#[tokio::main]
async fn main() {
pretty_env_logger::init();
log::info!("Starting shared state bot...");
2020-03-04 09:15:23 +01:00
2021-03-05 22:24:10 +01:00
let bot = Bot::from_env().auto_send();
let messages_total = Arc::new(AtomicU64::new(0));
2020-03-04 09:15:23 +01:00
let handler = Update::filter_message().endpoint(
|msg: Message, bot: AutoSend<Bot>, messages_total: Arc<AtomicU64>| async move {
let previous = messages_total.fetch_add(1, Ordering::Relaxed);
bot.send_message(msg.chat.id, format!("I received {previous} messages in total."))
2022-01-06 12:59:50 +01:00
.await?;
2022-01-26 10:51:51 +01:00
respond(())
},
);
2022-01-26 10:51:51 +01:00
Dispatcher::builder(bot, handler)
// Pass the shared state to the handler as a dependency.
.dependencies(dptree::deps![messages_total])
.enable_ctrlc_handler()
.build()
.dispatch()
.await;
2020-03-04 09:15:23 +01:00
}