mirror of
https://github.com/teloxide/teloxide.git
synced 2024-12-22 22:46:39 +01:00
Use Arc<AtomicU64>
in examples/shared_state.rs
Former-commit-id: a48f6c8a44
This commit is contained in:
parent
b2653d0769
commit
d3f1e4058c
2 changed files with 16 additions and 10 deletions
|
@ -95,7 +95,6 @@ tower-http = { version = "0.2.5", features = ["trace"], optional = true }
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
rand = "0.8.3"
|
rand = "0.8.3"
|
||||||
pretty_env_logger = "0.4.0"
|
pretty_env_logger = "0.4.0"
|
||||||
once_cell = "1.9.0"
|
|
||||||
serde = "1"
|
serde = "1"
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
tokio = { version = "1.8", features = ["fs", "rt-multi-thread", "macros"] }
|
tokio = { version = "1.8", features = ["fs", "rt-multi-thread", "macros"] }
|
||||||
|
|
|
@ -1,27 +1,34 @@
|
||||||
// This bot answers how many messages it received in total on every message.
|
// This bot answers how many messages it received in total on every message.
|
||||||
|
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
use std::sync::{
|
||||||
|
atomic::{AtomicU64, Ordering},
|
||||||
|
Arc,
|
||||||
|
};
|
||||||
|
|
||||||
use once_cell::sync::Lazy;
|
|
||||||
use teloxide::prelude::*;
|
use teloxide::prelude::*;
|
||||||
|
|
||||||
static MESSAGES_TOTAL: Lazy<AtomicU64> = Lazy::new(AtomicU64::default);
|
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() {
|
async fn main() {
|
||||||
pretty_env_logger::init();
|
pretty_env_logger::init();
|
||||||
log::info!("Starting shared state bot...");
|
log::info!("Starting shared state bot...");
|
||||||
|
|
||||||
let bot = Bot::from_env().auto_send();
|
let bot = Bot::from_env().auto_send();
|
||||||
|
let messages_total = Arc::new(AtomicU64::new(0));
|
||||||
|
|
||||||
let handler = Update::filter_message().branch(dptree::endpoint(
|
let handler = Update::filter_message().endpoint(
|
||||||
|msg: Message, bot: AutoSend<Bot>| async move {
|
|msg: Message, bot: AutoSend<Bot>, messages_total: Arc<AtomicU64>| async move {
|
||||||
let previous = MESSAGES_TOTAL.fetch_add(1, Ordering::Relaxed);
|
let previous = messages_total.fetch_add(1, Ordering::Relaxed);
|
||||||
bot.send_message(msg.chat.id, format!("I received {previous} messages in total."))
|
bot.send_message(msg.chat.id, format!("I received {previous} messages in total."))
|
||||||
.await?;
|
.await?;
|
||||||
respond(())
|
respond(())
|
||||||
},
|
},
|
||||||
));
|
);
|
||||||
|
|
||||||
Dispatcher::builder(bot, handler).build().setup_ctrlc_handler().dispatch().await;
|
Dispatcher::builder(bot, handler)
|
||||||
|
// Pass the shared state to the handler as a dependency.
|
||||||
|
.dependencies(dptree::deps![messages_total])
|
||||||
|
.build()
|
||||||
|
.setup_ctrlc_handler()
|
||||||
|
.dispatch()
|
||||||
|
.await;
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue