From 3c0ba7e35d74cb46f2ebba6639566a9b18c7cc6e Mon Sep 17 00:00:00 2001 From: alemi Date: Tue, 2 Jan 2024 04:55:02 +0100 Subject: [PATCH] feat: add telegram notifier --- Cargo.toml | 2 +- src/notifications/telegram.rs | 51 ++++++++++++++++++++++------------- 2 files changed, 34 insertions(+), 19 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index c708564..d0bee07 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,5 +25,5 @@ teloxide = { version = "0.12.2", features = ["macros"], optional = true } toml = "0.8.8" [features] -default = [] +default = ["telegram"] telegram = ["dep:teloxide"] diff --git a/src/notifications/telegram.rs b/src/notifications/telegram.rs index 019c1dc..feaca6e 100644 --- a/src/notifications/telegram.rs +++ b/src/notifications/telegram.rs @@ -1,24 +1,39 @@ use teloxide::prelude::*; -lazy_static::lazy_static! { - static ref BOT : Bot = Bot::from_env(); - static ref CHAT_ID : RwLock = RwLock::new(ChatId(0)); // TODO ewwwwwww +use crate::model::Page; + +use super::NotificationProcessor; + +pub struct TGNotifier { + bot: Bot, + chat_id: i64, } -async fn suggestion_inner(payload: Suggestion) -> (StatusCode, Json) { - let message = format!( - "[{}] {} | {}", - html_escape::encode_text(payload.author.as_deref().unwrap_or("anon")), - html_escape::encode_text(payload.contact.as_deref().unwrap_or("N/A")), - html_escape::encode_text(&payload.body) - ); - - match BOT - .send_message(*CHAT_ID.read().await, message) - .parse_mode(teloxide::types::ParseMode::Html) - .await - { - Ok(x) => (StatusCode::OK, Json(Acknowledgement::Sent(x.text().unwrap_or("").into()))), - Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(Acknowledgement::Refused(e.to_string()))), +impl TGNotifier { + pub fn new(token: &str, chat_id: i64) -> Self { + TGNotifier { + chat_id, + bot: Bot::new(token), + } + } +} + +#[async_trait::async_trait] +impl NotificationProcessor for TGNotifier { + async fn process(&self, notification: &Page) { + let message = format!( + "[{}] {} | {}", + html_escape::encode_text(¬ification.author), + html_escape::encode_text(notification.contact.as_deref().unwrap_or("N/A")), + html_escape::encode_text(¬ification.body) + ); + + if let Err(e) = self.bot + .send_message(ChatId(self.chat_id), message) + .parse_mode(teloxide::types::ParseMode::Html) + .await + { + tracing::error!("could not send message on telegram: {}", e); + } } }