41 lines
1.3 KiB
Rust
41 lines
1.3 KiB
Rust
use serde_json::{json, Value};
|
|
|
|
#[derive(Clone)]
|
|
pub struct Telegram {
|
|
bot_token: String,
|
|
chat_id: String,
|
|
}
|
|
|
|
impl Telegram {
|
|
pub fn from_env() -> Option<Self> {
|
|
let bot_token = std::env::var("ROUTINE_TELEGRAM_BOT_TOKEN").ok()?;
|
|
let chat_id = std::env::var("ROUTINE_TELEGRAM_CHAT_ID").ok()?;
|
|
Some(Self { bot_token, chat_id })
|
|
}
|
|
|
|
pub fn send_message(&self, text: &str) -> Result<(), String> {
|
|
let url = format!("https://api.telegram.org/bot{}/sendMessage", self.bot_token);
|
|
let payload = json!({
|
|
"chat_id": self.chat_id,
|
|
"text": text,
|
|
})
|
|
.to_string();
|
|
let response = minreq::post(&url)
|
|
.with_header("Content-Type", "application/json")
|
|
.with_body(payload)
|
|
.send()
|
|
.map_err(|_| "Telegram request failed".to_owned())?;
|
|
let body: Value = serde_json::from_str(
|
|
response
|
|
.as_str()
|
|
.map_err(|_| "Telegram returned a non-UTF-8 response".to_owned())?,
|
|
)
|
|
.map_err(|_| "Telegram returned invalid JSON".to_owned())?;
|
|
if body.get("ok").and_then(Value::as_bool) == Some(true) {
|
|
Ok(())
|
|
} else {
|
|
Err("Telegram rejected the message".to_owned())
|
|
}
|
|
}
|
|
}
|