commit
Add editing, reactions, system tag and crowd names
- d!edit / d!e edits the replied-to or latest proxied message, keeping buttons, attachments and spoilers - React ❌ to delete a proxied message (owner only), ❓ to get sender info by DM - Webhook names end with the system tag from the site - More than three speakers show "A, B, C & N more" with the site favicon Co-Authored-By: Sandrone <[email protected]>
diff --git a/src/api/system.ts b/src/api/system.ts
new file mode 100644
index 0000000..7d0c040
--- /dev/null
+++ b/src/api/system.ts
@@ -0,0 +1,22 @@
+/* src/api/system.ts */
+
+import { apiBase } from "../config/constants.ts";
+import { system } from "../state/system.ts";
+
+export async function refreshSystem(): Promise<void> {
+ try {
+ const response = await fetch(`${apiBase}/system`);
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+
+ const info = await response.json() as {
+ name: string | null;
+ tag: string | null;
+ };
+
+ system.name = info.name;
+ system.tag = info.tag;
+ } catch (error) {
+ // Keep the old tag so names don't flicker during an outage
+ console.error("System refresh failed:", error);
+ }
+}
diff --git a/src/commands/edit.ts b/src/commands/edit.ts
new file mode 100644
index 0000000..b001388
--- /dev/null
+++ b/src/commands/edit.ts
@@ -0,0 +1,21 @@
+/* src/commands/edit.ts */
+
+import type { Message } from "discord.js";
+
+import { editProxied } from "../discord/editMessage.ts";
+
+export async function editCommand(
+ message: Message,
+ _args: string[],
+ rest: string,
+): Promise<void> {
+ const problem = await editProxied(message, rest);
+
+ if (problem) {
+ await message.reply(problem);
+ return;
+ }
+
+ // Tidy like a real edit: the command itself disappears
+ await message.delete();
+}
diff --git a/src/commands/index.ts b/src/commands/index.ts
index f301ecb..9591394 100644
--- a/src/commands/index.ts
+++ b/src/commands/index.ts
@@ -3,16 +3,29 @@
import type { Message } from "discord.js";
import { autoproxyCommand } from "./autoproxy.ts";
+import { editCommand } from "./edit.ts";
import { parseCommand } from "./parse.ts";
-type CommandHandler = (message: Message, args: string[]) => Promise<void>;
+type CommandHandler = (
+ message: Message,
+ args: string[],
+ rest: string,
+) => Promise<void>;
+
+const helpText = [
+ "`d!edit <text>` edits the message you reply to, or your latest proxied message. `d!e` works too.",
+ "`d!autoproxy` shows the state, `d!autoproxy on|off` sets it. `d!ap` works too.",
+ "React ❌ to delete a proxied message, ❓ to see who sent it.",
+].join("\n");
const commands: Record<string, CommandHandler> = {
+ edit: editCommand,
+ e: editCommand,
autoproxy: autoproxyCommand,
ap: autoproxyCommand,
- help: (message) => message.reply(
- "`d!autoproxy` shows the state, `d!autoproxy on|off` sets it. `d!ap` works too.",
- ).then(() => {}),
+ help: async (message) => {
+ await message.reply(helpText);
+ },
};
// True when the message was a command, so it isn't proxied as well
@@ -26,6 +39,6 @@ export async function runCommand(message: Message): Promise<boolean> {
return true;
}
- await handler(message, parsed.args);
+ await handler(message, parsed.args, parsed.rest);
return true;
}
diff --git a/src/commands/parse.ts b/src/commands/parse.ts
index bbbee3d..e85f83f 100644
--- a/src/commands/parse.ts
+++ b/src/commands/parse.ts
@@ -5,20 +5,23 @@ export const commandPrefix = "d!";
export interface ParsedCommand {
name: string;
args: string[];
+ // Everything after the name, untouched, for commands that take free text
+ rest: string;
}
export function parseCommand(content: string): ParsedCommand | null {
if (!content.toLowerCase().startsWith(commandPrefix)) return null;
- const [name, ...args] = content
- .slice(commandPrefix.length)
- .trim()
- .split(/\s+/);
+ const body = content.slice(commandPrefix.length).trimStart();
+ const name = body.split(/\s/, 1)[0];
if (!name) return null;
+ const rest = body.slice(name.length).trim();
+
return {
name: name.toLowerCase(),
- args: args.map((arg) => arg.toLowerCase()),
+ args: rest ? rest.toLowerCase().split(/\s+/) : [],
+ rest,
};
}
diff --git a/src/config/constants.ts b/src/config/constants.ts
index ff71aea..332d969 100644
--- a/src/config/constants.ts
+++ b/src/config/constants.ts
@@ -9,3 +9,6 @@ export const reconnectMs = 5 * 1000;
export const webhookDefaultName = "proxyBot";
export const mergedAvatarSize = 512;
+
+// Too many faces for a merge, so a crowd gets the site's icon
+export const crowdAvatarUrl = "https://doughmination.co.uk/favicon.png";
diff --git a/src/discord/avatar.ts b/src/discord/avatar.ts
index f6c7bfa..34a5448 100644
--- a/src/discord/avatar.ts
+++ b/src/discord/avatar.ts
@@ -3,7 +3,9 @@
import { Buffer } from "node:buffer";
import type { Webhook } from "discord.js";
+import { crowdAvatarUrl } from "../config/constants.ts";
import { avatarOf, mergeAvatars } from "../images/merge.ts";
+import { maxNamedSpeakers } from "../proxy/names.ts";
import type { Member } from "../proxy/types.ts";
import { client } from "./client.ts";
@@ -22,6 +24,8 @@ export async function avatarFor(
return avatarOf(speakers[0]) ?? botAvatar;
}
+ if (speakers.length > maxNamedSpeakers) return crowdAvatarUrl;
+
const key = speakers.map((member) => member.id).join(",");
if (webhookAvatarKeys.get(webhook.id) === key) return undefined;
diff --git a/src/discord/client.ts b/src/discord/client.ts
index d7cb031..38ebe16 100644
--- a/src/discord/client.ts
+++ b/src/discord/client.ts
@@ -1,11 +1,18 @@
/* src/discord/client.ts */
-import { Client, GatewayIntentBits } from "discord.js";
+import { Client, GatewayIntentBits, Partials } from "discord.js";
export const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
+ GatewayIntentBits.GuildMessageReactions,
+ ],
+ // Lets ❌ and ❓ work on messages sent before the bot last started
+ partials: [
+ Partials.Message,
+ Partials.Reaction,
+ Partials.User,
],
});
diff --git a/src/discord/editComponents.ts b/src/discord/editComponents.ts
new file mode 100644
index 0000000..fad3fd6
--- /dev/null
+++ b/src/discord/editComponents.ts
@@ -0,0 +1,73 @@
+/* src/discord/editComponents.ts */
+
+// Discord's component type numbers; importing discord.js here would make tests need env access
+export const ComponentType = {
+ ActionRow: 1,
+ TextDisplay: 10,
+ MediaGallery: 12,
+ File: 13,
+} as const;
+
+// Loose JSON so the existing message's components can pass straight through
+// deno-lint-ignore no-explicit-any
+type ComponentJson = Record<string, any>;
+
+// Discord hands back CDN URLs, but File components only accept attachment://
+function toAttachmentUrl(url: string, attachmentNames: Set<string>): string {
+ try {
+ const name = decodeURIComponent(new URL(url).pathname.split("/").pop() ?? "");
+ return attachmentNames.has(name) ? `attachment://${name}` : url;
+ } catch {
+ return url;
+ }
+}
+
+function rewriteMedia(
+ component: ComponentJson,
+ attachmentNames: Set<string>,
+): ComponentJson {
+ if (component.type === ComponentType.MediaGallery) {
+ return {
+ ...component,
+ items: component.items.map((item: ComponentJson) => ({
+ ...item,
+ media: {
+ url: toAttachmentUrl(item.media.url, attachmentNames),
+ },
+ })),
+ };
+ }
+
+ if (component.type === ComponentType.File) {
+ return {
+ ...component,
+ file: {
+ url: toAttachmentUrl(component.file.url, attachmentNames),
+ },
+ };
+ }
+
+ return component;
+}
+
+// Swaps the text block for new text, keeping buttons and attachments as they were
+export function replaceText(
+ components: ComponentJson[],
+ text: string,
+ attachmentNames: string[],
+): ComponentJson[] {
+ const names = new Set(attachmentNames);
+ const kept = components
+ .filter((component) => component.type !== ComponentType.TextDisplay)
+ .map((component) => rewriteMedia(component, names));
+
+ if (!text) return kept;
+
+ return [
+ {
+ type: ComponentType.TextDisplay,
+ content: text,
+ },
+ ...kept,
+ ];
+}
diff --git a/src/discord/editMessage.ts b/src/discord/editMessage.ts
new file mode 100644
index 0000000..f7a5541
--- /dev/null
+++ b/src/discord/editMessage.ts
@@ -0,0 +1,65 @@
+/* src/discord/editMessage.ts */
+
+import {
+ type APIMessageTopLevelComponent,
+ MessageReferenceType,
+ type Message,
+} from "discord.js";
+
+import { client } from "./client.ts";
+import { replaceText } from "./editComponents.ts";
+import { isProxied } from "./ownership.ts";
+import { getWebhook } from "./webhooks.ts";
+
+const searchDepth = 50;
+
+// The replied-to message if there is one, otherwise the newest proxied message here
+async function findTarget(command: Message): Promise<Message | null> {
+ if (command.reference?.type === MessageReferenceType.Default) {
+ const replied = await command.fetchReference().catch(() => null);
+ return replied && isProxied(replied) ? replied : null;
+ }
+
+ const recent = await command.channel.messages.fetch({
+ limit: searchDepth,
+ before: command.id,
+ });
+
+ return recent.find(isProxied) ?? null;
+}
+
+// Returns an error to show, or null when the edit went through
+export async function editProxied(
+ command: Message,
+ text: string,
+): Promise<string | null> {
+ const target = await findTarget(command);
+ if (!target?.webhookId) {
+ return `No proxied message found. Reply to one, or send one in the last ${searchDepth} messages.`;
+ }
+
+ if (!text && target.attachments.size === 0) {
+ return "That would leave the message empty. Use ❌ to delete it instead.";
+ }
+
+ const channelWebhook = await getWebhook(command);
+ const webhook = channelWebhook?.id === target.webhookId
+ ? channelWebhook
+ : await client.fetchWebhook(target.webhookId);
+
+ await webhook.editMessage(target.id, {
+ components: replaceText(
+ target.components.map((component) => component.toJSON()),
+ text,
+ target.attachments.map((attachment) => attachment.name),
+ ) as APIMessageTopLevelComponent[],
+ // Passing them back is what keeps them; leaving this out would drop them
+ attachments: [...target.attachments.values()],
+ threadId: command.channel.isThread() ? command.channel.id : undefined,
+ allowedMentions: {
+ parse: ["users"],
+ },
+ });
+
+ return null;
+}
diff --git a/src/discord/ownership.ts b/src/discord/ownership.ts
new file mode 100644
index 0000000..ce44ab9
--- /dev/null
+++ b/src/discord/ownership.ts
@@ -0,0 +1,12 @@
+/* src/discord/ownership.ts */
+
+import type { Message, PartialMessage } from "discord.js";
+
+import { client } from "./client.ts";
+
+// Webhooks the bot created stamp its application id on every message they send
+export function isProxied(message: Message | PartialMessage): boolean {
+ return Boolean(message.webhookId)
+ && message.applicationId !== null
+ && message.applicationId === client.application?.id;
+}
diff --git a/src/discord/proxyMessage.ts b/src/discord/proxyMessage.ts
index 3c5c18e..b333ed9 100644
--- a/src/discord/proxyMessage.ts
+++ b/src/discord/proxyMessage.ts
@@ -33,7 +33,7 @@ export async function proxyMessage(message: Message): Promise<void> {
flags: MessageFlags.IsComponentsV2,
components: layout.components,
files: layout.files,
- username: webhookName(match.members),
+ username: webhookName(match.members, system.tag),
avatarURL: await avatarFor(webhook, match.members),
threadId: message.channel.isThread() ? message.channel.id : undefined,
// shortcut: only user pings pass through, add role checks if you need @role or @everyone
diff --git a/src/discord/reactions.ts b/src/discord/reactions.ts
new file mode 100644
index 0000000..0b70e58
--- /dev/null
+++ b/src/discord/reactions.ts
@@ -0,0 +1,49 @@
+/* src/discord/reactions.ts */
+
+import type {
+ MessageReaction,
+ PartialMessageReaction,
+ PartialUser,
+ User,
+} from "discord.js";
+
+import { ownerUserId } from "../config/env.ts";
+import { system } from "../state/system.ts";
+import { isProxied } from "./ownership.ts";
+
+const deleteEmoji = "❌";
+const infoEmoji = "❓";
+
+export async function handleReaction(
+ partialReaction: MessageReaction | PartialMessageReaction,
+ partialUser: User | PartialUser,
+): Promise<void> {
+ const emoji = partialReaction.emoji.name;
+ if (emoji !== deleteEmoji && emoji !== infoEmoji) return;
+
+ // Reactions on messages from before startup arrive as partials
+ const reaction = partialReaction.partial
+ ? await partialReaction.fetch()
+ : partialReaction;
+ const user = partialUser.partial ? await partialUser.fetch() : partialUser;
+ const message = reaction.message.partial
+ ? await reaction.message.fetch()
+ : reaction.message;
+
+ if (user.bot || !isProxied(message)) return;
+
+ if (emoji === deleteEmoji) {
+ // Only the system can delete its own messages
+ if (user.id === ownerUserId) await message.delete();
+ return;
+ }
+
+ const systemLine = system.name ? ` of **${system.name}**` : "";
+
+ // DMs can be closed; the info just doesn't arrive then
+ await user.send(
+ `**${message.author.username}**${systemLine}\nSent by <@${ownerUserId}>\n${message.url}`,
+ ).catch(() => {});
+
+ await reaction.users.remove(user.id).catch(() => {});
+}
diff --git a/src/main.ts b/src/main.ts
index 9c2e316..2794e7d 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -4,11 +4,13 @@ import { Events } from "discord.js";
import { fetchFronters } from "./api/fronters.ts";
import { refreshMembers } from "./api/members.ts";
+import { refreshSystem } from "./api/system.ts";
import { connectLive } from "./api/live.ts";
import { memberRefreshMs } from "./config/constants.ts";
import { discordToken } from "./config/env.ts";
import { client } from "./discord/client.ts";
import { proxyMessage } from "./discord/proxyMessage.ts";
+import { handleReaction } from "./discord/reactions.ts";
import { updateStatus } from "./discord/status.ts";
import { loadSettings } from "./state/settings.ts";
@@ -23,8 +25,16 @@ client.on(Events.MessageCreate, (message) => {
});
});
+client.on(Events.MessageReactionAdd, (reaction, user) => {
+ handleReaction(reaction, user).catch((error) => {
+ console.error("Reaction failed:", error);
+ });
+});
+
await loadSettings();
+await refreshSystem();
await refreshMembers();
+setInterval(refreshSystem, memberRefreshMs);
setInterval(refreshMembers, memberRefreshMs);
// The site doesn't retry failed broadcasts, so a slow poll catches anything missed
diff --git a/src/proxy/names.ts b/src/proxy/names.ts
index 3d58e9b..31f0f0d 100644
--- a/src/proxy/names.ts
+++ b/src/proxy/names.ts
@@ -2,17 +2,34 @@
import type { Member } from "./types.ts";
+// Past this many speakers, names collapse to "& N more"
+export const maxNamedSpeakers = 3;
+
+const webhookNameLimit = 80;
+
function displayName(member: Member): string {
return member.display_name ?? member.name;
}
+function speakerNames(members: Member[]): string {
+ const named = members.slice(0, maxNamedSpeakers).map(displayName);
+ const hidden = members.length - named.length;
+
+ if (hidden > 0) named.push(`${hidden} more`);
+
+ // "A", "A & B", "A, B & C", "A, B, C & 2 more"
+ const last = named.pop();
+ return named.length > 0 ? `${named.join(", ")} & ${last}` : last ?? "";
+}
+
// Discord rejects webhook names over 80 chars or containing "discord"
-export function webhookName(members: Member[]): string {
- return members
- .map(displayName)
- .join(" & ")
+export function webhookName(members: Member[], tag: string | null): string {
+ const suffix = tag ? ` ${tag}` : "";
+ const names = speakerNames(members).slice(0, webhookNameLimit - suffix.length);
+
+ return `${names}${suffix}`
.replace(/discord/gi, "dïscord")
- .slice(0, 80);
+ .slice(0, webhookNameLimit);
}
// Custom status text is capped at 128 chars
diff --git a/src/state/system.ts b/src/state/system.ts
index 5f0a7c5..2a89c36 100644
--- a/src/state/system.ts
+++ b/src/state/system.ts
@@ -4,9 +4,13 @@ import type { Member } from "../proxy/types.ts";
// Last known data from the site, kept through outages
export const system: {
+ name: string | null;
+ tag: string | null;
members: Member[];
fronters: Member[];
} = {
+ name: null,
+ tag: null,
members: [],
fronters: [],
};
diff --git a/tests/commands/parse_test.ts b/tests/commands/parse_test.ts
index 2a2c869..b26fbbf 100644
--- a/tests/commands/parse_test.ts
+++ b/tests/commands/parse_test.ts
@@ -8,9 +8,18 @@ Deno.test("parses name and args, case-insensitive", () => {
assertEquals(parseCommand("D!AutoProxy OFF"), {
name: "autoproxy",
args: ["off"],
+ rest: "OFF",
});
});
+Deno.test("rest keeps the original text for edits", () => {
+ assertEquals(parseCommand("d!edit Hello World")?.rest, "Hello World");
+});
+
+Deno.test("no args gives an empty list", () => {
+ assertEquals(parseCommand("d!help")?.args, []);
+});
+
Deno.test("plain messages are not commands", () => {
assertEquals(parseCommand("hello d!autoproxy"), null);
});
diff --git a/tests/discord/editComponents_test.ts b/tests/discord/editComponents_test.ts
new file mode 100644
index 0000000..2a44a20
--- /dev/null
+++ b/tests/discord/editComponents_test.ts
@@ -0,0 +1,72 @@
+/* tests/discord/editComponents_test.ts */
+
+import { assertEquals } from "@std/assert";
+import { ComponentType, replaceText } from "../../src/discord/editComponents.ts";
+
+const cdn = "https://cdn.discordapp.com/attachments/1/2";
+
+const sent = [
+ {
+ type: ComponentType.TextDisplay,
+ id: 1,
+ content: "old",
+ },
+ {
+ type: ComponentType.ActionRow,
+ id: 2,
+ components: [],
+ },
+ {
+ type: ComponentType.MediaGallery,
+ id: 3,
+ items: [
+ {
+ media: {
+ url: `${cdn}/0-cat.png?ex=abc`,
+ proxy_url: "x",
+ },
+ spoiler: true,
+ },
+ ],
+ },
+ {
+ type: ComponentType.File,
+ id: 4,
+ file: {
+ url: `${cdn}/1-notes%20v2.txt`,
+ },
+ },
+];
+
+const names = ["0-cat.png", "1-notes v2.txt"];
+
+Deno.test("new text replaces the old and goes first", () => {
+ const edited = replaceText(sent, "new", names);
+
+ assertEquals(edited[0], {
+ type: ComponentType.TextDisplay,
+ content: "new",
+ });
+ assertEquals(edited.length, 4);
+});
+
+Deno.test("attachments point back at attachment:// and keep spoilers", () => {
+ const edited = replaceText(sent, "new", names);
+
+ assertEquals(edited[2].items[0], {
+ media: {
+ url: "attachment://0-cat.png",
+ },
+ spoiler: true,
+ });
+ assertEquals(edited[3].file.url, "attachment://1-notes v2.txt");
+});
+
+Deno.test("empty text drops the text block", () => {
+ const edited = replaceText(sent, "", names);
+
+ assertEquals(
+ edited.some((component) => component.type === ComponentType.TextDisplay),
+ false,
+ );
+});
diff --git a/tests/proxy/names_test.ts b/tests/proxy/names_test.ts
index 363d042..c1be869 100644
--- a/tests/proxy/names_test.ts
+++ b/tests/proxy/names_test.ts
@@ -11,7 +11,30 @@ const host = {
};
Deno.test("webhook name joins co-fronters", () => {
- assertEquals(webhookName([host, member("02")]), "Clove (Host) & 02");
+ assertEquals(webhookName([host, member("02")], null), "Clove (Host) & 02");
+});
+
+Deno.test("more than three speakers collapse to a count", () => {
+ const crowd = ["a", "b", "c", "d", "e"].map((id) => member(id));
+
+ assertEquals(webhookName(crowd, null), "a, b, c & 2 more");
+});
+
+Deno.test("three speakers use commas then &", () => {
+ const trio = ["a", "b", "c"].map((id) => member(id));
+
+ assertEquals(webhookName(trio, null), "a, b & c");
+});
+
+Deno.test("system tag goes on the end and always survives", () => {
+ const longName = {
+ ...member("x"),
+ display_name: "n".repeat(100),
+ };
+ const name = webhookName([longName], "TAG");
+
+ assertEquals(name.length, 80);
+ assertEquals(name.endsWith(" TAG"), true);
});
Deno.test("webhook name dodges the discord ban", () => {
@@ -20,7 +43,7 @@ Deno.test("webhook name dodges the discord ban", () => {
display_name: "Discord fan",
};
- assertEquals(webhookName([named]), "dïscord fan");
+ assertEquals(webhookName([named], null), "dïscord fan");
});
Deno.test("fronting status lists display names", () => {