-
Notifications
You must be signed in to change notification settings - Fork 119
/
reconnection.rs
63 lines (54 loc) · 2.19 KB
/
reconnection.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//! this example demonstrate how to implement custom Reconnection Polies
use grammers_client::session::Session;
use grammers_client::{Client, Config, InitParams, ReconnectionPolicy};
use std::ops::ControlFlow;
use std::time::Duration;
use tokio::runtime;
type Result = std::result::Result<(), Box<dyn std::error::Error>>;
/// note that this can contain any value you need, in this case, its empty
struct MyPolicy;
impl ReconnectionPolicy for MyPolicy {
///this is the only function you need to implement,
/// it gives you the attempted reconnections, and `self` in case you have any data in your struct.
/// you should return a [`ControlFlow`] which can be either `Break` or `Continue`, break will **NOT** attempt a reconnection,
/// `Continue` **WILL** try to reconnect after the given **Duration**.
///
/// in this example we are simply sleeping exponentially based on the attempted count,
/// however this is not a really good practice for production since we are just doing 2 raised to the power of attempts and that will result to massive
/// numbers very soon, just an example!
fn should_retry(&self, attempts: usize) -> ControlFlow<(), Duration> {
let duration = u64::pow(2, attempts as _);
ControlFlow::Continue(Duration::from_millis(duration))
}
}
async fn async_main() -> Result {
println!("Connecting to Telegram...");
let client = Client::connect(Config {
session: Session::load_file_or_create("ping.session")?,
api_id: 1, // not actually logging in, but has to look real
api_hash: "".to_string(),
params: InitParams {
reconnection_policy: &MyPolicy,
..Default::default()
},
})
.await?;
/// happy listening to updates forever!!
use grammers_client::Update;
loop {
let update = client.next_update().await?;
match update {
Update::NewMessage(message) if !message.outgoing() => {
message.respond(message.text()).await?;
}
_ => {}
}
}
}
fn main() -> Result {
runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async_main())
}