commit
Store autoproxy setting per server
Settings are keyed by guild id, default autoproxy to off, and are added on join, removed on leave, and synced with the guild list on startup. Outages that mark a guild unavailable keep its settings. Co-Authored-By: Sandrone <[email protected]>
diff --git a/src/commands/autoproxy.ts b/src/commands/autoproxy.ts
index ab55c1b..3584efa 100644
--- a/src/commands/autoproxy.ts
+++ b/src/commands/autoproxy.ts
@@ -2,7 +2,7 @@
import type { Message } from "discord.js";
-import { saveSettings, settings } from "../state/settings.ts";
+import { guildSettings, saveSettings } from "../state/settings.ts";
export async function autoproxyCommand(
message: Message,
@@ -10,13 +10,16 @@ export async function autoproxyCommand(
): Promise<void> {
const [choice] = args;
+ // Commands only run from server messages, so guildId is always set
+ const autoproxy = guildSettings(message.guildId!).autoproxy;
+
if (choice === "on" || choice === "off") {
- settings.autoproxy.enabled = choice === "on";
+ autoproxy.enabled = 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.enabled ? "on" : "off"}**.`);
+ await message.reply(`Autoproxy in this server is **${autoproxy.enabled ? "on" : "off"}**.`);
}
diff --git a/src/commands/help.ts b/src/commands/help.ts
index 8e9f9f9..644e791 100644
--- a/src/commands/help.ts
+++ b/src/commands/help.ts
@@ -5,7 +5,7 @@ import type { Message } from "discord.js";
const helpText = [
"`d!edit <text>` edits the message you reply to, or your latest proxied message. `d!e` works too.",
"`d!explain` explains the bot, and plurality. `d!ex` works too,",
- "`d!autoproxy` shows the state, `d!autoproxy on|off` sets it. `d!ap` works too.",
+ "`d!autoproxy` shows the state for this server, `d!autoproxy on|off` sets it. `d!ap` works too.",
"-# React ❌ to delete a proxied message, ❓ to see who sent it.",
].join("\n");
diff --git a/src/discord/proxyMessage.ts b/src/discord/proxyMessage.ts
index 929dcfb..ddfaeda 100644
--- a/src/discord/proxyMessage.ts
+++ b/src/discord/proxyMessage.ts
@@ -6,7 +6,7 @@ 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 { guildSettings } from "../state/settings.ts";
import { system } from "../state/system.ts";
import { avatarFor } from "./avatar.ts";
import { buildLayout } from "./layout.ts";
@@ -21,7 +21,7 @@ export async function proxyMessage(message: Message): Promise<void> {
// Commands never get proxied
if (await runCommand(message)) return;
- const fronters = settings.autoproxy.enabled ? system.fronters : [];
+ const fronters = guildSettings(message.guildId).autoproxy.enabled ? system.fronters : [];
const match = pickProxy(system.members, fronters, message.content);
if (!match) return;
if (!match.content && message.attachments.size === 0) return;
diff --git a/src/main.ts b/src/main.ts
index 0175166..87c35fe 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -14,11 +14,35 @@ import { handleReaction } from "./discord/reactions.ts";
import { notifyReply } from "./discord/replyNotice.ts";
import { updateStatus } from "./discord/status.ts";
import { markActive } from "./state/activity.ts";
-import { loadSettings } from "./state/settings.ts";
+import {
+ addGuild,
+ loadSettings,
+ removeGuild,
+ syncGuilds,
+} from "./state/settings.ts";
client.once(Events.ClientReady, (ready) => {
console.log(`Logged in as ${ready.user.tag}`);
updateStatus();
+
+ syncGuilds(ready.guilds.cache.keys()).catch((error) => {
+ console.error("Guild sync failed:", error);
+ });
+});
+
+client.on(Events.GuildCreate, (guild) => {
+ addGuild(guild.id).catch((error) => {
+ console.error("Guild add failed:", error);
+ });
+});
+
+client.on(Events.GuildDelete, (guild) => {
+ // An outage also fires this; only a real leave or kick drops the settings
+ if (!guild.available) return;
+
+ removeGuild(guild.id).catch((error) => {
+ console.error("Guild remove failed:", error);
+ });
});
client.on(Events.MessageCreate, (message) => {
diff --git a/src/state/settings.ts b/src/state/settings.ts
index 7b6174d..e31aae3 100644
--- a/src/state/settings.ts
+++ b/src/state/settings.ts
@@ -5,30 +5,77 @@ import { dump, load } from "jpcl-lang";
// Resolved from this file, so it works whatever directory the service starts in
const settingsFile = new URL("../../data/settings.jp", import.meta.url);
-// Each top-level key is a [section] in the .jp file
-export interface Settings {
+// One [guildId] section per server in the .jp file
+export interface GuildSettings {
autoproxy: {
enabled: boolean;
};
}
-const defaults: Settings = {
+const defaults: GuildSettings = {
autoproxy: {
- enabled: true,
+ enabled: false,
},
};
-export const settings: Settings = structuredClone(defaults);
+// One entry per server the bot is in
+export const settings: Record<string, GuildSettings> = {};
+
+// Merge per section, so keys added later keep their defaults
+function withDefaults(saved: Partial<GuildSettings> = {}): GuildSettings {
+ return {
+ autoproxy: {
+ ...defaults.autoproxy,
+ ...saved.autoproxy,
+ },
+ };
+}
+
+// Returns the stored entry, creating it, so edits are kept by saveSettings
+export function guildSettings(guildId: string): GuildSettings {
+ settings[guildId] ??= withDefaults();
+ return settings[guildId];
+}
+
+// Adds servers joined and drops servers left, including while the bot was offline
+export async function syncGuilds(guildIds: Iterable<string>): Promise<void> {
+ const current = new Set(guildIds);
+ let changed = false;
+
+ for (const guildId of current) {
+ if (settings[guildId]) continue;
+ settings[guildId] = withDefaults();
+ changed = true;
+ }
+
+ for (const guildId of Object.keys(settings)) {
+ if (current.has(guildId)) continue;
+ delete settings[guildId];
+ changed = true;
+ }
+
+ if (changed) await saveSettings();
+}
+
+export async function addGuild(guildId: string): Promise<void> {
+ guildSettings(guildId);
+ await saveSettings();
+}
+
+export async function removeGuild(guildId: string): Promise<void> {
+ delete settings[guildId];
+ await saveSettings();
+}
export async function loadSettings(): Promise<void> {
try {
- const saved = await load(settingsFile) as Partial<Settings>;
+ const saved = await load(settingsFile) as Record<string, Partial<GuildSettings>>;
- // Merge per section, so keys added later keep their defaults
- settings.autoproxy = {
- ...defaults.autoproxy,
- ...saved.autoproxy,
- };
+ for (const [guildId, guild] of Object.entries(saved)) {
+ // Skips leftovers from the old global format, like [autoproxy]
+ if (!/^\d+$/.test(guildId)) continue;
+ settings[guildId] = withDefaults(guild);
+ }
} catch (error) {
// First run has no file yet; anything else is worth a log
if ((error as { code?: string }).code !== "ENOENT") {
diff --git a/tests/state/settings_test.ts b/tests/state/settings_test.ts
new file mode 100644
index 0000000..dbb017d
--- /dev/null
+++ b/tests/state/settings_test.ts
@@ -0,0 +1,16 @@
+/* tests/state/settings_test.ts */
+
+import { assertEquals } from "@std/assert";
+
+import { guildSettings, settings } from "../../src/state/settings.ts";
+
+Deno.test("autoproxy is per server and off by default", () => {
+ guildSettings("1").autoproxy.enabled = true;
+
+ assertEquals(guildSettings("1").autoproxy.enabled, true);
+ assertEquals(guildSettings("2").autoproxy.enabled, false);
+
+ // Leaves no test entries behind for other tests
+ delete settings["1"];
+ delete settings["2"];
+});