feat(bot): add edit modal to /changelog for last-minute copy tweaks
/changelog edit=true resolves the target entry (latest or one version, ranges rejected) and opens a modal prefilled with its raw markdown instead of posting. Submit re-checks staff, renders the edited text through the existing splitForDiscord pipeline and posts the amber embed(s). One-shot by design: CHANGELOG.md is never written back. Entries over the 4000-char modal cap refuse edit mode. Modal path skips deferReply (first-response rule, same as /announce); submits route through bot/index.ts on the ptf-changelog-edit: prefix.
This commit is contained in:
parent
000036beda
commit
3eb8ada8f8
4 changed files with 211 additions and 4 deletions
|
|
@ -23,7 +23,7 @@ bot/
|
|||
signup.ts # /signup (DM-only, creates Payload user with temp password)
|
||||
link.ts # /link (global, links discordId to existing user)
|
||||
announce.ts # /announce (guild-only, staff only; message omitted = compose modal with channel picker, handler in this file)
|
||||
changelog.ts # /changelog (guild-only, staff only; posts a CHANGELOG.md entry to #releases, native markdown, splits long entries)
|
||||
changelog.ts # /changelog (guild-only, staff only; posts a CHANGELOG.md entry to #releases, native markdown, splits long entries; edit=true opens a prefilled modal to tweak the copy before posting)
|
||||
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)
|
||||
|
|
@ -63,7 +63,7 @@ bot/
|
|||
|
||||
## Feature flow: changelogs
|
||||
|
||||
`/changelog` (guild-only, staff only) posts a `CHANGELOG.md` release entry to the releases channel (`DISCORD_CHANGELOG_CHANNEL_ID`, falling back to `DISCORD_ANNOUNCE_CHANNEL_ID`). `/changelog` targets the newest entry; `/changelog v0.4.0` targets a specific version (for catching up on missed posts); `/changelog v0.3.0..v0.5.0` targets a range (inclusive slice, output oldest-to-newest). Either range end is open (`v0.3.0..` to the latest, `..v0.5.0` from the oldest) and a reversed range is normalized. Rendering lives in `bot/lib/changelogRender.ts` (pure, no Discord/Payload deps): entries are split on `# vX.Y.Z` headers, `### ` sections become Discord markdown headings (`### `, the deepest level Discord renders), bullets become `•`, and entries over Discord's 4096-char limit are split across messages at section boundaries. The command reads `CHANGELOG.md` from the repo root relative to the file (works from the deploy server) and posts each version as its own amber embed, the first message of each version carrying the `Changelog vX.Y.Z` title and multi-message versions adding a page footer. Ranges spanning more than `WIDE_RANGE_THRESHOLD` (10) versions post an ephemeral warning but proceed. Idempotency ("don't repost") is intentionally out of scope for the manual command; the same rendering can be reused by a future automatic trigger.
|
||||
`/changelog` (guild-only, staff only) posts a `CHANGELOG.md` release entry to the releases channel (`DISCORD_CHANGELOG_CHANNEL_ID`, falling back to `DISCORD_ANNOUNCE_CHANNEL_ID`). `/changelog` targets the newest entry; `/changelog v0.4.0` targets a specific version (for catching up on missed posts); `/changelog v0.3.0..v0.5.0` targets a range (inclusive slice, output oldest-to-newest). Either range end is open (`v0.3.0..` to the latest, `..v0.5.0` from the oldest) and a reversed range is normalized. **Edit mode** (`edit=true`): instead of posting, opens a modal prefilled with the target entry's raw markdown so staff can make last-minute copy tweaks right in Discord; submit renders the edited text through the same pipeline and posts it. One-shot by design: the edit shapes only the post about to happen, `CHANGELOG.md` (baked into the deployed image) is never written back. Single-version targets only (ranges are rejected ephemerally), entries over the 4000-char modal input cap refuse edit mode with a pointer to the file. The modal must be the first response, so the edit path checks staff and shows the modal WITHOUT deferring (same pattern as `/announce`); submits route through `bot/index.ts` on the `ptf-changelog-edit:` custom-id prefix and re-check staff. Rendering lives in `bot/lib/changelogRender.ts` (pure, no Discord/Payload deps): entries are split on `# vX.Y.Z` headers, `### ` sections become Discord markdown headings (`### `, the deepest level Discord renders), bullets become `•`, and entries over Discord's 4096-char limit are split across messages at section boundaries. The command reads `CHANGELOG.md` from the repo root relative to the file (works from the deploy server) and posts each version as its own amber embed, the first message of each version carrying the `Changelog vX.Y.Z` title and multi-message versions adding a page footer. Ranges spanning more than `WIDE_RANGE_THRESHOLD` (10) versions post an ephemeral warning but proceed. Idempotency ("don't repost") is intentionally out of scope for the manual command; the same rendering can be reused by a future automatic trigger.
|
||||
|
||||
## Feature flow: attendance
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,14 @@
|
|||
import {
|
||||
EmbedBuilder,
|
||||
LabelBuilder,
|
||||
MessageFlags,
|
||||
ModalBuilder,
|
||||
SlashCommandBuilder,
|
||||
TextInputBuilder,
|
||||
TextInputStyle,
|
||||
type ChatInputCommandInteraction,
|
||||
type InteractionReplyOptions,
|
||||
type ModalSubmitInteraction,
|
||||
type TextBasedChannelFields,
|
||||
type Guild,
|
||||
} from "discord.js";
|
||||
|
|
@ -13,8 +20,10 @@ import type { BotCommand } from "./index";
|
|||
import { botConfig } from "@/bot/config";
|
||||
import { isStaff } from "@/bot/lib/roles";
|
||||
import {
|
||||
parseChangelog,
|
||||
resolveChangelog,
|
||||
resolveChangelogRange,
|
||||
splitForDiscord,
|
||||
type ResolvedChangelog,
|
||||
type ChangelogBatch,
|
||||
} from "@/bot/lib/changelogRender";
|
||||
|
|
@ -31,6 +40,20 @@ const ANNOUNCE_COLOR = 0xf59e0b;
|
|||
/** Ranges spanning more versions than this trigger an ephemeral warning. */
|
||||
const WIDE_RANGE_THRESHOLD = 10;
|
||||
|
||||
/** Modal submit prefix; the version being edited follows the colon. */
|
||||
const EDIT_MODAL_PREFIX = "ptf-changelog-edit:";
|
||||
|
||||
/** Custom id of the single entry field inside the edit modal. */
|
||||
const ENTRY_INPUT_ID = "entry";
|
||||
|
||||
/** Discord caps modal text inputs at 4000 characters. */
|
||||
const MODAL_INPUT_MAX = 4000;
|
||||
|
||||
const ephemeralMsg = (content: string): InteractionReplyOptions => ({
|
||||
content,
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
|
||||
interface VersionPost {
|
||||
version: string;
|
||||
messages: string[];
|
||||
|
|
@ -78,6 +101,155 @@ const postVersion = async (
|
|||
return posted;
|
||||
};
|
||||
|
||||
/**
|
||||
* Edit mode: resolve the target entry's raw markdown and open it in a modal
|
||||
* instead of posting. Must run WITHOUT deferring (a modal is only valid as the
|
||||
* first response, inside Discord's 3-second window; same pattern as /announce).
|
||||
* The edit is one-shot: it shapes the post about to happen, CHANGELOG.md stays
|
||||
* untouched (the deployed copy is baked into the image and not writable anyway).
|
||||
*/
|
||||
const openEditModal = async (
|
||||
interaction: ChatInputCommandInteraction,
|
||||
guild: Guild,
|
||||
payload: Payload,
|
||||
rangeArg: string | null | undefined,
|
||||
): Promise<void> => {
|
||||
try {
|
||||
const member = await guild.members.fetch(interaction.user.id);
|
||||
if (!(await isStaff(member, payload))) {
|
||||
await interaction.reply(ephemeralMsg("You don't have permission to post a changelog."));
|
||||
return;
|
||||
}
|
||||
if (rangeArg?.includes("..")) {
|
||||
await interaction.reply(
|
||||
ephemeralMsg(
|
||||
"Edit mode works on one version at a time. Drop the range or the edit flag.",
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let content: string;
|
||||
try {
|
||||
content = readFileSync(CHANGELOG_PATH, "utf8");
|
||||
} catch (error) {
|
||||
await interaction.reply(
|
||||
ephemeralMsg(
|
||||
`Could not read ${path.basename(CHANGELOG_PATH)}: ${
|
||||
error instanceof Error ? error.message : "Unknown error"
|
||||
}`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const entries = parseChangelog(content);
|
||||
const wanted = rangeArg ? rangeArg.replace(/^v/i, "").trim() : undefined;
|
||||
const target = wanted
|
||||
? entries.find((entry) => entry.version === wanted)
|
||||
: entries[0];
|
||||
if (!target) {
|
||||
await interaction.reply(
|
||||
ephemeralMsg(
|
||||
wanted
|
||||
? `No changelog entry found for version ${rangeArg}.`
|
||||
: "The changelog file has no entries to post.",
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const raw = target.rawBody.trim();
|
||||
if (raw.length > MODAL_INPUT_MAX) {
|
||||
await interaction.reply(
|
||||
ephemeralMsg(
|
||||
`This entry is ${raw.length} characters, over the ${MODAL_INPUT_MAX}-character modal limit. Edit CHANGELOG.md directly instead.`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const modal = new ModalBuilder()
|
||||
.setCustomId(`${EDIT_MODAL_PREFIX}${target.version}`)
|
||||
.setTitle(`Edit Changelog v${target.version}`.slice(0, 45));
|
||||
const input = new TextInputBuilder()
|
||||
.setCustomId(ENTRY_INPUT_ID)
|
||||
.setStyle(TextInputStyle.Paragraph)
|
||||
.setMaxLength(MODAL_INPUT_MAX)
|
||||
.setRequired(true);
|
||||
// An empty entry still opens the editor; only a non-empty body can prefill.
|
||||
if (raw.length > 0) input.setValue(raw);
|
||||
modal.addLabelComponents(
|
||||
new LabelBuilder()
|
||||
.setLabel(`Entry markdown (v${target.version})`)
|
||||
.setDescription("Discord markdown; posts to #releases as one or more embeds")
|
||||
.setTextInputComponent(input),
|
||||
);
|
||||
await interaction.showModal(modal);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
payload.logger.error(`[Bot] /changelog edit failed: ${message}`);
|
||||
if (!interaction.replied && !interaction.deferred) {
|
||||
await interaction
|
||||
.reply(ephemeralMsg("Something went wrong opening the changelog editor."))
|
||||
.catch(() => {});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** Modal submit: render the edited entry through the normal pipeline and post it. */
|
||||
export const handleChangelogEditModal = async (
|
||||
interaction: ModalSubmitInteraction,
|
||||
payload: Payload,
|
||||
): Promise<void> => {
|
||||
try {
|
||||
if (!interaction.inGuild() || !interaction.guild) {
|
||||
await interaction.reply(ephemeralMsg("This command only works in a server."));
|
||||
return;
|
||||
}
|
||||
// Re-check on submit: the modal can sit open while roles change.
|
||||
const member = await interaction.guild.members.fetch(interaction.user.id);
|
||||
if (!(await isStaff(member, payload))) {
|
||||
await interaction.reply(ephemeralMsg("You don't have permission to post a changelog."));
|
||||
return;
|
||||
}
|
||||
|
||||
const version = interaction.customId.slice(EDIT_MODAL_PREFIX.length);
|
||||
const edited = interaction.fields.getTextInputValue(ENTRY_INPUT_ID).trim();
|
||||
if (!edited) {
|
||||
await interaction.reply(ephemeralMsg("The entry was empty; nothing posted."));
|
||||
return;
|
||||
}
|
||||
|
||||
const channel = await resolveChannel(interaction.guild);
|
||||
if (!channel) {
|
||||
await interaction.reply(
|
||||
ephemeralMsg(
|
||||
"The releases channel isn't configured or isn't reachable (set DISCORD_CHANGELOG_CHANNEL_ID, or DISCORD_ANNOUNCE_CHANNEL_ID as a fallback).",
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const posted = await postVersion(channel, version, splitForDiscord(edited));
|
||||
await interaction.reply(
|
||||
ephemeralMsg(
|
||||
posted > 1
|
||||
? `Posted **Changelog v${version}** (edited, ${posted} messages).`
|
||||
: `Posted **Changelog v${version}** (edited).`,
|
||||
),
|
||||
);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
payload.logger.error(`[Bot] /changelog edit submit failed: ${message}`);
|
||||
if (!interaction.replied && !interaction.deferred) {
|
||||
await interaction
|
||||
.reply(ephemeralMsg("Something went wrong posting the edited changelog."))
|
||||
.catch(() => {});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const changelogCommand: BotCommand = {
|
||||
builder: new SlashCommandBuilder()
|
||||
.setName("changelog")
|
||||
|
|
@ -88,6 +260,13 @@ export const changelogCommand: BotCommand = {
|
|||
.setDescription(
|
||||
"Version or range: v0.4.0, v0.3.0..v0.5.0, open ends (v0.3.0.., ..v0.5.0). Omit for latest.",
|
||||
),
|
||||
)
|
||||
.addBooleanOption((option) =>
|
||||
option
|
||||
.setName("edit")
|
||||
.setDescription(
|
||||
"Open the entry in an editable modal before posting (single version only).",
|
||||
),
|
||||
) as SlashCommandBuilder,
|
||||
execute: async (interaction, payload) => {
|
||||
if (!interaction.inGuild() || !interaction.guild) {
|
||||
|
|
@ -98,6 +277,14 @@ export const changelogCommand: BotCommand = {
|
|||
return;
|
||||
}
|
||||
|
||||
// Edit mode answers with a modal, which must be the first response
|
||||
// (Discord rejects modals after a defer), so branch BEFORE deferring.
|
||||
const rangeArg = interaction.options.getString("range")?.trim();
|
||||
if (interaction.options.getBoolean("edit")) {
|
||||
await openEditModal(interaction, interaction.guild, payload, rangeArg);
|
||||
return;
|
||||
}
|
||||
|
||||
// Acknowledge immediately: the permission check (uncached member fetch +
|
||||
// DB lookups) and the file/Discord I/O below can exceed Discord's 3-second
|
||||
// interaction window, which otherwise shows "The application did not respond".
|
||||
|
|
@ -110,8 +297,6 @@ export const changelogCommand: BotCommand = {
|
|||
return;
|
||||
}
|
||||
|
||||
const rangeArg = interaction.options.getString("range")?.trim();
|
||||
|
||||
let content: string;
|
||||
try {
|
||||
content = readFileSync(CHANGELOG_PATH, "utf8");
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import config from "@payload-config";
|
|||
import { botConfig } from "./config";
|
||||
import { commands } from "./commands";
|
||||
import { handleAnnounceModal } from "./commands/announce";
|
||||
import { handleChangelogEditModal } from "./commands/changelog";
|
||||
import { handlePresenceModal } from "./commands/discordPresence";
|
||||
import { services } from "./services";
|
||||
import { handleButtonInteraction } from "./events/interactionCreate";
|
||||
|
|
@ -86,6 +87,10 @@ const main = async () => {
|
|||
await handleAnnounceModal(interaction, payload);
|
||||
return;
|
||||
}
|
||||
if (interaction.isModalSubmit() && interaction.customId.startsWith("ptf-changelog-edit:")) {
|
||||
await handleChangelogEditModal(interaction, payload);
|
||||
return;
|
||||
}
|
||||
if (interaction.isModalSubmit() && interaction.customId.startsWith("ptf-rp-edit")) {
|
||||
await handlePresenceModal(interaction, payload);
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -231,6 +231,23 @@ describe("empty-section fallback", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("edit-mode round trip (modal prefill -> post)", () => {
|
||||
it("renders the trimmed raw body exactly like the normal posting path", () => {
|
||||
const prefilled = parseChangelog(SAMPLE)[0].rawBody.trim(); // what the modal shows
|
||||
expect(splitForDiscord(prefilled)).toEqual(resolveChangelog(SAMPLE).messages);
|
||||
});
|
||||
|
||||
it("posts last-minute edits through the same renderer", () => {
|
||||
const edited = parseChangelog(SAMPLE)[0].rawBody
|
||||
.trim()
|
||||
.replace("- Fixed a bug.", "- Fixed a bug (hotfix).");
|
||||
const rendered = splitForDiscord(edited).join("\n\n");
|
||||
expect(rendered).toContain("Fixed a bug (hotfix).");
|
||||
expect(rendered).toContain("### Fixes");
|
||||
expect(rendered).not.toContain("- Fixed a bug.\n");
|
||||
});
|
||||
});
|
||||
|
||||
describe("real CHANGELOG.md", () => {
|
||||
it("parses and renders the shipped entries", () => {
|
||||
const content = readFileSync(CHANGELOG_PATH, "utf8");
|
||||
|
|
|
|||
Loading…
Reference in a new issue