Files
sorsfonalak/services/worker/src/telegram.rs
T
fecoandClaude Opus 5.5 a571abdb65
CI / test (push) Successful in 1m49s
CI / build (push) Successful in 8m27s
CI / deploy (push) Skipped
worker: Telegram notice about every purchase (notify task)
A separate worker task, apart from invoicing: each paid checkout is
announced once to the operator's Telegram chat ('Páros csomag, 6 000 Ft',
marked when it was a test payment), without the buyer's data. Outages
and rate limits are retried; a wrong token or chat is logged, not
retried. Needs TELEGRAM_BOT_TOKEN (.env.secrets) and TELEGRAM_CHAT_ID.

Also fixes the worker test that still expected the old sign-up e-mail
subject (CI failed on it since 7d6a6c3).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-21 19:04:20 +00:00

73 lines
2.4 KiB
Rust

//! Short notices to the operator's Telegram chat through a bot (Bot API
//! `sendMessage`).
use std::time::Duration;
use serde_json::json;
pub const DEFAULT_API_URL: &str = "https://api.telegram.org";
pub struct Telegram {
http: reqwest::Client,
api: String,
token: String,
chat_id: String,
}
impl Telegram {
pub fn new(api: &str, token: &str, chat_id: &str) -> Self {
let http = reqwest::Client::builder().timeout(Duration::from_secs(10)).build().expect("http client");
Self { http, api: api.trim_end_matches('/').to_owned(), token: token.to_owned(), chat_id: chat_id.to_owned() }
}
/// Sends `text` as a plain message.
pub async fn send(&self, text: &str) -> Result<(), SendError> {
let url = format!("{}/bot{}/sendMessage", self.api, self.token);
let body = json!({ "chat_id": self.chat_id, "text": text, "disable_web_page_preview": true });
match self.http.post(&url).json(&body).send().await {
Ok(res) if res.status().is_success() => Ok(()),
Ok(res) => {
let status = res.status();
let detail: String = res.text().await.unwrap_or_default().chars().take(200).collect();
// A wrong token or chat stays wrong; rate limits and outages pass.
let permanent = status.is_client_error() && status != reqwest::StatusCode::TOO_MANY_REQUESTS;
Err(SendError { permanent, message: format!("{status}: {detail}") })
}
// The URL holds the bot token: keep it out of the message.
Err(e) => Err(SendError { permanent: false, message: e.without_url().to_string() }),
}
}
}
#[derive(Debug)]
pub struct SendError {
/// Retrying will not help (e.g. a wrong token or chat ID).
pub permanent: bool,
pub message: String,
}
/// "6 000 Ft"
pub fn huf(amount: i32) -> String {
let digits = amount.unsigned_abs().to_string();
let mut out = String::new();
for (i, c) in digits.chars().enumerate() {
if i > 0 && (digits.len() - i).is_multiple_of(3) {
out.push('\u{a0}');
}
out.push(c);
}
format!("{}{out}\u{a0}Ft", if amount < 0 { "-" } else { "" })
}
#[cfg(test)]
mod tests {
use super::huf;
#[test]
fn forints() {
assert_eq!(huf(990), "990\u{a0}Ft");
assert_eq!(huf(6000), "6\u{a0}000\u{a0}Ft");
assert_eq!(huf(1234567), "1\u{a0}234\u{a0}567\u{a0}Ft");
}
}