//! Short notices to the operator's Telegram chat through a bot (Bot API //! `sendMessage`). use std::time::Duration; use serde_json::json; pub const DEFAULT_API_URL: &str = "https://api.telegram.org"; pub struct Telegram { http: reqwest::Client, api: String, token: String, chat_id: String, } impl Telegram { pub fn new(api: &str, token: &str, chat_id: &str) -> Self { let http = reqwest::Client::builder().timeout(Duration::from_secs(10)).build().expect("http client"); Self { http, api: api.trim_end_matches('/').to_owned(), token: token.to_owned(), chat_id: chat_id.to_owned() } } /// Sends `text` as a plain message. pub async fn send(&self, text: &str) -> Result<(), SendError> { let url = format!("{}/bot{}/sendMessage", self.api, self.token); let body = json!({ "chat_id": self.chat_id, "text": text, "disable_web_page_preview": true }); match self.http.post(&url).json(&body).send().await { Ok(res) if res.status().is_success() => Ok(()), Ok(res) => { let status = res.status(); let detail: String = res.text().await.unwrap_or_default().chars().take(200).collect(); // A wrong token or chat stays wrong; rate limits and outages pass. let permanent = status.is_client_error() && status != reqwest::StatusCode::TOO_MANY_REQUESTS; Err(SendError { permanent, message: format!("{status}: {detail}") }) } // The URL holds the bot token: keep it out of the message. Err(e) => Err(SendError { permanent: false, message: e.without_url().to_string() }), } } } #[derive(Debug)] pub struct SendError { /// Retrying will not help (e.g. a wrong token or chat ID). pub permanent: bool, pub message: String, } /// "6 000 Ft" pub fn huf(amount: i32) -> String { let digits = amount.unsigned_abs().to_string(); let mut out = String::new(); for (i, c) in digits.chars().enumerate() { if i > 0 && (digits.len() - i).is_multiple_of(3) { out.push('\u{a0}'); } out.push(c); } format!("{}{out}\u{a0}Ft", if amount < 0 { "-" } else { "" }) } #[cfg(test)] mod tests { use super::huf; #[test] fn forints() { assert_eq!(huf(990), "990\u{a0}Ft"); assert_eq!(huf(6000), "6\u{a0}000\u{a0}Ft"); assert_eq!(huf(1234567), "1\u{a0}234\u{a0}567\u{a0}Ft"); } }