//! 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, /// Topics in private chats are enabled for the bot (`getMe` only). #[serde(default)] pub has_topics_enabled: Option, } #[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 message_thread_id: Option, #[serde(default)] pub is_topic_message: Option, #[serde(default)] pub text: Option, #[serde(default)] pub reply_to_message: Option>, } impl Message { /// The topic the message belongs to, if any. pub fn topic(&self) -> Option { self.message_thread_id .filter(|_| self.is_topic_message.unwrap_or(true)) } } #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub struct CallbackQuery { pub id: String, #[serde(default)] pub from: Option, #[serde(default)] pub message: Option, #[serde(default)] pub data: Option, } /// The user pressed the stop button of a streamed draft. #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub struct MessageGenerationStopped { pub chat: Chat, #[serde(default)] pub message_thread_id: Option, pub draft_id: i64, } #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub struct ForumTopic { pub message_thread_id: i64, #[serde(default)] pub name: String, } #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub struct Update { pub update_id: i64, #[serde(default)] pub message: Option, #[serde(default)] pub edited_message: Option, #[serde(default)] pub callback_query: Option, #[serde(default)] pub stopped_message_generation: Option, } impl Update { /// Chat the update comes from. pub fn chat_id(&self) -> Option { self.message .as_ref() .or(self.edited_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) }) .or_else(|| { self.stopped_message_generation .as_ref() .map(|stopped| stopped.chat.id) }) } } /// `DisabledButton`: currently an empty object. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct DisabledButton {} /// One inline keyboard button. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct Button { pub text: String, #[serde(skip_serializing_if = "Option::is_none")] pub callback_data: Option, #[serde(skip_serializing_if = "Option::is_none")] pub url: Option, /// `success` (green), `danger` (red) or `primary` (blue). #[serde(skip_serializing_if = "Option::is_none")] pub style: Option<&'static str>, #[serde(skip_serializing_if = "Option::is_none")] pub disabled: Option, } impl Button { pub fn callback(text: impl Into, data: impl Into) -> Self { Self { text: text.into(), callback_data: Some(data.into()), url: None, style: None, disabled: None, } } pub fn link(text: impl Into, url: impl Into) -> Self { Self { text: text.into(), callback_data: None, url: Some(url.into()), style: None, disabled: None, } } /// A button that does nothing, used to show an outcome in place of choices. pub fn disabled(text: impl Into) -> Self { Self { text: text.into(), callback_data: None, url: None, style: None, disabled: Some(DisabledButton {}), } } pub fn styled(mut self, style: &'static str) -> Self { self.style = Some(style); self } } /// A message entity; offsets and lengths are in UTF-16 code units. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct Entity { #[serde(rename = "type")] pub kind: &'static str, pub offset: usize, pub length: usize, } #[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", "edited_message", "callback_query", "stopped_message_generation", ], }); if let Some(offset) = offset { body["offset"] = json!(offset); } self.call( "getUpdates", body, Duration::from_secs(timeout_secs) + REQUEST_TIMEOUT, ) .await } async fn call_unit(&self, method: &str, body: Value) -> Result<(), ApiError> { self.call::(method, body, REQUEST_TIMEOUT) .await .map(|_| ()) } pub async fn send_message( &self, chat_id: i64, thread: Option, text: &str, entities: &[Entity], buttons: Option<&[Vec