Files
imeai-aKode/akode-rs/telegram/src/api.rs
2026-11-12 08:21:25 +01:00

258 lines
7.0 KiB
Rust

//! 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<u64>,
},
#[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<u64> {
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<String>,
#[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<String>,
#[serde(default)]
pub reply_to_message: Option<Box<Message>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct CallbackQuery {
pub id: String,
#[serde(default)]
pub message: Option<Message>,
#[serde(default)]
pub data: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct Update {
pub update_id: i64,
#[serde(default)]
pub message: Option<Message>,
#[serde(default)]
pub callback_query: Option<CallbackQuery>,
}
impl Update {
/// Chat the update comes from.
pub fn chat_id(&self) -> Option<i64> {
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<T> {
ok: bool,
#[serde(default = "Option::default")]
result: Option<T>,
#[serde(default)]
error_code: Option<i64>,
#[serde(default)]
description: Option<String>,
#[serde(default)]
parameters: Option<ResponseParameters>,
}
#[derive(Deserialize)]
struct ResponseParameters {
#[serde(default)]
retry_after: Option<u64>,
}
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<T: DeserializeOwned>(
&self,
method: &str,
body: Value,
timeout: Duration,
) -> Result<T, ApiError> {
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<T> = 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<User, ApiError> {
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<i64>,
timeout_secs: u64,
) -> Result<Vec<Update>, 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<i64>,
buttons: Option<&[Vec<Button>]>,
) -> Result<Message, ApiError> {
let mut body = json!({ "chat_id": chat_id, "text": text });
if let Some(reply_to) = reply_to {
body["reply_parameters"] =
json!({ "message_id": reply_to, "allow_sending_without_reply": true });
}
if let Some(buttons) = buttons {
body["reply_markup"] = json!({ "inline_keyboard": buttons });
}
self.call("sendMessage", body, REQUEST_TIMEOUT).await
}
/// Replaces a message's text; the inline keyboard is removed.
pub async fn edit_message_text(
&self,
chat_id: i64,
message_id: i64,
text: &str,
) -> Result<(), ApiError> {
let body = json!({ "chat_id": chat_id, "message_id": message_id, "text": text });
self.call::<Value>("editMessageText", body, REQUEST_TIMEOUT)
.await
.map(|_| ())
}
pub async fn answer_callback_query(&self, id: &str, text: &str) -> Result<(), ApiError> {
let body = json!({ "callback_query_id": id, "text": text });
self.call::<Value>("answerCallbackQuery", body, REQUEST_TIMEOUT)
.await
.map(|_| ())
}
}