Skip to content

Instantly share code, notes, and snippets.

@Jezza
Created May 16, 2022 15:34
Show Gist options
  • Save Jezza/cc2463de638bb33757c9cb8c6d7243f0 to your computer and use it in GitHub Desktop.
Save Jezza/cc2463de638bb33757c9cb8c6d7243f0 to your computer and use it in GitHub Desktop.
Just a very basic teloxide base for bots.
use std::future::Future;
use std::time::Duration;
use teloxide_core::prelude::*;
use teloxide_core::types::{ChatId, MediaKind, MediaText, MessageKind, Update, UpdateKind};
pub const WAIT_TIME: Duration = Duration::from_secs(5);
pub const MAX_ATTEMPTS: u32 = 5;
pub fn extract_text(update: Update) -> Option<(ChatId, MediaText)> {
let msg = match update.kind {
UpdateKind::Message(msg) => msg,
kind => {
println!("Unsupported update: {:#?}", kind);
return None;
}
};
let common = match msg.kind {
MessageKind::Common(common) => common,
kind => {
println!("Unsupported message: {:#?}", kind);
return None;
}
};
let text = match common.media_kind {
MediaKind::Text(text) => text,
kind => {
println!("Unsupported media: {:#?}", kind);
return None;
}
};
Some((msg.chat.id, text))
}
pub async fn on_update<F, Fut>(
bot: &teloxide_core::Bot,
wait_time: std::time::Duration,
max_attempts: u32,
handler: F,
)
where F: Fn(teloxide_core::Bot, teloxide_core::types::Update) -> Fut,
Fut: Future<Output=()>,
{
let bot = bot.clone();
let mut offset = 0;
let mut attempts = 0;
loop {
let response = bot.get_updates()
.offset(offset)
.limit(1)
.timeout(10)
.send()
.await;
match response {
Ok(updates) => {
attempts = 0;
let update = match updates.into_iter().next() {
Some(update) => update,
None => {
tokio::time::sleep(wait_time).await;
continue;
}
};
offset = update.id + 1;
handler(bot.clone(), update).await;
}
Err(err) => {
eprintln!("Unable to request updates: {:?}", err);
attempts += 1;
if attempts > max_attempts {
eprintln!("Stopping!");
break;
}
continue;
}
}
tokio::time::sleep(wait_time).await;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment