commit
Updates
diff --git a/src/avatars.rs b/src/avatars.rs
index 41e2362..f923635 100644
--- a/src/avatars.rs
+++ b/src/avatars.rs
@@ -23,10 +23,10 @@ pub struct Avatars {
pub fn avatar_urls(speakers: &[Member]) -> Vec<String> {
speakers
- .iter()
- .filter_map(Member::webhook_avatar)
- .map(str::to_owned)
- .collect()
+ .iter()
+ .filter_map(Member::webhook_avatar)
+ .map(str::to_owned)
+ .collect()
}
impl Avatars {
@@ -34,8 +34,10 @@ impl Avatars {
if urls.is_empty() {
return Ok(Vec::new());
}
+
let cell = {
let mut cached = self.merged.lock().await;
+
match &*cached {
Some((key, cell)) if key == &urls => cell.clone(),
_ => {
@@ -58,6 +60,7 @@ impl Bot {
speakers: &[Member],
) -> Option<String> {
let fallback = || Some(ctx.cache.current_user().face());
+
match speakers {
[member] => return member.webhook_avatar().map(str::to_owned).or_else(fallback),
many if many.len() > MAX_NAMED => {
@@ -67,26 +70,29 @@ impl Bot {
}
let urls = avatar_urls(speakers);
+
if self.avatars.installed.lock().await.get(&webhook.id) == Some(&urls) {
return None;
}
let result = async {
let png = self.avatars.png(&self.web, urls.clone()).await?;
+
if png.is_empty() {
return Ok::<_, anyhow::Error>(false);
}
+
let token = webhook
- .token
- .as_ref()
- .map(ExposeSecret::expose_secret)
- .ok_or_else(|| anyhow::anyhow!("webhook had no token"))?;
+ .token
+ .as_ref()
+ .map(ExposeSecret::expose_secret)
+ .ok_or_else(|| anyhow::anyhow!("webhook had no token"))?;
let data = serde_json::json!({
"avatar": format!("data:image/png;base64,{}", STANDARD.encode(png)),
});
ctx.http
- .edit_webhook_with_token(webhook.id, token, &data, None)
- .await?;
+ .edit_webhook_with_token(webhook.id, token, &data, None)
+ .await?;
self.avatars.installed.lock().await.insert(webhook.id, urls);
Ok(true)
}
@@ -107,6 +113,7 @@ async fn merge(web: &reqwest::Client, urls: &[String]) -> anyhow::Result<Vec<u8>
let images = futures_util::future::try_join_all(urls.iter().map(|url| async move {
let mut response = web.get(url).send().await?.error_for_status()?;
let mut bytes = Vec::new();
+
while let Some(chunk) = response.chunk().await? {
anyhow::ensure!(
bytes.len() + chunk.len() <= 16 * 1024 * 1024,
@@ -114,8 +121,9 @@ async fn merge(web: &reqwest::Client, urls: &[String]) -> anyhow::Result<Vec<u8>
);
bytes.extend_from_slice(&chunk);
}
+
Ok::<_, anyhow::Error>(bytes)
- }))
+ }))
.await?;
let directory = tempfile::tempdir()?;
@@ -124,7 +132,7 @@ async fn merge(web: &reqwest::Client, urls: &[String]) -> anyhow::Result<Vec<u8>
command.current_dir(directory.path()).kill_on_drop(true);
command.args([
"-limit", "thread", "2", "-limit", "memory", "128MiB", "-limit", "disk", "128MiB",
- ]);
+ ]);
for (index, bytes) in images.iter().enumerate() {
let format = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
@@ -157,11 +165,12 @@ async fn merge(web: &reqwest::Client, urls: &[String]) -> anyhow::Result<Vec<u8>
dimensions,
"+repage".into(),
")".into(),
- ]);
+ ]);
}
+
command.args(["+append", "png:-"]);
let output =
- tokio::time::timeout(std::time::Duration::from_secs(15), command.output()).await??;
+ tokio::time::timeout(std::time::Duration::from_secs(15), command.output()).await??;
anyhow::ensure!(
output.status.success(),
"ImageMagick failed: {}",
diff --git a/src/cards.rs b/src/cards.rs
index 7424c2a..9d54785 100644
--- a/src/cards.rs
+++ b/src/cards.rs
@@ -54,6 +54,7 @@ fn shorten(content: &str) -> String {
if utf16_len(content) > 1000 {
return format!("{}…", truncate(content, 999));
}
+
content.into()
}
@@ -62,9 +63,9 @@ fn colour(input: Option<&str>) -> u32 {
let full;
let hex = if hex.len() == 3 && hex.is_ascii() {
full = hex
- .chars()
- .flat_map(|digit| [digit, digit])
- .collect::<String>();
+ .chars()
+ .flat_map(|digit| [digit, digit])
+ .collect::<String>();
&full
} else {
hex
@@ -73,23 +74,26 @@ fn colour(input: Option<&str>) -> u32 {
if hex.len() == 6 && hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return u32::from_str_radix(hex, 16).unwrap_or(ACCENT);
}
+
ACCENT
}
pub fn member_card(member: &Member) -> Value {
let name = member
- .display_name
- .as_deref()
- .filter(|name| !name.is_empty())
- .unwrap_or(&member.name);
+ .display_name
+ .as_deref()
+ .filter(|name| !name.is_empty())
+ .unwrap_or(&member.name);
let mut heading = format!("## {name}");
+
if let Some(pronouns) = member
- .pronouns
- .as_deref()
- .filter(|pronouns| !pronouns.is_empty())
+ .pronouns
+ .as_deref()
+ .filter(|pronouns| !pronouns.is_empty())
{
heading.push_str(&format!("\n{pronouns}"));
}
+
if let Some(status) = &member.status {
let status_line = format!(
"{} {}",
@@ -101,18 +105,21 @@ pub fn member_card(member: &Member) -> Value {
let mut components = vec![header(heading, member.avatar_url.as_deref())];
let mut details = Vec::new();
+
if let Some(description) = member
- .description
- .as_deref()
- .filter(|value| !value.is_empty())
+ .description
+ .as_deref()
+ .filter(|value| !value.is_empty())
{
details.push(format!("**About**\n{}", shorten(description)));
}
+
for (label, entries) in [("Tags", &member.tags), ("Pride", &member.pride)] {
if !entries.is_empty() {
details.push(format!("**{label}**\n{}", entries.join(", ")));
}
}
+
if !details.is_empty() {
components.push(json!({ "type": 14 }));
components.push(text(details.join("\n\n")));
@@ -122,7 +129,7 @@ pub fn member_card(member: &Member) -> Value {
components.push(link(
"Open page",
format!("https://doughmination.co.uk/{id}"),
- ));
+ ));
container(colour(member.color.as_deref()), components)
}
@@ -133,6 +140,7 @@ pub fn info(
system: Option<&str>,
) -> Vec<Value> {
let mut footer = vec![format!("Sent by <@{owner}>")];
+
if let Some(name) = system.filter(|name| !name.is_empty()) {
footer.push(name.into());
}
@@ -140,9 +148,11 @@ pub fn info(
let mut components = match members {
Some(members) => {
let hidden = members.len().saturating_sub(MAX_NAMED);
+
if hidden > 0 {
footer.insert(0, format!("& {hidden} more"));
}
+
members.iter().take(MAX_NAMED).map(member_card).collect()
}
None => vec![container(
@@ -160,11 +170,11 @@ pub fn info(
pub fn display_name(message: &Message) -> &str {
message
- .member
- .as_ref()
- .and_then(|member| member.nick.as_deref())
- .or(message.author.global_name.as_deref())
- .unwrap_or(&message.author.name)
+ .member
+ .as_ref()
+ .and_then(|member| member.nick.as_deref())
+ .or(message.author.global_name.as_deref())
+ .unwrap_or(&message.author.name)
}
pub fn reply(message: &Message, target: &Message) -> Vec<Value> {
@@ -172,10 +182,10 @@ pub fn reply(message: &Message, target: &Message) -> Vec<Value> {
"*Sent an attachment*".to_owned()
} else {
shorten(&message.content)
- .split('\n')
- .map(|line| format!("> {line}"))
- .collect::<Vec<_>>()
- .join("\n")
+ .split('\n')
+ .map(|line| format!("> {line}"))
+ .collect::<Vec<_>>()
+ .join("\n")
};
let heading = format!(
"### ↪ {} replied to {}\n{body}",
@@ -189,8 +199,10 @@ pub fn reply(message: &Message, target: &Message) -> Vec<Value> {
link("Jump to reply", message.link()),
],
)];
+
if !message.content.is_empty() && !message.attachments.is_empty() {
components.push(text("-# Also sent an attachment"));
}
+
components
}
diff --git a/src/commands.rs b/src/commands.rs
deleted file mode 100644
index 9778574..0000000
--- a/src/commands.rs
+++ /dev/null
@@ -1,229 +0,0 @@
-// src/commands.rs
-
-use std::time::Instant;
-
-use serde_json::json;
-use serenity::all::{Context, GuildId, Message};
-
-use crate::{Bot, cards, discord, proxy, site::API};
-
-const HELP: &str = include_str!("help.txt");
-const EXPLAIN: &str = include_str!("explain.txt");
-
-impl Bot {
- pub async fn command(
- &self,
- ctx: &Context,
- message: &Message,
- guild: GuildId,
- ) -> anyhow::Result<bool> {
- let Some((name, args, rest)) = proxy::command(&message.content) else {
- return Ok(false);
- };
-
- let reply = match name.as_str() {
- "help" => HELP.trim_end().into(),
- "explain" | "ex" => EXPLAIN
- .trim_end()
- .replace("<@OWNER>", &format!("<@{}>", self.owner)),
- "autoproxy" | "ap" => self.autoproxy(guild, &args).await?,
- "ping" => {
- self.ping(ctx, message).await?;
- return Ok(true);
- }
- "edit" | "e" => {
- let Some(problem) = self.edit(ctx, message, rest).await? else {
- return Ok(true);
- };
- problem.into()
- }
- "member" | "m" => {
- if args.len() != 1 {
- "Use `d$member <member>`, like `d$member aether`.".into()
- } else {
- let state = self.system.read().await;
- let match_card = state
- .members
- .iter()
- .find(|member| member.name.to_lowercase() == args[0])
- .map(cards::member_card);
- drop(state);
- if let Some(card) = match_card {
- discord::reply(
- ctx,
- message,
- json!({
- "flags": cards::COMPONENTS_V2,
- "components": [card],
- }),
- )
- .await?;
- return Ok(true);
- }
- format!("No member called `{}`.", args[0])
- }
- }
- "reproxy" | "rp" | "switch" | "sw" => {
- let switching = matches!(name.as_str(), "switch" | "sw");
- if args.is_empty() {
- if switching {
- "Use `d$switch <member>`, like `d$switch c1`, several like `d$sw c1 c2`, or `d$sw out`.".into()
- } else {
- "Use `d$reproxy <member>`, like `d$reproxy c1`. Several work too: `d$rp c1 c2`.".into()
- }
- } else if switching && args == ["out"] {
- match self.switch_front(&[]).await {
- Ok(()) => "Switched out. Nobody is fronting.".into(),
- Err(problem) => problem,
- }
- } else {
- let state = self.system.read().await;
- let mut found = Vec::new();
- let mut missing = Vec::new();
- for name in &args {
- match state
- .members
- .iter()
- .find(|member| member.name.to_lowercase() == *name)
- {
- Some(member) => found.push(member.clone()),
- None => missing.push(format!("`{name}`")),
- }
- }
- drop(state);
- if !missing.is_empty() {
- format!(
- "No member called {}. Use their short name, like `c1`.",
- missing.join(", ")
- )
- } else if switching {
- let ids = found
- .iter()
- .map(|member| member.id.as_str())
- .collect::<Vec<_>>();
- match self.switch_front(&ids).await {
- Ok(()) => {
- let speakers = found.iter().collect::<Vec<_>>();
- format!("Switched in **{}**.", proxy::webhook_name(&speakers, None))
- }
- Err(problem) => problem,
- }
- } else {
- let Some(problem) = self.reproxy(ctx, message, found).await? else {
- return Ok(true);
- };
- problem.into()
- }
- }
- }
- _ => format!("Unknown command `{name}`. Try `d$help`."),
- };
-
- discord::reply(ctx, message, json!({ "content": reply })).await?;
- Ok(true)
- }
-
- async fn autoproxy(&self, guild: GuildId, args: &[String]) -> anyhow::Result<String> {
- let global = args.iter().any(|arg| arg == "-g");
- let choice = args
- .iter()
- .find(|arg| arg.as_str() != "-g")
- .map(String::as_str);
- let mut settings = self.settings.lock().await;
- let current = settings.guilds.get(&guild).copied().unwrap_or(false);
- let current_name = if current { "on" } else { "off" };
- let total = settings.guilds.len();
-
- let enabled = match choice {
- Some("on") => true,
- Some("off") => false,
- None if global => {
- let enabled_count = settings.guilds.values().filter(|&&enabled| enabled).count();
- return Ok(format!(
- "Autoproxy is **on** in {enabled_count} of {total} servers."
- ));
- }
- None => return Ok(format!("Autoproxy in this server is **{current_name}**.")),
- _ if global => return Ok("Use `d$autoproxy -g on` or `d$autoproxy -g off`.".into()),
- _ => {
- return Ok(
- "Use `d$autoproxy on|off`, or `d$autoproxy -g on|off` for every server.".into(),
- );
- }
- };
-
- let choice = if enabled { "on" } else { "off" };
- let mut updated = settings.clone();
- let response = if global {
- updated
- .guilds
- .values_mut()
- .for_each(|value| *value = enabled);
- format!("Autoproxy is now **{choice}** in all {total} servers.")
- } else if current == enabled {
- return Ok(format!("Autoproxy in this server is already **{choice}**."));
- } else {
- updated.guilds.insert(guild, enabled);
- format!("Autoproxy in this server is now **{choice}**.")
- };
- updated.save()?;
- *settings = updated;
- Ok(response)
- }
-
- async fn ping(&self, ctx: &Context, message: &Message) -> anyhow::Result<()> {
- let manager = self.shards.get().expect("shard manager has been set");
- let heartbeat = manager
- .runners
- .lock()
- .await
- .get(&ctx.shard_id)
- .and_then(|runner| runner.latency)
- .map_or_else(
- || "not measured yet".into(),
- |duration| format!("{} ms", duration.as_millis()),
- );
- let report = |discord: &str, api: &str| {
- format!(
- "🏓 Pong!\nDiscord heartbeat: {heartbeat}\nDiscord round trip: {discord}\nSystem API: {api}"
- )
- };
-
- let api = async {
- let started = Instant::now();
- let response = self.web.get(format!("{API}/system")).send().await;
- let elapsed = started.elapsed().as_millis();
- match response {
- Ok(response) if response.status().is_success() => format!("{elapsed} ms"),
- Ok(response) => format!("HTTP {} after {elapsed} ms", response.status().as_u16()),
- Err(error) => format!("failed ({error})"),
- }
- };
- let discord = async {
- let started = Instant::now();
- let response = discord::reply(
- ctx,
- message,
- json!({
- "content": report("measuring…", "measuring…"),
- }),
- )
- .await?;
- Ok::<_, anyhow::Error>((response, format!("{} ms", started.elapsed().as_millis())))
- };
- let (api, discord) = tokio::join!(api, discord);
- let (response, elapsed) = discord?;
- ctx.http
- .edit_message(
- message.channel_id,
- response,
- &json!({
- "content": report(&elapsed, &api),
- "allowed_mentions": discord::user_mentions(),
- }),
- Vec::new(),
- )
- .await?;
- Ok(())
- }
-}
diff --git a/src/commands/autoproxy/mod.rs b/src/commands/autoproxy/mod.rs
new file mode 100644
index 0000000..fbc9578
--- /dev/null
+++ b/src/commands/autoproxy/mod.rs
@@ -0,0 +1,59 @@
+// src/commands/autoproxy/mod.rs
+
+use serenity::all::GuildId;
+
+use crate::Bot;
+
+impl Bot {
+ pub(super) async fn autoproxy(
+ &self,
+ guild: GuildId,
+ args: &[String],
+ ) -> anyhow::Result<String> {
+ let global = args.iter().any(|arg| arg == "-g");
+ let choice = args
+ .iter()
+ .find(|arg| arg.as_str() != "-g")
+ .map(String::as_str);
+ let mut settings = self.settings.lock().await;
+ let current = settings.guilds.get(&guild).copied().unwrap_or(false);
+ let current_name = if current { "on" } else { "off" };
+ let total = settings.guilds.len();
+
+ let enabled = match choice {
+ Some("on") => true,
+ Some("off") => false,
+ None if global => {
+ let enabled_count = settings.guilds.values().filter(|&&enabled| enabled).count();
+ return Ok(format!(
+ "Autoproxy is **on** in {enabled_count} of {total} servers."
+ ));
+ }
+ None => return Ok(format!("Autoproxy in this server is **{current_name}**.")),
+ _ if global => return Ok("Use `d$autoproxy -g on` or `d$autoproxy -g off`.".into()),
+ _ => {
+ return Ok(
+ "Use `d$autoproxy on|off`, or `d$autoproxy -g on|off` for every server.".into(),
+ );
+ }
+ };
+
+ let choice = if enabled { "on" } else { "off" };
+ let mut updated = settings.clone();
+ let response = if global {
+ updated
+ .guilds
+ .values_mut()
+ .for_each(|value| *value = enabled);
+ format!("Autoproxy is now **{choice}** in all {total} servers.")
+ } else if current == enabled {
+ return Ok(format!("Autoproxy in this server is already **{choice}**."));
+ } else {
+ updated.guilds.insert(guild, enabled);
+ format!("Autoproxy in this server is now **{choice}**.")
+ };
+ updated.save()?;
+ *settings = updated;
+ Ok(response)
+ }
+}
diff --git a/src/commands/edit/mod.rs b/src/commands/edit/mod.rs
new file mode 100644
index 0000000..b5e7251
--- /dev/null
+++ b/src/commands/edit/mod.rs
@@ -0,0 +1,75 @@
+// src/commands/edit/mod.rs
+
+use secrecy::ExposeSecret;
+use serde_json::json;
+use serenity::all::{Context, Message};
+
+use crate::{
+ Bot, cards,
+ discord::{Destination, NO_TARGET, Target, existing_media, user_mentions},
+ proxy,
+};
+
+impl Bot {
+ pub(super) async fn edit(
+ &self,
+ ctx: &Context,
+ command: &Message,
+ content: &str,
+ ) -> anyhow::Result<Option<&'static str>> {
+ let Some(Target {
+ message: target,
+ components,
+ classic,
+ }) = self.target(ctx, command).await?
+ else {
+ return Ok(Some(NO_TARGET));
+ };
+
+ if content.is_empty() && target.attachments.is_empty() {
+ return Ok(Some(
+ "That would leave the message empty. Use ❌ to delete it instead.",
+ ));
+ }
+
+ if classic && proxy::utf16_len(content) > 2000 {
+ return Ok(Some(
+ "Messages with links can only be 2000 characters long.",
+ ));
+ }
+
+ let Some(dest) =
+ Destination::resolve(ctx, command.channel_id, command.guild_id.unwrap()).await?
+ else {
+ return Ok(Some("Can't use webhooks in this channel."));
+ };
+ let id = target.webhook_id.unwrap();
+ let webhook = id.to_webhook(&ctx.http).await?;
+ let token = webhook
+ .token
+ .as_ref()
+ .map(ExposeSecret::expose_secret)
+ .ok_or_else(|| anyhow::anyhow!("webhook had no token"))?;
+ let mut payload = json!({ "allowed_mentions": user_mentions() });
+
+ if classic {
+ payload["content"] = json!(content);
+ } else {
+ let (mut components, attachments) = existing_media(&target, components, true);
+
+ if !content.is_empty() {
+ components.insert(0, cards::text(content));
+ }
+
+ payload["components"] = json!(components);
+ payload["attachments"] = json!(attachments);
+ }
+
+ ctx.http
+ .edit_webhook_message(id, dest.thread, token, target.id, &payload, Vec::new())
+ .await
+ .map_err(|_| anyhow::anyhow!("Discord rejected webhook edit"))?;
+ command.delete(&ctx.http).await?;
+ Ok(None)
+ }
+}
diff --git a/src/explain.txt b/src/commands/explain/explain.txt
similarity index 100%
rename from src/explain.txt
rename to src/commands/explain/explain.txt
diff --git a/src/commands/explain/mod.rs b/src/commands/explain/mod.rs
new file mode 100644
index 0000000..56b1535
--- /dev/null
+++ b/src/commands/explain/mod.rs
@@ -0,0 +1,11 @@
+// src/commands/explain/mod.rs
+
+use crate::Bot;
+
+impl Bot {
+ pub(super) fn explain(&self) -> String {
+ include_str!("explain.txt")
+ .trim_end()
+ .replace("<@OWNER>", &format!("<@{}>", self.owner))
+ }
+}
diff --git a/src/commands/fban/mod.rs b/src/commands/fban/mod.rs
new file mode 100644
index 0000000..446f508
--- /dev/null
+++ b/src/commands/fban/mod.rs
@@ -0,0 +1,51 @@
+// src/commands/fban/mod.rs
+
+use serde_json::json;
+use serenity::all::{Context, Message};
+
+use crate::discord;
+
+const USAGE: &str = "Use `d$fban <@user or user ID> <reason>`.";
+
+pub(super) async fn run(
+ ctx: &Context,
+ message: &Message,
+ input: &str,
+) -> anyhow::Result<Option<String>> {
+ let Some((target, reason)) = input.split_once(char::is_whitespace) else {
+ return Ok(Some(USAGE.into()));
+ };
+ let reason = reason.trim_start();
+
+ let user_id = target
+ .strip_prefix("<@")
+ .and_then(|mention| mention.strip_suffix('>'))
+ .map_or(target, |mention| {
+ mention.strip_prefix('!').unwrap_or(mention)
+ });
+
+ if !user_id.bytes().all(|byte| byte.is_ascii_digit())
+ || !user_id.parse::<u64>().is_ok_and(|id| id > 0)
+ || reason.is_empty()
+ {
+ return Ok(Some(USAGE.into()));
+ }
+
+ discord::reply(
+ ctx,
+ message,
+ json!({
+ "embeds": [{
+ "title": "🔨 User fake-banned",
+ "description": reason,
+ "color": 0xED4245,
+ "fields": [{
+ "name": "User",
+ "value": format!("<@{user_id}>"),
+ }],
+ }],
+ }),
+ )
+ .await?;
+ Ok(None)
+}
diff --git a/src/help.txt b/src/commands/help/help.txt
similarity index 92%
rename from src/help.txt
rename to src/commands/help/help.txt
index ead1329..3922349 100644
--- a/src/help.txt
+++ b/src/commands/help/help.txt
@@ -5,4 +5,5 @@
`d$switch <member>` sets who's fronting on the site, like `d$switch c1 c2`. `d$switch out` clears it. `d$sw` works too.
`d$member <member>` shows a member's card, like `d$member aether`. `d$m` works too.
`d$ping` shows how fast Discord and the system API respond.
+`d$fban <@user or user ID> <reason>` posts a fake ban embed.
-# React ❌ to delete a proxied message, ❓ to see who sent it.
diff --git a/src/commands/help/mod.rs b/src/commands/help/mod.rs
new file mode 100644
index 0000000..58f750d
--- /dev/null
+++ b/src/commands/help/mod.rs
@@ -0,0 +1,5 @@
+// src/commands/help/mod.rs
+
+pub(super) fn text() -> &'static str {
+ include_str!("help.txt").trim_end()
+}
diff --git a/src/commands/member/mod.rs b/src/commands/member/mod.rs
new file mode 100644
index 0000000..2ddbf2f
--- /dev/null
+++ b/src/commands/member/mod.rs
@@ -0,0 +1,44 @@
+// src/commands/member/mod.rs
+
+use serde_json::json;
+use serenity::all::{Context, Message};
+
+use crate::{Bot, cards, discord};
+
+impl Bot {
+ pub(super) async fn member(
+ &self,
+ ctx: &Context,
+ message: &Message,
+ args: &[String],
+ ) -> anyhow::Result<Option<String>> {
+ let [name] = args else {
+ return Ok(Some(
+ "Use `d$member <member>`, like `d$member aether`.".into(),
+ ));
+ };
+
+ let state = self.system.read().await;
+ let match_card = state
+ .members
+ .iter()
+ .find(|member| member.name.to_lowercase() == *name)
+ .map(cards::member_card);
+ drop(state);
+
+ let Some(card) = match_card else {
+ return Ok(Some(format!("No member called `{name}`.")));
+ };
+
+ discord::reply(
+ ctx,
+ message,
+ json!({
+ "flags": cards::COMPONENTS_V2,
+ "components": [card],
+ }),
+ )
+ .await?;
+ Ok(None)
+ }
+}
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
new file mode 100644
index 0000000..20de25b
--- /dev/null
+++ b/src/commands/mod.rs
@@ -0,0 +1,80 @@
+// src/commands/mod.rs
+
+mod autoproxy;
+mod edit;
+mod explain;
+mod fban;
+mod help;
+mod member;
+mod ping;
+mod reproxy;
+mod switch;
+
+use serde_json::json;
+use serenity::all::{Context, GuildId, Message};
+
+use crate::{
+ Bot, discord,
+ proxy::{self, Member},
+};
+
+impl Bot {
+ pub async fn command(
+ &self,
+ ctx: &Context,
+ message: &Message,
+ guild: GuildId,
+ ) -> anyhow::Result<bool> {
+ let Some((name, args, rest)) = proxy::command(&message.content) else {
+ return Ok(false);
+ };
+
+ let reply = match name.as_str() {
+ "help" => Some(help::text().into()),
+ "explain" | "ex" => Some(self.explain()),
+ "autoproxy" | "ap" => Some(self.autoproxy(guild, &args).await?),
+ "edit" | "e" => self.edit(ctx, message, rest).await?.map(str::to_owned),
+ "fban" => fban::run(ctx, message, rest).await?,
+ "member" | "m" => self.member(ctx, message, &args).await?,
+ "ping" => {
+ self.ping(ctx, message).await?;
+ None
+ }
+ "reproxy" | "rp" => self.reproxy(ctx, message, &args).await?,
+ "switch" | "sw" => Some(self.switch(&args).await),
+ _ => Some(format!("Unknown command `{name}`. Try `d$help`.")),
+ };
+
+ if let Some(reply) = reply {
+ discord::reply(ctx, message, json!({ "content": reply })).await?;
+ }
+
+ Ok(true)
+ }
+
+ async fn command_members(&self, args: &[String]) -> Result<Vec<Member>, String> {
+ let state = self.system.read().await;
+ let mut found = Vec::new();
+ let mut missing = Vec::new();
+
+ for name in args {
+ match state
+ .members
+ .iter()
+ .find(|member| member.name.to_lowercase() == *name)
+ {
+ Some(member) => found.push(member.clone()),
+ None => missing.push(format!("`{name}`")),
+ }
+ }
+
+ if missing.is_empty() {
+ Ok(found)
+ } else {
+ Err(format!(
+ "No member called {}. Use their short name, like `c1`.",
+ missing.join(", ")
+ ))
+ }
+ }
+}
diff --git a/src/commands/ping/mod.rs b/src/commands/ping/mod.rs
new file mode 100644
index 0000000..91d7a80
--- /dev/null
+++ b/src/commands/ping/mod.rs
@@ -0,0 +1,67 @@
+// src/commands/ping/mod.rs
+
+use std::time::Instant;
+
+use serde_json::json;
+use serenity::all::{Context, Message};
+
+use crate::{Bot, discord, site::API};
+
+impl Bot {
+ pub(super) async fn ping(&self, ctx: &Context, message: &Message) -> anyhow::Result<()> {
+ let manager = self.shards.get().expect("shard manager has been set");
+ let heartbeat = manager
+ .runners
+ .lock()
+ .await
+ .get(&ctx.shard_id)
+ .and_then(|runner| runner.latency)
+ .map_or_else(
+ || "not measured yet".into(),
+ |duration| format!("{} ms", duration.as_millis()),
+ );
+ let report = |discord: &str, api: &str| {
+ format!(
+ "🏓 Pong!\nDiscord heartbeat: {heartbeat}\nDiscord round trip: {discord}\nSystem API: {api}"
+ )
+ };
+
+ let api = async {
+ let started = Instant::now();
+ let response = self.web.get(format!("{API}/system")).send().await;
+ let elapsed = started.elapsed().as_millis();
+
+ match response {
+ Ok(response) if response.status().is_success() => format!("{elapsed} ms"),
+ Ok(response) => format!("HTTP {} after {elapsed} ms", response.status().as_u16()),
+ Err(error) => format!("failed ({error})"),
+ }
+ };
+ let discord = async {
+ let started = Instant::now();
+ let response = discord::reply(
+ ctx,
+ message,
+ json!({
+ "content": report("measuring…", "measuring…"),
+ }),
+ )
+ .await?;
+ Ok::<_, anyhow::Error>((response, format!("{} ms", started.elapsed().as_millis())))
+ };
+ let (api, discord) = tokio::join!(api, discord);
+ let (response, elapsed) = discord?;
+ ctx.http
+ .edit_message(
+ message.channel_id,
+ response,
+ &json!({
+ "content": report(&elapsed, &api),
+ "allowed_mentions": discord::user_mentions(),
+ }),
+ Vec::new(),
+ )
+ .await?;
+ Ok(())
+ }
+}
diff --git a/src/commands/reproxy/mod.rs b/src/commands/reproxy/mod.rs
new file mode 100644
index 0000000..7b64ee1
--- /dev/null
+++ b/src/commands/reproxy/mod.rs
@@ -0,0 +1,81 @@
+// src/commands/reproxy/mod.rs
+
+use serde_json::json;
+use serenity::all::{Context, Message};
+
+use crate::{
+ Bot,
+ cards::COMPONENTS_V2,
+ discord::{Destination, NO_TARGET, Target, existing_media},
+};
+
+impl Bot {
+ pub(super) async fn reproxy(
+ &self,
+ ctx: &Context,
+ command: &Message,
+ args: &[String],
+ ) -> anyhow::Result<Option<String>> {
+ if args.is_empty() {
+ return Ok(Some(
+ "Use `d$reproxy <member>`, like `d$reproxy c1`. Several work too: `d$rp c1 c2`."
+ .into(),
+ ));
+ }
+
+ let speakers = match self.command_members(args).await {
+ Ok(found) => found,
+ Err(problem) => return Ok(Some(problem)),
+ };
+
+ let Some(Target {
+ message: target,
+ components,
+ classic,
+ }) = self.target(ctx, command).await?
+ else {
+ return Ok(Some(NO_TARGET.into()));
+ };
+ let Some(dest) =
+ Destination::resolve(ctx, command.channel_id, command.guild_id.unwrap()).await?
+ else {
+ return Ok(Some("Can't use webhooks in this channel.".into()));
+ };
+
+ let (components, _) = existing_media(&target, components, false);
+ let attachments: Vec<_> = target
+ .attachments
+ .iter()
+ .enumerate()
+ .map(|(index, file)| json!({ "id": index, "filename": file.filename }))
+ .collect();
+ let mut payload = json!({ "attachments": attachments });
+
+ if classic {
+ payload["content"] = json!(target.content);
+ } else {
+ payload["flags"] = json!(COMPONENTS_V2);
+ payload["components"] = json!(components);
+ }
+
+ let files = futures_util::future::try_join_all(
+ target
+ .attachments
+ .iter()
+ .map(|file| self.download(&file.url, file.filename.clone())),
+ )
+ .await?;
+
+ let slot = self.channel_webhook(&dest).await;
+ let mut locked = slot.lock().await;
+ let webhook = Self::ensure_webhook(ctx, &dest, &mut locked).await?;
+ let (sent, _) = self
+ .send_proxy(ctx, &dest, &webhook, &speakers, payload, files)
+ .await?;
+ drop(locked);
+ self.remember(sent, speakers).await;
+ target.delete(&ctx.http).await?;
+ command.delete(&ctx.http).await?;
+ Ok(None)
+ }
+}
diff --git a/src/commands/switch/mod.rs b/src/commands/switch/mod.rs
new file mode 100644
index 0000000..fcd9e2b
--- /dev/null
+++ b/src/commands/switch/mod.rs
@@ -0,0 +1,35 @@
+// src/commands/switch/mod.rs
+
+use crate::{Bot, proxy};
+
+impl Bot {
+ pub(super) async fn switch(&self, args: &[String]) -> String {
+ if args.is_empty() {
+ return "Use `d$switch <member>`, like `d$switch c1`, several like `d$sw c1 c2`, or `d$sw out`.".into();
+ }
+
+ if args == ["out"] {
+ return match self.switch_front(&[]).await {
+ Ok(()) => "Switched out. Nobody is fronting.".into(),
+ Err(problem) => problem,
+ };
+ }
+
+ let found = match self.command_members(args).await {
+ Ok(found) => found,
+ Err(problem) => return problem,
+ };
+
+ let ids = found
+ .iter()
+ .map(|member| member.id.as_str())
+ .collect::<Vec<_>>();
+ match self.switch_front(&ids).await {
+ Ok(()) => {
+ let speakers = found.iter().collect::<Vec<_>>();
+ format!("Switched in **{}**.", proxy::webhook_name(&speakers, None))
+ }
+ Err(problem) => problem,
+ }
+ }
+}
diff --git a/src/discord.rs b/src/discord.rs
index 9d25d27..69d0199 100644
--- a/src/discord.rs
+++ b/src/discord.rs
@@ -18,7 +18,7 @@ use crate::{
};
pub const NO_TARGET: &str =
- "No proxied message found. Reply to one, or send one in the last 50 messages.";
+"No proxied message found. Reply to one, or send one in the last 50 messages.";
pub fn user_mentions() -> Value {
json!({ "parse": ["users"], "replied_user": false })
@@ -26,18 +26,18 @@ pub fn user_mentions() -> Value {
pub fn owned(ctx: &Context, message: &Message) -> bool {
message.webhook_id.is_some()
- && ctx
- .http
- .application_id()
- .is_some_and(|id| Some(id) == message.application_id)
+ && ctx
+ .http
+ .application_id()
+ .is_some_and(|id| Some(id) == message.application_id)
}
pub fn classic(content: &str) -> bool {
static LINK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"https?://\S").unwrap());
proxy::utf16_len(content) <= 2000
- && LINK
- .find_iter(content)
- .any(|hit| !content[..hit.start()].ends_with('<'))
+ && LINK
+ .find_iter(content)
+ .any(|hit| !content[..hit.start()].ends_with('<'))
}
fn is_thread(kind: ChannelType) -> bool {
@@ -49,6 +49,7 @@ fn is_thread(kind: ChannelType) -> bool {
pub async fn reference(ctx: &Context, message: &Message) -> Option<Message> {
let reference = message.message_reference.as_ref()?;
+
if reference.kind != MessageReferenceKind::Default {
return None;
}
@@ -58,8 +59,8 @@ pub async fn reference(ctx: &Context, message: &Message) -> Option<Message> {
}
let mut target = fetch_target(ctx, reference.channel_id, reference.message_id?)
- .await?
- .message;
+ .await?
+ .message;
target.guild_id = target.guild_id.or(reference.guild_id).or(message.guild_id);
Some(target)
}
@@ -97,32 +98,32 @@ async fn send_json(ctx: &Context, channel_id: ChannelId, payload: &Value) -> any
.http
.fire(
Request::new(Route::ChannelMessages { channel_id }, LightMethod::Post)
- .body(Some(serde_json::to_vec(payload)?)),
+ .body(Some(serde_json::to_vec(payload)?)),
)
.await?)
}
-struct Target {
- message: Message,
- components: Vec<Value>,
- classic: bool,
+pub(crate) struct Target {
+ pub(crate) message: Message,
+ pub(crate) components: Vec<Value>,
+ pub(crate) classic: bool,
}
impl Target {
fn from_json(mut raw: Value) -> serde_json::Result<Self> {
let classic = raw["flags"].as_u64().unwrap_or_default() & u64::from(COMPONENTS_V2) == 0;
let components = raw
- .as_object_mut()
- .and_then(|object| object.remove("components"))
- .and_then(|components| components.as_array().cloned())
- .unwrap_or_default();
+ .as_object_mut()
+ .and_then(|object| object.remove("components"))
+ .and_then(|components| components.as_array().cloned())
+ .unwrap_or_default();
raw.as_object_mut()
- .map(|object| object.remove("referenced_message"));
+ .map(|object| object.remove("referenced_message"));
Ok(Self {
message: serde_json::from_value(raw)?,
components,
classic,
- })
+ })
}
}
@@ -132,34 +133,34 @@ async fn fetch_target(
message_id: MessageId,
) -> Option<Target> {
let raw = ctx
- .http
- .fire::<Value>(Request::new(
- Route::ChannelMessage {
- channel_id,
- message_id,
- },
- LightMethod::Get,
+ .http
+ .fire::<Value>(Request::new(
+ Route::ChannelMessage {
+ channel_id,
+ message_id,
+ },
+ LightMethod::Get,
))
- .await
- .ok()?;
+ .await
+ .ok()?;
Target::from_json(raw).ok()
}
-struct Destination {
+pub(crate) struct Destination {
parent: ChannelId,
- thread: Option<ChannelId>,
+ pub(crate) thread: Option<ChannelId>,
}
impl Destination {
- async fn resolve(
+ pub(crate) async fn resolve(
ctx: &Context,
channel: ChannelId,
guild_id: GuildId,
) -> anyhow::Result<Option<Self>> {
let cached = ctx
- .cache
- .guild(guild_id)
- .and_then(|guild| guild.channels.get(&channel).cloned());
+ .cache
+ .guild(guild_id)
+ .and_then(|guild| guild.channels.get(&channel).cloned());
let guild = match cached {
Some(guild) => guild,
None => match channel.to_channel(&ctx.http).await? {
@@ -167,38 +168,41 @@ impl Destination {
_ => return Ok(None),
},
};
+
if is_thread(guild.kind) {
return Ok(guild.parent_id.map(|parent| Self {
parent,
thread: Some(channel),
- }));
+ }));
}
+
if !matches!(
guild.kind,
ChannelType::Text | ChannelType::News | ChannelType::Voice | ChannelType::Stage
) {
return Ok(None);
}
+
Ok(Some(Self {
parent: channel,
thread: None,
- }))
+ }))
}
}
-type LockedWebhook = Arc<Mutex<Option<Webhook>>>;
+pub(crate) type LockedWebhook = Arc<Mutex<Option<Webhook>>>;
impl Bot {
- async fn channel_webhook(&self, dest: &Destination) -> LockedWebhook {
+ pub(crate) async fn channel_webhook(&self, dest: &Destination) -> LockedWebhook {
self.webhooks
- .lock()
- .await
- .entry(dest.parent)
- .or_default()
- .clone()
+ .lock()
+ .await
+ .entry(dest.parent)
+ .or_default()
+ .clone()
}
- async fn ensure_webhook(
+ pub(crate) async fn ensure_webhook(
ctx: &Context,
dest: &Destination,
slot: &mut Option<Webhook>,
@@ -206,21 +210,22 @@ impl Bot {
if let Some(webhook) = slot {
return Ok(webhook.clone());
}
+
let bot = ctx.cache.current_user().id;
let existing = dest
- .parent
- .webhooks(&ctx.http)
- .await?
- .into_iter()
- .find(|hook| {
- hook.user.as_ref().is_some_and(|user| user.id == bot) && hook.token.is_some()
+ .parent
+ .webhooks(&ctx.http)
+ .await?
+ .into_iter()
+ .find(|hook| {
+ hook.user.as_ref().is_some_and(|user| user.id == bot) && hook.token.is_some()
});
let webhook = match existing {
Some(webhook) => webhook,
None => {
dest.parent
- .create_webhook(&ctx.http, CreateWebhook::new("proxyBot"))
- .await?
+ .create_webhook(&ctx.http, CreateWebhook::new("proxyBot"))
+ .await?
}
};
*slot = Some(webhook.clone());
@@ -235,13 +240,13 @@ impl Bot {
) -> anyhow::Result<()> {
let started = Instant::now();
let enabled = self
- .settings
- .lock()
- .await
- .guilds
- .get(&guild)
- .copied()
- .unwrap_or(false);
+ .settings
+ .lock()
+ .await
+ .guilds
+ .get(&guild)
+ .copied()
+ .unwrap_or(false);
let (speakers, content) = {
let state = self.system.read().await;
let fronters = if enabled {
@@ -258,9 +263,11 @@ impl Bot {
content.to_owned(),
)
};
+
if content.is_empty() && message.attachments.is_empty() {
return Ok(());
}
+
let Some(dest) = Destination::resolve(ctx, message.channel_id, guild).await? else {
return Ok(());
};
@@ -270,8 +277,8 @@ impl Bot {
let mut locked = slot.lock().await;
let webhook = Self::ensure_webhook(ctx, &dest, &mut locked).await?;
let (sent, send_ms) = self
- .send_proxy(ctx, &dest, &webhook, &speakers, payload, files)
- .await?;
+ .send_proxy(ctx, &dest, &webhook, &speakers, payload, files)
+ .await?;
drop(locked);
self.remember(sent, speakers).await;
@@ -284,7 +291,7 @@ impl Bot {
Ok(())
}
- async fn send_proxy(
+ pub(crate) async fn send_proxy(
&self,
ctx: &Context,
dest: &Destination,
@@ -296,45 +303,49 @@ impl Bot {
let tag = self.system.read().await.info.tag.clone();
let speakers_ref = speakers.iter().collect::<Vec<_>>();
payload["username"] = json!(proxy::webhook_name(&speakers_ref, tag.as_deref()));
+
if let Some(url) = self.avatar(ctx, webhook, speakers).await {
payload["avatar_url"] = json!(url);
}
+
payload["allowed_mentions"] = user_mentions();
let token = webhook
- .token
- .as_ref()
- .map(ExposeSecret::expose_secret)
- .ok_or_else(|| anyhow::anyhow!("webhook had no token"))?;
+ .token
+ .as_ref()
+ .map(ExposeSecret::expose_secret)
+ .ok_or_else(|| anyhow::anyhow!("webhook had no token"))?;
let started = Instant::now();
let sent = if files.is_empty() {
let mut params = vec![("wait", "true".into()), ("with_components", "true".into())];
+
if let Some(thread) = dest.thread {
params.push(("thread_id", thread.to_string()));
}
+
ctx.http
- .fire::<Value>(
- Request::new(
- Route::WebhookWithToken {
- webhook_id: webhook.id,
- token,
- },
- LightMethod::Post,
- )
- .body(Some(serde_json::to_vec(&payload)?))
- .params(Some(params)),
+ .fire::<Value>(
+ Request::new(
+ Route::WebhookWithToken {
+ webhook_id: webhook.id,
+ token,
+ },
+ LightMethod::Post,
)
- .await?
+ .body(Some(serde_json::to_vec(&payload)?))
+ .params(Some(params)),
+ )
+ .await?
} else {
// Serenity's raw webhook helper leaves every upload ID at zero.
// Build the multipart form with the same indices as the attachment metadata.
self.upload_webhook(webhook.id, token, dest.thread, &payload, &files)
- .await?
+ .await?
};
Ok((
serde_json::from_value(sent["id"].clone())?,
started.elapsed().as_millis(),
- ))
+ ))
}
async fn upload_webhook(
@@ -347,67 +358,78 @@ impl Bot {
) -> anyhow::Result<Value> {
let mut url = reqwest::Url::parse("https://discord.com/api/v10/webhooks/")?;
url.path_segments_mut()
- .expect("Discord API URL has a path")
- .pop_if_empty()
- .push(&webhook.to_string())
- .push(token);
+ .expect("Discord API URL has a path")
+ .pop_if_empty()
+ .push(&webhook.to_string())
+ .push(token);
url.query_pairs_mut()
- .append_pair("wait", "true")
- .append_pair("with_components", "true");
+ .append_pair("wait", "true")
+ .append_pair("with_components", "true");
+
if let Some(thread) = thread {
url.query_pairs_mut()
- .append_pair("thread_id", &thread.to_string());
+ .append_pair("thread_id", &thread.to_string());
}
let payload_json = serde_json::to_string(payload)?;
+
for attempt in 0..3 {
let mut form =
- reqwest::multipart::Form::new().text("payload_json", payload_json.clone());
+ reqwest::multipart::Form::new().text("payload_json", payload_json.clone());
+
for (index, file) in files.iter().enumerate() {
let part = reqwest::multipart::Part::bytes(file.data.clone())
- .file_name(file.filename.clone());
+ .file_name(file.filename.clone());
form = form.part(format!("files[{index}]"), part);
}
let response = self
- .web
- .post(url.clone())
- .multipart(form)
- .send()
- .await
- .map_err(reqwest::Error::without_url)?;
+ .web
+ .post(url.clone())
+ .multipart(form)
+ .send()
+ .await
+ .map_err(reqwest::Error::without_url)?;
let status = response.status();
+
if status == reqwest::StatusCode::TOO_MANY_REQUESTS && attempt < 2 {
let rate_limit = response
- .json::<Value>()
- .await
- .map_err(reqwest::Error::without_url)?;
+ .json::<Value>()
+ .await
+ .map_err(reqwest::Error::without_url)?;
+
if let Some(seconds) = rate_limit["retry_after"].as_f64()
- && (0.0..=60.0).contains(&seconds)
+ && (0.0..=60.0).contains(&seconds)
{
tokio::time::sleep(std::time::Duration::from_secs_f64(seconds)).await;
continue;
}
} else if status.is_success() {
return response
- .json()
- .await
- .map_err(|error| error.without_url().into());
+ .json()
+ .await
+ .map_err(|error| error.without_url().into());
}
+
anyhow::bail!("Discord rejected webhook upload (HTTP {status})");
}
+
anyhow::bail!("Discord webhook upload exceeded the retry limit")
}
- async fn download(&self, url: &str, filename: String) -> anyhow::Result<CreateAttachment> {
+ pub(crate) async fn download(
+ &self,
+ url: &str,
+ filename: String,
+ ) -> anyhow::Result<CreateAttachment> {
let bytes = self
- .web
- .get(url)
- .send()
- .await?
- .error_for_status()?
- .bytes()
- .await?;
+ .web
+ .get(url)
+ .send()
+ .await?
+ .error_for_status()?
+ .bytes()
+ .await?;
Ok(CreateAttachment::bytes(bytes.to_vec(), filename))
}
@@ -418,23 +440,26 @@ impl Bot {
content: &str,
) -> anyhow::Result<(Value, Vec<CreateAttachment>)> {
static BAD_FILENAME: LazyLock<Regex> =
- LazyLock::new(|| Regex::new(r"[^A-Za-z0-9_.-]").unwrap());
+ LazyLock::new(|| Regex::new(r"[^A-Za-z0-9_.-]").unwrap());
let classic = classic(content);
let mut components = Vec::new();
+
if !classic && !content.is_empty() {
components.push(cards::text(content));
}
+
if let Some(original) = reference(ctx, message).await {
components.push(cards::link(
&format!("↪ {}", cards::display_name(&original)),
original.link(),
- ));
+ ));
}
let mut gallery = Vec::new();
let mut other = Vec::new();
let mut downloads = Vec::new();
let mut attachments = Vec::new();
+
for (index, attachment) in message.attachments.iter().enumerate() {
let name = format!(
"{index}-{}",
@@ -452,8 +477,10 @@ impl Bot {
if classic {
continue;
}
+
let url = format!("attachment://{name}");
let kind = attachment.content_type.as_deref().unwrap_or_default();
+
if kind.starts_with("image/") || kind.starts_with("video/") {
gallery.push(json!({
"media": { "url": url },
@@ -467,31 +494,39 @@ impl Bot {
}));
}
}
+
if !gallery.is_empty() {
components.push(json!({ "type": 12, "items": gallery }));
}
+
components.extend(other);
let mut payload = json!({
"components": components,
"attachments": attachments,
});
+
if classic {
payload["content"] = json!(content);
} else {
payload["flags"] = json!(COMPONENTS_V2);
}
+
Ok((
payload,
futures_util::future::try_join_all(downloads).await?,
- ))
+ ))
}
- async fn target(&self, ctx: &Context, command: &Message) -> anyhow::Result<Option<Target>> {
+ pub(crate) async fn target(
+ &self,
+ ctx: &Context,
+ command: &Message,
+ ) -> anyhow::Result<Option<Target>> {
if let Some(reference) = command
- .message_reference
- .as_ref()
- .filter(|reference| reference.kind == MessageReferenceKind::Default)
+ .message_reference
+ .as_ref()
+ .filter(|reference| reference.kind == MessageReferenceKind::Default)
{
let Some(id) = reference.message_id else {
return Ok(None);
@@ -502,18 +537,19 @@ impl Bot {
}
let cached = ctx
- .cache
- .channel_messages(command.channel_id)
- .and_then(|messages| {
- messages
- .values()
- .filter(|message| message.id < command.id && owned(ctx, message))
- .map(|message| message.id)
- .max()
+ .cache
+ .channel_messages(command.channel_id)
+ .and_then(|messages| {
+ messages
+ .values()
+ .filter(|message| message.id < command.id && owned(ctx, message))
+ .map(|message| message.id)
+ .max()
});
+
if let Some(id) = cached
- && let Some(target) = fetch_target(ctx, command.channel_id, id).await
- && owned(ctx, &target.message)
+ && let Some(target) = fetch_target(ctx, command.channel_id, id).await
+ && owned(ctx, &target.message)
{
return Ok(Some(target));
}
@@ -534,121 +570,9 @@ impl Bot {
.filter_map(|raw| Target::from_json(raw).ok())
.find(|target| owned(ctx, &target.message)))
}
-
- pub async fn edit(
- &self,
- ctx: &Context,
- command: &Message,
- content: &str,
- ) -> anyhow::Result<Option<&'static str>> {
- let Some(Target {
- message: target,
- components,
- classic,
- }) = self.target(ctx, command).await?
- else {
- return Ok(Some(NO_TARGET));
- };
- if content.is_empty() && target.attachments.is_empty() {
- return Ok(Some(
- "That would leave the message empty. Use ❌ to delete it instead.",
- ));
- }
- if classic && proxy::utf16_len(content) > 2000 {
- return Ok(Some(
- "Messages with links can only be 2000 characters long.",
- ));
- }
-
- let Some(dest) =
- Destination::resolve(ctx, command.channel_id, command.guild_id.unwrap()).await?
- else {
- return Ok(Some("Can't use webhooks in this channel."));
- };
- let id = target.webhook_id.unwrap();
- let webhook = id.to_webhook(&ctx.http).await?;
- let token = webhook
- .token
- .as_ref()
- .map(ExposeSecret::expose_secret)
- .ok_or_else(|| anyhow::anyhow!("webhook had no token"))?;
- let mut payload = json!({ "allowed_mentions": user_mentions() });
- if classic {
- payload["content"] = json!(content);
- } else {
- let (mut components, attachments) = existing_media(&target, components, true);
- if !content.is_empty() {
- components.insert(0, cards::text(content));
- }
- payload["components"] = json!(components);
- payload["attachments"] = json!(attachments);
- }
-
- ctx.http
- .edit_webhook_message(id, dest.thread, token, target.id, &payload, Vec::new())
- .await
- .map_err(|_| anyhow::anyhow!("Discord rejected webhook edit"))?;
- command.delete(&ctx.http).await?;
- Ok(None)
- }
-
- pub async fn reproxy(
- &self,
- ctx: &Context,
- command: &Message,
- speakers: Vec<Member>,
- ) -> anyhow::Result<Option<&'static str>> {
- let Some(Target {
- message: target,
- components,
- classic,
- }) = self.target(ctx, command).await?
- else {
- return Ok(Some(NO_TARGET));
- };
- let Some(dest) =
- Destination::resolve(ctx, command.channel_id, command.guild_id.unwrap()).await?
- else {
- return Ok(Some("Can't use webhooks in this channel."));
- };
-
- let (components, _) = existing_media(&target, components, false);
- let attachments: Vec<_> = target
- .attachments
- .iter()
- .enumerate()
- .map(|(index, file)| json!({ "id": index, "filename": file.filename }))
- .collect();
- let mut payload = json!({ "attachments": attachments });
- if classic {
- payload["content"] = json!(target.content);
- } else {
- payload["flags"] = json!(COMPONENTS_V2);
- payload["components"] = json!(components);
- }
- let files = futures_util::future::try_join_all(
- target
- .attachments
- .iter()
- .map(|file| self.download(&file.url, file.filename.clone())),
- )
- .await?;
-
- let slot = self.channel_webhook(&dest).await;
- let mut locked = slot.lock().await;
- let webhook = Self::ensure_webhook(ctx, &dest, &mut locked).await?;
- let (sent, _) = self
- .send_proxy(ctx, &dest, &webhook, &speakers, payload, files)
- .await?;
- drop(locked);
- self.remember(sent, speakers).await;
- target.delete(&ctx.http).await?;
- command.delete(&ctx.http).await?;
- Ok(None)
- }
}
-fn existing_media(
+pub(crate) fn existing_media(
message: &Message,
mut components: Vec<Value>,
remove_text: bool,
@@ -665,16 +589,18 @@ fn existing_media(
return;
};
let Some(last) = parsed
- .path_segments()
- .and_then(|mut parts| parts.next_back())
+ .path_segments()
+ .and_then(|mut parts| parts.next_back())
else {
return;
};
let name = percent_decode_str(last).decode_utf8_lossy();
+
if message.attachments.iter().any(|file| file.filename == name) {
*media = json!({ "url": format!("attachment://{name}") });
}
};
+
for component in &mut components {
match component["type"].as_u64() {
Some(12) => {
@@ -688,11 +614,12 @@ fn existing_media(
_ => {}
}
}
+
let attachments = message
- .attachments
- .iter()
- .map(|file| json!({ "id": file.id, "filename": file.filename }))
- .collect();
+ .attachments
+ .iter()
+ .map(|file| json!({ "id": file.id, "filename": file.filename }))
+ .collect();
(components, attachments)
}
@@ -729,7 +656,7 @@ mod tests {
assert!(!target.classic);
let (edited, attachments) =
- existing_media(&target.message, target.components.clone(), true);
+ existing_media(&target.message, target.components.clone(), true);
assert_eq!(edited.len(), 3);
assert_eq!(edited[0]["type"], 1);
assert_eq!(
diff --git a/src/main.rs b/src/main.rs
index e0bb6a5..a3f25bc 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,11 +1,17 @@
// src/main.rs
mod avatars;
+
mod cards;
+
mod commands;
+
mod discord;
+
mod proxy;
+
mod settings;
+
mod site;
#[cfg(test)]
@@ -44,9 +50,11 @@ struct Bot {
impl Bot {
async fn remember(&self, message: MessageId, members: Vec<Member>) {
let mut senders = self.senders.lock().await;
+
if senders.len() == 1000 {
senders.pop_front();
}
+
senders.push_back((message, members));
}
@@ -58,10 +66,12 @@ impl Bot {
let mut settings = self.settings.lock().await;
let mut updated = settings.clone();
change(&mut updated);
+
if updated.guilds != settings.guilds {
updated.save()?;
*settings = updated;
}
+
Ok(())
}
@@ -69,28 +79,33 @@ impl Bot {
let Some(guild) = message.guild_id else {
return Ok(());
};
+
if message.webhook_id.is_some() || message.author.bot {
return Ok(());
}
+
if message.author.id == self.owner {
self.mark_active(message.channel_id).await;
+
if !self.command(ctx, message, guild).await? {
self.proxy_message(ctx, message, guild).await?;
}
} else {
let active = self
- .activity
- .lock()
- .await
- .get(&message.channel_id)
- .is_some_and(|seen| seen.elapsed() < Duration::from_secs(300));
+ .activity
+ .lock()
+ .await
+ .get(&message.channel_id)
+ .is_some_and(|seen| seen.elapsed() < Duration::from_secs(300));
+
if !active
- && let Some(target) = discord::reference(ctx, message).await
- && discord::owned(ctx, &target)
+ && let Some(target) = discord::reference(ctx, message).await
+ && discord::owned(ctx, &target)
{
discord::dm(ctx, self.owner, cards::reply(message, &target)).await?;
}
}
+
Ok(())
}
@@ -103,37 +118,42 @@ impl Bot {
let ReactionType::Unicode(emoji) = &reaction.emoji else {
return Ok(());
};
+
if !matches!(emoji.as_str(), "❌" | "❓") || (emoji == "❌" && user != self.owner) {
return Ok(());
}
+
let bot = match &reaction.member {
Some(member) => member.user.bot,
None => user.to_user(ctx).await?.bot,
};
+
if bot {
return Ok(());
}
let message = reaction
- .channel_id
- .message(&ctx.http, reaction.message_id)
- .await?;
+ .channel_id
+ .message(&ctx.http, reaction.message_id)
+ .await?;
+
if !discord::owned(ctx, &message) {
return Ok(());
}
+
if emoji == "❌" {
message.delete(&ctx.http).await?;
return Ok(());
}
let members = self
- .senders
- .lock()
- .await
- .iter()
- .rev()
- .find(|(id, _)| *id == message.id)
- .map(|(_, members)| members.clone());
+ .senders
+ .lock()
+ .await
+ .iter()
+ .rev()
+ .find(|(id, _)| *id == message.id)
+ .map(|(_, members)| members.clone());
let system_name = self.system.read().await.info.name.clone();
let result = discord::dm(
ctx,
@@ -148,14 +168,16 @@ impl Bot {
.await;
let _ = ctx
- .http
- .delete_reaction(reaction.channel_id, message.id, user, &reaction.emoji)
- .await;
+ .http
+ .delete_reaction(reaction.channel_id, message.id, user, &reaction.emoji)
+ .await;
+
if let Err(error) = result
- && !matches!(error.downcast_ref::<serenity::Error>(), Some(serenity::Error::Http(HttpError::UnsuccessfulRequest(response))) if response.error.code == 50007)
+ && !matches!(error.downcast_ref::<serenity::Error>(), Some(serenity::Error::Http(HttpError::UnsuccessfulRequest(response))) if response.error.code == 50007)
{
return Err(error);
}
+
Ok(())
}
}
@@ -168,19 +190,21 @@ impl EventHandler for Handler {
ctx.http.set_application_id(ready.application.id);
ctx.set_activity(Some(ActivityData::custom(proxy::fronting_status(
&self.0.system.read().await.fronters,
- ))));
+ ))));
println!("Logged in as {}", ready.user.name);
let ids: std::collections::HashSet<_> = ready.guilds.iter().map(|guild| guild.id).collect();
+
if let Err(error) = self
- .0
- .update_settings(|settings| {
- settings.guilds.retain(|guild, _| ids.contains(guild));
- for guild in ids {
- settings.guilds.entry(guild).or_default();
- }
+ .0
+ .update_settings(|settings| {
+ settings.guilds.retain(|guild, _| ids.contains(guild));
+
+ for guild in ids {
+ settings.guilds.entry(guild).or_default();
+ }
})
- .await
+ .await
{
eprintln!("Guild sync failed: {error}");
}
@@ -193,11 +217,11 @@ impl EventHandler for Handler {
async fn guild_create(&self, _ctx: Context, guild: Guild, _is_new: Option<bool>) {
if let Err(error) = self
- .0
- .update_settings(|settings| {
- settings.guilds.entry(guild.id).or_default();
+ .0
+ .update_settings(|settings| {
+ settings.guilds.entry(guild.id).or_default();
})
- .await
+ .await
{
eprintln!("Guild add failed: {error}");
}
@@ -205,12 +229,12 @@ impl EventHandler for Handler {
async fn guild_delete(&self, _ctx: Context, guild: UnavailableGuild, _full: Option<Guild>) {
if !guild.unavailable
- && let Err(error) = self
- .0
- .update_settings(|settings| {
- settings.guilds.remove(&guild.id);
- })
- .await
+ && let Err(error) = self
+ .0
+ .update_settings(|settings| {
+ settings.guilds.remove(&guild.id);
+ })
+ .await
{
eprintln!("Guild remove failed: {error}");
}
@@ -227,6 +251,7 @@ impl EventHandler for Handler {
if user == self.0.owner {
self.0.mark_active(reaction.channel_id).await;
}
+
if let Err(error) = self.0.on_reaction(&ctx, &reaction, user).await {
eprintln!("Reaction handling failed: {error}");
}
@@ -247,22 +272,23 @@ async fn main() -> anyhow::Result<()> {
Err(dotenvy::Error::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error).context("could not load .env"),
}
+
let token = std::env::var("DISCORD_TOKEN").context("DISCORD_TOKEN is required")?;
anyhow::ensure!(!token.is_empty(), "DISCORD_TOKEN is required");
let owner = std::env::var("OWNER_ID")
- .context("OWNER_ID is required")?
- .parse::<UserId>()
- .context("OWNER_ID must be a Discord user ID")?;
+ .context("OWNER_ID is required")?
+ .parse::<UserId>()
+ .context("OWNER_ID must be a Discord user ID")?;
let settings = Settings::load(Settings::PATH).context("could not load data/settings.jp")?;
let bot = Arc::new(Bot {
owner,
site_token: std::env::var("SITE_TOKEN")
- .ok()
- .filter(|token| !token.is_empty()),
+ .ok()
+ .filter(|token| !token.is_empty()),
web: reqwest::Client::builder()
- .timeout(Duration::from_secs(15))
- .build()?,
+ .timeout(Duration::from_secs(15))
+ .build()?,
system: RwLock::default(),
settings: Mutex::new(settings),
webhooks: Mutex::default(),
@@ -271,20 +297,20 @@ async fn main() -> anyhow::Result<()> {
senders: Mutex::default(),
shards: OnceCell::new(),
started: AtomicBool::new(false),
- });
+ });
bot.initial_refresh().await;
let intents = GatewayIntents::GUILDS
- | GatewayIntents::GUILD_MESSAGES
- | GatewayIntents::MESSAGE_CONTENT
- | GatewayIntents::GUILD_MESSAGE_REACTIONS
- | GatewayIntents::GUILD_MESSAGE_TYPING;
+ | GatewayIntents::GUILD_MESSAGES
+ | GatewayIntents::MESSAGE_CONTENT
+ | GatewayIntents::GUILD_MESSAGE_REACTIONS
+ | GatewayIntents::GUILD_MESSAGE_TYPING;
let mut cache = serenity::cache::Settings::default();
cache.max_messages = 200;
let mut client = Client::builder(token, intents)
- .event_handler(Handler(bot.clone()))
- .cache_settings(cache)
- .await?;
+ .event_handler(Handler(bot.clone()))
+ .cache_settings(cache)
+ .await?;
// Set before the first gateway event can be processed.
let _ = bot.shards.set(client.shard_manager.clone());
client.start().await?;
diff --git a/src/proxy.rs b/src/proxy.rs
index 9b5c72d..73f07f2 100644
--- a/src/proxy.rs
+++ b/src/proxy.rs
@@ -45,8 +45,8 @@ impl Member {
pub fn webhook_avatar(&self) -> Option<&str> {
self.webhook_avatar_url
- .as_deref()
- .or(self.avatar_url.as_deref())
+ .as_deref()
+ .or(self.avatar_url.as_deref())
}
}
@@ -56,20 +56,22 @@ pub fn utf16_len(text: &str) -> usize {
pub fn truncate(text: &str, limit: usize) -> &str {
let mut remaining = limit;
+
for (index, character) in text.char_indices() {
let Some(next) = remaining.checked_sub(character.len_utf16()) else {
return &text[..index];
};
remaining = next;
}
+
text
}
fn tag_pattern(tag: &str) -> String {
static WHITESPACE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\s\u{feff}]+").unwrap());
WHITESPACE
- .replace_all(®ex::escape(tag), r"[\s\u{feff}]+")
- .into_owned()
+ .replace_all(®ex::escape(tag), r"[\s\u{feff}]+")
+ .into_owned()
}
pub fn pick<'a>(
@@ -89,6 +91,7 @@ pub fn pick<'a>(
let prefix = tag.prefix.as_deref().unwrap_or_default();
let suffix = tag.suffix.as_deref().unwrap_or_default();
let length = utf16_len(prefix) + utf16_len(suffix);
+
if length <= best_length {
continue;
}
@@ -101,6 +104,7 @@ pub fn pick<'a>(
let Ok(regex) = Regex::new(&pattern) else {
continue;
};
+
if let Some(captures) = regex.captures(content) {
let text = if member.keep_proxy {
content
@@ -118,9 +122,9 @@ pub fn pick<'a>(
}
let speaking: Vec<_> = fronters
- .iter()
- .filter(|member| member.autoproxy_enabled != Some(false))
- .collect();
+ .iter()
+ .filter(|member| member.autoproxy_enabled != Some(false))
+ .collect();
(!speaking.is_empty()).then_some((speaking, content))
}
@@ -129,12 +133,13 @@ pub const MAX_NAMED: usize = 3;
pub fn webhook_name(members: &[&Member], tag: Option<&str>) -> String {
static DISCORD: LazyLock<Regex> = LazyLock::new(|| Regex::new("(?i)discord").unwrap());
let mut names: Vec<_> = members
- .iter()
- .take(MAX_NAMED)
- .map(|member| member.display_name())
- .collect();
+ .iter()
+ .take(MAX_NAMED)
+ .map(|member| member.display_name())
+ .collect();
let hidden = members.len().saturating_sub(MAX_NAMED);
let extra = format!("{hidden} more");
+
if hidden > 0 {
names.push(&extra);
}
@@ -146,13 +151,13 @@ pub fn webhook_name(members: &[&Member], tag: Option<&str>) -> String {
format!("{} & {last}", names.join(", "))
};
let suffix = tag
- .filter(|tag| !tag.is_empty())
- .map(|tag| format!(" ~ {tag}"))
- .unwrap_or_default();
+ .filter(|tag| !tag.is_empty())
+ .map(|tag| format!(" ~ {tag}"))
+ .unwrap_or_default();
let names = truncate(&names, 80_usize.saturating_sub(utf16_len(&suffix)));
let name = DISCORD
- .replace_all(&format!("{names}{suffix}"), "dïscord")
- .into_owned();
+ .replace_all(&format!("{names}{suffix}"), "dïscord")
+ .into_owned();
truncate(&name, 80).to_owned()
}
@@ -160,19 +165,22 @@ pub fn fronting_status(fronters: &[Member]) -> String {
if fronters.is_empty() {
return "Nobody fronting".into();
}
+
let names = fronters
- .iter()
- .map(Member::display_name)
- .collect::<Vec<_>>()
- .join(", ");
+ .iter()
+ .map(Member::display_name)
+ .collect::<Vec<_>>()
+ .join(", ");
truncate(&format!("Fronting: {names}"), 128).to_owned()
}
pub fn command(content: &str) -> Option<(String, Vec<String>, &str)> {
let prefix = content.get(..2)?;
+
if !prefix.eq_ignore_ascii_case("d$") {
return None;
}
+
let body = content[2..].trim_start();
let name = body.split_whitespace().next()?;
let rest = body[name.len()..].trim();
diff --git a/src/settings.rs b/src/settings.rs
index 0ca56bc..788e0f7 100644
--- a/src/settings.rs
+++ b/src/settings.rs
@@ -17,7 +17,7 @@ impl Settings {
let root = match jpcl::load(path, &jpcl::ParseOptions::default()) {
Ok(root) => root,
Err(jpcl::Error::Io { source, .. })
- if source.kind() == std::io::ErrorKind::NotFound =>
+ if source.kind() == std::io::ErrorKind::NotFound =>
{
return Ok(Self::default());
}
@@ -25,14 +25,14 @@ impl Settings {
};
let guilds = root
- .iter()
- .filter_map(|(key, _)| {
- let guild = key.parse::<u64>().ok().filter(|id| *id > 0)?;
- let path = format!("{key}.autoproxy.enabled");
- let enabled = jpcl::get_path(&root, &path) == Some(&jpcl::Value::Bool(true));
- Some((GuildId::new(guild), enabled))
+ .iter()
+ .filter_map(|(key, _)| {
+ let guild = key.parse::<u64>().ok().filter(|id| *id > 0)?;
+ let path = format!("{key}.autoproxy.enabled");
+ let enabled = jpcl::get_path(&root, &path) == Some(&jpcl::Value::Bool(true));
+ Some((GuildId::new(guild), enabled))
})
- .collect();
+ .collect();
Ok(Self { guilds })
}
@@ -43,6 +43,7 @@ impl Settings {
pub(crate) fn save_to(&self, path: impl AsRef<Path>) -> anyhow::Result<()> {
let mut root = jpcl::Object::new();
+
for (guild, enabled) in &self.guilds {
let mut autoproxy = jpcl::Object::new();
autoproxy.insert("enabled", jpcl::Value::Bool(*enabled));
@@ -50,6 +51,7 @@ impl Settings {
entry.insert("autoproxy", jpcl::Value::Object(autoproxy));
root.insert(guild.to_string(), jpcl::Value::Object(entry));
}
+
jpcl::dump(&root, path, &jpcl::StringifyOptions::default())?;
Ok(())
}
diff --git a/src/site.rs b/src/site.rs
index a730bfd..c673c6b 100644
--- a/src/site.rs
+++ b/src/site.rs
@@ -73,22 +73,24 @@ impl Bot {
async fn set_front(&self, ctx: &Context, front: Front) {
let status = fronting_status(&front.members);
let speakers: Vec<_> = front
- .members
- .iter()
- .filter(|member| member.autoproxy_enabled != Some(false))
- .cloned()
- .collect();
+ .members
+ .iter()
+ .filter(|member| member.autoproxy_enabled != Some(false))
+ .cloned()
+ .collect();
self.system.write().await.fronters = front.members;
ctx.set_activity(Some(ActivityData::custom(status)));
+
if (2..=crate::proxy::MAX_NAMED).contains(&speakers.len()) {
let avatars = self.avatars.clone();
let web = self.web.clone();
tokio::spawn(async move {
let urls = crate::avatars::avatar_urls(&speakers);
+
if let Err(error) = avatars.png(&web, urls).await {
eprintln!("Avatar premerge failed: {error}");
}
- });
+ });
}
}
@@ -106,6 +108,7 @@ impl Bot {
pub async fn poll(self: Arc<Self>, ctx: Context) {
let mut timer = tokio::time::interval(REFRESH);
timer.tick().await;
+
loop {
timer.tick().await;
tokio::join!(
@@ -121,6 +124,7 @@ impl Bot {
if let Err(error) = self.live_session(&ctx).await {
eprintln!("Live socket closed: {error}");
}
+
tokio::time::sleep(Duration::from_secs(5)).await;
}
}
@@ -171,20 +175,21 @@ impl Bot {
pub async fn switch_front(&self, ids: &[&str]) -> Result<(), String> {
let token = self
- .site_token
- .as_ref()
- .ok_or("Switching isn't set up. Add `SITE_TOKEN` to the bot's `.env`.")?;
+ .site_token
+ .as_ref()
+ .ok_or("Switching isn't set up. Add `SITE_TOKEN` to the bot's `.env`.")?;
let response = self
- .web
- .post(format!("{API}/switch"))
- .bearer_auth(token)
- .json(&serde_json::json!({ "members": ids }))
- .send()
- .await
- .map_err(|error| {
- eprintln!("Switch failed: {error}");
- "Couldn't reach the site to switch.".to_owned()
+ .web
+ .post(format!("{API}/switch"))
+ .bearer_auth(token)
+ .json(&serde_json::json!({ "members": ids }))
+ .send()
+ .await
+ .map_err(|error| {
+ eprintln!("Switch failed: {error}");
+ "Couldn't reach the site to switch.".to_owned()
})?;
+
match response.status().as_u16() {
200..=299 => Ok(()),
401 => Err(
diff --git a/src/tests.rs b/src/tests.rs
index 4d93f6b..c2d09cf 100644
--- a/src/tests.rs
+++ b/src/tests.rs
@@ -29,6 +29,7 @@ fn tags_strip_prefixes_and_suffixes() {
member("brackets", Some("["), Some("]")),
member("spaced", Some("Ae "), None),
];
+
for (input, name, expected) in [
("C: hi", "short", "hi"),
("C1: hi", "long", "hi"),
@@ -40,6 +41,7 @@ fn tags_strip_prefixes_and_suffixes() {
assert_eq!(speakers[0].id, name);
assert_eq!(content, expected);
}
+
assert!(proxy::pick(&members, &[], "Aehi").is_none());
assert!(proxy::pick(&members, &[], "plain message").is_none());
}
@@ -192,7 +194,7 @@ fn member_card_displays_profile_and_info_caps_crowds() {
first.status = Some(MemberStatus {
text: "Coding again...".into(),
emoji: Some("💻".into()),
- });
+ });
let card = cards::member_card(&first);
assert_eq!(card["accent_color"], 0xcba6f7);
@@ -218,13 +220,15 @@ fn member_card_displays_profile_and_info_caps_crowds() {
let crowd = vec![first; 10];
let shown = cards::info(&webhook, Some(&crowd), owner, None);
+
fn count(component: &Value) -> usize {
let children = component["components"]
- .as_array()
- .map_or(0, |items| items.iter().map(count).sum());
+ .as_array()
+ .map_or(0, |items| items.iter().map(count).sum());
let accessory = component.get("accessory").map_or(0, count);
1 + children + accessory
}
+
assert!(shown.iter().map(count).sum::<usize>() <= 40);
assert!(shown[3]["content"].as_str().unwrap().contains("& 7 more"));
}