1
0
Fork 0

refactor(bot): export render and send helpers for debug reuse

This commit is contained in:
Jason Fraley 2026-10-26 18:07:05 -04:00
parent 282b313cd5
commit 6263730d9c
9 changed files with 76 additions and 48 deletions

View file

@ -30,7 +30,7 @@ import {
// CHANGELOG.md sits at the repo root; resolve it relative to this file so the // CHANGELOG.md sits at the repo root; resolve it relative to this file so the
// path is correct regardless of the process working directory. // path is correct regardless of the process working directory.
const CHANGELOG_PATH = path.resolve( export const CHANGELOG_PATH = path.resolve(
path.dirname(fileURLToPath(import.meta.url)), path.dirname(fileURLToPath(import.meta.url)),
"../../../CHANGELOG.md", "../../../CHANGELOG.md",
); );
@ -80,21 +80,27 @@ const resolveChannel = async (guild: Guild): Promise<TextBasedChannelFields | nu
* Post one version's messages as amber embeds. The first carries the version * Post one version's messages as amber embeds. The first carries the version
* title; multi-message versions add a page footer so order stays clear. * title; multi-message versions add a page footer so order stays clear.
*/ */
const postVersion = async ( export const renderVersionEmbeds = (version: string, messages: string[]): EmbedBuilder[] => {
const total = messages.length;
return messages.map((message, i) => {
const embed = new EmbedBuilder()
.setTitle(`Changelog v${version}`)
.setColor(ANNOUNCE_COLOR)
.setDescription(message);
if (total > 1) {
embed.setFooter({ text: `Page ${i + 1}/${total}` });
}
return embed;
});
};
export const postVersion = async (
channel: TextBasedChannelFields, channel: TextBasedChannelFields,
version: string, version: string,
messages: string[], messages: string[],
): Promise<number> => { ): Promise<number> => {
const total = messages.length;
let posted = 0; let posted = 0;
for (let i = 0; i < messages.length; i += 1) { for (const embed of renderVersionEmbeds(version, messages)) {
const embed = new EmbedBuilder()
.setTitle(`Changelog v${version}`)
.setColor(ANNOUNCE_COLOR)
.setDescription(messages[i]);
if (total > 1) {
embed.setFooter({ text: `Page ${i + 1}/${total}` });
}
await channel.send({ embeds: [embed] }); await channel.send({ embeds: [embed] });
posted += 1; posted += 1;
} }

View file

@ -66,7 +66,7 @@ const formatLinks = (links: ReminderLink[], appUrl: string): string => {
return lines.join("\n").slice(0, 1024) || "-"; return lines.join("\n").slice(0, 1024) || "-";
}; };
const renderReminderEmbed = ( export const renderReminderEmbed = (
mission: Mission, mission: Mission,
rateLeaders: ReminderLink[], rateLeaders: ReminderLink[],
rateSubordinates: ReminderLink[], rateSubordinates: ReminderLink[],

View file

@ -30,11 +30,14 @@ let reconcileRunning = false;
const errorMessage = (error: unknown): string => const errorMessage = (error: unknown): string =>
error instanceof Error ? error.message : "Unknown error"; error instanceof Error ? error.message : "Unknown error";
type SideOpsChannel = TextBasedChannelFields & { export type SideOpsChannel = TextBasedChannelFields & {
messages: { fetch(options: { limit: number }): Promise<Collection<string, Message>> }; messages: { fetch(options: { limit: number }): Promise<Collection<string, Message>> };
}; };
const getSideOpsChannel = async (client: Client, channelId: string): Promise<SideOpsChannel> => { export const getSideOpsChannel = async (
client: Client,
channelId: string,
): Promise<SideOpsChannel> => {
const channel = await client.channels.fetch(channelId); const channel = await client.channels.fetch(channelId);
if (!channel || !("send" in channel) || !("messages" in channel)) { if (!channel || !("send" in channel) || !("messages" in channel)) {
throw new Error(`[Bot] Side-ops channel ${channelId} is not a text channel.`); throw new Error(`[Bot] Side-ops channel ${channelId} is not a text channel.`);
@ -43,16 +46,16 @@ const getSideOpsChannel = async (client: Client, channelId: string): Promise<Sid
}; };
/** Configured role ID wins; otherwise resolve the role by name in the guild. */ /** Configured role ID wins; otherwise resolve the role by name in the guild. */
const resolveZeusRoleId = async (client: Client): Promise<string | null> => { export const resolveZeusRoleId = async (client: Client): Promise<string | null> => {
if (botConfig.communityZeusRoleId) return botConfig.communityZeusRoleId; if (botConfig.communityZeusRoleId) return botConfig.communityZeusRoleId;
const guild = await client.guilds.fetch(botConfig.guildId); const guild = await client.guilds.fetch(botConfig.guildId);
const role = guild.roles.cache.find((role) => role.name === SIDE_OPS_NOTICE_ROLE_NAME); const role = guild.roles.cache.find((role) => role.name === SIDE_OPS_NOTICE_ROLE_NAME);
return role?.id ?? null; return role?.id ?? null;
}; };
const renderNotice = (zeusRoleId: string | null): string => { export const renderNotice = (zeusRoleId: string | null, now = new Date()): string => {
const mention = zeusRoleId ? `<@&${zeusRoleId}> ` : ""; const mention = zeusRoleId ? `<@&${zeusRoleId}> ` : "";
const { epoch } = upcomingFridayRange(new Date()); const { epoch } = upcomingFridayRange(now);
return ( return (
`${mention}The Friday op slot (<t:${epoch}:D>) is still open, and you are welcome to host an op: ` + `${mention}The Friday op slot (<t:${epoch}:D>) is still open, and you are welcome to host an op: ` +
`schedule one via the Friday Ops calendar at ${botConfig.appUrl}/intelligence/missions/calendar. ` + `schedule one via the Friday Ops calendar at ${botConfig.appUrl}/intelligence/missions/calendar. ` +
@ -67,7 +70,7 @@ const CLAIM_LINE_PATTERN =
const creditedNameOf = (content: string): string | null => const creditedNameOf = (content: string): string | null =>
content.match(CLAIM_LINE_PATTERN)?.[1] ?? null; content.match(CLAIM_LINE_PATTERN)?.[1] ?? null;
const findNoticeMessage = async ( export const findNoticeMessage = async (
channel: SideOpsChannel, channel: SideOpsChannel,
token: string, token: string,
): Promise<Message | null> => { ): Promise<Message | null> => {

View file

@ -26,7 +26,7 @@ let reconcileRunning = false;
const errorMessage = (error: unknown): string => const errorMessage = (error: unknown): string =>
error instanceof Error ? error.message : "Unknown error"; error instanceof Error ? error.message : "Unknown error";
const renderReminderEmbed = (mission: Mission): EmbedBuilder => { export const renderReminderEmbed = (mission: Mission): EmbedBuilder => {
const startUnix = Math.floor(new Date(mission.classification.startDateTime).getTime() / 1000); const startUnix = Math.floor(new Date(mission.classification.startDateTime).getTime() / 1000);
return new EmbedBuilder() return new EmbedBuilder()
.setTitle(`⏰ Op starting soon: ${missionTitle(mission)}`) .setTitle(`⏰ Op starting soon: ${missionTitle(mission)}`)
@ -38,7 +38,7 @@ const renderReminderEmbed = (mission: Mission): EmbedBuilder => {
}); });
}; };
const mentionsFor = (users: User[]): string[] => export const mentionsFor = (users: User[]): string[] =>
users users
.filter((user) => user.discordId) .filter((user) => user.discordId)
.map((user) => `<@${user.discordId as string}>`); .map((user) => `<@${user.discordId as string}>`);

View file

@ -213,7 +213,7 @@ export const renderCancelledEmbed = (mission: Mission): EmbedBuilder =>
.setDescription("This operation has been cancelled.") .setDescription("This operation has been cancelled.")
.setColor(CANCELLED_COLOR); .setColor(CANCELLED_COLOR);
const renderCancelledNoticeEmbed = (mission: Mission): EmbedBuilder => export const renderCancelledNoticeEmbed = (mission: Mission): EmbedBuilder =>
new EmbedBuilder() new EmbedBuilder()
.setTitle(`Cancelled: ${missionTitle(mission)}`) .setTitle(`Cancelled: ${missionTitle(mission)}`)
.setDescription( .setDescription(
@ -223,7 +223,7 @@ const renderCancelledNoticeEmbed = (mission: Mission): EmbedBuilder =>
.setColor(CANCELLED_COLOR) .setColor(CANCELLED_COLOR)
.setTimestamp(); .setTimestamp();
const renderRescheduledEmbed = (mission: Mission, rollCallDueUnix: number | null): EmbedBuilder => { export const renderRescheduledEmbed = (mission: Mission, rollCallDueUnix: number | null): EmbedBuilder => {
const startUnix = Math.floor(new Date(mission.classification.startDateTime).getTime() / 1000); const startUnix = Math.floor(new Date(mission.classification.startDateTime).getTime() / 1000);
return new EmbedBuilder() return new EmbedBuilder()
.setTitle(`Rescheduled: ${missionTitle(mission)}`) .setTitle(`Rescheduled: ${missionTitle(mission)}`)
@ -255,7 +255,7 @@ export const buildAttendanceRow = (missionId: number): ActionRowBuilder<ButtonBu
.setLabel("❌ No"), .setLabel("❌ No"),
); );
const getOpsChannel = async ( export const getOpsChannel = async (
client: Client, client: Client,
opsChannelId: string, opsChannelId: string,
): Promise<TextBasedChannelFields> => { ): Promise<TextBasedChannelFields> => {
@ -266,7 +266,18 @@ const getOpsChannel = async (
return channel as unknown as TextBasedChannelFields; return channel as unknown as TextBasedChannelFields;
}; };
const postEmbed = async ( export const buildRollCallMessage = async (
payload: Payload,
mission: Mission,
): Promise<{ embeds: EmbedBuilder[]; components: ActionRowBuilder<ButtonBuilder>[] }> => {
const summary = await getMissionAttendance(payload, mission.id);
return {
embeds: [renderAttendanceEmbed(mission, summary)],
components: [buildAttendanceRow(mission.id)],
};
};
export const postEmbed = async (
client: Client, client: Client,
payload: Payload, payload: Payload,
opsChannelId: string, opsChannelId: string,
@ -301,7 +312,7 @@ const postEmbed = async (
}); });
}; };
interface ModlistInfo { export interface ModlistInfo {
id: number; id: number;
name: string; name: string;
filename: string; filename: string;
@ -310,7 +321,7 @@ interface ModlistInfo {
updatedAt: string; updatedAt: string;
} }
const resolveModlist = async (payload: Payload, mission: Mission): Promise<ModlistInfo | null> => { export const resolveModlist = async (payload: Payload, mission: Mission): Promise<ModlistInfo | null> => {
const raw = mission.gameDetails.gameSetup?.requiredMods; const raw = mission.gameDetails.gameSetup?.requiredMods;
if (raw == null || typeof raw === "number") return null; if (raw == null || typeof raw === "number") return null;
const modlist = raw as ModList; const modlist = raw as ModList;
@ -337,7 +348,7 @@ const modlistHash = (modlist: ModlistInfo): string =>
updatedAt: modlist.updatedAt, updatedAt: modlist.updatedAt,
}); });
const renderModlistEmbed = ( export const renderModlistEmbed = (
mission: Mission, mission: Mission,
modlist: ModlistInfo, modlist: ModlistInfo,
kind: "new" | "updated", kind: "new" | "updated",
@ -354,15 +365,12 @@ const renderModlistEmbed = (
return embed; return embed;
}; };
const postModlistMessage = async ( export const buildModlistMessage = async (
client: Client,
payload: Payload, payload: Payload,
opsChannelId: string,
mission: Mission, mission: Mission,
modlist: ModlistInfo, modlist: ModlistInfo,
kind: "new" | "updated", kind: "new" | "updated",
): Promise<void> => { ): Promise<{ embeds: EmbedBuilder[]; files?: AttachmentBuilder[] }> => {
const channel = await getOpsChannel(client, opsChannelId);
const embed = renderModlistEmbed(mission, modlist, kind); const embed = renderModlistEmbed(mission, modlist, kind);
let files: AttachmentBuilder[] | undefined; let files: AttachmentBuilder[] | undefined;
@ -389,7 +397,19 @@ const postModlistMessage = async (
embed.addFields({ name: "Download", value: `${botConfig.appUrl}${modlist.url}` }); embed.addFields({ name: "Download", value: `${botConfig.appUrl}${modlist.url}` });
} }
await channel.send({ embeds: [embed], files }); return { embeds: [embed], files };
};
export const postModlistMessage = async (
client: Client,
payload: Payload,
opsChannelId: string,
mission: Mission,
modlist: ModlistInfo,
kind: "new" | "updated",
): Promise<void> => {
const channel = await getOpsChannel(client, opsChannelId);
await channel.send(await buildModlistMessage(payload, mission, modlist, kind));
}; };
/** /**

View file

@ -43,6 +43,16 @@ const eligibleForDm = (owner: User, type?: string | null): boolean => {
return true; return true;
}; };
export const renderNotificationEmbed = (notification: UserNotification): EmbedBuilder =>
new EmbedBuilder()
.setTitle(notification.title)
.setDescription(notification.message ?? null)
.setColor(EMBED_COLOR)
.addFields({
name: "Link",
value: `${botConfig.appUrl}${notification.link ?? ""}`,
});
const poll = async (client: Client, payload: Payload): Promise<void> => { const poll = async (client: Client, payload: Payload): Promise<void> => {
try { try {
if (cursor === null) { if (cursor === null) {
@ -76,18 +86,7 @@ const poll = async (client: Client, payload: Payload): Promise<void> => {
if (!eligibleForDm(owner, notification.type)) continue; if (!eligibleForDm(owner, notification.type)) continue;
const target = await client.users.fetch(owner.discordId as string); const target = await client.users.fetch(owner.discordId as string);
await target.send({ await target.send({ embeds: [renderNotificationEmbed(notification)] });
embeds: [
new EmbedBuilder()
.setTitle(notification.title)
.setDescription(notification.message ?? null)
.setColor(EMBED_COLOR)
.addFields({
name: "Link",
value: `${botConfig.appUrl}${notification.link ?? ""}`,
}),
],
});
sent++; sent++;
if (sent < MAX_SENDS_PER_TICK) await sleep(SEND_DELAY_MS); if (sent < MAX_SENDS_PER_TICK) await sleep(SEND_DELAY_MS);
} catch { } catch {

View file

@ -30,7 +30,7 @@ let running = false;
const errorMessage = (error: unknown): string => const errorMessage = (error: unknown): string =>
error instanceof Error ? error.message : "Unknown error"; error instanceof Error ? error.message : "Unknown error";
const buildEmbed = (doc: GameEventLog): EmbedBuilder => { export const buildEmbed = (doc: GameEventLog): EmbedBuilder => {
const epoch = Math.floor(new Date(doc.timestamp).getTime() / 1000); const epoch = Math.floor(new Date(doc.timestamp).getTime() / 1000);
const embed = new EmbedBuilder() const embed = new EmbedBuilder()
.setTitle("NPC Dispatch") .setTitle("NPC Dispatch")

View file

@ -38,7 +38,7 @@ const errorMessage = (error: unknown): string =>
const creatorIdOf = (mission: Mission): number | null => const creatorIdOf = (mission: Mission): number | null =>
typeof mission.createdBy === "object" ? (mission.createdBy?.id ?? null) : (mission.createdBy ?? null); typeof mission.createdBy === "object" ? (mission.createdBy?.id ?? null) : (mission.createdBy ?? null);
const renderReminderEmbed = (mission: Mission, now: Date): EmbedBuilder => { export const renderReminderEmbed = (mission: Mission, now: Date): EmbedBuilder => {
const days = daysUntil(mission.classification.startDateTime, now); const days = daysUntil(mission.classification.startDateTime, now);
const when = days === 0 ? "today" : days === 1 ? "tomorrow" : `in ${days} days`; const when = days === 0 ? "today" : days === 1 ? "tomorrow" : `in ${days} days`;
return new EmbedBuilder() return new EmbedBuilder()

View file

@ -35,7 +35,7 @@ const fetchUser = (payload: Payload, id: number): Promise<User> =>
const fetchAssignment = (payload: Payload, id: number): Promise<Assignment> => const fetchAssignment = (payload: Payload, id: number): Promise<Assignment> =>
payload.findByID({ collection: "assignments", id, depth: 0, overrideAccess: true }); payload.findByID({ collection: "assignments", id, depth: 0, overrideAccess: true });
const contextFor = async ( export const contextFor = async (
payload: Payload, payload: Payload,
doc: AssignmentTransfer, doc: AssignmentTransfer,
): Promise<TransferContext> => { ): Promise<TransferContext> => {