50 lines
1.7 KiB
TypeScript
50 lines
1.7 KiB
TypeScript
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
|
|
|
|
function userIdFromToken(token: string): string | undefined {
|
|
try {
|
|
const segment = token.split(".")[0];
|
|
const padded = segment + "=".repeat((4 - (segment.length % 4)) % 4);
|
|
return Buffer.from(padded, "base64").toString("utf8");
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
export function resolveDiscordUserId(api: OpenClawPluginApi, accountId: string): string | undefined {
|
|
const root = (api.config as Record<string, unknown>) || {};
|
|
const channels = (root.channels as Record<string, unknown>) || {};
|
|
const discord = (channels.discord as Record<string, unknown>) || {};
|
|
const accounts = (discord.accounts as Record<string, Record<string, unknown>>) || {};
|
|
const acct = accounts[accountId];
|
|
if (!acct?.token || typeof acct.token !== "string") return undefined;
|
|
return userIdFromToken(acct.token);
|
|
}
|
|
|
|
export async function sendModeratorMessage(
|
|
token: string,
|
|
channelId: string,
|
|
content: string,
|
|
logger: { info: (msg: string) => void; warn: (msg: string) => void },
|
|
): Promise<boolean> {
|
|
try {
|
|
const r = await fetch(`https://discord.com/api/v10/channels/${channelId}/messages`, {
|
|
method: "POST",
|
|
headers: {
|
|
Authorization: `Bot ${token}`,
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({ content }),
|
|
});
|
|
if (!r.ok) {
|
|
const text = await r.text();
|
|
logger.warn(`dirigent: moderator send failed (${r.status}): ${text}`);
|
|
return false;
|
|
}
|
|
logger.info(`dirigent: moderator message sent to channel=${channelId}`);
|
|
return true;
|
|
} catch (err) {
|
|
logger.warn(`dirigent: moderator send error: ${String(err)}`);
|
|
return false;
|
|
}
|
|
}
|