Files
imeai-aKode/akode-rs/telegram/src/api.rs
andrea.difonzo 973acc59c9 aKode 0.3.1: Shift+Tab a tre modalità e topic di Telegram più puliti
- Shift+Tab: default, plan, accesso completo (preset di /permissions,
  saltato se i requisiti non lo permettono; uscendo tornano i permessi
  di prima). Modalità sotto il riquadro di scrittura, a sinistra, e in
  /stato su Telegram.
- Telegram: topic creato al primo turno; sessioni chiuse senza turni
  perdono il topic, le altre diventano «(chiusa)» con nuovi tentativi;
  topic di «Nuova chat» assegnati con i pulsanti, i comandi lì ricevono
  risposta nella chat principale; pulizia all'avvio.
- Versione 0.3.1 e novità nel README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:46:19 +01:00

445 lines
13 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,
/// Topics in private chats are enabled for the bot (`getMe` only).
#[serde(default)]
pub has_topics_enabled: Option<bool>,
}
#[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<i64>,
#[serde(default)]
pub is_topic_message: Option<bool>,
#[serde(default)]
pub text: Option<String>,
#[serde(default)]
pub reply_to_message: Option<Box<Message>>,
}
impl Message {
/// The topic the message belongs to, if any.
pub fn topic(&self) -> Option<i64> {
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<User>,
#[serde(default)]
pub message: Option<Message>,
#[serde(default)]
pub data: Option<String>,
}
/// 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<i64>,
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<Message>,
#[serde(default)]
pub edited_message: Option<Message>,
#[serde(default)]
pub callback_query: Option<CallbackQuery>,
#[serde(default)]
pub stopped_message_generation: Option<MessageGenerationStopped>,
}
impl Update {
/// Chat the update comes from.
pub fn chat_id(&self) -> Option<i64> {
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<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
/// `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<DisabledButton>,
}
impl Button {
pub fn callback(text: impl Into<String>, data: impl Into<String>) -> Self {
Self {
text: text.into(),
callback_data: Some(data.into()),
url: None,
style: None,
disabled: None,
}
}
pub fn link(text: impl Into<String>, url: impl Into<String>) -> 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<String>) -> 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<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",
"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::<Value>(method, body, REQUEST_TIMEOUT)
.await
.map(|_| ())
}
pub async fn send_message(
&self,
chat_id: i64,
thread: Option<i64>,
text: &str,
entities: &[Entity],
buttons: Option<&[Vec<Button>]>,
) -> Result<Message, ApiError> {
let mut body = json!({ "chat_id": chat_id, "text": text });
if let Some(thread) = thread {
body["message_thread_id"] = json!(thread);
}
if !entities.is_empty() {
body["entities"] = json!(entities);
}
if let Some(buttons) = buttons {
body["reply_markup"] = json!({ "inline_keyboard": buttons });
}
self.call("sendMessage", body, REQUEST_TIMEOUT).await
}
/// Replaces a message's text; without `buttons` the inline keyboard is removed.
pub async fn edit_message_text(
&self,
chat_id: i64,
message_id: i64,
text: &str,
entities: &[Entity],
buttons: Option<&[Vec<Button>]>,
) -> Result<(), ApiError> {
let mut body = json!({ "chat_id": chat_id, "message_id": message_id, "text": text });
if !entities.is_empty() {
body["entities"] = json!(entities);
}
if let Some(buttons) = buttons {
body["reply_markup"] = json!({ "inline_keyboard": buttons });
}
self.call_unit("editMessageText", body).await
}
/// Answers a button press with a short notice shown only to the user who pressed it.
pub async fn answer_callback_query(&self, id: &str, text: &str) -> Result<(), ApiError> {
let body = json!({ "callback_query_id": id, "text": text });
self.call_unit("answerCallbackQuery", body).await
}
/// Sets the command menu of private chats.
pub async fn set_my_commands(&self, commands: &[(&str, &str)]) -> Result<(), ApiError> {
let commands: Vec<Value> = commands
.iter()
.map(|(command, description)| json!({ "command": command, "description": description }))
.collect();
let body = json!({ "commands": commands, "scope": { "type": "all_private_chats" } });
self.call_unit("setMyCommands", body).await
}
pub async fn create_forum_topic(&self, chat_id: i64, name: &str) -> Result<ForumTopic, ApiError> {
let body = json!({ "chat_id": chat_id, "name": name });
self.call("createForumTopic", body, REQUEST_TIMEOUT).await
}
pub async fn edit_forum_topic(
&self,
chat_id: i64,
thread: i64,
name: &str,
) -> Result<(), ApiError> {
let body = json!({ "chat_id": chat_id, "message_thread_id": thread, "name": name });
self.call_unit("editForumTopic", body).await
}
/// Deletes a topic with all its messages (supergroups and private chats).
pub async fn delete_forum_topic(&self, chat_id: i64, thread: i64) -> Result<(), ApiError> {
let body = json!({ "chat_id": chat_id, "message_thread_id": thread });
self.call_unit("deleteForumTopic", body).await
}
/// Streams a partial message (a temporary preview, replaced by the next message).
pub async fn send_message_draft(
&self,
chat_id: i64,
thread: Option<i64>,
draft_id: i64,
text: &str,
) -> Result<(), ApiError> {
let mut body = json!({
"chat_id": chat_id,
"draft_id": draft_id,
"text": text,
"can_stop": true,
});
if let Some(thread) = thread {
body["message_thread_id"] = json!(thread);
}
self.call_unit("sendMessageDraft", body).await
}
/// Sets one standard reaction on a message, or clears it with `None`.
pub async fn set_message_reaction(
&self,
chat_id: i64,
message_id: i64,
emoji: Option<&str>,
) -> Result<(), ApiError> {
let reaction: Vec<Value> = emoji
.map(|emoji| json!({ "type": "emoji", "emoji": emoji }))
.into_iter()
.collect();
let body = json!({ "chat_id": chat_id, "message_id": message_id, "reaction": reaction });
self.call_unit("setMessageReaction", body).await
}
}