Telegram: un topic per sessione, streaming, pulsanti e impostazioni
- Menu comandi (setMyCommands, chat private): /sessioni /nuova /stato /stop /impostazioni /aiuto; /usa rimosso. - Un topic per sessione (createForumTopic in chat privata), nome "<cartella> · <modello>", rinominato al cambio di modello e "(chiusa)" alla chiusura; mappa salvata in AKODE_HOME/telegram-topics.json. Senza topic: prefisso [cartella · modello] e scelta della sessione con pulsanti. - /sessioni con Apri (link al topic), Stato e Stop; il messaggio si aggiorna modificandolo. - Streaming con sendMessageDraft (can_stop, al massimo 1/s, stop = interrompe il turno), messaggio finale con piede "ctx · t/s · durata". - Approvazioni con pulsanti colorati, poi un pulsante disattivato con l'esito. - Piano come elenco modificato; reazioni ricevuto/fatto configurabili. - /impostazioni con interruttori Sì/No salvati in [telegram] (streaming, reactions nuovi). - Messaggi modificati: un comando modificato riparte, il testo no. - Pulsanti con token opachi lato server; allowlist anche sui pulsanti. - Nessuna emoji nei testi in uscita (test dedicato). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -63,6 +63,9 @@ pub struct User {
|
||||
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)]
|
||||
@@ -75,27 +78,61 @@ 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 {
|
||||
@@ -103,6 +140,7 @@ impl Update {
|
||||
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
|
||||
@@ -110,14 +148,78 @@ impl Update {
|
||||
.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,
|
||||
pub callback_data: 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)]
|
||||
@@ -204,7 +306,12 @@ impl TelegramApi {
|
||||
) -> Result<Vec<Update>, ApiError> {
|
||||
let mut body = json!({
|
||||
"timeout": timeout_secs,
|
||||
"allowed_updates": ["message", "callback_query"],
|
||||
"allowed_updates": [
|
||||
"message",
|
||||
"edited_message",
|
||||
"callback_query",
|
||||
"stopped_message_generation",
|
||||
],
|
||||
});
|
||||
if let Some(offset) = offset {
|
||||
body["offset"] = json!(offset);
|
||||
@@ -217,17 +324,26 @@ impl TelegramApi {
|
||||
.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,
|
||||
reply_to: Option<i64>,
|
||||
entities: &[Entity],
|
||||
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(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 });
|
||||
@@ -235,23 +351,88 @@ impl TelegramApi {
|
||||
self.call("sendMessage", body, REQUEST_TIMEOUT).await
|
||||
}
|
||||
|
||||
/// Replaces a message's text; the inline keyboard is removed.
|
||||
/// 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 body = json!({ "chat_id": chat_id, "message_id": message_id, "text": text });
|
||||
self.call::<Value>("editMessageText", body, REQUEST_TIMEOUT)
|
||||
.await
|
||||
.map(|_| ())
|
||||
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::<Value>("answerCallbackQuery", body, REQUEST_TIMEOUT)
|
||||
.await
|
||||
.map(|_| ())
|
||||
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
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user