import type { FastifyBaseLogger } from "fastify"; import type { SlackClient } from "../slack/slack.ts"; export type InviteCmd = { type: "invite"; channel: string; thread: string }; export async function handleInviteCommand({ cmd, slackClient, inviteChannel, log, }: { cmd: InviteCmd; slackClient: SlackClient; inviteChannel: string; log: FastifyBaseLogger; }): Promise { if (cmd.channel !== inviteChannel) { log.info({ channel: cmd.channel }, "invite: ignored outside invite channel"); return; } let parentText: string; try { parentText = (await slackClient.getThreadParent({ channel: cmd.channel, thread_ts: cmd.thread })).text; } catch (err) { log.error({ err, channel: cmd.channel, thread: cmd.thread }, "invite: getThreadParent failed"); await slackClient.sendMessage({ msg: "Couldn't look up the invite request. Try again or invite manually.", channel: cmd.channel, thread_ts: cmd.thread, }); return; } const email = extractEmail(parentText); if (!email) { log.warn({ channel: cmd.channel, thread: cmd.thread }, "invite: no email found in parent message"); await slackClient.sendMessage({ msg: "Couldn't find an email in the request message. Invite manually.", channel: cmd.channel, thread_ts: cmd.thread, }); return; } try { await slackClient.inviteUser({ email }); log.info({ email, channel: cmd.channel }, "invite: sent"); await slackClient.sendMessage({ msg: `Invited \`${email}\``, channel: cmd.channel, thread_ts: cmd.thread, }); } catch (err) { log.error({ err, email, channel: cmd.channel }, "invite: inviteUser failed"); await slackClient.sendMessage({ msg: `Invite failed for \`${email}\`: ${(err as Error).message}`, channel: cmd.channel, thread_ts: cmd.thread, }); } } export function extractEmail(text: string): string | undefined { // Slack auto-linkifies emails in message text to . const match = text.match(/^Email:\s*(?:]+)(?:\|[^>]*)?>|(.+))$/m); return (match?.[1] ?? match?.[2])?.trim().replace(/^`|`$/g, ""); }