import type { AppMentionEvent } from "@slack/web-api"; import type { FastifyBaseLogger } from "fastify"; import type { EventsClient } from "../events/events.ts"; import { handleEventsCommand, type EventsCmd } from "./events.ts"; import { handleInviteCommand, type InviteCmd } from "./invites.ts"; import type { SlackClient } from "../slack/slack.ts"; import { withSpan } from "../telemetry.ts"; interface CommandHandler { handleBotMention(msg: AppMentionEvent, log: FastifyBaseLogger): Promise; } interface CommandHandlerDeps { eventsClient: EventsClient; slackClient: SlackClient; inviteChannel: string; } type Command = EventsCmd | InviteCmd; export function newCommandHandler(deps: CommandHandlerDeps): CommandHandler { function msgToCommand(msg: AppMentionEvent): Command | null { const msgSansBot = msg.text?.replace(/^<@.+>\s+/, ""); if (msgSansBot?.startsWith("!events")) { return { type: "events", channel: msg.channel, thread: msg.thread_ts ?? msg.ts }; } if (msgSansBot?.startsWith("!invite") && msg.thread_ts) { return { type: "invite", channel: msg.channel, thread: msg.thread_ts }; } return null; } return { async handleBotMention(msg: AppMentionEvent, log: FastifyBaseLogger): Promise { const cmd = msgToCommand(msg); if (!cmd) { log.info({ text: msg.text }, "command: message did not match any command"); return; } log.info({ command: cmd.type, channel: cmd.channel }, "command: dispatching"); await withSpan( "command.handle", { "command.type": cmd.type, "slack.channel": cmd.channel }, async () => { switch (cmd.type) { case "events": await handleEventsCommand({ cmd, ...deps, log }); break; case "invite": await handleInviteCommand({ cmd, slackClient: deps.slackClient, inviteChannel: deps.inviteChannel, log, }); break; } }, ); }, }; }