//! Minimal Telegram Bot API client. Errors never carry the request URL, which contains //! the bot token. use std::fmt; use std::time::Duration; use serde::Deserialize; use serde::Serialize; use serde::de::DeserializeOwned; use serde_json::Value; use serde_json::json; use crate::TELEGRAM_API_BASE; #[derive(Clone)] pub struct TelegramApi { client: reqwest::Client, base: String, token: String, } impl fmt::Debug for TelegramApi { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("TelegramApi") .field("base", &self.base) .finish_non_exhaustive() } } #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum ApiError { #[error("Telegram non raggiungibile: {0}")] Network(String), #[error("Telegram ha risposto {code}: {description}")] Api { code: i64, description: String, retry_after: Option, }, #[error("risposta di Telegram non valida: {0}")] Decode(String), } impl ApiError { /// Seconds Telegram asked to wait (429), if any. pub fn retry_after(&self) -> Option { match self { Self::Api { retry_after, .. } => *retry_after, _ => None, } } /// The token was refused (revoked or mistyped). pub fn is_unauthorized(&self) -> bool { matches!(self, Self::Api { code: 401 | 404, .. }) } } #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub struct User { pub id: i64, #[serde(default)] pub username: Option, #[serde(default)] pub first_name: String, } #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub struct Chat { pub id: i64, } #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub struct Message { pub message_id: i64, pub chat: Chat, #[serde(default)] pub text: Option, #[serde(default)] pub reply_to_message: Option>, } #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub struct CallbackQuery { pub id: String, #[serde(default)] pub message: Option, #[serde(default)] pub data: Option, } #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub struct Update { pub update_id: i64, #[serde(default)] pub message: Option, #[serde(default)] pub callback_query: Option, } impl Update { /// Chat the update comes from. pub fn chat_id(&self) -> Option { self.message .as_ref() .map(|message| message.chat.id) .or_else(|| { self.callback_query .as_ref() .and_then(|query| query.message.as_ref()) .map(|message| message.chat.id) }) } } /// One inline keyboard button. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct Button { pub text: String, pub callback_data: String, } #[derive(Deserialize)] struct Envelope { ok: bool, #[serde(default = "Option::default")] result: Option, #[serde(default)] error_code: Option, #[serde(default)] description: Option, #[serde(default)] parameters: Option, } #[derive(Deserialize)] struct ResponseParameters { #[serde(default)] retry_after: Option, } const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); impl TelegramApi { pub fn new(token: &str) -> Self { Self::with_base_url(TELEGRAM_API_BASE, token) } /// Client for another base URL; only tests use it (a mock server). pub fn with_base_url(base: &str, token: &str) -> Self { akode_utils_rustls_provider::ensure_rustls_crypto_provider(); let client = reqwest::Client::builder() .connect_timeout(Duration::from_secs(15)) .build() .unwrap_or_default(); Self { client, base: base.trim_end_matches('/').to_string(), token: token.trim().to_string(), } } async fn call( &self, method: &str, body: Value, timeout: Duration, ) -> Result { let url = format!("{}/bot{}/{method}", self.base, self.token); let response = self .client .post(url) .timeout(timeout) .json(&body) .send() .await .map_err(|err| ApiError::Network(err.without_url().to_string()))?; let envelope: Envelope = response .json() .await .map_err(|err| ApiError::Decode(err.without_url().to_string()))?; if envelope.ok { envelope .result .ok_or_else(|| ApiError::Decode("risultato mancante".to_string())) } else { Err(ApiError::Api { code: envelope.error_code.unwrap_or_default(), description: envelope.description.unwrap_or_default(), retry_after: envelope.parameters.and_then(|p| p.retry_after), }) } } pub async fn get_me(&self) -> Result { self.call("getMe", json!({}), REQUEST_TIMEOUT).await } /// Long poll: waits up to `timeout_secs` for new updates after `offset`. pub async fn get_updates( &self, offset: Option, timeout_secs: u64, ) -> Result, ApiError> { let mut body = json!({ "timeout": timeout_secs, "allowed_updates": ["message", "callback_query"], }); if let Some(offset) = offset { body["offset"] = json!(offset); } self.call( "getUpdates", body, Duration::from_secs(timeout_secs) + REQUEST_TIMEOUT, ) .await } pub async fn send_message( &self, chat_id: i64, text: &str, reply_to: Option, buttons: Option<&[Vec