feature: post discord webhook on quote creation

This commit is contained in:
2026-04-29 00:54:44 +02:00
parent 851f73f639
commit 1578c3a708
5 changed files with 641 additions and 1 deletions

View File

@@ -9,6 +9,8 @@ use uuid::Uuid;
use crate::{database::DatabaseError, persons::Name};
mod webhook;
#[derive(Serialize)]
pub struct Quote {
pub id: Uuid,

56
src/quotes/webhook.rs Normal file
View File

@@ -0,0 +1,56 @@
use reqwest::Url;
use std::time::Duration;
use crate::quotes::Quote;
impl Quote {
pub fn post_msg_webhook(&self, url: Url) {
let mut message = String::new();
for line in &self.lines {
let authors = line
.attribution
.iter()
.map(|n| n.name.as_str())
.collect::<Vec<_>>()
.join(", ");
message.push_str(&format!("> {}\n", line.content));
message.push_str(&format!("~ {}\n", authors));
}
message.push_str(&format!("\n-# {}", self.timestamp));
let escape_md = |s: &str| s.replace('*', "\\*").replace('_', "\\_");
if let Some(ctx) = &self.location {
message.push_str(&format!(" | Location: {}", escape_md(ctx)));
}
if let Some(ctx) = &self.context {
message.push_str(&format!(" | Context: *{}*", escape_md(ctx)));
}
tokio::spawn(async move {
let client = match reqwest::Client::builder()
.timeout(Duration::from_secs(10))
.build()
{
Ok(c) => c,
Err(e) => {
log::error!("Failed to construct reqwest Client while sending webhook! {e}");
return;
}
};
let body = serde_json::json!({
"content": message
});
match client.post(url).json(&body).send().await {
Ok(response) => {
if let Err(e) = response.error_for_status() {
log::error!("Webhook responded with an HTTP error! {e}");
}
}
Err(e) => {
log::error!("Failed to POST webhook! {e}");
}
}
});
}
}

View File

@@ -6,6 +6,7 @@ use axum::{
use axum_extra::extract::Form;
use chrono::NaiveDateTime;
use maud::{Markup, PreEscaped, html};
use reqwest::Url;
use serde::Deserialize;
use uuid::Uuid;
@@ -178,5 +179,12 @@ pub async fn form(
LogEntry::new(&mut *tx, u, LogAction::CreateQuote { id: q.id }).await?;
tx.commit().await?;
if let Ok(webhook_url) = std::env::var("DISCORD_WEBHOOK_URL") {
match Url::parse(&webhook_url) {
Ok(u) => q.post_msg_webhook(u),
Err(e) => log::error!("Tried to post webhook, failed to parse url: {e}"),
}
}
Ok(Redirect::to("/dashboard").into_response())
}