1
0
Fork 0

feat(bot): add editable Discord Rich Presence via command and CMS

Adds a discord-presence Payload Global as the single source of truth for the bot's Discord activity. Two writers update it and either takes effect live: the admin CMS page and the /discord-presence command (view/edit/clear, guild-only, gated by new discord:rp:read and discord:rp:update permissions). A poll loop reconciles Discord's live presence from the Global so CMS edits propagate without a restart; disabled or blank presence sets the bot idle.
This commit is contained in:
Jason Fraley 2026-10-12 10:21:37 -04:00
parent c984f08ea0
commit 8148aeb22d
16 changed files with 40986 additions and 6 deletions

View file

@ -166,6 +166,7 @@ Dependency: `discord.js` ^14 (add to root `package.json`). Script: `"bot": "bun
| `DISCORD_COMMUNITY_ZEUS_ROLE_ID` | no | Community Zeus role ping (falls back to resolving the role by name) |
| `DISCORD_ANNOUNCE_MENTION_ROLE_ID` | no | Role auto-mentioned in `/announce` when called without a message (compose dialog). Unset disables it |
| `DISCORD_SIDE_OPS_POLL_MS` | no | default 1800000 (30 min) |
| `DISCORD_PRESENCE_POLL_MS` | no | default 30000 (30s); reconcile loop for the bot's Rich Presence from the `discord-presence` Global |
`APP_URL` already exists — used for login links in DMs.

View file

@ -8,7 +8,7 @@ Standalone long-running process (`bun run bot`). Imports `@payload-config` direc
## Env
Required: `DISCORD_TOKEN`, `DISCORD_GUILD_ID` (fail-fast on missing vars in `config.ts`). Optional: `DISCORD_OPS_CHANNEL_ID`, `DISCORD_ANNOUNCE_CHANNEL_ID`, `DISCORD_CHANGELOG_CHANNEL_ID` (dedicated #releases channel for `/changelog`; falls back to the announce channel), `DISCORD_STAFF_ROLE_IDS`, `DISCORD_SIDE_OPS_CHANNEL_ID` (Friday open-slot notice channel), `DISCORD_COMMUNITY_ZEUS_ROLE_ID` (role ping for that notice), `APP_URL`, plus poll intervals `DISCORD_ATTENDANCE_POLL_MS` (default 60s), `DISCORD_NOTIFICATION_POLL_MS` (default 20s), `DISCORD_EVALUATION_POLL_MS` (default 60s), `DISCORD_IMMINENT_POLL_MS` (default 60s), `DISCORD_SIDE_OPS_POLL_MS` (default 30 min). Logs through `payload.logger`.
Required: `DISCORD_TOKEN`, `DISCORD_GUILD_ID` (fail-fast on missing vars in `config.ts`). Optional: `DISCORD_OPS_CHANNEL_ID`, `DISCORD_ANNOUNCE_CHANNEL_ID`, `DISCORD_CHANGELOG_CHANNEL_ID` (dedicated #releases channel for `/changelog`; falls back to the announce channel), `DISCORD_STAFF_ROLE_IDS`, `DISCORD_SIDE_OPS_CHANNEL_ID` (Friday open-slot notice channel), `DISCORD_COMMUNITY_ZEUS_ROLE_ID` (role ping for that notice), `APP_URL`, plus poll intervals `DISCORD_ATTENDANCE_POLL_MS` (default 60s), `DISCORD_NOTIFICATION_POLL_MS` (default 20s), `DISCORD_EVALUATION_POLL_MS` (default 60s), `DISCORD_IMMINENT_POLL_MS` (default 60s), `DISCORD_SIDE_OPS_POLL_MS` (default 30 min), `DISCORD_PRESENCE_POLL_MS` (default 30s). Logs through `payload.logger`.
## Structure
@ -26,6 +26,7 @@ bot/
changelog.ts # /changelog (guild-only, staff only; posts a CHANGELOG.md entry to #releases, native markdown, splits long entries)
remindEvaluations.ts # /remind-evaluations (guild-only, staff only, manual evaluation-reminder trigger)
rollcall.ts # /rollcall (guild-only, staff only, force-send/refresh a roll-call)
discordPresence.ts # /discord-presence (guild-only, discord:rp:update; view/edit/clear the bot's Rich Presence via a prefilled modal)
events/
interactionCreate.ts # Routes ptf-att: RSVP button interactions
@ -41,17 +42,19 @@ bot/
signup.ts # Signup service logic
transferRequests.ts # Polls assignment transfer requests awaiting leader decision
transferDelivery.ts # Transfer leader-request / rejection / info delivery DMs
discordPresence.ts # Poll the discord-presence Global → reconcile the bot's live Rich Presence (in-memory last-applied diff)
lib/
roles.ts # isStaff check
resolve.ts # discordId ↔ Payload user lookups
transferMessaging.ts # Transfer embed builders + delivery keys
presence.ts # applyPresence: map the discord-presence Global → a discord.js activity (idle when disabled/blank)
```
## Command registration scope
- **Global** (DM-usable): `signup`, `link`, `ping`
- **Guild-only**: `announce`, `remind-evaluations`, `rollcall` (guild-scoped commands never appear in DMs)
- **Guild-only**: `announce`, `remind-evaluations`, `rollcall`, `discord-presence` (guild-scoped commands never appear in DMs)
## Feature flow: signup/link
@ -85,6 +88,15 @@ At 8 PM Eastern on Wednesday (`America/New_York`, evaluated via `isNoticeDue` in
`transferRequests` polls `assignment-transfers` for requests awaiting leader decision; leaders approve/deny via buttons handled in `transferInteractions.ts`; DMs are built by `lib/transferMessaging.ts` and sent through `transferDelivery.ts` (leader request, requester rejection notice, decision info). Web side: `src/lib/transfers/` + `/transfers` page.
## Feature flow: Discord Rich Presence
The bot's Discord activity (state/details/timestamps/images/party/join secret) has ONE source of truth: the `discord-presence` Payload Global (`src/collections/discord/DiscordPresence.ts`). Two independent writers update it and either takes effect live:
- **CMS**: edit the "Discord Rich Presence" global in the admin panel (gated by `discord:rp:update`).
- **Command**: `/discord-presence` (guild-only, gated by `discord:rp:update`) with `action=view|edit|clear`. `edit` opens a prefilled modal (all fields as text inputs, since this discord.js build cannot preselect modal select-menu defaults); submit writes the Global then applies immediately. `clear` disables + blanks every field. Modal submit routes through `bot/index.ts` on the `ptf-rp-edit:` custom-id prefix → `handlePresenceModal`.
A poll loop (`services/discordPresence.ts`, `DISCORD_PRESENCE_POLL_MS`, default 30s) reconciles Discord's live presence with the stored Global so CMS edits propagate without a restart; it holds an in-memory last-applied signature so a command edit isn't re-applied. `applyPresence` (`lib/presence.ts`) maps the Global to a discord.js activity: `state`→bold title (`name`), `details`→details line, timestamps are epoch **ms**, `partySize`/`partyMax`→`party.size [current,max]`, image keys are freeform (asset id or `data:image/...` URI). When disabled OR every field is blank the bot goes **idle** with no activity. The bot reads/writes the Global with `overrideAccess: true` (trusted internal process). Permissions `discord:rp:read`/`discord:rp:update` live in the "Discord Bot" group.
## Where to look
| Task | Path |
@ -100,6 +112,8 @@ At 8 PM Eastern on Wednesday (`America/New_York`, evaluated via `isNoticeDue` in
| Friday open-slot notice | `bot/services/fridayOpsNotice.ts` + `src/lib/intelligence/fridayOpsNotice.ts` |
| Transfer workflow | `bot/services/transferRequests.ts` + `lib/transferMessaging.ts` |
| User lookup patterns | `bot/lib/resolve.ts` |
| Edit bot Rich Presence (command) | `bot/commands/discordPresence.ts` (+ Global `src/collections/discord/DiscordPresence.ts`) |
| Rich Presence reconcile loop / mapping | `bot/services/discordPresence.ts` + `bot/lib/presence.ts` |
## Anti-patterns

View file

@ -0,0 +1,263 @@
import {
ActionRowBuilder,
EmbedBuilder,
type Client,
ModalBuilder,
type ModalSubmitInteraction,
MessageFlags,
SlashCommandBuilder,
ComponentType,
TextInputBuilder,
TextInputStyle,
type Interaction,
} from "discord.js";
import type { Payload } from "payload";
import type { DiscordPresence } from "@/payload-types";
import type { BotCommand } from "./index";
import { hasPermission } from "@/utils/access-control/hasPermission";
import { findUserByDiscordId } from "@/bot/lib/resolve";
import { ACTIVITY_TYPES } from "@/bot/lib/presence";
import { applyNow } from "@/bot/services/discordPresence";
/**
* `/discord-presence`: staff-only editor for the bot's Discord Rich Presence.
*
* Three actions: `view` (show the current config), `edit` (open a prefilled
* modal), and `clear` (disable + idle). The modal writes the Global and then
* applies the presence immediately via `applyNow`, so the change is live within
* the reply rather than waiting for the next poll tick.
*/
const MODAL_CUSTOM_ID = "ptf-rp-edit";
const EPHEMERAL = { flags: MessageFlags.Ephemeral } as const;
interface ModalField {
customId: string;
placeholder: string;
maxLength: number;
/** Current value rendered into the prefilled input. */
current: (doc: DiscordPresence) => string | number | null | undefined;
}
const MODAL_FIELDS: ModalField[] = [
{ customId: "activityType", placeholder: "playing | streaming | listening | watching | competing | custom", maxLength: 16, current: (d) => d.activityType },
{ customId: "enabled", placeholder: "true or false (default false)", maxLength: 8, current: (d) => (d.enabled ? "true" : "false") },
{ customId: "state", placeholder: "Playing Solo (max 32)", maxLength: 32, current: (d) => d.state },
{ customId: "details", placeholder: "Competitive (max 128)", maxLength: 128, current: (d) => d.details },
{ customId: "startTimestamp", placeholder: "epoch ms (blank = none)", maxLength: 20, current: (d) => d.startTimestamp },
{ customId: "endTimestamp", placeholder: "epoch ms (blank = none)", maxLength: 20, current: (d) => d.endTimestamp },
{ customId: "largeImageKey", placeholder: "asset id or URL (blank = none)", maxLength: 512, current: (d) => d.largeImageKey },
{ customId: "largeImageText", placeholder: "Numbani (max 128)", maxLength: 128, current: (d) => d.largeImageText },
{ customId: "smallImageKey", placeholder: "asset id or URL (blank = none)", maxLength: 512, current: (d) => d.smallImageKey },
{ customId: "smallImageText", placeholder: "Rogue - Level 100 (max 128)", maxLength: 128, current: (d) => d.smallImageText },
{ customId: "partyId", placeholder: "party id (blank = none)", maxLength: 128, current: (d) => d.partyId },
{ customId: "partySize", placeholder: "1-512", maxLength: 5, current: (d) => d.partySize },
{ customId: "partyMax", placeholder: "1-512", maxLength: 5, current: (d) => d.partyMax },
{ customId: "joinSecret", placeholder: "invite secret (blank = none)", maxLength: 128, current: (d) => d.joinSecret },
];
const ROW_SIZE = 5;
const MODAL_ROWS = Array.from(
{ length: Math.ceil(MODAL_FIELDS.length / ROW_SIZE) },
(_v, i) => MODAL_FIELDS.slice(i * ROW_SIZE, (i + 1) * ROW_SIZE),
);
const readGlobal = async (payload: Payload): Promise<DiscordPresence> =>
(await payload.findGlobal({ slug: "discord-presence", overrideAccess: true, depth: 0 })) as unknown as DiscordPresence;
const parseBool = (value: string): boolean => {
const normalized = value.trim().toLowerCase();
return normalized === "true" || normalized === "1" || normalized === "on" || normalized === "yes";
};
const parseNum = (value: string): number | null => {
const trimmed = value.trim();
if (!trimmed) return null;
const parsed = Number(trimmed);
return Number.isFinite(parsed) ? parsed : null;
};
const buildEmbed = (doc: DiscordPresence): EmbedBuilder => {
const embed = new EmbedBuilder()
.setColor(doc.enabled ? 0x57f287 : 0xeee6ff)
.setTitle("Discord Rich Presence")
.addFields(
{ name: "Enabled", value: doc.enabled ? "Yes" : "No (idle)", inline: true },
{ name: "Type", value: doc.activityType ?? "playing", inline: true },
);
const fields: { name: string; value: string | null }[] = [
{ name: "State", value: doc.state ?? null },
{ name: "Details", value: doc.details ?? null },
{ name: "Start (epoch ms)", value: doc.startTimestamp != null ? String(doc.startTimestamp) : null },
{ name: "End (epoch ms)", value: doc.endTimestamp != null ? String(doc.endTimestamp) : null },
{ name: "Large image", value: doc.largeImageKey ?? null },
{ name: "Large image text", value: doc.largeImageText ?? null },
{ name: "Small image", value: doc.smallImageKey ?? null },
{ name: "Small image text", value: doc.smallImageText ?? null },
{ name: "Party id", value: doc.partyId ?? null },
{ name: "Party size", value: doc.partySize != null ? `${doc.partySize}${doc.partyMax != null ? ` / ${doc.partyMax}` : ""}` : null },
{ name: "Join secret", value: doc.joinSecret ?? null },
];
embed.addFields(
...fields.filter((field): field is { name: string; value: string } => field.value !== null),
);
return embed;
};
const buildModal = (doc: DiscordPresence): ModalBuilder => {
const modal = new ModalBuilder().setCustomId(MODAL_CUSTOM_ID).setTitle("Edit Discord Rich Presence");
for (const row of MODAL_ROWS) {
modal.addActionRowComponents(
new ActionRowBuilder<TextInputBuilder>().addComponents(
...row.map((field) =>
new TextInputBuilder()
.setCustomId(field.customId)
.setStyle(TextInputStyle.Short)
.setMaxLength(field.maxLength)
.setRequired(false)
.setPlaceholder(field.placeholder)
.setValue(String(field.current(doc) ?? "")),
),
),
);
}
return modal;
};
const isAuthorized = async (
interaction: Interaction,
payload: Payload,
): Promise<boolean> => {
if (!interaction.inGuild() || !interaction.guild) return false;
const user = await findUserByDiscordId(payload, interaction.user.id);
return hasPermission(payload, user, "discord:rp:update");
};
export const discordPresenceCommand: BotCommand = {
builder: new SlashCommandBuilder()
.setName("discord-presence")
.setDescription("Edit the bot's Discord Rich Presence (staff only)")
.addStringOption((option) =>
option
.setName("action")
.setDescription("View the current presence, open the editor, or clear it")
.setRequired(true)
.addChoices(
{ name: "View", value: "view" },
{ name: "Edit", value: "edit" },
{ name: "Clear", value: "clear" },
),
) as SlashCommandBuilder,
execute: async (interaction, payload) => {
if (!(await isAuthorized(interaction, payload))) {
await interaction.reply({ content: "You don't have permission to edit Discord Rich Presence.", ...EPHEMERAL });
return;
}
const action = interaction.options.getString("action");
if (action === "clear") {
await interaction.deferReply({ ...EPHEMERAL });
try {
await payload.updateGlobal({
slug: "discord-presence",
overrideAccess: true,
data: { enabled: false, ...EMPTY_DATA() },
});
await applyNow(interaction.client as Client, payload);
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
await interaction.editReply(`Failed to clear the Discord Rich Presence: ${message}`);
return;
}
await interaction.editReply("Cleared the Discord Rich Presence. The bot is now idle.");
return;
}
if (action === "view") {
const doc = await readGlobal(payload);
await interaction.reply({ embeds: [buildEmbed(doc)], ...EPHEMERAL });
return;
}
// action === "edit"
const doc = await readGlobal(payload);
await interaction.showModal(buildModal(doc));
},
};
/** Blank out every field when clearing. */
const EMPTY_DATA = (): Partial<DiscordPresence> => ({
state: null,
details: null,
startTimestamp: null,
endTimestamp: null,
largeImageKey: null,
largeImageText: null,
smallImageKey: null,
smallImageText: null,
partyId: null,
partySize: null,
partyMax: null,
joinSecret: null,
});
/**
* Handles the `ptf-rp-edit` modal submit: validates the fields, writes the
* Global, and applies the presence immediately.
*/
export const handlePresenceModal = async (
interaction: ModalSubmitInteraction,
payload: Payload,
): Promise<void> => {
if (!(await isAuthorized(interaction, payload))) {
await interaction.reply({ content: "You don't have permission to edit Discord Rich Presence.", ...EPHEMERAL });
return;
}
const get = (customId: string): string => {
const field = interaction.fields.fields.get(customId);
return field?.type === ComponentType.TextInput ? field.value ?? "" : "";
};
const activityType = get("activityType").trim();
if (!Object.keys(ACTIVITY_TYPES).includes(activityType)) {
await interaction.reply({
content: `Invalid activity type "**${activityType || "(blank)"}**". Use one of: ${Object.keys(ACTIVITY_TYPES).join(", ")}.`,
...EPHEMERAL,
});
return;
}
const data: Record<string, unknown> = {
enabled: parseBool(get("enabled")),
activityType: activityType || "playing",
state: get("state").trim() || null,
details: get("details").trim() || null,
startTimestamp: parseNum(get("startTimestamp")),
endTimestamp: parseNum(get("endTimestamp")),
largeImageKey: get("largeImageKey").trim() || null,
largeImageText: get("largeImageText").trim() || null,
smallImageKey: get("smallImageKey").trim() || null,
smallImageText: get("smallImageText").trim() || null,
partyId: get("partyId").trim() || null,
partySize: parseNum(get("partySize")),
partyMax: parseNum(get("partyMax")),
joinSecret: get("joinSecret").trim() || null,
};
try {
await payload.updateGlobal({ slug: "discord-presence", overrideAccess: true, data });
await applyNow(interaction.client as Client, payload);
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
await interaction.reply({
content: `Failed to update the Discord Rich Presence: ${message}`,
...EPHEMERAL,
});
return;
}
await interaction.reply({ content: "Updated the Discord Rich Presence.", ...EPHEMERAL });
};

View file

@ -7,6 +7,7 @@ import { announceCommand } from "./announce";
import { changelogCommand } from "./changelog";
import { remindEvaluationsCommand } from "./remindEvaluations";
import { rollCallCommand } from "./rollcall";
import { discordPresenceCommand } from "./discordPresence";
export interface BotCommand {
builder: SlashCommandBuilder;
@ -27,4 +28,5 @@ export const commands: BotCommand[] = [
changelogCommand,
remindEvaluationsCommand,
rollCallCommand,
discordPresenceCommand,
];

View file

@ -16,6 +16,7 @@ export interface BotConfig {
imminentReminderPollMs: number;
sideOpsNoticePollMs: number;
achievementPollMs: number;
presencePollMs: number;
}
const required = (name: string): string => {
@ -64,4 +65,5 @@ export const botConfig: BotConfig = {
imminentReminderPollMs: pollMs("DISCORD_IMMINENT_POLL_MS", 60_000),
sideOpsNoticePollMs: pollMs("DISCORD_SIDE_OPS_POLL_MS", 1_800_000),
achievementPollMs: pollMs("DISCORD_ACHIEVEMENT_POLL_MS", 60_000),
presencePollMs: pollMs("DISCORD_PRESENCE_POLL_MS", 30_000),
};

View file

@ -4,6 +4,7 @@ import config from "@payload-config";
import { botConfig } from "./config";
import { commands } from "./commands";
import { handleAnnounceModal } from "./commands/announce";
import { handlePresenceModal } from "./commands/discordPresence";
import { services } from "./services";
import { handleButtonInteraction } from "./events/interactionCreate";
import { handleTransferInteraction } from "./events/transferInteractions";
@ -85,6 +86,10 @@ const main = async () => {
await handleAnnounceModal(interaction, payload);
return;
}
if (interaction.isModalSubmit() && interaction.customId.startsWith("ptf-rp-edit")) {
await handlePresenceModal(interaction, payload);
return;
}
if (!interaction.isChatInputCommand()) {
return;
}

136
src/bot/lib/presence.ts Normal file
View file

@ -0,0 +1,136 @@
import { ActivityType, type Client, type PresenceData } from "discord.js";
import type { Payload } from "payload";
import type { DiscordPresence } from "@/payload-types";
/**
* Maps the Global's `activityType` string to a discord.js `ActivityType`.
* Kept explicit so an unknown stored value falls back to `playing`.
*/
export const ACTIVITY_TYPES: Record<string, ActivityType> = {
playing: ActivityType.Playing,
streaming: ActivityType.Streaming,
listening: ActivityType.Listening,
watching: ActivityType.Watching,
competing: ActivityType.Competing,
custom: ActivityType.Custom,
};
/**
* Rich Presence activity shape. The installed discord.js typings expose only a
* trimmed `ActivitiesOptions` (name/state/url/type), so we model the full
* runtime shape here and cast at the `setPresence` boundary.
*/
interface PresenceActivity {
name?: string;
details?: string;
type?: ActivityType;
start?: number;
end?: number;
images?: Record<string, string>;
party?: { id?: string; size: [number, number] };
secret?: string;
}
const isBlank = (value: unknown): boolean =>
value === null || value === undefined || value === "";
/**
* True when the global carries nothing to show: disabled, or enabled but with
* every field blank. The bot then goes idle with no activity.
*/
const isEmptyPresence = (doc: DiscordPresence): boolean => {
if (!doc.enabled) return true;
return (
isBlank(doc.state) &&
isBlank(doc.details) &&
isBlank(doc.startTimestamp) &&
isBlank(doc.endTimestamp) &&
isBlank(doc.largeImageKey) &&
isBlank(doc.largeImageText) &&
isBlank(doc.smallImageKey) &&
isBlank(doc.smallImageText) &&
isBlank(doc.partyId) &&
isBlank(doc.partySize) &&
isBlank(doc.partyMax) &&
isBlank(doc.joinSecret)
);
};
/**
* Maps the Global's fields to a discord.js activity.
*
* `state` becomes the bold activity title (Discord's `name`), `details` the
* details line, matching the Rich Presence JSON the team edits. Timestamps are
* epoch milliseconds; `partySize`/`partyMax` become the `[current, max]` tuple.
*/
const str = (value: unknown): string | undefined =>
value == null || value === "" ? undefined : String(value);
const buildActivity = (doc: DiscordPresence): PresenceActivity => {
const activity = {
name: str(doc.state),
details: str(doc.details),
type: ACTIVITY_TYPES[doc.activityType] ?? ActivityType.Playing,
} as PresenceActivity;
if (doc.startTimestamp) activity.start = doc.startTimestamp;
if (doc.endTimestamp) activity.end = doc.endTimestamp;
const images: Record<string, string> = {};
const largeImage = str(doc.largeImageKey);
if (largeImage) images.largeImage = largeImage;
const largeImageText = str(doc.largeImageText);
if (largeImageText) images.largeImageText = largeImageText;
const smallImage = str(doc.smallImageKey);
if (smallImage) images.smallImage = smallImage;
const smallImageText = str(doc.smallImageText);
if (smallImageText) images.smallImageText = smallImageText;
if (Object.keys(images).length > 0) activity.images = images;
const partyId = str(doc.partyId);
const partySize = doc.partySize;
const partyMax = doc.partyMax;
if (partyId !== undefined || partySize !== undefined || partyMax !== undefined) {
const current = Number(partySize) || 1;
const max = Number(partyMax) || current;
activity.party = {
id: partyId,
size: [current, max],
};
}
const joinSecret = str(doc.joinSecret);
if (joinSecret) activity.secret = joinSecret;
return activity;
};
/**
* Reconcile the bot's Discord presence with the `discord-presence` Global.
*
* Reads the global with overrideAccess (trusted internal process), maps its
* fields to a discord.js activity, and applies it. When the global is disabled
* or blank the bot goes idle with no activity.
*/
export const applyPresence = async (client: Client, payload: Payload): Promise<void> => {
const user = client.user;
if (!user) return;
const doc = (await payload.findGlobal({
slug: "discord-presence",
overrideAccess: true,
depth: 0,
})) as unknown as DiscordPresence;
if (isEmptyPresence(doc)) {
await user.setPresence({ status: "idle", activities: [] });
return;
}
await user.setPresence({
status: "online",
// Cast: discord.js typings trim ActivitiesOptions to name/state/url/type,
// but the runtime accepts the full Rich Presence shape we build above.
activities: [buildActivity(doc) as unknown as NonNullable<PresenceData["activities"]>[number]],
});
};

View file

@ -0,0 +1,94 @@
import { type Client } from "discord.js";
import type { Payload } from "payload";
import type { DiscordPresence } from "@/payload-types";
import { botConfig } from "@/bot/config";
import { applyPresence } from "@/bot/lib/presence";
/**
* Discord Rich Presence reconcile loop.
*
* Polls the `discord-presence` Global every `DISCORD_PRESENCE_POLL_MS` (default
* 30s) and applies it to the bot's presence only when the Global changed since
* the last apply. The last-applied signature is held in memory, so a manual edit
* via the `/discord-presence` command (which applies immediately) is not
* re-applied by the loop. This is what makes CMS edits propagate to Discord
* without a bot restart.
*/
let reconcileRunning = false;
let lastSignature: string | null = null;
const errorMessage = (error: unknown): string =>
error instanceof Error ? error.message : "Unknown error";
/** Canonical snapshot of the fields that affect the applied presence. */
const signature = (doc: DiscordPresence): string =>
JSON.stringify([
doc.enabled,
doc.activityType,
doc.state,
doc.details,
doc.startTimestamp,
doc.endTimestamp,
doc.largeImageKey,
doc.largeImageText,
doc.smallImageKey,
doc.smallImageText,
doc.partyId,
doc.partySize,
doc.partyMax,
doc.joinSecret,
]);
/**
* Read the Global and apply it when it differs from what is currently live.
* Returns true when the presence was (re)applied.
*/
export const reconcile = async (client: Client, payload: Payload): Promise<boolean> => {
if (reconcileRunning) return false;
reconcileRunning = true;
try {
const doc = (await payload.findGlobal({
slug: "discord-presence",
overrideAccess: true,
depth: 0,
})) as unknown as DiscordPresence;
const next = signature(doc);
if (next === lastSignature) return false;
lastSignature = next;
await applyPresence(client, payload);
return true;
} catch (error) {
payload.logger.error(`[Bot] Discord presence reconcile failed: ${errorMessage(error)}`);
return false;
} finally {
reconcileRunning = false;
}
};
/**
* Force an immediate apply (used by the `/discord-presence` command after it
* writes the Global), and refresh the cached signature so the poll loop does
* not re-apply the same value.
*/
export const applyNow = async (client: Client, payload: Payload): Promise<void> => {
const doc = (await payload.findGlobal({
slug: "discord-presence",
overrideAccess: true,
depth: 0,
})) as unknown as DiscordPresence;
// Apply first; only cache the signature on success so a failed apply stays
// eligible for the poll loop to retry.
await applyPresence(client, payload);
lastSignature = signature(doc);
};
export const start = (client: Client, payload: Payload): void => {
payload.logger.info("[Bot] Discord presence service started");
void reconcile(client, payload);
setInterval(() => {
void reconcile(client, payload);
}, botConfig.presencePollMs);
};

View file

@ -8,6 +8,7 @@ import { start as startReadyReminders } from "./readyReminders";
import { start as startImminentReminders } from "./imminentReminders";
import { start as startFridayOpsNotice } from "./fridayOpsNotice";
import { start as startAchievementAnnouncements } from "./achievementAnnouncements";
import { start as startDiscordPresence } from "./discordPresence";
export type ServiceStarter = (client: Client, payload: Payload) => Promise<void> | void;
@ -20,4 +21,5 @@ export const services: ServiceStarter[] = [
startImminentReminders,
startFridayOpsNotice,
startAchievementAnnouncements,
startDiscordPresence,
];

View file

@ -0,0 +1,153 @@
import { GlobalConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
/**
* Discord Rich Presence configuration.
*
* Single source of truth for the bot's Discord activity. Two independent
* writers update it: the `/discord-presence` staff command and this CMS page.
* The bot polls this global and reconciles Discord's live presence with it
* (see `src/bot/services/discordPresence.ts`), so a change from either writer
* takes effect within one poll tick.
*
* Field names mirror Discord's Rich Presence JSON (the Discord Developer
* Portal shape shown to the team). Timestamps are epoch **milliseconds**.
* Image keys are freeform: an application asset id or a `data:image/...`
* base64 URI. Discord enforces the character limits documented per field.
*/
export const DiscordPresence: GlobalConfig = {
slug: "discord-presence",
label: "Discord Rich Presence",
access: {
read: requirePermission("discord:rp:read"),
update: requirePermission("discord:rp:update"),
},
fields: [
{
name: "enabled",
type: "checkbox",
defaultValue: false,
admin: {
description:
"Master switch. When off (or when no fields are set) the bot shows idle with no activity.",
},
},
{
name: "activityType",
type: "select",
required: true,
defaultValue: "playing",
options: [
{ label: "Playing", value: "playing" },
{ label: "Streaming", value: "streaming" },
{ label: "Listening", value: "listening" },
{ label: "Watching", value: "watching" },
{ label: "Competing", value: "competing" },
{ label: "Custom", value: "custom" },
],
admin: {
description:
"The activity line Discord shows. Maps to the activity 'type' (Playing, Streaming, etc.).",
},
},
{
name: "state",
type: "text",
maxLength: 32,
admin: {
description:
"Main line (max 32). Shown as the bold title, e.g. 'Playing Solo'.",
},
},
{
name: "details",
type: "text",
maxLength: 128,
admin: {
description: "Details line (max 128), e.g. 'Competitive'.",
},
},
{
name: "startTimestamp",
type: "number",
min: 1,
admin: {
description: "Activity start time, epoch milliseconds. Leave blank for none.",
},
},
{
name: "endTimestamp",
type: "number",
min: 1,
admin: {
description: "Activity end time, epoch milliseconds. Leave blank for none.",
},
},
{
name: "largeImageKey",
type: "text",
maxLength: 512,
admin: {
description: "Large asset id or URL (optional).",
},
},
{
name: "largeImageText",
type: "text",
maxLength: 128,
admin: {
description: "Hover text for the large image (max 128).",
},
},
{
name: "smallImageKey",
type: "text",
maxLength: 512,
admin: {
description: "Small asset id or URL (optional).",
},
},
{
name: "smallImageText",
type: "text",
maxLength: 128,
admin: {
description: "Hover text for the small image (max 128).",
},
},
{
name: "partyId",
type: "text",
maxLength: 128,
admin: {
description: "Party id (optional, max 128).",
},
},
{
name: "partySize",
type: "number",
min: 1,
max: 512,
admin: {
description: "Current party size (1-512).",
},
},
{
name: "partyMax",
type: "number",
min: 1,
max: 512,
admin: {
description: "Maximum party size (1-512).",
},
},
{
name: "joinSecret",
type: "text",
maxLength: 128,
admin: {
description: "Join secret / invite link (max 128).",
},
},
],
};

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -127,6 +127,7 @@ import * as migration_20261011_221250_add_minigame_estimated_release_date from '
import * as migration_20261012_014741_add_call_for_fire_versus from './20261012_014741_add_call_for_fire_versus';
import * as migration_20261012_015000_seed_call_for_fire_versus_registry from './20261012_015000_seed_call_for_fire_versus_registry';
import * as migration_20261012_030000_update_call_for_fire_versus_wording from './20261012_030000_update_call_for_fire_versus_wording';
import * as migration_20261012_134242_add_discord_presence_global from './20261012_134242_add_discord_presence_global';
export const migrations = [
{
@ -762,16 +763,21 @@ export const migrations = [
{
up: migration_20261012_014741_add_call_for_fire_versus.up,
down: migration_20261012_014741_add_call_for_fire_versus.down,
name: '20261012_014741_add_call_for_fire_versus'
name: '20261012_014741_add_call_for_fire_versus',
},
{
up: migration_20261012_015000_seed_call_for_fire_versus_registry.up,
down: migration_20261012_015000_seed_call_for_fire_versus_registry.down,
name: '20261012_015000_seed_call_for_fire_versus_registry'
name: '20261012_015000_seed_call_for_fire_versus_registry',
},
{
up: migration_20261012_030000_update_call_for_fire_versus_wording.up,
down: migration_20261012_030000_update_call_for_fire_versus_wording.down,
name: '20261012_030000_update_call_for_fire_versus_wording'
name: '20261012_030000_update_call_for_fire_versus_wording',
},
{
up: migration_20261012_134242_add_discord_presence_global.up,
down: migration_20261012_134242_add_discord_presence_global.down,
name: '20261012_134242_add_discord_presence_global'
},
];

View file

@ -277,11 +277,13 @@ export interface Config {
'game-rules': GameRule;
shims: Shim;
'minigame-rules': MinigameRule;
'discord-presence': DiscordPresence;
};
globalsSelect: {
'game-rules': GameRulesSelect<false> | GameRulesSelect<true>;
shims: ShimsSelect<false> | ShimsSelect<true>;
'minigame-rules': MinigameRulesSelect<false> | MinigameRulesSelect<true>;
'discord-presence': DiscordPresenceSelect<false> | DiscordPresenceSelect<true>;
};
locale: null;
widgets: {
@ -940,6 +942,8 @@ export interface Role {
| 'tickets:staff'
| 'discord:staff'
| 'discord:announce'
| 'discord:rp:read'
| 'discord:rp:update'
| 'custom-minefields:update'
| 'custom-minefields:delete'
| 'custom-minefield-scores:delete'
@ -3049,6 +3053,8 @@ export interface GameEventLog {
| 'tickets:staff'
| 'discord:staff'
| 'discord:announce'
| 'discord:rp:read'
| 'discord:rp:update'
| 'custom-minefields:update'
| 'custom-minefields:delete'
| 'custom-minefield-scores:delete'
@ -11991,6 +11997,71 @@ export interface MinigameRule {
updatedAt?: string | null;
createdAt?: string | null;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "discord-presence".
*/
export interface DiscordPresence {
id: number;
/**
* Master switch. When off (or when no fields are set) the bot shows idle with no activity.
*/
enabled?: boolean | null;
/**
* The activity line Discord shows. Maps to the activity 'type' (Playing, Streaming, etc.).
*/
activityType: 'playing' | 'streaming' | 'listening' | 'watching' | 'competing' | 'custom';
/**
* Main line (max 32). Shown as the bold title, e.g. 'Playing Solo'.
*/
state?: string | null;
/**
* Details line (max 128), e.g. 'Competitive'.
*/
details?: string | null;
/**
* Activity start time, epoch milliseconds. Leave blank for none.
*/
startTimestamp?: number | null;
/**
* Activity end time, epoch milliseconds. Leave blank for none.
*/
endTimestamp?: number | null;
/**
* Large asset id or URL (optional).
*/
largeImageKey?: string | null;
/**
* Hover text for the large image (max 128).
*/
largeImageText?: string | null;
/**
* Small asset id or URL (optional).
*/
smallImageKey?: string | null;
/**
* Hover text for the small image (max 128).
*/
smallImageText?: string | null;
/**
* Party id (optional, max 128).
*/
partyId?: string | null;
/**
* Current party size (1-512).
*/
partySize?: number | null;
/**
* Maximum party size (1-512).
*/
partyMax?: number | null;
/**
* Join secret / invite link (max 128).
*/
joinSecret?: string | null;
updatedAt?: string | null;
createdAt?: string | null;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "game-rules_select".
@ -12076,6 +12147,29 @@ export interface MinigameRulesSelect<T extends boolean = true> {
createdAt?: T;
globalType?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "discord-presence_select".
*/
export interface DiscordPresenceSelect<T extends boolean = true> {
enabled?: T;
activityType?: T;
state?: T;
details?: T;
startTimestamp?: T;
endTimestamp?: T;
largeImageKey?: T;
largeImageText?: T;
smallImageKey?: T;
smallImageText?: T;
partyId?: T;
partySize?: T;
partyMax?: T;
joinSecret?: T;
updatedAt?: T;
createdAt?: T;
globalType?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "collections_widget".

View file

@ -48,6 +48,7 @@ import { AssignmentTransfers } from "@/collections/users/AssignmentTransfers";
import { Technologies } from "@/collections/intelligence/Technologies";
import { TechCategories } from "@/collections/intelligence/TechCategories";
import { GameRules } from "@/collections/game/GameRules";
import { DiscordPresence } from "@/collections/discord/DiscordPresence";
import { GameStructures } from "@/collections/game/GameStructures";
import { GameHardResources } from "@/collections/game/GameHardResources";
import { GameEventLogs } from "@/collections/game/GameEventLogs";
@ -461,7 +462,7 @@ export default buildConfig({
},
},
},
globals: [GameRules, Shims, MinigameRules],
globals: [GameRules, Shims, MinigameRules, DiscordPresence],
collections: scopedCollections,
editor: lexicalEditor({
features: ({ defaultFeatures }) => {

View file

@ -767,6 +767,8 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
permissions: [
{ value: "discord:staff", label: "Bot Staff (isStaff)" },
{ value: "discord:announce", label: "Post Announcements (/announce)" },
{ value: "discord:rp:read", label: "Read Discord Rich Presence (/discord-presence view)" },
{ value: "discord:rp:update", label: "Edit Discord Rich Presence (/discord-presence edit)" },
],
},
{
@ -1158,6 +1160,8 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
"tickets:staff",
"discord:staff",
"discord:announce",
"discord:rp:read",
"discord:rp:update",
"custom-minefields:update",
"custom-minefields:delete",
"custom-minefield-scores:delete",