import type { OpenClawPluginApi } from "openclaw/plugin-sdk"; import type { DirigentConfig } from "../rules.js"; type DiscordControlAction = "channel-private-create" | "channel-private-update"; type ToolDeps = { api: OpenClawPluginApi; baseConfig: DirigentConfig; pickDefined: (obj: Record) => Record; getLivePluginConfig: (api: OpenClawPluginApi, fallback: DirigentConfig) => DirigentConfig; }; function parseAccountToken(api: OpenClawPluginApi, accountId?: string): { accountId: string; token: string } | null { const root = (api.config as Record) || {}; const channels = (root.channels as Record) || {}; const discord = (channels.discord as Record) || {}; const accounts = (discord.accounts as Record>) || {}; if (accountId && accounts[accountId] && typeof accounts[accountId].token === "string") { return { accountId, token: accounts[accountId].token as string }; } for (const [aid, rec] of Object.entries(accounts)) { if (typeof rec?.token === "string" && rec.token) return { accountId: aid, token: rec.token }; } return null; } async function discordRequest(token: string, method: string, path: string, body?: unknown): Promise<{ ok: boolean; status: number; text: string; json: any }> { const r = await fetch(`https://discord.com/api/v10${path}`, { method, headers: { Authorization: `Bot ${token}`, "Content-Type": "application/json", }, body: body === undefined ? undefined : JSON.stringify(body), }); const text = await r.text(); let json: any = null; try { json = text ? JSON.parse(text) : null; } catch { json = null; } return { ok: r.ok, status: r.status, text, json }; } function roleOrMemberType(v: unknown): number { if (typeof v === "number") return v; if (typeof v === "string" && v.toLowerCase() === "member") return 1; return 0; } export function registerDirigentTools(deps: ToolDeps): void { const { api, baseConfig, pickDefined, getLivePluginConfig } = deps; async function executeDiscordAction(action: DiscordControlAction, params: Record) { const live = getLivePluginConfig(api, baseConfig as DirigentConfig) as DirigentConfig & { enableDiscordControlTool?: boolean; discordControlAccountId?: string; }; if (live.enableDiscordControlTool === false) { return { content: [{ type: "text", text: "discord actions disabled by config" }], isError: true }; } const selected = parseAccountToken(api, (params.accountId as string | undefined) || live.discordControlAccountId); if (!selected) { return { content: [{ type: "text", text: "no Discord bot token found in channels.discord.accounts" }], isError: true }; } const token = selected.token; if (action === "channel-private-create") { const guildId = String(params.guildId || "").trim(); const name = String(params.name || "").trim(); if (!guildId || !name) return { content: [{ type: "text", text: "guildId and name are required" }], isError: true }; const allowedUserIds = Array.isArray(params.allowedUserIds) ? params.allowedUserIds.map(String) : []; const allowedRoleIds = Array.isArray(params.allowedRoleIds) ? params.allowedRoleIds.map(String) : []; const allowMask = String(params.allowMask || "1024"); const denyEveryoneMask = String(params.denyEveryoneMask || "1024"); const overwrites: any[] = [ { id: guildId, type: 0, allow: "0", deny: denyEveryoneMask }, ...allowedRoleIds.map((id) => ({ id, type: 0, allow: allowMask, deny: "0" })), ...allowedUserIds.map((id) => ({ id, type: 1, allow: allowMask, deny: "0" })), ]; const body = pickDefined({ name, type: typeof params.type === "number" ? params.type : 0, parent_id: params.parentId, topic: params.topic, position: params.position, nsfw: params.nsfw, permission_overwrites: overwrites, }); const resp = await discordRequest(token, "POST", `/guilds/${guildId}/channels`, body); if (!resp.ok) return { content: [{ type: "text", text: `discord action failed (${resp.status}): ${resp.text}` }], isError: true }; return { content: [{ type: "text", text: JSON.stringify({ ok: true, accountId: selected.accountId, channel: resp.json }, null, 2) }] }; } const channelId = String(params.channelId || "").trim(); if (!channelId) return { content: [{ type: "text", text: "channelId is required" }], isError: true }; const mode = String(params.mode || "merge").toLowerCase() === "replace" ? "replace" : "merge"; const addUserIds = Array.isArray(params.addUserIds) ? params.addUserIds.map(String) : []; const addRoleIds = Array.isArray(params.addRoleIds) ? params.addRoleIds.map(String) : []; const removeTargetIds = Array.isArray(params.removeTargetIds) ? params.removeTargetIds.map(String) : []; const allowMask = String(params.allowMask || "1024"); const denyMask = String(params.denyMask || "0"); const ch = await discordRequest(token, "GET", `/channels/${channelId}`); if (!ch.ok) return { content: [{ type: "text", text: `discord action failed (${ch.status}): ${ch.text}` }], isError: true }; const current = Array.isArray(ch.json?.permission_overwrites) ? [...ch.json.permission_overwrites] : []; const guildId = String(ch.json?.guild_id || ""); const everyone = current.find((x: any) => String(x?.id || "") === guildId && roleOrMemberType(x?.type) === 0); let next: any[] = mode === "replace" ? (everyone ? [everyone] : []) : current.filter((x: any) => !removeTargetIds.includes(String(x?.id || ""))); for (const id of addRoleIds) { next = next.filter((x: any) => String(x?.id || "") !== id); next.push({ id, type: 0, allow: allowMask, deny: denyMask }); } for (const id of addUserIds) { next = next.filter((x: any) => String(x?.id || "") !== id); next.push({ id, type: 1, allow: allowMask, deny: denyMask }); } const resp = await discordRequest(token, "PATCH", `/channels/${channelId}`, { permission_overwrites: next }); if (!resp.ok) return { content: [{ type: "text", text: `discord action failed (${resp.status}): ${resp.text}` }], isError: true }; return { content: [{ type: "text", text: JSON.stringify({ ok: true, accountId: selected.accountId, channel: resp.json }, null, 2) }] }; } api.registerTool({ name: "discord_channel_create", description: "Create a private Discord channel with specific user/role permissions.", parameters: { type: "object", additionalProperties: false, properties: { accountId: { type: "string" }, guildId: { type: "string" }, name: { type: "string" }, type: { type: "number" }, parentId: { type: "string" }, topic: { type: "string" }, position: { type: "number" }, nsfw: { type: "boolean" }, allowedUserIds: { type: "array", items: { type: "string" } }, allowedRoleIds: { type: "array", items: { type: "string" } }, allowMask: { type: "string" }, denyEveryoneMask: { type: "string" }, }, required: [], }, async execute(_id: string, params: Record) { return executeDiscordAction("channel-private-create", params); }, }, { optional: false }); api.registerTool({ name: "discord_channel_update", description: "Update permissions on an existing private Discord channel.", parameters: { type: "object", additionalProperties: false, properties: { accountId: { type: "string" }, channelId: { type: "string" }, mode: { type: "string", enum: ["merge", "replace"] }, addUserIds: { type: "array", items: { type: "string" } }, addRoleIds: { type: "array", items: { type: "string" } }, removeTargetIds: { type: "array", items: { type: "string" } }, allowMask: { type: "string" }, denyMask: { type: "string" }, }, required: [], }, async execute(_id: string, params: Record) { return executeDiscordAction("channel-private-update", params); }, }, { optional: false }); }