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.
263 lines
10 KiB
TypeScript
263 lines
10 KiB
TypeScript
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 });
|
|
};
|