import { ActionRowBuilder, ButtonBuilder, ButtonStyle, ComponentType, MessageFlags, SlashCommandBuilder, type ChatInputCommandInteraction, type Client, } from "discord.js"; import type { Payload } from "payload"; import type { BotCommand } from "./index"; import { botConfig } from "@/bot/config"; import { isStaff } from "@/bot/lib/roles"; import { debugActions, findDebugAction, type DebugAction, type DebugMode, type OutboundMessage, } from "@/bot/lib/debugActions"; const CONFIRM_TIMEOUT_MS = 30_000; const actionChoices = debugActions.map((action) => ({ name: action.name, value: action.name })); const formatError = (error: unknown): string => error instanceof Error ? error.message : "Unknown error"; const stripComponents = (message: OutboundMessage): OutboundMessage => ({ content: message.content, embeds: message.embeds, files: message.files, }); /** * Asks for a button press before a live change. Returns true only when the * caller clicks Confirm within the timeout; anything else cancels. */ const confirmLive = async ( interaction: ChatInputCommandInteraction, prompt: string, ): Promise => { const confirm = new ButtonBuilder() .setCustomId(`ptf-debug-confirm:${interaction.id}`) .setStyle(ButtonStyle.Danger) .setLabel("Confirm"); const cancel = new ButtonBuilder() .setCustomId(`ptf-debug-cancel:${interaction.id}`) .setStyle(ButtonStyle.Secondary) .setLabel("Cancel"); const row = new ActionRowBuilder().addComponents(confirm, cancel); const reply = await interaction.editReply({ content: prompt, components: [row] }); try { const press = await reply.awaitMessageComponent({ componentType: ComponentType.Button, filter: (press) => press.user.id === interaction.user.id, time: CONFIRM_TIMEOUT_MS, }); await press.update({ content: "Working...", components: [] }); return press.customId === `ptf-debug-confirm:${interaction.id}`; } catch { await interaction.editReply({ content: "Timed out. Nothing was changed.", components: [] }); return false; } }; const runPreview = async ( interaction: ChatInputCommandInteraction, payload: Payload, client: Client, action: DebugAction, target: string | undefined, ): Promise => { const message = stripComponents(await action.build(client, payload, target)); const header = `Preview of \`${action.name}\`. Nothing was posted or stored. Buttons are omitted in debug output.`; await interaction.editReply({ content: message.content ? `${header}\n\n${message.content}` : header, embeds: message.embeds, files: message.files, }); }; const runSandbox = async ( interaction: ChatInputCommandInteraction, payload: Payload, client: Client, action: DebugAction, target: string | undefined, ): Promise => { const debugChannelId = botConfig.debugChannelId; if (!debugChannelId) { await interaction.editReply( "Sandbox is disabled because DISCORD_DEBUG_CHANNEL_ID is not set. Use preview or live.", ); return; } const message = stripComponents(await action.build(client, payload, target)); const channel = await client.channels.fetch(debugChannelId); if (!channel || !("send" in channel)) { throw new Error(`Debug channel ${debugChannelId} is not a text channel.`); } await ( channel as unknown as { send(options: OutboundMessage & { allowedMentions: { parse: never[] } }): Promise; } ).send({ content: message.content, embeds: message.embeds, files: message.files, allowedMentions: { parse: [] }, }); await interaction.editReply( `Sent a sandbox copy of \`${action.name}\` to <#${debugChannelId}>. Nothing stored changed.`, ); }; const runLive = async ( interaction: ChatInputCommandInteraction, payload: Payload, client: Client, action: DebugAction, target: string | undefined, method: "edit" | "repost" | undefined, ): Promise => { if (!action.live) { await interaction.editReply( `\`${action.name}\` has no live mode. Use preview or sandbox instead.`, ); return; } const confirmed = await confirmLive( interaction, `This posts \`${action.name}\` to the **real** channel and may update stored state. Confirm?`, ); if (!confirmed) { await interaction.editReply({ content: `Cancelled. Nothing was posted for \`${action.name}\`.`, components: [], }); return; } const result = await action.live(client, payload, target, { method }); await interaction.editReply({ content: result, components: [] }); }; const runDelete = async ( interaction: ChatInputCommandInteraction, payload: Payload, client: Client, action: DebugAction, target: string | undefined, ): Promise => { if (!action.remove) { await interaction.editReply(`\`${action.name}\` has no tracked message to delete.`); return; } const confirmed = await confirmLive( interaction, `This **deletes** the tracked \`${action.name}\` message from the real channel. Confirm?`, ); if (!confirmed) { await interaction.editReply({ content: "Cancelled. Nothing was deleted.", components: [] }); return; } const result = await action.remove(client, payload, target); await interaction.editReply({ content: result, components: [] }); }; const runList = (): string => debugActions .map((action) => { const modes = ["preview", action.live ? "live" : null, "sandbox"] .filter(Boolean) .join(", "); return `**${action.name}**: ${action.description}\n target: ${action.targetHint}\n modes: ${modes}`; }) .join("\n\n"); const requireAction = (name: string): DebugAction => { const action = findDebugAction(name); if (!action) throw new Error(`Unknown debug action "${name}".`); return action; }; export const debugCommand: BotCommand = { builder: new SlashCommandBuilder() .setName("debug") .setDescription("Preview, sandbox, or live-repost bot messages (staff only)") .addSubcommand((sub) => sub.setName("list").setDescription("List the debuggable bot actions"), ) .addSubcommand((sub) => sub .setName("run") .setDescription("Render or send a bot message for a target") .addStringOption((option) => option .setName("action") .setDescription("Which bot message to run") .setRequired(true) .addChoices(...actionChoices), ) .addStringOption((option) => option .setName("target") .setDescription("Mission ID/name/code name, or the record ID the action expects"), ) .addStringOption((option) => option .setName("mode") .setDescription("preview (default, ephemeral), sandbox (debug channel), or live (real)") .addChoices( { name: "preview", value: "preview" }, { name: "sandbox", value: "sandbox" }, { name: "live", value: "live" }, ), ) .addStringOption((option) => option .setName("method") .setDescription("Live roll-call only: edit the existing message, or repost a fresh one") .addChoices( { name: "edit", value: "edit" }, { name: "repost", value: "repost" }, ), ), ) .addSubcommand((sub) => sub .setName("inspect") .setDescription("Show the stored bot-side state for a target") .addStringOption((option) => option .setName("action") .setDescription("Which bot message") .setRequired(true) .addChoices(...actionChoices), ) .addStringOption((option) => option.setName("target").setDescription("Target")), ) .addSubcommand((sub) => sub .setName("delete") .setDescription("Delete a tracked bot message (live, with confirmation)") .addStringOption((option) => option .setName("action") .setDescription("Which bot message") .setRequired(true) .addChoices(...actionChoices), ) .addStringOption((option) => option.setName("target").setDescription("Target")), ) as SlashCommandBuilder, execute: async (interaction, payload) => { if (!interaction.inGuild() || !interaction.guild) { await interaction.reply({ content: "This command only works in a server.", flags: MessageFlags.Ephemeral, }); return; } const member = await interaction.guild.members.fetch(interaction.user.id); if (!(await isStaff(member, payload))) { await interaction.reply({ content: "You don't have permission to use debug.", flags: MessageFlags.Ephemeral, }); return; } const subcommand = interaction.options.getSubcommand(); if (subcommand === "list") { await interaction.reply({ content: runList(), flags: MessageFlags.Ephemeral }); return; } await interaction.deferReply({ flags: MessageFlags.Ephemeral }); const client = interaction.client as Client; const actionName = interaction.options.getString("action", true); const target = interaction.options.getString("target")?.trim() || undefined; try { const action = requireAction(actionName); if (subcommand === "run") { const mode = (interaction.options.getString("mode") ?? "preview") as DebugMode; const method = interaction.options.getString("method") as "edit" | "repost" | null; if (mode === "preview") await runPreview(interaction, payload, client, action, target); else if (mode === "sandbox") await runSandbox(interaction, payload, client, action, target); else await runLive(interaction, payload, client, action, target, method ?? undefined); return; } if (subcommand === "inspect") { if (!action.inspect) { await interaction.editReply(`\`${action.name}\` has no stored state to inspect.`); return; } const state = await action.inspect(payload, target); await interaction.editReply( "```json\n" + JSON.stringify(state, null, 2) + "\n```", ); return; } if (subcommand === "delete") { await runDelete(interaction, payload, client, action, target); } } catch (error) { await interaction.editReply(`Debug failed: ${formatError(error)}`); } }, };