chessbaseLinux/website/server/src/telegram.rs

133 lines
4.8 KiB
Rust
Raw Normal View History

//! Notices to the owner's Telegram bot: a download from the site, a new installation, an
//! installation that runs again on a new day or after an update; `/stat` answers with
//! the numbers of today and of all time. Only the owner's chat is written to and
//! listened to. Off without `TELEGRAM_TOKEN` and `TELEGRAM_CHAT` in the environment.
use std::sync::Arc;
use std::time::Duration;
use serde_json::{Value, json};
pub struct Bot {
token: String,
chat: i64,
http: reqwest::Client,
}
impl Bot {
pub fn from_env() -> Option<Arc<Bot>> {
let token = std::env::var("TELEGRAM_TOKEN").ok().filter(|t| !t.is_empty())?;
let chat = std::env::var("TELEGRAM_CHAT").ok()?.trim().parse().ok()?;
let http = reqwest::Client::builder()
.user_agent("chesspenguin-site")
// Long polling waits up to 50 s for a message.
.timeout(Duration::from_secs(70))
.build()
.ok()?;
Some(Arc::new(Bot { token, chat, http }))
}
fn url(&self, method: &str) -> String {
format!("https://api.telegram.org/bot{}/{method}", self.token)
}
/// Sends `text` to the owner in the background (a failure is only logged).
pub fn send(self: &Arc<Self>, text: String) {
let bot = self.clone();
tokio::spawn(async move { bot.send_now(&text).await });
}
async fn send_now(&self, text: &str) {
let body = json!({
"chat_id": self.chat,
"text": text,
"disable_web_page_preview": true,
});
match self.http.post(self.url("sendMessage")).json(&body).send().await {
Ok(r) if !r.status().is_success() => eprintln!("telegram: {}", r.status()),
Err(e) => eprintln!("telegram: {}", e.without_url()),
_ => {}
}
}
/// Waits for the owner's commands (long polling) and answers them with `answer`.
pub async fn listen(self: Arc<Self>, answer: impl Fn(&str) -> Option<String>) {
let mut offset: i64 = 0;
loop {
let got = self
.http
.get(format!("{}?timeout=50&offset={offset}", self.url("getUpdates")))
.send()
.await;
let updates: Value = match got {
// 401: a wrong token; 409: another server listens to this bot.
Ok(r) if !r.status().is_success() => {
eprintln!("telegram: getUpdates {}", r.status());
tokio::time::sleep(Duration::from_secs(60)).await;
continue;
}
Ok(r) => r.json().await.unwrap_or(Value::Null),
Err(e) => {
eprintln!("telegram: {}", e.without_url());
tokio::time::sleep(Duration::from_secs(30)).await;
continue;
}
};
let Some(list) = updates["result"].as_array() else {
tokio::time::sleep(Duration::from_secs(30)).await;
continue;
};
for u in list {
offset = offset.max(u["update_id"].as_i64().unwrap_or(0) + 1);
let m = &u["message"];
if m["chat"]["id"].as_i64() != Some(self.chat) {
continue;
}
// "/stat", "/stat@chessPenguin_bot".
let command = m["text"].as_str().unwrap_or("").split(['@', ' ']).next().unwrap_or("");
if let Some(text) = answer(command) {
self.send_now(&text).await;
}
}
}
}
}
/// The flag of a country ("RU" → 🇷🇺), or nothing.
pub fn flag(country: Option<&str>) -> String {
match country {
Some(c) if c.len() == 2 && c.chars().all(|c| c.is_ascii_alphabetic()) => c
.to_ascii_uppercase()
.chars()
.filter_map(|c| char::from_u32(0x1F1E6 + (c as u32 - 'A' as u32)))
.collect(),
_ => String::new(),
}
}
/// "🇷🇺 Moscow" / "🇷🇺 RU" / "": where someone is, as short as it is known.
pub fn place(country: Option<&str>, region: Option<&str>, city: Option<&str>) -> String {
let name = city.or(region).or(country).unwrap_or("");
[flag(country), name.to_owned()]
.into_iter()
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join(" ")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn flags_and_places() {
assert_eq!(flag(Some("RU")), "🇷🇺");
assert_eq!(flag(Some("kz")), "🇰🇿");
assert_eq!(flag(None), "");
assert_eq!(flag(Some("—")), "");
assert_eq!(place(Some("RU"), Some("Moscow"), Some("Moscow")), "🇷🇺 Moscow");
assert_eq!(place(Some("UZ"), None, None), "🇺🇿 UZ");
assert_eq!(place(None, None, None), "");
}
}