clove/proxyBot
src/discord.rs
// src/discord.rs
use std::collections::HashSet;
use std::sync::Arc;
use std::time::Instant;
use percent_encoding::percent_decode_str;
use secrecy::ExposeSecret;
use anyhow::Context as _;
use serde_json::{Value, json};
use serenity::all::*;
use serenity::http::{LightMethod, Request, Route};
use tokio::sync::Mutex;
use crate::{
Bot,
proxy_log::ProxyLog,
cards::{self, COMPONENTS_V2},
proxy::{self, Member},
};
pub const NO_TARGET: &str =
"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 })
}
pub async fn apply_name_style(ctx: &Context, guild_id: GuildId) {
let fields = json!({
"display_name_font_id": 16,
"display_name_effect_id": 7,
"display_name_colors": [
0xD52D00,
0xFF9A56,
0xFFFFFF,
0xD362A4,
0xA30262,
],
});
let request = Request::new(Route::GuildMemberMe { guild_id }, LightMethod::Patch)
.body(Some(fields.to_string().into_bytes()));
if let Err(error) = ctx.http.request(request).await {
eprintln!("Name styling failed in guild {guild_id}: {error}");
}
}
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)
}
pub(crate) fn attachment_links(attachments: &[Attachment]) -> String {
attachment_links_with_spoilers(attachments, &HashSet::new())
}
pub(crate) fn attachment_links_with_spoilers(
attachments: &[Attachment],
spoilers: &HashSet<AttachmentId>,
) -> String {
attachments
.iter()
.map(|attachment| {
let url = reqwest::Url::parse(&attachment.url)
.ok()
.filter(is_attachment_url)
.map(|mut url| {
url.set_query(None);
url.to_string()
})
.unwrap_or_else(|| attachment.url.clone());
if attachment.filename.starts_with("SPOILER_") || spoilers.contains(&attachment.id) {
format!("||{url}||")
} else {
url
}
})
.collect::<Vec<_>>()
.join("\n")
}
fn is_attachment_url(url: &reqwest::Url) -> bool {
matches!(url.host_str(), Some("cdn.discordapp.com" | "media.discordapp.net"))
&& url.path().starts_with("/attachments/")
}
pub(crate) fn split_attachment_links(content: &str) -> (&str, &str) {
let (body, tail) = content.rsplit_once("\n\n").unwrap_or(("", content));
if !tail.is_empty()
&& tail.lines().all(|line| {
let url = line
.strip_prefix("||")
.and_then(|line| line.strip_suffix("||"))
.unwrap_or(line);
reqwest::Url::parse(url).is_ok_and(|parsed| {
!url.contains(char::is_whitespace)
&& parsed.query().is_none()
&& is_attachment_url(&parsed)
})
})
{
(body, tail)
} else {
(content, "")
}
}
pub(crate) fn proxy_payload(
body: &str,
links: &str,
mut buttons: Vec<Value>,
force_v2: bool,
) -> Value {
let content = message_text(body, links);
if !force_v2 && proxy::utf16_len(&content) <= 2000 {
return json!({
"content": content,
"components": buttons,
});
}
let mut components = text_displays(body, links, &content);
components.append(&mut buttons);
json!({
"flags": COMPONENTS_V2,
"components": components,
})
}
pub(crate) fn message_text(body: &str, links: &str) -> String {
if body.is_empty() || links.is_empty() {
format!("{body}{links}")
} else {
format!("{body}\n\n{links}")
}
}
pub(crate) fn text_displays(body: &str, links: &str, content: &str) -> Vec<Value> {
// Use separate text displays for the body and links if they exceed one display.
let mut components = Vec::new();
if proxy::utf16_len(&content) <= 4000 {
components.extend((!content.is_empty()).then(|| cards::text(&content)));
} else {
let mut remaining = body;
while !remaining.is_empty() {
let chunk = proxy::truncate(remaining, 4000);
components.push(cards::text(chunk));
remaining = &remaining[chunk.len()..];
}
let mut link_group = String::new();
for link in links.lines() {
if proxy::utf16_len(&link_group) + 1 + proxy::utf16_len(link) > 4000
&& !link_group.is_empty()
{
components.push(cards::text(std::mem::take(&mut link_group)));
}
if !link_group.is_empty() {
link_group.push('\n');
}
link_group.push_str(link);
}
components.extend((!link_group.is_empty()).then(|| cards::text(link_group)));
}
components
}
pub(crate) fn proxy_text(components: &[Value]) -> (String, String) {
let mut body = Vec::new();
let mut links = Vec::new();
for content in components.iter().filter_map(|component| {
(component["type"] == 10)
.then(|| component["content"].as_str())
.flatten()
}) {
let (text, attachment_urls) = split_attachment_links(content);
body.extend((!text.is_empty()).then_some(text));
links.extend((!attachment_urls.is_empty()).then_some(attachment_urls));
}
(body.join(""), links.join("\n"))
}
fn is_thread(kind: ChannelType) -> bool {
matches!(
kind,
ChannelType::NewsThread | ChannelType::PublicThread | ChannelType::PrivateThread
)
}
pub async fn reference(ctx: &Context, message: &Message) -> Option<Message> {
let reference = message.message_reference.as_ref()?;
if reference.kind != MessageReferenceKind::Default {
return None;
}
if let Some(original) = &message.referenced_message {
return Some((**original).clone());
}
let mut target = fetch_target(ctx, reference.channel_id, reference.message_id?)
.await?
.message;
target.guild_id = target.guild_id.or(reference.guild_id).or(message.guild_id);
Some(target)
}
pub async fn reply(
ctx: &Context,
message: &Message,
mut payload: Value,
) -> anyhow::Result<MessageId> {
payload["message_reference"] = json!({
"message_id": message.id,
"fail_if_not_exists": true,
});
payload["allowed_mentions"] = user_mentions();
let sent = send_json(ctx, message.channel_id, &payload).await?;
Ok(serde_json::from_value(sent["id"].clone())?)
}
pub async fn dm(ctx: &Context, user: UserId, components: Vec<Value>) -> anyhow::Result<Value> {
let channel = user.create_dm_channel(&ctx.http).await?;
send_json(
ctx,
channel.id,
&json!({
"flags": COMPONENTS_V2,
"components": components,
"allowed_mentions": { "parse": [] },
}),
)
.await
}
pub(crate) async fn send_json(ctx: &Context, channel_id: ChannelId, payload: &Value) -> anyhow::Result<Value> {
Ok(ctx
.http
.fire(
Request::new(Route::ChannelMessages { channel_id }, LightMethod::Post)
.body(Some(serde_json::to_vec(payload)?)),
)
.await?)
}
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();
raw.as_object_mut()
.map(|object| object.remove("referenced_message"));
Ok(Self {
message: serde_json::from_value(raw)?,
components,
classic,
})
}
}
async fn fetch_target(
ctx: &Context,
channel_id: ChannelId,
message_id: MessageId,
) -> Option<Target> {
let raw = ctx
.http
.fire::<Value>(Request::new(
Route::ChannelMessage {
channel_id,
message_id,
},
LightMethod::Get,
))
.await
.ok()?;
Target::from_json(raw).ok()
}
pub(crate) struct Destination {
parent: ChannelId,
pub(crate) thread: Option<ChannelId>,
}
impl Destination {
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());
let guild = match cached {
Some(guild) => guild,
None => match channel.to_channel(&ctx.http).await? {
Channel::Guild(guild) => guild,
_ => 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,
}))
}
}
pub(crate) type LockedWebhook = Arc<Mutex<Option<Webhook>>>;
impl Bot {
pub(crate) async fn channel_webhook(&self, dest: &Destination) -> LockedWebhook {
self.webhooks
.lock()
.await
.entry(dest.parent)
.or_default()
.clone()
}
pub(crate) async fn ensure_webhook(
ctx: &Context,
dest: &Destination,
slot: &mut Option<Webhook>,
) -> anyhow::Result<Webhook> {
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()
});
let webhook = match existing {
Some(webhook) => webhook,
None => {
dest.parent
.create_webhook(&ctx.http, CreateWebhook::new("proxyBot"))
.await?
}
};
*slot = Some(webhook.clone());
Ok(webhook)
}
pub async fn proxy_message(
&self,
ctx: &Context,
message: &Message,
guild: GuildId,
) -> anyhow::Result<()> {
let started = Instant::now();
let enabled = self
.settings
.lock()
.await
.guilds
.get(&guild)
.copied()
.unwrap_or(false);
let (speakers, content) = {
let state = self.system.read().await;
let fronters = if enabled {
state.fronters.as_slice()
} else {
&[]
};
let Some((speakers, content)) = proxy::pick(&state.members, fronters, &message.content)
else {
return Ok(());
};
(
speakers.into_iter().cloned().collect::<Vec<_>>(),
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(());
};
let buttons = reference(ctx, message)
.await
.map(|original| {
cards::link(
&format!("↪ {}", cards::display_name(&original)),
original.link(),
)
})
.into_iter()
.collect();
let payload = proxy_payload(&content, "", buttons, false);
let slot = self.channel_webhook(&dest).await;
let mut locked = slot.lock().await;
let webhook = Self::ensure_webhook(ctx, &dest, &mut locked).await?;
let replacement = self
.replace_proxy(
ctx,
&dest,
&webhook,
&speakers,
payload,
&message.attachments,
(guild, message),
)
.await?;
drop(locked);
let Some((sent, send_ms, attachments)) = replacement else {
return Ok(());
};
let speaker_refs = speakers.iter().collect::<Vec<_>>();
let label = format!("Proxied as {}", proxy::webhook_name(&speaker_refs, None));
let avatar = crate::avatars::log_avatar(&speakers).map(str::to_owned);
let links = attachment_links(&attachments);
self.remember(sent, speakers).await;
println!(
"Proxied in {}ms (send {send_ms}ms)",
started.elapsed().as_millis()
);
self.log_proxy(
ctx,
guild,
ProxyLog {
source: message,
sent,
label: &label,
content: &content,
links: &links,
avatar: avatar.as_deref(),
},
)
.await;
Ok(())
}
pub(crate) async fn replace_proxy(
&self,
ctx: &Context,
dest: &Destination,
webhook: &Webhook,
speakers: &[Member],
mut payload: Value,
attachments: &[Attachment],
(guild, source): (GuildId, &Message),
) -> anyhow::Result<Option<(MessageId, u128, Vec<Attachment>)>> {
let filenames = upload_layout(&mut payload, attachments);
let files = futures_util::future::try_join_all(
attachments
.iter()
.zip(filenames)
.map(|(attachment, filename)| async move {
let bytes = self
.web
.get(&attachment.url)
.send()
.await?
.error_for_status()?
.bytes()
.await?;
Ok::<_, reqwest::Error>(CreateAttachment::bytes(bytes.to_vec(), filename))
}),
)
.await
.map_err(reqwest::Error::without_url)?;
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()));
let avatar = self.avatar(ctx, webhook, speakers).await;
if let Some(url) = &avatar {
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"))?;
let mut params = vec![
("wait", "true".into()),
("with_components", "true".into()),
];
if let Some(thread) = dest.thread {
params.push(("thread_id", thread.to_string()));
}
let body = serde_json::to_vec(&payload)?;
let deletion = match self.delete_proxy_source(ctx, guild, source).await {
Ok(confirmation) => confirmation,
Err(error) if crate::proxy_log::unknown_message(&error) => return Ok(None),
Err(error) => return Err(error.into()),
};
let started = Instant::now();
let result = if files.is_empty() {
ctx.http.fire::<Value>(
Request::new(
Route::WebhookWithToken {
webhook_id: webhook.id,
token,
},
LightMethod::Post,
)
.body(Some(body))
.params(Some(params)),
)
.await
.map_err(anyhow::Error::from)
} else {
self.upload_webhook(webhook.id, token, dest.thread, &payload, &files)
.await
};
if let Some(confirmation) = deletion {
confirmation.send_replace(Some(result.is_ok()));
}
let mut sent = result.context("Could not proxy the message after deleting the original")?;
Ok(Some((
serde_json::from_value(sent["id"].take())?,
started.elapsed().as_millis(),
serde_json::from_value(sent["attachments"].take())?,
)))
}
async fn upload_webhook(
&self,
webhook: WebhookId,
token: &str,
thread: Option<ChannelId>,
payload: &Value,
files: &[CreateAttachment],
) -> 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);
url.query_pairs_mut()
.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());
}
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());
for (index, file) in files.iter().enumerate() {
let part = reqwest::multipart::Part::bytes(file.data.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)?;
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)?;
if let Some(seconds) = rate_limit["retry_after"].as_f64()
&& (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());
}
anyhow::bail!("Discord rejected webhook upload (HTTP {status})");
}
anyhow::bail!("Discord webhook upload exceeded the retry limit")
}
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)
{
let Some(id) = reference.message_id else {
return Ok(None);
};
return Ok(fetch_target(ctx, reference.channel_id, id)
.await
.filter(|target| owned(ctx, &target.message)));
}
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()
});
if let Some(id) = cached
&& let Some(target) = fetch_target(ctx, command.channel_id, id).await
&& owned(ctx, &target.message)
{
return Ok(Some(target));
}
let request = Request::new(
Route::ChannelMessages {
channel_id: command.channel_id,
},
LightMethod::Get,
)
.params(Some(vec![
("before", command.id.to_string()),
("limit", "50".into()),
]));
let recent = ctx.http.fire::<Vec<Value>>(request).await?;
Ok(recent
.into_iter()
.filter_map(|raw| Target::from_json(raw).ok())
.find(|target| owned(ctx, &target.message)))
}
}
fn upload_layout(payload: &mut Value, attachments: &[Attachment]) -> Vec<String> {
if attachments.is_empty() {
return Vec::new();
}
let is_v2 = payload["flags"] == COMPONENTS_V2;
let mut metadata = Vec::new();
let mut filenames = Vec::new();
let mut gallery = Vec::new();
let mut files = Vec::new();
for (index, attachment) in attachments.iter().enumerate() {
let spoiler = attachment.filename.starts_with("SPOILER_");
let mut filename = attachment.filename.clone();
if is_v2 {
filename = filename.replace(
|character: char| !character.is_ascii_alphanumeric() && !"-_.".contains(character),
"_",
);
let prefix = if spoiler { "SPOILER_" } else { "" };
while filenames.contains(&filename) {
let name = filename.strip_prefix(prefix).unwrap_or(&filename);
filename = format!("{prefix}{index}-{name}");
}
}
let mut entry = json!({
"id": index,
"filename": filename,
});
if let Some(description) = &attachment.description {
entry["description"] = json!(description);
}
if is_v2 {
let media = json!({ "url": format!("attachment://{filename}") });
let kind = attachment.content_type.as_deref().unwrap_or_default();
if attachment.width.is_some() || kind.starts_with("image/") || kind.starts_with("video/") {
gallery.push(json!({
"media": media,
"spoiler": spoiler,
}));
} else {
files.push(json!({
"type": 13,
"file": media,
"spoiler": spoiler,
}));
}
}
metadata.push(entry);
filenames.push(filename);
}
payload["attachments"] = json!(metadata);
if is_v2 {
let components = payload["components"].as_array_mut().unwrap();
if !gallery.is_empty() {
components.push(json!({
"type": 12,
"items": gallery,
}));
}
components.extend(files);
}
filenames
}
pub(crate) fn attachment_spoilers(
message: &Message,
components: &[Value],
) -> HashSet<AttachmentId> {
let media = components.iter().flat_map(|component| {
component["items"]
.as_array()
.map(Vec::as_slice)
.unwrap_or_else(|| std::slice::from_ref(component))
});
let spoiler_paths = media
.filter(|item| item["spoiler"] == true)
.filter_map(|item| item["media"]["url"].as_str().or(item["file"]["url"].as_str()))
.map(|url| url.split('?').next().unwrap_or(url))
.collect::<HashSet<_>>();
message.attachments.iter()
.filter(|attachment| {
let url = &attachment.url;
spoiler_paths.contains(url.split('?').next().unwrap_or(url))
})
.map(|attachment| attachment.id)
.collect()
}
pub(crate) fn existing_media(
message: &Message,
mut components: Vec<Value>,
remove_text: bool,
) -> (Vec<Value>, Vec<Value>) {
if remove_text {
components.retain(|component| component["type"] != 10);
}
let attachment_uri = |media: &mut Value| {
let Some(url) = media["url"].as_str() else {
return;
};
let Ok(parsed) = reqwest::Url::parse(url) else {
return;
};
let Some(last) = parsed
.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) => {
if let Some(items) = component["items"].as_array_mut() {
for item in items {
attachment_uri(&mut item["media"]);
}
}
}
Some(13) => attachment_uri(&mut component["file"]),
_ => {}
}
}
let attachments = message
.attachments
.iter()
.map(|file| json!({ "id": file.id, "filename": file.filename }))
.collect();
(components, attachments)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn native_uploads_keep_spoilers_and_bind_v2_media_to_the_uploaded_file() {
let mut image = crate::tests::attachment("SPOILER_cat video.gif");
image["content_type"] = json!("image/gif");
image["description"] = json!("A cat");
let message = crate::tests::message("speaker", "", vec![image]);
let mut classic = proxy_payload("", "", Vec::new(), false);
assert_eq!(
upload_layout(&mut classic, &message.attachments),
["SPOILER_cat video.gif"],
);
assert_eq!(classic["attachments"][0]["id"], 0);
assert_eq!(classic["attachments"][0]["description"], "A cat");
let mut v2 = proxy_payload("", "", Vec::new(), true);
assert_eq!(
upload_layout(&mut v2, &message.attachments),
["SPOILER_cat_video.gif"],
);
assert_eq!(
v2["components"][0],
json!({
"type": 12,
"items": [{
"media": { "url": "attachment://SPOILER_cat_video.gif" },
"spoiler": true,
}],
}),
);
}
#[test]
fn edits_and_reproxies_keep_raw_components_and_attachment_links() {
let message = crate::tests::message(
"speaker",
"",
vec![
crate::tests::attachment("cat.png"),
crate::tests::attachment("notes v2.txt"),
],
);
let components = vec![
cards::text("old"),
cards::link("Jump to reply", "https://discord.com/channels/1/2/3".into()),
json!({
"type": 12,
"items": [{
"media": { "url": "https://cdn.example/cat.png?ex=abc", "proxy_url": "x" },
"spoiler": true,
}],
}),
json!({ "type": 13, "file": { "url": "https://cdn.example/notes%20v2.txt" } }),
];
let mut raw = serde_json::to_value(message).unwrap();
raw["components"] = json!(components);
raw["flags"] = json!(COMPONENTS_V2);
let target = Target::from_json(raw).unwrap();
assert!(!target.classic);
let (edited, attachments) =
existing_media(&target.message, target.components.clone(), true);
assert_eq!(edited.len(), 3);
assert_eq!(edited[0]["type"], 1);
assert_eq!(
edited[1]["items"][0],
json!({
"media": { "url": "attachment://cat.png" },
"spoiler": true,
})
);
assert_eq!(edited[2]["file"]["url"], "attachment://notes v2.txt");
assert_eq!(attachments.len(), 2);
let (reproxied, _) = existing_media(&target.message, target.components, false);
assert_eq!(reproxied[0]["content"], "old");
}
}