Files
Dirigent/plugin/channel-resolver.ts

74 lines
2.2 KiB
TypeScript

export function extractDiscordChannelId(ctx: Record<string, unknown>, event?: Record<string, unknown>): string | undefined {
const candidates: unknown[] = [
ctx.conversationId,
ctx.OriginatingTo,
event?.to,
(event?.metadata as Record<string, unknown>)?.to,
];
for (const c of candidates) {
if (typeof c !== "string" || !c.trim()) continue;
const s = c.trim();
if (s.startsWith("channel:")) {
const id = s.slice("channel:".length);
if (/^\d+$/.test(id)) return id;
}
if (s.startsWith("discord:channel:")) {
const id = s.slice("discord:channel:".length);
if (/^\d+$/.test(id)) return id;
}
if (/^\d{15,}$/.test(s)) return s;
}
return undefined;
}
export function extractDiscordChannelIdFromSessionKey(sessionKey?: string): string | undefined {
if (!sessionKey) return undefined;
const canonical = sessionKey.match(/discord:(?:channel|group):(\d+)/);
if (canonical?.[1]) return canonical[1];
const suffix = sessionKey.match(/:channel:(\d+)$/);
if (suffix?.[1]) return suffix[1];
return undefined;
}
export function extractUntrustedConversationInfo(text: string): Record<string, unknown> | undefined {
const marker = "Conversation info (untrusted metadata):";
const idx = text.indexOf(marker);
if (idx < 0) return undefined;
const tail = text.slice(idx + marker.length);
const m = tail.match(/```json\s*([\s\S]*?)\s*```/i);
if (!m) return undefined;
try {
const parsed = JSON.parse(m[1]);
return parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : undefined;
} catch {
return undefined;
}
}
export function extractDiscordChannelIdFromConversationMetadata(conv: Record<string, unknown>): string | undefined {
if (typeof conv.chat_id === "string" && conv.chat_id.startsWith("channel:")) {
const id = conv.chat_id.slice("channel:".length);
if (/^\d+$/.test(id)) return id;
}
if (typeof conv.conversation_label === "string") {
const labelMatch = conv.conversation_label.match(/channel id:(\d+)/);
if (labelMatch?.[1]) return labelMatch[1];
}
if (typeof conv.channel_id === "string" && /^\d+$/.test(conv.channel_id)) {
return conv.channel_id;
}
return undefined;
}