Dough Git

commit

inital commit

commit
6281cdff87f004503e50b3fcfe0ef787173bdda2
author
Clove Twilight <[email protected]>
date
2026-11-15 23:06

diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..e9bf4b3
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,2 @@
+DISCORD_TOKEN=
+OWNER_ID=
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..2d7ec5c
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+.env
+node_modules/
diff --git a/deno.json b/deno.json
new file mode 100644
index 0000000..144be56
--- /dev/null
+++ b/deno.json
@@ -0,0 +1,10 @@
+{
+  "nodeModulesDir": "auto",
+  "tasks": {
+    "dev": "deno run --watch --allow-net --allow-env --allow-read --env-file=.env src/main.ts"
+  },
+  "imports": {
+    "@std/assert": "jsr:@std/assert@1",
+    "discord.js": "npm:discord.js@^14.28.1"
+  }
+}
diff --git a/deno.lock b/deno.lock
new file mode 100644
index 0000000..42f3029
--- /dev/null
+++ b/deno.lock
@@ -0,0 +1,161 @@
+{
+  "version": "5",
+  "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"
+  },
+  "jsr": {
+    "@std/[email protected]": {
+      "integrity": "eaada96ee120cb980bc47e040f82814d786fe8162ecc53c91d8df60b8755991e",
+      "dependencies": [
+        "jsr:@std/internal"
+      ]
+    },
+    "@std/[email protected]": {
+      "integrity": "291516b3d4c35024d6ffbc0a9df5bf4c64116e05b50012cf846710152d2ffdf7"
+    }
+  },
+  "npm": {
+    "@discordjs/[email protected]": {
+      "integrity": "sha512-AifaDWTw6WUDhKBn8E6mwwoyjDAcfsYq+ZE0nKSu1dMH1NLR22D3hGkNx+ctEv8NqHEHdAZnP5REteHDmn1lkA==",
+      "dependencies": [
+        "@discordjs/formatters",
+        "@discordjs/util",
+        "@sapphire/shapeshift",
+        "discord-api-types",
+        "fast-deep-equal",
+        "ts-mixer",
+        "tslib"
+      ]
+    },
+    "@discordjs/[email protected]": {
+      "integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ=="
+    },
+    "@discordjs/[email protected]": {
+      "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg=="
+    },
+    "@discordjs/[email protected]": {
+      "integrity": "sha512-y4UPwWhH6vChKRkGdMB4odasUbHOUwy7KL+OVwF86PvT6QVOwElx+TiI1/6kcmcEe+g5YRXJFiXSXUdabqZOvQ==",
+      "dependencies": [
+        "discord-api-types"
+      ]
+    },
+    "@discordjs/[email protected]": {
+      "integrity": "sha512-wvOylxNYJkwKjctS/Mn5GP1w9r3/rzyH+ThD1JlAca6zEdlHs8QWBBUQJpU5Q+W6DoIj/Ljh1IPlZs7hTU+UAg==",
+      "dependencies": [
+        "@discordjs/[email protected]",
+        "@discordjs/util",
+        "@sapphire/async-queue",
+        "@sapphire/snowflake",
+        "@vladfrangu/async_event_emitter",
+        "discord-api-types",
+        "magic-bytes.js",
+        "tslib",
+        "undici"
+      ]
+    },
+    "@discordjs/[email protected]": {
+      "integrity": "sha512-3LKP7F2+atl9vJFhaBjn4nOaSWahZ/yWjOvA4e5pnXkt2qyXRCHLxoBQy81GFtLGCq7K9lPm9R517M1U+/90Qg==",
+      "dependencies": [
+        "discord-api-types"
+      ]
+    },
+    "@discordjs/[email protected]": {
+      "integrity": "sha512-wPlQDxEmlDg5IxhJPuxXr3Vy9AjYq5xCvFWGJyD7w7Np8ZGu+Mc+97LCoEc/+AYCo2IDpKioiH0/c/mj5ZR9Uw==",
+      "dependencies": [
+        "@discordjs/[email protected]",
+        "@discordjs/rest",
+        "@discordjs/util",
+        "@sapphire/async-queue",
+        "@types/ws",
+        "@vladfrangu/async_event_emitter",
+        "discord-api-types",
+        "tslib",
+        "ws"
+      ]
+    },
+    "@sapphire/[email protected]": {
+      "integrity": "sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg=="
+    },
+    "@sapphire/[email protected]": {
+      "integrity": "sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==",
+      "dependencies": [
+        "fast-deep-equal",
+        "lodash"
+      ]
+    },
+    "@sapphire/[email protected]": {
+      "integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ=="
+    },
+    "@types/[email protected]": {
+      "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
+      "dependencies": [
+        "undici-types"
+      ]
+    },
+    "@types/[email protected]": {
+      "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==",
+      "dependencies": [
+        "@types/node"
+      ]
+    },
+    "@vladfrangu/[email protected]": {
+      "integrity": "sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-6utghVho47hBzmx8nIp+pKEDDNIlVk6On/J5Y1Q529payNLZjBsrw+mt+G5Y3NYRE3kgta6eBx5hRYVyfHGdOA=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-Je5OcqgurnIUQK4vR+gQnmzOf/lNQsD6d/UkV8ZOj+bFa5zJXPyiGXlbywp2EagwshVT18y7YNQNSRd3FjYkDw==",
+      "dependencies": [
+        "@discordjs/builders",
+        "@discordjs/[email protected]",
+        "@discordjs/formatters",
+        "@discordjs/rest",
+        "@discordjs/util",
+        "@discordjs/ws",
+        "@sapphire/snowflake",
+        "discord-api-types",
+        "fast-deep-equal",
+        "lodash.snakecase",
+        "magic-bytes.js",
+        "tslib",
+        "undici"
+      ]
+    },
+    "[email protected]": {
+      "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA=="
+    }
+  },
+  "workspace": {
+    "dependencies": [
+      "jsr:@std/assert@1",
+      "npm:discord.js@^14.28.1"
+    ]
+  }
+}
diff --git a/src/main.ts b/src/main.ts
new file mode 100644
index 0000000..68425e8
--- /dev/null
+++ b/src/main.ts
@@ -0,0 +1,236 @@
+/* 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);
+    }
+}
+
+client.once(Events.ClientReady, (ready) => {
+    console.log(`Logged in as ${ready.user.tag}`);
+    refreshFronting();
+    setInterval(refreshFronting, frontingRefreshMs);
+});
+
+client.on(Events.MessageCreate, (message) => {
+    handleMessage(message).catch((error) => {
+        console.error("Proxy failed:", error);
+    });
+});
+
+await refreshMembers();
+setInterval(refreshMembers, refreshMs);
+await client.login(token);
diff --git a/src/proxy.ts b/src/proxy.ts
new file mode 100644
index 0000000..8d1ee03
--- /dev/null
+++ b/src/proxy.ts
@@ -0,0 +1,71 @@
+/* src/proxy.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;
+}
+
+// Longest tag wins, so "C1:" beats "C:"
+export function matchProxyTags(
+    members: Member[],
+    content: string,
+): ProxyMatch | null {
+    let best: ProxyMatch | null = null;
+    let bestLength = -1;
+
+    for (const member of members) {
+        for (const tag of member.proxy_tags) {
+            const prefix = tag.prefix ?? "";
+            const suffix = tag.suffix ?? "";
+            const tagLength = prefix.length + suffix.length;
+
+            if (tagLength === 0) continue;
+            if (tagLength <= bestLength) continue;
+            if (content.length < tagLength) continue;
+            if (!content.startsWith(prefix)) continue;
+            if (!content.endsWith(suffix)) continue;
+
+            const inner = content.slice(
+                prefix.length,
+                content.length - suffix.length,
+            );
+
+            best = {
+                member,
+                content: member.keep_proxy ? content : inner.trim(),
+            };
+            bestLength = tagLength;
+        }
+    }
+
+    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_test.ts b/src/proxy_test.ts
new file mode 100644
index 0000000..b3b68a3
--- /dev/null
+++ b/src/proxy_test.ts
@@ -0,0 +1,72 @@
+/* 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");
+});