commit
Add live fronting, autoproxy, co-front avatars and d! commands
- Fronting arrives over the system site's socket, with a slow poll fallback - Untagged messages proxy as everyone fronting; a leading backslash skips it - Co-fronts get a merged avatar and joined names - d!autoproxy on/off, saved to data/settings.json - Code split into api, commands, config, discord, images, proxy and state Co-Authored-By: Sandrone <[email protected]>
diff --git a/.gitignore b/.gitignore
index b19e0d0..634f4a8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,4 @@
.env
node_modules/
-*/supervise/
\ No newline at end of file
+*/supervise/
+data/
diff --git a/deno.json b/deno.json
index 0784c91..7d04bfd 100644
--- a/deno.json
+++ b/deno.json
@@ -1,10 +1,11 @@
{
"nodeModulesDir": "auto",
"tasks": {
- "start": "deno run --watch --allow-net --allow-env --allow-read --env-file=.env src/main.ts"
+ "start": "deno run --watch --allow-net --allow-env --allow-read --allow-write=./data --env-file=.env src/main.ts"
},
"imports": {
"@std/assert": "jsr:@std/assert@1",
- "discord.js": "npm:discord.js@^14.28.1"
+ "discord.js": "npm:discord.js@^14.28.1",
+ "imagescript": "npm:[email protected]"
}
}
diff --git a/deno.lock b/deno.lock
index 42f3029..307f184 100644
--- a/deno.lock
+++ b/deno.lock
@@ -3,7 +3,8 @@
"specifiers": {
"jsr:@std/assert@1": "1.0.19",
"jsr:@std/internal@^1.0.12": "1.0.14",
- "npm:discord.js@^14.28.1": "14.28.1"
+ "npm:discord.js@^14.28.1": "14.28.1",
+ "npm:[email protected]": "1.3.0"
},
"jsr": {
"@std/[email protected]": {
@@ -127,6 +128,10 @@
"[email protected]": {
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="
},
+ "[email protected]": {
+ "integrity": "sha512-lCYzQrWzdnA68K03oMj/BUlBJrVBnslzDOgGFymAp49NmdGEJxGeN7sHh5mCva0nQkq+kkKSuru2zLf1m04+3A==",
+ "deprecated": true
+ },
"[email protected]": {
"integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw=="
},
@@ -155,7 +160,8 @@
"workspace": {
"dependencies": [
"jsr:@std/assert@1",
- "npm:discord.js@^14.28.1"
+ "npm:discord.js@^14.28.1",
+ "npm:[email protected]"
]
}
}
diff --git a/src/api/fronters.ts b/src/api/fronters.ts
new file mode 100644
index 0000000..facff43
--- /dev/null
+++ b/src/api/fronters.ts
@@ -0,0 +1,24 @@
+/* src/api/fronters.ts */
+
+import { apiBase } from "../config/constants.ts";
+import { updateStatus } from "../discord/status.ts";
+import type { Member } from "../proxy/types.ts";
+import { system } from "../state/system.ts";
+
+export function setFronters(fronters: Member[]): void {
+ system.fronters = fronters;
+ updateStatus();
+}
+
+export async function fetchFronters(): Promise<void> {
+ try {
+ const response = await fetch(`${apiBase}/fronters`);
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+
+ const fronting = await response.json() as { members: Member[] };
+ setFronters(fronting.members);
+ } catch (error) {
+ // Keep the last known front rather than dropping autoproxy
+ console.error("Fronting fetch failed:", error);
+ }
+}
diff --git a/src/api/live.ts b/src/api/live.ts
new file mode 100644
index 0000000..c75ddf4
--- /dev/null
+++ b/src/api/live.ts
@@ -0,0 +1,60 @@
+/* src/api/live.ts */
+
+import { pingMs, reconnectMs, socketUrl } from "../config/constants.ts";
+import type { Member } from "../proxy/types.ts";
+import { fetchFronters, setFronters } from "./fronters.ts";
+
+interface LiveEvent {
+ type?: string;
+ data?: {
+ members?: Member[];
+ };
+}
+
+function receive(raw: string): void {
+ let event: LiveEvent;
+
+ try {
+ event = JSON.parse(raw);
+ } catch {
+ return;
+ }
+
+ if (event.type === "fronters_update" && event.data?.members) {
+ setFronters(event.data.members);
+ }
+}
+
+// Same socket the website listens to; resync on every connect to cover missed events
+export function connectLive(): void {
+ const socket = new WebSocket(socketUrl);
+ let awaitingPong = false;
+ let pingTimer: ReturnType<typeof setInterval> | undefined;
+
+ socket.onopen = () => {
+ console.log("Live socket open");
+ fetchFronters();
+
+ pingTimer = setInterval(() => {
+ if (awaitingPong) return socket.close();
+
+ awaitingPong = true;
+ socket.send("ping");
+ }, pingMs);
+ };
+
+ socket.onmessage = (event) => {
+ if (event.data === "pong") {
+ awaitingPong = false;
+ return;
+ }
+
+ receive(String(event.data));
+ };
+
+ socket.onclose = () => {
+ clearInterval(pingTimer);
+ console.log("Live socket closed, reconnecting");
+ setTimeout(connectLive, reconnectMs);
+ };
+}
diff --git a/src/api/members.ts b/src/api/members.ts
new file mode 100644
index 0000000..f364a9e
--- /dev/null
+++ b/src/api/members.ts
@@ -0,0 +1,18 @@
+/* src/api/members.ts */
+
+import { apiBase } from "../config/constants.ts";
+import type { Member } from "../proxy/types.ts";
+import { system } from "../state/system.ts";
+
+export async function refreshMembers(): Promise<void> {
+ try {
+ const response = await fetch(`${apiBase}/members`);
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+
+ system.members = await response.json() as Member[];
+ console.log(`Loaded ${system.members.length} members`);
+ } catch (error) {
+ // Keep the old list so proxying survives a site outage
+ console.error("Member refresh failed:", error);
+ }
+}
diff --git a/src/commands/autoproxy.ts b/src/commands/autoproxy.ts
new file mode 100644
index 0000000..e30b412
--- /dev/null
+++ b/src/commands/autoproxy.ts
@@ -0,0 +1,22 @@
+/* src/commands/autoproxy.ts */
+
+import type { Message } from "discord.js";
+
+import { saveSettings, settings } from "../state/settings.ts";
+
+export async function autoproxyCommand(
+ message: Message,
+ args: string[],
+): Promise<void> {
+ const [choice] = args;
+
+ if (choice === "on" || choice === "off") {
+ settings.autoproxy = choice === "on";
+ await saveSettings();
+ } else if (choice !== undefined) {
+ await message.reply("Use `d!autoproxy on` or `d!autoproxy off`.");
+ return;
+ }
+
+ await message.reply(`Autoproxy is **${settings.autoproxy ? "on" : "off"}**.`);
+}
diff --git a/src/commands/index.ts b/src/commands/index.ts
new file mode 100644
index 0000000..f301ecb
--- /dev/null
+++ b/src/commands/index.ts
@@ -0,0 +1,31 @@
+/* src/commands/index.ts */
+
+import type { Message } from "discord.js";
+
+import { autoproxyCommand } from "./autoproxy.ts";
+import { parseCommand } from "./parse.ts";
+
+type CommandHandler = (message: Message, args: string[]) => Promise<void>;
+
+const commands: Record<string, CommandHandler> = {
+ autoproxy: autoproxyCommand,
+ ap: autoproxyCommand,
+ help: (message) => message.reply(
+ "`d!autoproxy` shows the state, `d!autoproxy on|off` sets it. `d!ap` works too.",
+ ).then(() => {}),
+};
+
+// True when the message was a command, so it isn't proxied as well
+export async function runCommand(message: Message): Promise<boolean> {
+ const parsed = parseCommand(message.content);
+ if (!parsed) return false;
+
+ const handler = commands[parsed.name];
+ if (!handler) {
+ await message.reply(`Unknown command \`${parsed.name}\`. Try \`d!help\`.`);
+ return true;
+ }
+
+ await handler(message, parsed.args);
+ return true;
+}
diff --git a/src/commands/parse.ts b/src/commands/parse.ts
new file mode 100644
index 0000000..bbbee3d
--- /dev/null
+++ b/src/commands/parse.ts
@@ -0,0 +1,24 @@
+/* src/commands/parse.ts */
+
+export const commandPrefix = "d!";
+
+export interface ParsedCommand {
+ name: string;
+ args: 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+/);
+
+ if (!name) return null;
+
+ return {
+ name: name.toLowerCase(),
+ args: args.map((arg) => arg.toLowerCase()),
+ };
+}
diff --git a/src/config/constants.ts b/src/config/constants.ts
new file mode 100644
index 0000000..ff71aea
--- /dev/null
+++ b/src/config/constants.ts
@@ -0,0 +1,11 @@
+/* src/config/constants.ts */
+
+export const apiBase = "https://doughmination.co.uk/api/plural";
+export const socketUrl = "wss://doughmination.co.uk/api/plural/ws";
+
+export const memberRefreshMs = 5 * 60 * 1000;
+export const pingMs = 30 * 1000;
+export const reconnectMs = 5 * 1000;
+
+export const webhookDefaultName = "proxyBot";
+export const mergedAvatarSize = 512;
diff --git a/src/config/env.ts b/src/config/env.ts
new file mode 100644
index 0000000..a75ed17
--- /dev/null
+++ b/src/config/env.ts
@@ -0,0 +1,11 @@
+/* src/config/env.ts */
+
+const token = Deno.env.get("DISCORD_TOKEN");
+const ownerId = Deno.env.get("OWNER_ID");
+
+if (!token || !ownerId) {
+ throw new Error("Set DISCORD_TOKEN and OWNER_ID in .env");
+}
+
+export const discordToken: string = token;
+export const ownerUserId: string = ownerId;
diff --git a/src/discord/avatar.ts b/src/discord/avatar.ts
new file mode 100644
index 0000000..f6c7bfa
--- /dev/null
+++ b/src/discord/avatar.ts
@@ -0,0 +1,49 @@
+/* src/discord/avatar.ts */
+
+import { Buffer } from "node:buffer";
+import type { Webhook } from "discord.js";
+
+import { avatarOf, mergeAvatars } from "../images/merge.ts";
+import type { Member } from "../proxy/types.ts";
+import { client } from "./client.ts";
+
+// Which front each webhook's own avatar was merged for, by webhook id
+const webhookAvatarKeys = new Map<string, string>();
+let mergedAvatar: { key: string; png: Uint8Array } | null = null;
+
+// One member: per-message avatar URL. Several: the webhook's own avatar becomes the merge
+export async function avatarFor(
+ webhook: Webhook,
+ speakers: Member[],
+): Promise<string | undefined> {
+ const botAvatar = client.user?.displayAvatarURL();
+
+ if (speakers.length === 1) {
+ return avatarOf(speakers[0]) ?? botAvatar;
+ }
+
+ const key = speakers.map((member) => member.id).join(",");
+ if (webhookAvatarKeys.get(webhook.id) === key) return undefined;
+
+ try {
+ if (mergedAvatar?.key !== key) {
+ const png = await mergeAvatars(speakers);
+ if (!png) return botAvatar;
+
+ mergedAvatar = {
+ key,
+ png,
+ };
+ }
+
+ await webhook.edit({
+ avatar: Buffer.from(mergedAvatar.png),
+ });
+ webhookAvatarKeys.set(webhook.id, key);
+ return undefined;
+ } catch (error) {
+ // A broken merge shouldn't stop the message going out
+ console.error("Avatar merge failed:", error);
+ return botAvatar;
+ }
+}
diff --git a/src/discord/client.ts b/src/discord/client.ts
new file mode 100644
index 0000000..d7cb031
--- /dev/null
+++ b/src/discord/client.ts
@@ -0,0 +1,11 @@
+/* src/discord/client.ts */
+
+import { Client, GatewayIntentBits } from "discord.js";
+
+export const client = new Client({
+ intents: [
+ GatewayIntentBits.Guilds,
+ GatewayIntentBits.GuildMessages,
+ GatewayIntentBits.MessageContent,
+ ],
+});
diff --git a/src/discord/layout.ts b/src/discord/layout.ts
new file mode 100644
index 0000000..1bee628
--- /dev/null
+++ b/src/discord/layout.ts
@@ -0,0 +1,99 @@
+/* src/discord/layout.ts */
+
+import {
+ ActionRowBuilder,
+ type AttachmentPayload,
+ ButtonBuilder,
+ ButtonStyle,
+ FileBuilder,
+ MediaGalleryBuilder,
+ MediaGalleryItemBuilder,
+ MessageReferenceType,
+ TextDisplayBuilder,
+ type Message,
+ type MessageActionRowComponentBuilder,
+} from "discord.js";
+
+type TopLevelComponent =
+ | TextDisplayBuilder
+ | ActionRowBuilder<MessageActionRowComponentBuilder>
+ | MediaGalleryBuilder
+ | FileBuilder;
+
+export interface Layout {
+ components: TopLevelComponent[];
+ files: AttachmentPayload[];
+}
+
+// Webhooks can't truly reply, so link back with a button instead
+async function replyButton(message: Message): Promise<ButtonBuilder | null> {
+ if (message.reference?.type !== MessageReferenceType.Default) return null;
+
+ const original = await message.fetchReference().catch(() => null);
+ if (!original) return null;
+
+ const name = original.member?.displayName ?? original.author.displayName;
+
+ return new ButtonBuilder()
+ .setStyle(ButtonStyle.Link)
+ .setLabel(`↪ ${name}`.slice(0, 80))
+ .setURL(original.url);
+}
+
+// Components v2 only shows attachments that a component points at
+export async function buildLayout(
+ message: Message,
+ content: string,
+): Promise<Layout> {
+ const components: TopLevelComponent[] = [];
+ const files: AttachmentPayload[] = [];
+ const button = await replyButton(message);
+
+ if (content) {
+ components.push(new TextDisplayBuilder().setContent(content));
+ }
+
+ // Own row under the text; a Section accessory sits beside it and looks wrong
+ if (button) {
+ components.push(
+ new ActionRowBuilder<MessageActionRowComponentBuilder>()
+ .addComponents(button),
+ );
+ }
+
+ const gallery = new MediaGalleryBuilder();
+ const otherFiles: FileBuilder[] = [];
+
+ for (const [index, attachment] of [...message.attachments.values()].entries()) {
+ // attachment:// must match Discord's sanitised filename exactly
+ const name = `${index}-${attachment.name.replace(/[^\w.-]/g, "_")}`;
+ const type = attachment.contentType ?? "";
+
+ files.push({
+ attachment: attachment.url,
+ name,
+ });
+
+ if (type.startsWith("image/") || type.startsWith("video/")) {
+ gallery.addItems(
+ new MediaGalleryItemBuilder()
+ .setURL(`attachment://${name}`)
+ .setSpoiler(attachment.spoiler),
+ );
+ } else {
+ otherFiles.push(
+ new FileBuilder()
+ .setURL(`attachment://${name}`)
+ .setSpoiler(attachment.spoiler),
+ );
+ }
+ }
+
+ if (gallery.items.length > 0) components.push(gallery);
+ components.push(...otherFiles);
+
+ return {
+ components,
+ files,
+ };
+}
diff --git a/src/discord/proxyMessage.ts b/src/discord/proxyMessage.ts
new file mode 100644
index 0000000..3c5c18e
--- /dev/null
+++ b/src/discord/proxyMessage.ts
@@ -0,0 +1,47 @@
+/* src/discord/proxyMessage.ts */
+
+import { MessageFlags, type Message } from "discord.js";
+
+import { runCommand } from "../commands/index.ts";
+import { ownerUserId } from "../config/env.ts";
+import { pickProxy } from "../proxy/autoproxy.ts";
+import { webhookName } from "../proxy/names.ts";
+import { settings } from "../state/settings.ts";
+import { system } from "../state/system.ts";
+import { avatarFor } from "./avatar.ts";
+import { buildLayout } from "./layout.ts";
+import { getWebhook } from "./webhooks.ts";
+
+export async function proxyMessage(message: Message): Promise<void> {
+ if (message.author.id !== ownerUserId) return;
+ if (message.webhookId || !message.inGuild()) return;
+
+ // Commands never get proxied
+ if (await runCommand(message)) return;
+
+ const fronters = settings.autoproxy ? system.fronters : [];
+ const match = pickProxy(system.members, fronters, message.content);
+ if (!match) return;
+ if (!match.content && message.attachments.size === 0) return;
+
+ const webhook = await getWebhook(message);
+ if (!webhook) return;
+
+ const layout = await buildLayout(message, match.content);
+
+ await webhook.send({
+ flags: MessageFlags.IsComponentsV2,
+ components: layout.components,
+ files: layout.files,
+ username: webhookName(match.members),
+ 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
+ allowedMentions: {
+ parse: ["users"],
+ },
+ });
+
+ // Delete only after the proxied copy is sent, so nothing is lost
+ await message.delete();
+}
diff --git a/src/discord/status.ts b/src/discord/status.ts
new file mode 100644
index 0000000..d24aad3
--- /dev/null
+++ b/src/discord/status.ts
@@ -0,0 +1,22 @@
+/* src/discord/status.ts */
+
+import { ActivityType } from "discord.js";
+
+import { frontingStatus } from "../proxy/names.ts";
+import { system } from "../state/system.ts";
+import { client } from "./client.ts";
+
+// Safe to call before login; the ready handler calls it again
+export function updateStatus(): void {
+ if (!client.isReady()) return;
+
+ client.user.setPresence({
+ activities: [
+ {
+ name: "Custom Status",
+ type: ActivityType.Custom,
+ state: frontingStatus(system.fronters),
+ },
+ ],
+ });
+}
diff --git a/src/discord/webhooks.ts b/src/discord/webhooks.ts
new file mode 100644
index 0000000..5278935
--- /dev/null
+++ b/src/discord/webhooks.ts
@@ -0,0 +1,30 @@
+/* src/discord/webhooks.ts */
+
+import type { Message, Webhook } from "discord.js";
+
+import { webhookDefaultName } from "../config/constants.ts";
+import { client } from "./client.ts";
+
+const webhooks = new Map<string, Webhook>();
+
+// Threads can't own webhooks, so they borrow the parent channel's
+export async function getWebhook(message: Message): Promise<Webhook | null> {
+ const channel = message.channel.isThread()
+ ? message.channel.parent
+ : message.channel;
+
+ if (!channel || !("fetchWebhooks" in channel)) return null;
+
+ const cached = webhooks.get(channel.id);
+ if (cached) return cached;
+
+ const existing = await channel.fetchWebhooks();
+ const webhook = existing.find(
+ (hook) => hook.owner?.id === client.user?.id,
+ ) ?? await channel.createWebhook({
+ name: webhookDefaultName,
+ });
+
+ webhooks.set(channel.id, webhook);
+ return webhook;
+}
diff --git a/src/images/merge.ts b/src/images/merge.ts
new file mode 100644
index 0000000..a372d37
--- /dev/null
+++ b/src/images/merge.ts
@@ -0,0 +1,40 @@
+/* src/images/merge.ts */
+
+import { Image } from "imagescript";
+
+import { mergedAvatarSize } from "../config/constants.ts";
+import type { Member } from "../proxy/types.ts";
+
+export function avatarOf(member: Member): string | null {
+ return member.webhook_avatar_url ?? member.avatar_url;
+}
+
+// One vertical strip per member, left to right in front order
+export async function mergeAvatars(members: Member[]): Promise<Uint8Array | null> {
+ const size = mergedAvatarSize;
+ const urls = members
+ .map(avatarOf)
+ .filter((url): url is string => url !== null);
+
+ if (urls.length === 0) return null;
+
+ const stripWidth = Math.floor(size / urls.length);
+ const canvas = new Image(size, size);
+
+ for (const [index, url] of urls.entries()) {
+ const response = await fetch(url);
+ if (!response.ok) throw new Error(`Avatar ${url}: HTTP ${response.status}`);
+
+ const decoded = await Image.decode(new Uint8Array(await response.arrayBuffer()));
+ if (!(decoded instanceof Image)) continue;
+
+ // Last strip takes the rounding remainder so there's no gap on the right
+ const width = index === urls.length - 1
+ ? size - stripWidth * index
+ : stripWidth;
+
+ canvas.composite(decoded.cover(width, size), stripWidth * index, 0);
+ }
+
+ return await canvas.encode();
+}
diff --git a/src/main.ts b/src/main.ts
index 68425e8..9c2e316 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -1,236 +1,33 @@
/* src/main.ts */
-import {
- ActionRowBuilder,
- ActivityType,
- type AttachmentPayload,
- ButtonBuilder,
- ButtonStyle,
- Client,
- Events,
- FileBuilder,
- GatewayIntentBits,
- MediaGalleryBuilder,
- MediaGalleryItemBuilder,
- MessageFlags,
- MessageReferenceType,
- TextDisplayBuilder,
- type Message,
- type MessageActionRowComponentBuilder,
- type Webhook,
-} from "discord.js";
-
-import {
- frontingStatus,
- matchProxyTags,
- webhookName,
- type Member,
-} from "./proxy.ts";
-
-const apiBase = "https://doughmination.co.uk/api/plural";
-const refreshMs = 5 * 60 * 1000;
-const frontingRefreshMs = 60 * 1000;
-
-const token = Deno.env.get("DISCORD_TOKEN");
-const ownerId = Deno.env.get("OWNER_ID");
-
-if (!token || !ownerId) {
- throw new Error("Set DISCORD_TOKEN and OWNER_ID in .env");
-}
-
-let members: Member[] = [];
-const webhooks = new Map<string, Webhook>();
-
-async function refreshMembers(): Promise<void> {
- try {
- const response = await fetch(`${apiBase}/members`);
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
-
- members = await response.json();
- console.log(`Loaded ${members.length} members`);
- } catch (error) {
- // Keep the old list so proxying survives a site outage
- console.error("Member refresh failed:", error);
- }
-}
-
-async function getWebhook(message: Message): Promise<Webhook | null> {
- const channel = message.channel.isThread()
- ? message.channel.parent
- : message.channel;
-
- if (!channel || !("fetchWebhooks" in channel)) return null;
-
- const cached = webhooks.get(channel.id);
- if (cached) return cached;
-
- const existing = await channel.fetchWebhooks();
- const webhook = existing.find(
- (hook) => hook.owner?.id === client.user?.id,
- ) ?? await channel.createWebhook({
- name: "proxyBot",
- });
-
- webhooks.set(channel.id, webhook);
- return webhook;
-}
-
-type TopLevelComponent =
- | TextDisplayBuilder
- | ActionRowBuilder<MessageActionRowComponentBuilder>
- | MediaGalleryBuilder
- | FileBuilder;
-
-// Webhooks can't truly reply, so link back with a button instead
-async function replyButton(message: Message): Promise<ButtonBuilder | null> {
- if (message.reference?.type !== MessageReferenceType.Default) return null;
-
- const original = await message.fetchReference().catch(() => null);
- if (!original) return null;
-
- const name = original.member?.displayName ?? original.author.displayName;
-
- return new ButtonBuilder()
- .setStyle(ButtonStyle.Link)
- .setLabel(`↪ ${name}`.slice(0, 80))
- .setURL(original.url);
-}
-
-// Components v2 only shows attachments that a component points at
-async function buildLayout(message: Message, content: string): Promise<{
- components: TopLevelComponent[];
- files: AttachmentPayload[];
-}> {
- const components: TopLevelComponent[] = [];
- const files: AttachmentPayload[] = [];
- const button = await replyButton(message);
-
- if (content) {
- components.push(new TextDisplayBuilder().setContent(content));
- }
-
- // Own row under the text; a Section accessory sits beside it and looks wrong
- if (button) {
- components.push(
- new ActionRowBuilder<MessageActionRowComponentBuilder>()
- .addComponents(button),
- );
- }
-
- const gallery = new MediaGalleryBuilder();
- const otherFiles: FileBuilder[] = [];
-
- for (const [index, attachment] of [...message.attachments.values()].entries()) {
- // attachment:// must match Discord's sanitised filename exactly
- const name = `${index}-${attachment.name.replace(/[^\w.-]/g, "_")}`;
- const type = attachment.contentType ?? "";
-
- files.push({
- attachment: attachment.url,
- name,
- });
-
- if (type.startsWith("image/") || type.startsWith("video/")) {
- gallery.addItems(
- new MediaGalleryItemBuilder()
- .setURL(`attachment://${name}`)
- .setSpoiler(attachment.spoiler),
- );
- } else {
- otherFiles.push(
- new FileBuilder()
- .setURL(`attachment://${name}`)
- .setSpoiler(attachment.spoiler),
- );
- }
- }
-
- if (gallery.items.length > 0) components.push(gallery);
- components.push(...otherFiles);
-
- return {
- components,
- files,
- };
-}
-
-async function handleMessage(message: Message): Promise<void> {
- if (message.author.id !== ownerId) return;
- if (message.webhookId || !message.inGuild()) return;
-
- const match = matchProxyTags(members, message.content);
- if (!match) return;
- if (!match.content && message.attachments.size === 0) return;
-
- const webhook = await getWebhook(message);
- if (!webhook) return;
-
- const layout = await buildLayout(message, match.content);
-
- await webhook.send({
- flags: MessageFlags.IsComponentsV2,
- components: layout.components,
- files: layout.files,
- username: webhookName(match.member),
- avatarURL: match.member.webhook_avatar_url
- ?? match.member.avatar_url
- ?? undefined,
- threadId: message.channel.isThread() ? message.channel.id : undefined,
- // shortcut: only user pings pass through, add role checks if you need @role or @everyone
- allowedMentions: {
- parse: ["users"],
- },
- });
-
- // Delete only after the proxied copy is sent, so nothing is lost
- await message.delete();
-}
-
-const client = new Client({
- intents: [
- GatewayIntentBits.Guilds,
- GatewayIntentBits.GuildMessages,
- GatewayIntentBits.MessageContent,
- ],
-});
-
-// shortcut: polls every minute, switch to the site's /v2/ws fronters_update feed if lag bothers you
-async function refreshFronting(): Promise<void> {
- if (!client.isReady()) return;
-
- try {
- const response = await fetch(`${apiBase}/fronters`);
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
-
- const fronting: { members: Member[] } = await response.json();
-
- client.user.setPresence({
- activities: [
- {
- name: "Custom Status",
- type: ActivityType.Custom,
- state: frontingStatus(fronting.members),
- },
- ],
- });
- } catch (error) {
- // Leave the last status up rather than blanking it
- console.error("Fronting refresh failed:", error);
- }
-}
+import { Events } from "discord.js";
+
+import { fetchFronters } from "./api/fronters.ts";
+import { refreshMembers } from "./api/members.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 { updateStatus } from "./discord/status.ts";
+import { loadSettings } from "./state/settings.ts";
client.once(Events.ClientReady, (ready) => {
console.log(`Logged in as ${ready.user.tag}`);
- refreshFronting();
- setInterval(refreshFronting, frontingRefreshMs);
+ updateStatus();
});
client.on(Events.MessageCreate, (message) => {
- handleMessage(message).catch((error) => {
+ proxyMessage(message).catch((error) => {
console.error("Proxy failed:", error);
});
});
+await loadSettings();
await refreshMembers();
-setInterval(refreshMembers, refreshMs);
-await client.login(token);
+setInterval(refreshMembers, memberRefreshMs);
+
+// The site doesn't retry failed broadcasts, so a slow poll catches anything missed
+setInterval(fetchFronters, memberRefreshMs);
+connectLive();
+await client.login(discordToken);
diff --git a/src/proxy/autoproxy.ts b/src/proxy/autoproxy.ts
new file mode 100644
index 0000000..e992b7f
--- /dev/null
+++ b/src/proxy/autoproxy.ts
@@ -0,0 +1,25 @@
+/* src/proxy/autoproxy.ts */
+
+import { matchProxyTags } from "./tags.ts";
+import type { Member, ProxyMatch } from "./types.ts";
+
+// Tags win; otherwise everyone fronting speaks together. A leading "\" skips it
+export function pickProxy(
+ members: Member[],
+ fronters: Member[],
+ content: string,
+): ProxyMatch | null {
+ const tagged = matchProxyTags(members, content);
+ if (tagged) return tagged;
+ if (content.startsWith("\\")) return null;
+
+ const speaking = fronters.filter(
+ (member) => member.autoproxy_enabled !== false,
+ );
+ if (speaking.length === 0) return null;
+
+ return {
+ members: speaking,
+ content,
+ };
+}
diff --git a/src/proxy/names.ts b/src/proxy/names.ts
new file mode 100644
index 0000000..3d58e9b
--- /dev/null
+++ b/src/proxy/names.ts
@@ -0,0 +1,23 @@
+/* src/proxy/names.ts */
+
+import type { Member } from "./types.ts";
+
+function displayName(member: Member): string {
+ return member.display_name ?? member.name;
+}
+
+// Discord rejects webhook names over 80 chars or containing "discord"
+export function webhookName(members: Member[]): string {
+ return members
+ .map(displayName)
+ .join(" & ")
+ .replace(/discord/gi, "dïscord")
+ .slice(0, 80);
+}
+
+// Custom status text is capped at 128 chars
+export function frontingStatus(fronters: Member[]): string {
+ if (fronters.length === 0) return "Nobody fronting";
+
+ return `Fronting: ${fronters.map(displayName).join(", ")}`.slice(0, 128);
+}
diff --git a/src/proxy.ts b/src/proxy/tags.ts
similarity index 51%
rename from src/proxy.ts
rename to src/proxy/tags.ts
index 8d1ee03..e471f5b 100644
--- a/src/proxy.ts
+++ b/src/proxy/tags.ts
@@ -1,24 +1,6 @@
-/* src/proxy.ts */
+/* src/proxy/tags.ts */
-export interface ProxyTag {
- prefix: string | null;
- suffix: string | null;
-}
-
-export interface Member {
- id: string;
- name: string;
- display_name: string | null;
- avatar_url: string | null;
- webhook_avatar_url: string | null;
- proxy_tags: ProxyTag[];
- keep_proxy: boolean;
-}
-
-export interface ProxyMatch {
- member: Member;
- content: string;
-}
+import type { Member, ProxyMatch } from "./types.ts";
// Longest tag wins, so "C1:" beats "C:"
export function matchProxyTags(
@@ -46,7 +28,7 @@ export function matchProxyTags(
);
best = {
- member,
+ members: [member],
content: member.keep_proxy ? content : inner.trim(),
};
bestLength = tagLength;
@@ -55,17 +37,3 @@ export function matchProxyTags(
return best;
}
-
-// Custom status text is capped at 128 chars
-export function frontingStatus(fronters: Member[]): string {
- if (fronters.length === 0) return "Nobody fronting";
-
- const names = fronters.map((member) => member.display_name ?? member.name);
- return `Fronting: ${names.join(", ")}`.slice(0, 128);
-}
-
-// Discord rejects webhook names over 80 chars or containing "discord"
-export function webhookName(member: Member): string {
- const name = member.display_name ?? member.name;
- return name.replace(/discord/gi, "dïscord").slice(0, 80);
-}
diff --git a/src/proxy/types.ts b/src/proxy/types.ts
new file mode 100644
index 0000000..42fa8e6
--- /dev/null
+++ b/src/proxy/types.ts
@@ -0,0 +1,22 @@
+/* src/proxy/types.ts */
+
+export interface ProxyTag {
+ prefix: string | null;
+ suffix: string | null;
+}
+
+export interface Member {
+ id: string;
+ name: string;
+ display_name: string | null;
+ avatar_url: string | null;
+ webhook_avatar_url: string | null;
+ proxy_tags: ProxyTag[];
+ keep_proxy: boolean;
+ autoproxy_enabled: boolean | null;
+}
+
+export interface ProxyMatch {
+ members: Member[];
+ content: string;
+}
diff --git a/src/proxy_test.ts b/src/proxy_test.ts
deleted file mode 100644
index b3b68a3..0000000
--- a/src/proxy_test.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-/* src/proxy_test.ts */
-
-import { assertEquals } from "@std/assert";
-import {
- frontingStatus,
- matchProxyTags,
- webhookName,
- type Member,
-} from "./proxy.ts";
-
-function member(
- id: string,
- prefix: string | null,
- suffix: string | null,
-): Member {
- return {
- id,
- name: id,
- display_name: null,
- avatar_url: null,
- webhook_avatar_url: null,
- proxy_tags: [{ prefix, suffix }],
- keep_proxy: false,
- };
-}
-
-const members = [
- member("short", "C:", null),
- member("long", "C1:", null),
- member("brackets", "[", "]"),
-];
-
-Deno.test("prefix match strips the tag", () => {
- assertEquals(matchProxyTags(members, "C: hi")?.content, "hi");
-});
-
-Deno.test("longest tag wins", () => {
- assertEquals(matchProxyTags(members, "C1: hi")?.member.id, "long");
-});
-
-Deno.test("prefix and suffix match", () => {
- const match = matchProxyTags(members, "[hello]");
-
- assertEquals(match?.member.id, "brackets");
- assertEquals(match?.content, "hello");
-});
-
-Deno.test("no tag means no match", () => {
- assertEquals(matchProxyTags(members, "plain message"), null);
-});
-
-Deno.test("webhook name dodges the discord ban", () => {
- const named = {
- ...member("x", null, null),
- display_name: "Discord fan",
- };
-
- assertEquals(webhookName(named), "dïscord fan");
-});
-
-Deno.test("fronting status lists display names", () => {
- const host = {
- ...member("c1", null, null),
- display_name: "Clove (Host)",
- };
-
- assertEquals(
- frontingStatus([host, member("02", null, null)]),
- "Fronting: Clove (Host), 02",
- );
- assertEquals(frontingStatus([]), "Nobody fronting");
-});
diff --git a/src/state/settings.ts b/src/state/settings.ts
new file mode 100644
index 0000000..9d72157
--- /dev/null
+++ b/src/state/settings.ts
@@ -0,0 +1,32 @@
+/* src/state/settings.ts */
+
+// Resolved from this file, so it works whatever directory the service starts in
+const settingsDir = new URL("../../data/", import.meta.url);
+const settingsFile = new URL("settings.json", settingsDir);
+
+export interface Settings {
+ autoproxy: boolean;
+}
+
+const defaults: Settings = {
+ autoproxy: true,
+};
+
+export const settings: Settings = { ...defaults };
+
+export async function loadSettings(): Promise<void> {
+ try {
+ const saved = JSON.parse(await Deno.readTextFile(settingsFile));
+ Object.assign(settings, saved);
+ } catch (error) {
+ // First run has no file yet; anything else is worth a log
+ if (!(error instanceof Deno.errors.NotFound)) {
+ console.error("Settings load failed, using defaults:", error);
+ }
+ }
+}
+
+export async function saveSettings(): Promise<void> {
+ await Deno.mkdir(settingsDir, { recursive: true });
+ await Deno.writeTextFile(settingsFile, JSON.stringify(settings, null, 4));
+}
diff --git a/src/state/system.ts b/src/state/system.ts
new file mode 100644
index 0000000..5f0a7c5
--- /dev/null
+++ b/src/state/system.ts
@@ -0,0 +1,12 @@
+/* src/state/system.ts */
+
+import type { Member } from "../proxy/types.ts";
+
+// Last known data from the site, kept through outages
+export const system: {
+ members: Member[];
+ fronters: Member[];
+} = {
+ members: [],
+ fronters: [],
+};
diff --git a/tests/commands/parse_test.ts b/tests/commands/parse_test.ts
new file mode 100644
index 0000000..2a2c869
--- /dev/null
+++ b/tests/commands/parse_test.ts
@@ -0,0 +1,20 @@
+/* tests/commands/parse_test.ts */
+
+import { assertEquals } from "@std/assert";
+
+import { parseCommand } from "../../src/commands/parse.ts";
+
+Deno.test("parses name and args, case-insensitive", () => {
+ assertEquals(parseCommand("D!AutoProxy OFF"), {
+ name: "autoproxy",
+ args: ["off"],
+ });
+});
+
+Deno.test("plain messages are not commands", () => {
+ assertEquals(parseCommand("hello d!autoproxy"), null);
+});
+
+Deno.test("bare prefix is not a command", () => {
+ assertEquals(parseCommand("d! "), null);
+});
diff --git a/tests/fixtures.ts b/tests/fixtures.ts
new file mode 100644
index 0000000..1905981
--- /dev/null
+++ b/tests/fixtures.ts
@@ -0,0 +1,20 @@
+/* tests/fixtures.ts */
+
+import type { Member } from "../src/proxy/types.ts";
+
+export function member(
+ id: string,
+ prefix: string | null = null,
+ suffix: string | null = null,
+): Member {
+ return {
+ id,
+ name: id,
+ display_name: null,
+ avatar_url: null,
+ webhook_avatar_url: null,
+ proxy_tags: [{ prefix, suffix }],
+ keep_proxy: false,
+ autoproxy_enabled: null,
+ };
+}
diff --git a/tests/proxy/autoproxy_test.ts b/tests/proxy/autoproxy_test.ts
new file mode 100644
index 0000000..0c25299
--- /dev/null
+++ b/tests/proxy/autoproxy_test.ts
@@ -0,0 +1,40 @@
+/* tests/proxy/autoproxy_test.ts */
+
+import { assertEquals } from "@std/assert";
+
+import { pickProxy } from "../../src/proxy/autoproxy.ts";
+import { member } from "../fixtures.ts";
+
+const tagged = member("tagged", "T:");
+const host = member("host");
+const quiet = {
+ ...member("quiet"),
+ autoproxy_enabled: false,
+};
+
+Deno.test("tags beat autoproxy", () => {
+ const match = pickProxy([tagged], [host], "T: hi");
+
+ assertEquals(match?.members.map((speaker) => speaker.id), ["tagged"]);
+});
+
+Deno.test("untagged messages go to everyone fronting", () => {
+ const match = pickProxy([tagged], [host, member("co")], "hi");
+
+ assertEquals(match?.members.map((speaker) => speaker.id), ["host", "co"]);
+ assertEquals(match?.content, "hi");
+});
+
+Deno.test("members with autoproxy off are left out", () => {
+ const match = pickProxy([], [host, quiet], "hi");
+
+ assertEquals(match?.members.map((speaker) => speaker.id), ["host"]);
+});
+
+Deno.test("backslash skips autoproxy", () => {
+ assertEquals(pickProxy([], [host], "\\not proxied"), null);
+});
+
+Deno.test("nobody fronting means no proxy", () => {
+ assertEquals(pickProxy([], [], "hi"), null);
+});
diff --git a/tests/proxy/names_test.ts b/tests/proxy/names_test.ts
new file mode 100644
index 0000000..363d042
--- /dev/null
+++ b/tests/proxy/names_test.ts
@@ -0,0 +1,32 @@
+/* tests/proxy/names_test.ts */
+
+import { assertEquals } from "@std/assert";
+
+import { frontingStatus, webhookName } from "../../src/proxy/names.ts";
+import { member } from "../fixtures.ts";
+
+const host = {
+ ...member("c1"),
+ display_name: "Clove (Host)",
+};
+
+Deno.test("webhook name joins co-fronters", () => {
+ assertEquals(webhookName([host, member("02")]), "Clove (Host) & 02");
+});
+
+Deno.test("webhook name dodges the discord ban", () => {
+ const named = {
+ ...member("x"),
+ display_name: "Discord fan",
+ };
+
+ assertEquals(webhookName([named]), "dïscord fan");
+});
+
+Deno.test("fronting status lists display names", () => {
+ assertEquals(
+ frontingStatus([host, member("02")]),
+ "Fronting: Clove (Host), 02",
+ );
+ assertEquals(frontingStatus([]), "Nobody fronting");
+});
diff --git a/tests/proxy/tags_test.ts b/tests/proxy/tags_test.ts
new file mode 100644
index 0000000..19faaf9
--- /dev/null
+++ b/tests/proxy/tags_test.ts
@@ -0,0 +1,31 @@
+/* tests/proxy/tags_test.ts */
+
+import { assertEquals } from "@std/assert";
+
+import { matchProxyTags } from "../../src/proxy/tags.ts";
+import { member } from "../fixtures.ts";
+
+const members = [
+ member("short", "C:"),
+ member("long", "C1:"),
+ member("brackets", "[", "]"),
+];
+
+Deno.test("prefix match strips the tag", () => {
+ assertEquals(matchProxyTags(members, "C: hi")?.content, "hi");
+});
+
+Deno.test("longest tag wins", () => {
+ assertEquals(matchProxyTags(members, "C1: hi")?.members[0].id, "long");
+});
+
+Deno.test("prefix and suffix match", () => {
+ const match = matchProxyTags(members, "[hello]");
+
+ assertEquals(match?.members[0].id, "brackets");
+ assertEquals(match?.content, "hello");
+});
+
+Deno.test("no tag means no match", () => {
+ assertEquals(matchProxyTags(members, "plain message"), null);
+});