import { ChannelSelectMenuBuilder, ChannelType, ComponentType, EmbedBuilder, LabelBuilder, MessageFlags, ModalBuilder, SlashCommandBuilder, TextInputBuilder, TextInputStyle, type InteractionReplyOptions, type ModalSubmitInteraction, type TextBasedChannelFields, } from "discord.js"; import type { Payload } from "payload"; import type { BotCommand } from "./index"; import { botConfig } from "@/bot/config"; import { isStaff } from "@/bot/lib/roles"; const ANNOUNCE_COLOR = 0xf59e0b; const ANNOUNCE_MODAL_PREFIX = "ptf-announce:"; const TITLE_INPUT_ID = "ptf-announce-title"; const BODY_INPUT_ID = "ptf-announce-body"; const CHANNEL_INPUT_ID = "ptf-announce-channel"; /** Modal paragraph inputs cap at 4000 chars; the embed description limit is 4096. */ const MAX_BODY_LENGTH = 4000; const ephemeral = (content: string): InteractionReplyOptions => ({ content, flags: MessageFlags.Ephemeral, }); const modalText = (fields: ModalSubmitInteraction["fields"], customId: string): string => { const field = fields.fields.get(customId); return field?.type === ComponentType.TextInput ? field.value : ""; }; const modalChannelId = (fields: ModalSubmitInteraction["fields"]): string | null => { const field = fields.fields.get(CHANNEL_INPUT_ID); if (field?.type !== ComponentType.ChannelSelect) return null; return field.channels?.first()?.id ?? null; }; const postAnnouncement = async ( channel: TextBasedChannelFields, title: string, message: string, mentionRoleId?: string | null, ): Promise => { // The role mention has to live in `content`, not the embed description: // Discord only pings on a mention in the message content, never inside an embed. await channel.send({ content: mentionRoleId ? `<@&${mentionRoleId}>` : undefined, embeds: [ new EmbedBuilder() .setTitle(title || "Announcement") .setDescription(message) .setColor(ANNOUNCE_COLOR), ], }); }; export const announceCommand: BotCommand = { builder: new SlashCommandBuilder() .setName("announce") .setDescription("Post an announcement to a channel") .addStringOption((option) => option .setName("message") .setDescription("Announcement text, or leave blank to compose in a dialog") .setRequired(false), ) .addChannelOption((option) => option.setName("channel").setDescription("Channel to post to"), ) as SlashCommandBuilder, execute: async (interaction, payload) => { if (!interaction.inGuild() || !interaction.guild) { await interaction.reply(ephemeral("This command only works in a server.")); return; } const member = await interaction.guild.members.fetch(interaction.user.id); if (!(await isStaff(member, payload))) { await interaction.reply(ephemeral("You don't have permission to announce.")); return; } const message = (interaction.options.getString("message") ?? "").trim(); const option = interaction.options.getChannel("channel"); const channelId = option?.id ?? botConfig.announceChannelId; if (!channelId) { await interaction.reply( ephemeral( "No announce channel is configured (set DISCORD_ANNOUNCE_CHANNEL_ID) and no channel was given.", ), ); return; } if (!message) { // customId carries the default channel as the fallback: modal submits // don't carry the command's options. const modal = new ModalBuilder() .setCustomId(`${ANNOUNCE_MODAL_PREFIX}${channelId}`) .setTitle("Post an announcement"); modal.addLabelComponents( new LabelBuilder().setLabel("Title (optional)").setTextInputComponent( new TextInputBuilder() .setCustomId(TITLE_INPUT_ID) .setStyle(TextInputStyle.Short) .setMaxLength(256) .setRequired(false), ), new LabelBuilder().setLabel("Announcement text").setTextInputComponent( new TextInputBuilder() .setCustomId(BODY_INPUT_ID) .setStyle(TextInputStyle.Paragraph) .setMaxLength(MAX_BODY_LENGTH) .setRequired(true) .setPlaceholder( "Paste your announcement. Markdown (headings, lists, bold, code) is supported.", ), ), new LabelBuilder() .setLabel("Channel (optional)") .setDescription("Defaults to the configured app updates channel.") .setChannelSelectMenuComponent( new ChannelSelectMenuBuilder() .setCustomId(CHANNEL_INPUT_ID) .addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement) .setDefaultChannels(channelId) .setRequired(false), ), ); await interaction.showModal(modal); return; } const optionChannel = option && "send" in option ? (option as TextBasedChannelFields) : null; const channel = optionChannel ?? (await interaction.guild.channels.fetch(channelId)); if (!channel || !("send" in channel)) { await interaction.reply(ephemeral("That channel isn't a text channel.")); return; } await postAnnouncement(channel as TextBasedChannelFields, "Announcement", message); const name = (channel as unknown as { name?: string | null }).name ?? channelId; await interaction.reply(ephemeral(`Announcement posted to #${name}.`)); }, }; export const handleAnnounceModal = async ( interaction: ModalSubmitInteraction, payload: Payload, ): Promise => { try { if (!interaction.inGuild() || !interaction.guild) { await interaction.reply(ephemeral("This command only works in a server.")); return; } const member = await interaction.guild.members.fetch(interaction.user.id); if (!(await isStaff(member, payload))) { await interaction.reply(ephemeral("You don't have permission to announce.")); return; } // The modal custom id is "ptf-announce:", written when the modal // was opened. A channel picked in the modal overrides it. const customChannelId = interaction.customId.slice(ANNOUNCE_MODAL_PREFIX.length); const resolvedId = modalChannelId(interaction.fields) ?? (customChannelId || botConfig.announceChannelId); if (!resolvedId) { await interaction.reply(ephemeral("No announce channel is configured.")); return; } const channel = await interaction.guild.channels.fetch(resolvedId); if (!channel || !("send" in channel)) { await interaction.reply(ephemeral("That channel isn't a text channel.")); return; } const title = modalText(interaction.fields, TITLE_INPUT_ID).trim(); const message = modalText(interaction.fields, BODY_INPUT_ID).trim(); if (!message) { await interaction.reply(ephemeral("The announcement text was empty.")); return; } await postAnnouncement( channel as TextBasedChannelFields, title, message, botConfig.announceMentionRoleId, ); const name = (channel as unknown as { name?: string | null }).name ?? resolvedId; await interaction.reply(ephemeral(`Announcement posted to #${name}.`)); } catch (error) { const message = error instanceof Error ? error.message : "Unknown error"; payload.logger.error(`[Bot] Announce modal failed: ${message}`); if (!interaction.replied && !interaction.deferred) { await interaction.reply(ephemeral("Something went wrong while posting the announcement.")); } } };