1
0
Fork 0

feat(npc-dialogue): post opted-in event effects to Discord dispatch channel

Event nodes gain a 'Post this event to the Discord NPC dispatch channel'
checkbox. The flag rides emit() onto game_event_logs (discordRequested +
announcement bookkeeping columns, migration add_event_log_discord_fields),
and a new bot poller stamps pending rows into an amber NPC Dispatch embed
with relative-time mention and a link back to the source contact.

Bot delivery itself is unverifiable locally (no Discord token or channel id
in dev); the DB-side contract is covered by an integration test and a live
probe walk confirmed discord_requested persists end to end.
This commit is contained in:
Jason Fraley 2026-10-14 16:57:33 -04:00
parent 20c70151e3
commit 88e89c9e55
16 changed files with 41298 additions and 2 deletions

View file

@ -73,6 +73,11 @@ APP_PORT=3000
# DISCORD_STAFF_ROLE_IDS=
# DISCORD_ATTENDANCE_POLL_MS=
# DISCORD_NOTIFICATION_POLL_MS=
# NPC dispatch: dialogue event effects flagged "Post to Discord" are posted as
# amber embeds to this channel by the bot poll service (queued on the game
# event log entry until posted). Unset disables posting.
# DISCORD_NPC_EVENT_CHANNEL_ID=
# DISCORD_NPC_EVENT_POLL_MS=
# --- Usage analytics (Microsoft Clarity) ---
# Project ID from clarity.microsoft.com (Settings > Project ID). Optional;

View file

@ -145,6 +145,13 @@ Dependency: `discord.js` ^14 (add to root `package.json`). Script: `"bot": "bun
- **Dedup**: no DB state. The notice embeds a stable per-Friday `<t:epoch:D>` token; before posting, the service scans the last 100 channel messages for it, so restarts never double-post.
- **Claim credit**: when a non-cancelled mission later appears on that Friday whose creator is not a superuser (`getFridayClaimant` in `src/lib/intelligence/fridayOpsNotice.ts`, earliest `createdAt` wins; superuser- or staff-created missions never claim), the service edits the notice in place, appending "This slot was claimed by \<user\>. Thank you for hosting for our community!". If the claiming op is later cancelled or deleted, the claim line is stripped and the notice reverts to the open-slot state (a claim swap between polls re-credits the new claimant). Idempotent via a claim-line check on the message content; the edit half runs whenever the notice is still in the recent-messages window, regardless of day, so a Thursday claim still lands.
### G. NPC dispatch announcements (dialogue events → channel)
- **Trigger**: a dialogue event node with an emit/reward/flag effect authored with `discord: true`. `runEffect` passes `discordRequested` into `emitGameEvent`, which persists it on the `game-event-logs` entry; nothing talks to Discord at emit time.
- **Poll loop** (`src/bot/services/npcEventAnnouncements.ts`, every `DISCORD_NPC_EVENT_POLL_MS`, default 60s): query entries with `discordRequested = true` and no `discordAnnouncedAt`, oldest first, cap 5 posts/tick. Channel from `DISCORD_NPC_EVENT_CHANNEL_ID`; unset disables the service.
- **Embed**: amber "NPC Dispatch" with the event message, a `<t:epoch:R>` reported field, and a Source link to the speaking NPC's contact page when the event targets `game-npcs`.
- **Idempotency**: one-shot markers on the log entry (`discordAnnouncedAt` + `discordMessageId`), stamped only after a successful send; failures stay queued and retry next tick.
### Authz (`src/bot/lib/roles.ts`)
`isStaff(member)`: caller has any `DISCORD_STAFF_ROLE_IDS`, **or** their linked Payload user has roles `admin`/`developer`. RSVP/signup/link are open to all members. The bot performs Payload writes with `overrideAccess` and relies on these checks + its own validations.
@ -167,6 +174,8 @@ Dependency: `discord.js` ^14 (add to root `package.json`). Script: `"bot": "bun
| `DISCORD_ANNOUNCE_MENTION_ROLE_ID` | no | Role auto-mentioned in `/announce` when called without a message (compose dialog). Unset disables it |
| `DISCORD_SIDE_OPS_POLL_MS` | no | default 1800000 (30 min) |
| `DISCORD_PRESENCE_POLL_MS` | no | default 30000 (30s); reconcile loop for the bot's Rich Presence from the `discord-presence` Global |
| `DISCORD_NPC_EVENT_CHANNEL_ID` | no | NPC dispatch channel for dialogue events flagged "Post to Discord"; unset disables posting |
| `DISCORD_NPC_EVENT_POLL_MS` | no | default 60000 (60s) |
`APP_URL` already exists — used for login links in DMs.

View file

@ -114,6 +114,7 @@ async function runEffect(
// Author override: "public" puts the entry in every member's feed;
// undefined keeps the restricted narrative default (see visibility.ts).
visibility: effect.eventVisibility,
discordRequested: effect.discord,
});
break;
}
@ -127,6 +128,7 @@ async function runEffect(
targetId: npcId,
data: { effect: "reward", unconfigured: true },
visibility: effect.eventVisibility,
discordRequested: effect.discord,
});
break;
}
@ -155,6 +157,7 @@ async function runEffect(
targetId: npcId,
data: { effect: "flag", key, op, amount },
visibility: effect.eventVisibility,
discordRequested: effect.discord,
});
break;
}

View file

@ -8,7 +8,7 @@ Standalone long-running process (`bun run bot`). Imports `@payload-config` direc
## Env
Required: `DISCORD_TOKEN`, `DISCORD_GUILD_ID` (fail-fast on missing vars in `config.ts`). Optional: `DISCORD_OPS_CHANNEL_ID`, `DISCORD_ANNOUNCE_CHANNEL_ID`, `DISCORD_CHANGELOG_CHANNEL_ID` (dedicated #releases channel for `/changelog`; falls back to the announce channel), `DISCORD_STAFF_ROLE_IDS`, `DISCORD_SIDE_OPS_CHANNEL_ID` (Friday open-slot notice channel), `DISCORD_COMMUNITY_ZEUS_ROLE_ID` (role ping for that notice), `APP_URL`, plus poll intervals `DISCORD_ATTENDANCE_POLL_MS` (default 60s), `DISCORD_NOTIFICATION_POLL_MS` (default 20s), `DISCORD_EVALUATION_POLL_MS` (default 60s), `DISCORD_IMMINENT_POLL_MS` (default 60s), `DISCORD_SIDE_OPS_POLL_MS` (default 30 min), `DISCORD_PRESENCE_POLL_MS` (default 30s). Logs through `payload.logger`.
Required: `DISCORD_TOKEN`, `DISCORD_GUILD_ID` (fail-fast on missing vars in `config.ts`). Optional: `DISCORD_OPS_CHANNEL_ID`, `DISCORD_ANNOUNCE_CHANNEL_ID`, `DISCORD_CHANGELOG_CHANNEL_ID` (dedicated #releases channel for `/changelog`; falls back to the announce channel), `DISCORD_STAFF_ROLE_IDS`, `DISCORD_SIDE_OPS_CHANNEL_ID` (Friday open-slot notice channel), `DISCORD_COMMUNITY_ZEUS_ROLE_ID` (role ping for that notice), `DISCORD_NPC_EVENT_CHANNEL_ID` (NPC dispatch channel for dialogue events; unset disables posting), `APP_URL`, plus poll intervals `DISCORD_ATTENDANCE_POLL_MS` (default 60s), `DISCORD_NOTIFICATION_POLL_MS` (default 20s), `DISCORD_EVALUATION_POLL_MS` (default 60s), `DISCORD_IMMINENT_POLL_MS` (default 60s), `DISCORD_SIDE_OPS_POLL_MS` (default 30 min), `DISCORD_PRESENCE_POLL_MS` (default 30s), `DISCORD_NPC_EVENT_POLL_MS` (default 60s). Logs through `payload.logger`.
## Structure
@ -39,6 +39,7 @@ bot/
evaluationReminders.ts # Post-mission evaluation reminder DMs (one-shot marker on Missions)
imminentReminders.ts # Pre-op reminder: thread on the roll-call message + attendee pings (one-shot marker on Missions)
fridayOpsNotice.ts # Weekly notice: pings Community Zeus in #side-ops when the upcoming Friday has no op
npcEventAnnouncements.ts # Poll game-event-logs flagged discordRequested → post amber "NPC Dispatch" embeds, stamp discordAnnouncedAt + discordMessageId
signup.ts # Signup service logic
transferRequests.ts # Polls assignment transfer requests awaiting leader decision
transferDelivery.ts # Transfer leader-request / rejection / info delivery DMs
@ -110,6 +111,7 @@ A poll loop (`services/discordPresence.ts`, `DISCORD_PRESENCE_POLL_MS`, default
| Evaluation reminder logic | `bot/services/evaluationReminders.ts` + `src/lib/evaluations/reminders.ts` |
| Imminent-op reminder logic | `bot/services/imminentReminders.ts` + `src/lib/intelligence/imminentReminders.ts` |
| Friday open-slot notice | `bot/services/fridayOpsNotice.ts` + `src/lib/intelligence/fridayOpsNotice.ts` |
| NPC dispatch posting (dialogue events) | `bot/services/npcEventAnnouncements.ts` + `discordRequested`/`discordAnnouncedAt` on game-event-logs |
| Transfer workflow | `bot/services/transferRequests.ts` + `lib/transferMessaging.ts` |
| User lookup patterns | `bot/lib/resolve.ts` |
| Edit bot Rich Presence (command) | `bot/commands/discordPresence.ts` (+ Global `src/collections/discord/DiscordPresence.ts`) |

View file

@ -9,6 +9,7 @@ export interface BotConfig {
communityZeusRoleId: string | null;
changelogChannelId: string | null;
announceMentionRoleId: string | null;
npcEventChannelId: string | null;
attendancePollMs: number;
notificationPollMs: number;
evaluationPollMs: number;
@ -17,6 +18,7 @@ export interface BotConfig {
sideOpsNoticePollMs: number;
achievementPollMs: number;
presencePollMs: number;
npcEventPollMs: number;
}
const required = (name: string): string => {
@ -58,6 +60,7 @@ export const botConfig: BotConfig = {
communityZeusRoleId: optional("DISCORD_COMMUNITY_ZEUS_ROLE_ID"),
changelogChannelId: optional("DISCORD_CHANGELOG_CHANNEL_ID"),
announceMentionRoleId: optional("DISCORD_ANNOUNCE_MENTION_ROLE_ID"),
npcEventChannelId: optional("DISCORD_NPC_EVENT_CHANNEL_ID"),
attendancePollMs: pollMs("DISCORD_ATTENDANCE_POLL_MS", 60_000),
notificationPollMs: pollMs("DISCORD_NOTIFICATION_POLL_MS", 20_000),
evaluationPollMs: pollMs("DISCORD_EVALUATION_POLL_MS", 60_000),
@ -66,4 +69,5 @@ export const botConfig: BotConfig = {
sideOpsNoticePollMs: pollMs("DISCORD_SIDE_OPS_POLL_MS", 1_800_000),
achievementPollMs: pollMs("DISCORD_ACHIEVEMENT_POLL_MS", 60_000),
presencePollMs: pollMs("DISCORD_PRESENCE_POLL_MS", 30_000),
npcEventPollMs: pollMs("DISCORD_NPC_EVENT_POLL_MS", 60_000),
};

View file

@ -8,6 +8,7 @@ import { start as startReadyReminders } from "./readyReminders";
import { start as startImminentReminders } from "./imminentReminders";
import { start as startFridayOpsNotice } from "./fridayOpsNotice";
import { start as startAchievementAnnouncements } from "./achievementAnnouncements";
import { start as startNpcEventAnnouncements } from "./npcEventAnnouncements";
import { start as startDiscordPresence } from "./discordPresence";
export type ServiceStarter = (client: Client, payload: Payload) => Promise<void> | void;
@ -21,5 +22,6 @@ export const services: ServiceStarter[] = [
startImminentReminders,
startFridayOpsNotice,
startAchievementAnnouncements,
startNpcEventAnnouncements,
startDiscordPresence,
];

View file

@ -0,0 +1,114 @@
import { type Client, EmbedBuilder } from "discord.js";
import type { Payload } from "payload";
import { botConfig } from "@/bot/config";
import type { GameEventLog } from "@/payload-types";
/**
* NPC dispatch announcements: poll game-event-log entries that a dialogue
* event effect flagged with `discordRequested` but that were never posted,
* send one embed per event to the NPC dispatch channel, then stamp
* `discordAnnouncedAt` + `discordMessageId` on the log entry.
*
* The stamp happens only after a successful send, so a failed or missing
* post stays queued and retries on the next tick. Per-tick cap keeps the
* channel (and Discord rate limits) calm when a session replays many beats.
*
* The Next app never talks to Discord; this service owns the bot side.
*/
const MAX_POSTS_PER_TICK = 5;
const BATCH_LIMIT = 20;
/** Minimal text-channel shape we rely on (mirrors achievementAnnouncements). */
type DispatchChannel = {
send(payload: { embeds: EmbedBuilder[] }): Promise<{ id: string }>;
};
let running = false;
const errorMessage = (error: unknown): string =>
error instanceof Error ? error.message : "Unknown error";
const buildEmbed = (doc: GameEventLog): EmbedBuilder => {
const epoch = Math.floor(new Date(doc.timestamp).getTime() / 1000);
const embed = new EmbedBuilder()
.setTitle("NPC Dispatch")
.setDescription(doc.message.slice(0, 1000))
.setColor(0xf59e0b)
.addFields({ name: "Reported", value: `<t:${epoch}:R>`, inline: true });
// Dialogue events target the NPC that spoke; link its contact page so the
// reader can find who said it.
if (doc.targetCollection === "game-npcs" && doc.targetId) {
embed.addFields({
name: "Source",
value: `[Contact file](${botConfig.appUrl}/personnel/contacts/${doc.targetId})`,
inline: true,
});
}
return embed;
};
const poll = async (client: Client, payload: Payload): Promise<void> => {
if (running) return;
running = true;
try {
const channelId = botConfig.npcEventChannelId;
if (!channelId) return;
const res = await payload.find({
collection: "game-event-logs",
where: {
discordRequested: { equals: true },
discordAnnouncedAt: { exists: false },
},
sort: "timestamp",
limit: BATCH_LIMIT,
depth: 0,
overrideAccess: true,
});
if (res.docs.length === 0) return;
const channel = await client.channels.fetch(channelId);
if (!channel || !("send" in channel)) {
throw new Error(`[Bot] NPC dispatch channel ${channelId} is not a text channel.`);
}
const textChannel = channel as unknown as DispatchChannel;
let posted = 0;
for (const doc of res.docs.slice(0, MAX_POSTS_PER_TICK)) {
try {
const message = await textChannel.send({ embeds: [buildEmbed(doc)] });
await payload.update({
collection: "game-event-logs",
id: doc.id,
data: { discordAnnouncedAt: new Date().toISOString(), discordMessageId: message.id },
overrideAccess: true,
depth: 0,
});
posted += 1;
} catch (error) {
// Leave this entry queued so the next tick retries it.
payload.logger.error(
`[Bot] NPC dispatch post for event ${doc.id} failed: ${errorMessage(error)}`,
);
}
}
if (posted > 0) {
payload.logger.info(`[Bot] NPC dispatch announcements posted: ${posted}`);
}
} catch (error) {
payload.logger.error(`[Bot] NPC dispatch poll failed: ${errorMessage(error)}`);
} finally {
running = false;
}
};
export const start = (client: Client, payload: Payload): void => {
payload.logger.info("[Bot] NPC dispatch announcement service started");
void poll(client, payload);
setInterval(() => {
void poll(client, payload);
}, botConfig.npcEventPollMs);
};

View file

@ -173,5 +173,28 @@ export const GameEventLogs: CollectionConfig = {
name: "data",
type: "json",
},
{
name: "discordRequested",
type: "checkbox",
defaultValue: false,
index: true,
admin: {
description:
"Queued for the bot's NPC dispatch channel. Set at emit time by dialogue event effects; the poll service stamps the announcement columns once posted.",
},
},
{
name: "discordAnnouncedAt",
type: "date",
admin: {
readOnly: true,
description: "Set by the bot when the dispatch posts. Empty with a request above means queued or retrying.",
},
},
{
name: "discordMessageId",
type: "text",
admin: { readOnly: true, description: "Discord message id of the posted dispatch." },
},
],
};

View file

@ -651,6 +651,18 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
Show this event to everyone (normally staff only)
</label>
)}
{draft.effect && draft.effect.type !== "notify" && (
<label className="flex items-center gap-2 text-xs text-white/60">
<Checkbox
checked={draft.effect.discord === true}
onCheckedChange={(checked) =>
patchEffect({ discord: checked === true ? true : undefined })
}
className="border-white/30 data-[state=checked]:border-indigo-500 data-[state=checked]:bg-indigo-500"
/>
Post this event to the Discord NPC dispatch channel
</label>
)}
</div>
)}

View file

@ -114,6 +114,12 @@ export interface NpcDialogueEffect {
* in every member's event feed. Omitted means "use the default policy".
*/
eventVisibility?: "public" | "restricted";
/**
* Queue the emitted game-event entry for the bot's Discord NPC dispatch
* channel (emit, reward, flag). Reserve for milestone beats; the poll
* service posts the message once and stamps the log entry.
*/
discord?: boolean;
/** Flag key to write (flag). */
flagKey?: string;
/** Write mode (flag). */

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,17 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "game_event_logs" ADD COLUMN "discord_requested" boolean DEFAULT false;
ALTER TABLE "game_event_logs" ADD COLUMN "discord_announced_at" timestamp(3) with time zone;
ALTER TABLE "game_event_logs" ADD COLUMN "discord_message_id" varchar;
CREATE INDEX "game_event_logs_discord_requested_idx" ON "game_event_logs" USING btree ("discord_requested");`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
DROP INDEX "game_event_logs_discord_requested_idx";
ALTER TABLE "game_event_logs" DROP COLUMN "discord_requested";
ALTER TABLE "game_event_logs" DROP COLUMN "discord_announced_at";
ALTER TABLE "game_event_logs" DROP COLUMN "discord_message_id";`)
}

View file

@ -135,6 +135,7 @@ import * as migration_20261012_185409_add_award_rules_automation from './2026101
import * as migration_20261013_183041_add_journal_contribution_type from './20261013_183041_add_journal_contribution_type';
import * as migration_20261013_184745_add_garage_fields from './20261013_184745_add_garage_fields';
import * as migration_20261014_192950_add_npc_dialogue_states from './20261014_192950_add_npc_dialogue_states';
import * as migration_20261014_203529_add_event_log_discord_fields from './20261014_203529_add_event_log_discord_fields';
export const migrations = [
{
@ -820,6 +821,11 @@ export const migrations = [
{
up: migration_20261014_192950_add_npc_dialogue_states.up,
down: migration_20261014_192950_add_npc_dialogue_states.down,
name: '20261014_192950_add_npc_dialogue_states'
name: '20261014_192950_add_npc_dialogue_states',
},
{
up: migration_20261014_203529_add_event_log_discord_fields.up,
down: migration_20261014_203529_add_event_log_discord_fields.down,
name: '20261014_203529_add_event_log_discord_fields'
},
];

View file

@ -3241,6 +3241,18 @@ export interface GameEventLog {
| number
| boolean
| null;
/**
* Queued for the bot's NPC dispatch channel. Set at emit time by dialogue event effects; the poll service stamps the announcement columns once posted.
*/
discordRequested?: boolean | null;
/**
* Set by the bot when the dispatch posts. Empty with a request above means queued or retrying.
*/
discordAnnouncedAt?: string | null;
/**
* Discord message id of the posted dispatch.
*/
discordMessageId?: string | null;
updatedAt: string;
createdAt: string;
}
@ -9042,6 +9054,9 @@ export interface GameEventLogsSelect<T extends boolean = true> {
targetCollection?: T;
targetId?: T;
data?: T;
discordRequested?: T;
discordAnnouncedAt?: T;
discordMessageId?: T;
updatedAt?: T;
createdAt?: T;
}

View file

@ -67,6 +67,12 @@ interface GameEventInput {
visibility?: EventVisibility;
/** Any-of permission gate for restricted events. See `visibility`. */
requiredPermissions?: Permission[];
/**
* Queue this entry for the bot's NPC dispatch channel (the poll service
* posts it and stamps `discordAnnouncedAt`). Only meaningful for events
* worth broadcasting unit-wide; dialogue event effects set it per authoring.
*/
discordRequested?: boolean;
}
export async function emitGameEvent(
@ -92,6 +98,7 @@ export async function emitGameEvent(
structure: event.structure,
visibility: policy.visibility,
requiredPermissions: policy.requiredPermissions,
discordRequested: event.discordRequested === true,
},
depth: 0,
// Bins and tests run without an authenticated user; create access on

View file

@ -0,0 +1,79 @@
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
let payload: Payload;
const RUN = `evdisc-${Date.now().toString(36)}`;
const TIMEOUT = 30_000;
const eventIds: number[] = [];
/** Emit an event and return its persisted document. */
async function emit(input: Parameters<typeof emitGameEvent>[1]) {
await emitGameEvent(payload, input);
const res = await payload.find({
collection: "game-event-logs",
where: { message: { equals: input.message } },
sort: "-id",
limit: 1,
overrideAccess: true,
depth: 0,
});
const doc = res.docs[0];
expect(doc).toBeDefined();
eventIds.push(doc.id);
return doc;
}
describe("discordRequested flag on game events", () => {
beforeAll(async () => {
payload = await getPayload({ config });
}, TIMEOUT);
afterAll(async () => {
for (const id of eventIds) {
await payload
.delete({ collection: "game-event-logs", id, overrideAccess: true })
.catch(() => {});
}
});
it(
"persists discordRequested when the emitter opts in",
async () => {
const doc = await emit({
type: EventTypes.NpcDialogue,
message: `${RUN} opted in`,
discordRequested: true,
});
expect(doc.discordRequested).toBe(true);
// The bot stamps these only after posting; emitting must leave them clear.
expect(doc.discordAnnouncedAt).toBeFalsy();
expect(doc.discordMessageId).toBeFalsy();
},
TIMEOUT,
);
it(
"defaults to false when omitted or explicitly false",
async () => {
const omitted = await emit({
type: EventTypes.NpcDialogue,
message: `${RUN} omitted`,
});
expect(omitted.discordRequested).toBe(false);
const explicitFalse = await emit({
type: EventTypes.NpcDialogue,
message: `${RUN} explicit false`,
discordRequested: false,
});
expect(explicitFalse.discordRequested).toBe(false);
},
TIMEOUT,
);
});