Add shared Discord persona webhook pipe
This commit is contained in:
parent
c2ac081712
commit
97650aaafe
8 changed files with 603 additions and 17 deletions
|
|
@ -1,3 +1,31 @@
|
|||
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
|
||||
const PERSONA_WEBHOOK_NAME = "VoidBot Persona Pipe";
|
||||
const PERSONA_WEBHOOK_CACHE_PATH = resolve(
|
||||
__dirname,
|
||||
"../../../.voidbot/private/discord-webhook-cache.json",
|
||||
);
|
||||
const THREAD_CHANNEL_TYPES = new Set([10, 11, 12]);
|
||||
|
||||
export interface DiscordPersonaOptions {
|
||||
personaName?: string;
|
||||
personaAvatarUrl?: string;
|
||||
}
|
||||
|
||||
interface NormalizedDiscordPersonaOptions {
|
||||
personaName: string;
|
||||
personaAvatarUrl?: string;
|
||||
}
|
||||
|
||||
interface CachedWebhookRecord {
|
||||
id: string;
|
||||
token: string;
|
||||
channelId: string;
|
||||
name: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export async function openOwnerDmChannel(
|
||||
botToken: string,
|
||||
recipientId: string,
|
||||
|
|
@ -31,7 +59,20 @@ export async function postDiscordMessage(
|
|||
channelId: string,
|
||||
content: string,
|
||||
replyToMessageId?: string,
|
||||
): Promise<{ id: string }> {
|
||||
persona?: DiscordPersonaOptions,
|
||||
): Promise<{ id: string; transport: "bot" | "webhook" }> {
|
||||
const normalizedPersona = normalizePersonaOptions(persona);
|
||||
|
||||
if (normalizedPersona) {
|
||||
return postDiscordPersonaMessage(
|
||||
botToken,
|
||||
channelId,
|
||||
content,
|
||||
normalizedPersona,
|
||||
replyToMessageId,
|
||||
);
|
||||
}
|
||||
|
||||
const response = await fetch(`https://discord.com/api/v10/channels/${channelId}/messages`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
|
|
@ -62,5 +103,270 @@ export async function postDiscordMessage(
|
|||
throw new Error("Discord message post returned no message id.");
|
||||
}
|
||||
|
||||
return { id: payload.id };
|
||||
return { id: payload.id, transport: "bot" };
|
||||
}
|
||||
|
||||
async function postDiscordPersonaMessage(
|
||||
botToken: string,
|
||||
channelId: string,
|
||||
content: string,
|
||||
persona: NormalizedDiscordPersonaOptions,
|
||||
replyToMessageId?: string,
|
||||
): Promise<{ id: string; transport: "webhook" }> {
|
||||
const target = await resolveWebhookTarget(botToken, channelId);
|
||||
let webhook = getCachedPersonaWebhook(target.webhookChannelId);
|
||||
|
||||
if (!webhook) {
|
||||
webhook = await createPersonaWebhook(botToken, target.webhookChannelId);
|
||||
writeCachedPersonaWebhook(target.webhookChannelId, webhook);
|
||||
}
|
||||
|
||||
try {
|
||||
return await executePersonaWebhook(webhook, {
|
||||
threadId: target.threadId,
|
||||
content,
|
||||
replyToMessageId,
|
||||
username: persona.personaName,
|
||||
avatarUrl: persona.personaAvatarUrl,
|
||||
});
|
||||
} catch (error) {
|
||||
if (!isStaleWebhookError(error)) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
clearCachedPersonaWebhook(target.webhookChannelId);
|
||||
const refreshedWebhook = await createPersonaWebhook(botToken, target.webhookChannelId);
|
||||
writeCachedPersonaWebhook(target.webhookChannelId, refreshedWebhook);
|
||||
return executePersonaWebhook(refreshedWebhook, {
|
||||
threadId: target.threadId,
|
||||
content,
|
||||
replyToMessageId,
|
||||
username: persona.personaName,
|
||||
avatarUrl: persona.personaAvatarUrl,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveWebhookTarget(botToken: string, channelId: string): Promise<{
|
||||
webhookChannelId: string;
|
||||
threadId?: string;
|
||||
}> {
|
||||
const channel = await getDiscordChannel(botToken, channelId);
|
||||
|
||||
if (THREAD_CHANNEL_TYPES.has(channel.type)) {
|
||||
if (!channel.parent_id) {
|
||||
throw new Error(`Discord thread ${channelId} has no parent channel for webhook routing.`);
|
||||
}
|
||||
|
||||
return {
|
||||
webhookChannelId: channel.parent_id,
|
||||
threadId: channel.id,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
webhookChannelId: channel.id,
|
||||
threadId: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async function getDiscordChannel(
|
||||
botToken: string,
|
||||
channelId: string,
|
||||
): Promise<{ id: string; type: number; parent_id?: string }> {
|
||||
const response = await fetch(`https://discord.com/api/v10/channels/${channelId}`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Authorization: `Bot ${botToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch Discord channel: ${response.status} ${await response.text()}`);
|
||||
}
|
||||
|
||||
const payload = (await response.json()) as { id?: string; type?: number; parent_id?: string };
|
||||
|
||||
if (!payload.id || typeof payload.type !== "number") {
|
||||
throw new Error(`Discord channel lookup for ${channelId} returned malformed data.`);
|
||||
}
|
||||
|
||||
return {
|
||||
id: payload.id,
|
||||
type: payload.type,
|
||||
parent_id: payload.parent_id,
|
||||
};
|
||||
}
|
||||
|
||||
async function createPersonaWebhook(
|
||||
botToken: string,
|
||||
channelId: string,
|
||||
): Promise<CachedWebhookRecord> {
|
||||
const response = await fetch(`https://discord.com/api/v10/channels/${channelId}/webhooks`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bot ${botToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: PERSONA_WEBHOOK_NAME,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to create Discord webhook: ${response.status} ${await response.text()}`);
|
||||
}
|
||||
|
||||
const payload = (await response.json()) as { id?: string; token?: string };
|
||||
|
||||
if (!payload.id || !payload.token) {
|
||||
throw new Error(`Discord webhook creation for channel ${channelId} returned no executable token.`);
|
||||
}
|
||||
|
||||
return {
|
||||
id: payload.id,
|
||||
token: payload.token,
|
||||
channelId,
|
||||
name: PERSONA_WEBHOOK_NAME,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
async function executePersonaWebhook(
|
||||
webhook: CachedWebhookRecord,
|
||||
{
|
||||
threadId,
|
||||
content,
|
||||
replyToMessageId,
|
||||
username,
|
||||
avatarUrl,
|
||||
}: {
|
||||
threadId?: string;
|
||||
content: string;
|
||||
replyToMessageId?: string;
|
||||
username: string;
|
||||
avatarUrl?: string;
|
||||
},
|
||||
): Promise<{ id: string; transport: "webhook" }> {
|
||||
const url = new URL(`https://discord.com/api/v10/webhooks/${webhook.id}/${webhook.token}`);
|
||||
url.searchParams.set("wait", "true");
|
||||
|
||||
if (threadId) {
|
||||
url.searchParams.set("thread_id", threadId);
|
||||
}
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
content,
|
||||
username,
|
||||
avatar_url: avatarUrl,
|
||||
message_reference: replyToMessageId
|
||||
? {
|
||||
message_id: replyToMessageId,
|
||||
fail_if_not_exists: false,
|
||||
}
|
||||
: undefined,
|
||||
allowed_mentions: {
|
||||
parse: [],
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to execute Discord webhook: ${response.status} ${await response.text()}`);
|
||||
}
|
||||
|
||||
const payload = (await response.json()) as { id?: string };
|
||||
|
||||
if (!payload.id) {
|
||||
throw new Error("Discord webhook execution returned no message id.");
|
||||
}
|
||||
|
||||
return { id: payload.id, transport: "webhook" };
|
||||
}
|
||||
|
||||
function normalizePersonaOptions(
|
||||
options?: DiscordPersonaOptions,
|
||||
): NormalizedDiscordPersonaOptions | undefined {
|
||||
const personaName = trimOptionalString(options?.personaName);
|
||||
const personaAvatarUrl = trimOptionalString(options?.personaAvatarUrl);
|
||||
|
||||
if (!personaName && !personaAvatarUrl) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (!personaName) {
|
||||
throw new Error("personaName is required when posting through the shared persona webhook pipe.");
|
||||
}
|
||||
|
||||
return {
|
||||
personaName: personaName.slice(0, 80),
|
||||
personaAvatarUrl,
|
||||
};
|
||||
}
|
||||
|
||||
function trimOptionalString(value?: string): string | undefined {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
function getCachedPersonaWebhook(channelId: string): CachedWebhookRecord | undefined {
|
||||
const cache = readPersonaWebhookCache();
|
||||
return cache[channelId];
|
||||
}
|
||||
|
||||
function writeCachedPersonaWebhook(channelId: string, webhook: CachedWebhookRecord): void {
|
||||
const cache = readPersonaWebhookCache();
|
||||
cache[channelId] = webhook;
|
||||
writePersonaWebhookCache(cache);
|
||||
}
|
||||
|
||||
function clearCachedPersonaWebhook(channelId: string): void {
|
||||
const cache = readPersonaWebhookCache();
|
||||
if (cache[channelId]) {
|
||||
delete cache[channelId];
|
||||
writePersonaWebhookCache(cache);
|
||||
}
|
||||
}
|
||||
|
||||
function readPersonaWebhookCache(): Record<string, CachedWebhookRecord> {
|
||||
try {
|
||||
const raw = stripLeadingBom(readFileSync(PERSONA_WEBHOOK_CACHE_PATH, "utf8"));
|
||||
const parsed = JSON.parse(raw) as Record<string, CachedWebhookRecord> | null;
|
||||
return parsed && typeof parsed === "object" ? parsed : {};
|
||||
} catch (error) {
|
||||
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
|
||||
return {};
|
||||
}
|
||||
|
||||
if (error instanceof SyntaxError) {
|
||||
return {};
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function writePersonaWebhookCache(cache: Record<string, CachedWebhookRecord>): void {
|
||||
mkdirSync(dirname(PERSONA_WEBHOOK_CACHE_PATH), { recursive: true });
|
||||
writeFileSync(PERSONA_WEBHOOK_CACHE_PATH, `${JSON.stringify(cache, null, 2)}\n`, "utf8");
|
||||
}
|
||||
|
||||
function stripLeadingBom(input: string): string {
|
||||
return input.charCodeAt(0) === 0xfeff ? input.slice(1) : input;
|
||||
}
|
||||
|
||||
function isStaleWebhookError(error: unknown): boolean {
|
||||
if (!(error instanceof Error)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
error.message.includes("Failed to execute Discord webhook: 401") ||
|
||||
error.message.includes("Failed to execute Discord webhook: 404")
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,6 +28,8 @@ export const postDiscordMessageInputSchema = {
|
|||
channelId: z.string().min(1),
|
||||
content: z.string().min(1).max(1800),
|
||||
replyToMessageId: z.string().min(1).optional(),
|
||||
personaName: z.string().min(1).max(80).optional(),
|
||||
personaAvatarUrl: z.string().url().max(512).optional(),
|
||||
};
|
||||
|
||||
export const searchSourcesInputSchema = {
|
||||
|
|
@ -67,6 +69,8 @@ export interface PostDiscordMessageArgs {
|
|||
channelId: string;
|
||||
content: string;
|
||||
replyToMessageId?: string;
|
||||
personaName?: string;
|
||||
personaAvatarUrl?: string;
|
||||
}
|
||||
|
||||
export interface ListIndexedReposArgs {
|
||||
|
|
|
|||
|
|
@ -301,7 +301,7 @@ export function registerVoidbotTools(
|
|||
{
|
||||
title: "Post Discord Message",
|
||||
description:
|
||||
"Post a message to a Discord channel or thread as Void. Use this for constructive proactive participation, moderation nudges, or replies when speaking in-channel would genuinely help. Set replyToMessageId to reply to a specific message; omit it for a fresh post.",
|
||||
"Post a message to a Discord channel or thread. Use this for constructive proactive participation, moderation nudges, or replies when speaking in-channel would genuinely help. Set replyToMessageId to reply to a specific message; omit it for a fresh post. Supply personaName and optional personaAvatarUrl when an agent should speak through the shared webhook pipe as itself instead of the base bot identity.",
|
||||
inputSchema: postDiscordMessageInputSchema,
|
||||
annotations: {
|
||||
readOnlyHint: false,
|
||||
|
|
@ -311,7 +311,7 @@ export function registerVoidbotTools(
|
|||
},
|
||||
},
|
||||
async (input: PostDiscordMessageArgs): Promise<CallToolResult> => {
|
||||
const { channelId, content, replyToMessageId } = input;
|
||||
const { channelId, content, replyToMessageId, personaName, personaAvatarUrl } = input;
|
||||
|
||||
if (!context.config.botToken) {
|
||||
return {
|
||||
|
|
@ -335,21 +335,29 @@ export function registerVoidbotTools(
|
|||
channelId,
|
||||
content,
|
||||
replyToMessageId,
|
||||
{
|
||||
personaName,
|
||||
personaAvatarUrl,
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: replyToMessageId
|
||||
? `Posted a reply in Discord channel ${channelId} as message ${posted.id}.`
|
||||
: `Posted a message in Discord channel ${channelId} as message ${posted.id}.`,
|
||||
text:
|
||||
replyToMessageId
|
||||
? `Posted a reply in Discord channel ${channelId} as message ${posted.id} via ${posted.transport}.`
|
||||
: `Posted a message in Discord channel ${channelId} as message ${posted.id} via ${posted.transport}.`,
|
||||
},
|
||||
],
|
||||
structuredContent: {
|
||||
sent: true,
|
||||
channelId,
|
||||
messageId: posted.id,
|
||||
transport: posted.transport,
|
||||
personaName: personaName ?? null,
|
||||
personaAvatarUrl: personaAvatarUrl ?? null,
|
||||
replyToMessageId: replyToMessageId ?? null,
|
||||
},
|
||||
};
|
||||
|
|
|
|||
Loading…
Reference in a new issue