Spaces:
Paused
Paused
File size: 8,664 Bytes
87fc763 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 | /**
* Twitch channel plugin for OpenClaw.
*
* Main plugin export combining all adapters (outbound, actions, status, gateway).
* This is the primary entry point for the Twitch channel integration.
*/
import type { OpenClawConfig } from "openclaw/plugin-sdk";
import { buildChannelConfigSchema } from "openclaw/plugin-sdk";
import type {
ChannelAccountSnapshot,
ChannelCapabilities,
ChannelLogSink,
ChannelMeta,
ChannelPlugin,
ChannelResolveKind,
ChannelResolveResult,
TwitchAccountConfig,
} from "./types.js";
import { twitchMessageActions } from "./actions.js";
import { removeClientManager } from "./client-manager-registry.js";
import { TwitchConfigSchema } from "./config-schema.js";
import { DEFAULT_ACCOUNT_ID, getAccountConfig, listAccountIds } from "./config.js";
import { twitchOnboardingAdapter } from "./onboarding.js";
import { twitchOutbound } from "./outbound.js";
import { probeTwitch } from "./probe.js";
import { resolveTwitchTargets } from "./resolver.js";
import { collectTwitchStatusIssues } from "./status.js";
import { resolveTwitchToken } from "./token.js";
import { isAccountConfigured } from "./utils/twitch.js";
/**
* Twitch channel plugin.
*
* Implements the ChannelPlugin interface to provide Twitch chat integration
* for OpenClaw. Supports message sending, receiving, access control, and
* status monitoring.
*/
export const twitchPlugin: ChannelPlugin<TwitchAccountConfig> = {
/** Plugin identifier */
id: "twitch",
/** Plugin metadata */
meta: {
id: "twitch",
label: "Twitch",
selectionLabel: "Twitch (Chat)",
docsPath: "/channels/twitch",
blurb: "Twitch chat integration",
aliases: ["twitch-chat"],
} satisfies ChannelMeta,
/** Onboarding adapter */
onboarding: twitchOnboardingAdapter,
/** Pairing configuration */
pairing: {
idLabel: "twitchUserId",
normalizeAllowEntry: (entry) => entry.replace(/^(twitch:)?user:?/i, ""),
notifyApproval: async ({ id }) => {
// Note: Twitch doesn't support DMs from bots, so pairing approval is limited
// We'll log the approval instead
console.warn(`Pairing approved for user ${id} (notification sent via chat if possible)`);
},
},
/** Supported chat capabilities */
capabilities: {
chatTypes: ["group"],
} satisfies ChannelCapabilities,
/** Configuration schema for Twitch channel */
configSchema: buildChannelConfigSchema(TwitchConfigSchema),
/** Account configuration management */
config: {
/** List all configured account IDs */
listAccountIds: (cfg: OpenClawConfig): string[] => listAccountIds(cfg),
/** Resolve an account config by ID */
resolveAccount: (cfg: OpenClawConfig, accountId?: string | null): TwitchAccountConfig => {
const account = getAccountConfig(cfg, accountId ?? DEFAULT_ACCOUNT_ID);
if (!account) {
// Return a default/empty account if not configured
return {
username: "",
accessToken: "",
clientId: "",
enabled: false,
} as TwitchAccountConfig;
}
return account;
},
/** Get the default account ID */
defaultAccountId: (): string => DEFAULT_ACCOUNT_ID,
/** Check if an account is configured */
isConfigured: (_account: unknown, cfg: OpenClawConfig): boolean => {
const account = getAccountConfig(cfg, DEFAULT_ACCOUNT_ID);
const tokenResolution = resolveTwitchToken(cfg, { accountId: DEFAULT_ACCOUNT_ID });
return account ? isAccountConfigured(account, tokenResolution.token) : false;
},
/** Check if an account is enabled */
isEnabled: (account: TwitchAccountConfig | undefined): boolean => account?.enabled !== false,
/** Describe account status */
describeAccount: (account: TwitchAccountConfig | undefined) => {
return {
accountId: DEFAULT_ACCOUNT_ID,
enabled: account?.enabled !== false,
configured: account ? isAccountConfigured(account, account?.accessToken) : false,
};
},
},
/** Outbound message adapter */
outbound: twitchOutbound,
/** Message actions adapter */
actions: twitchMessageActions,
/** Resolver adapter for username -> user ID resolution */
resolver: {
resolveTargets: async ({
cfg,
accountId,
inputs,
kind,
runtime,
}: {
cfg: OpenClawConfig;
accountId?: string | null;
inputs: string[];
kind: ChannelResolveKind;
runtime: import("../../../src/runtime.js").RuntimeEnv;
}): Promise<ChannelResolveResult[]> => {
const account = getAccountConfig(cfg, accountId ?? DEFAULT_ACCOUNT_ID);
if (!account) {
return inputs.map((input) => ({
input,
resolved: false,
note: "account not configured",
}));
}
// Adapt RuntimeEnv.log to ChannelLogSink
const log: ChannelLogSink = {
info: (msg) => runtime.log(msg),
warn: (msg) => runtime.log(msg),
error: (msg) => runtime.error(msg),
debug: (msg) => runtime.log(msg),
};
return await resolveTwitchTargets(inputs, account, kind, log);
},
},
/** Status monitoring adapter */
status: {
/** Default runtime state */
defaultRuntime: {
accountId: DEFAULT_ACCOUNT_ID,
running: false,
lastStartAt: null,
lastStopAt: null,
lastError: null,
},
/** Build channel summary from snapshot */
buildChannelSummary: ({ snapshot }: { snapshot: ChannelAccountSnapshot }) => ({
configured: snapshot.configured ?? false,
running: snapshot.running ?? false,
lastStartAt: snapshot.lastStartAt ?? null,
lastStopAt: snapshot.lastStopAt ?? null,
lastError: snapshot.lastError ?? null,
probe: snapshot.probe,
lastProbeAt: snapshot.lastProbeAt ?? null,
}),
/** Probe account connection */
probeAccount: async ({
account,
timeoutMs,
}: {
account: TwitchAccountConfig;
timeoutMs: number;
}): Promise<unknown> => {
return await probeTwitch(account, timeoutMs);
},
/** Build account snapshot with current status */
buildAccountSnapshot: ({
account,
cfg,
runtime,
probe,
}: {
account: TwitchAccountConfig;
cfg: OpenClawConfig;
runtime?: ChannelAccountSnapshot;
probe?: unknown;
}): ChannelAccountSnapshot => {
const twitch = (cfg as Record<string, unknown>).channels as
| Record<string, unknown>
| undefined;
const twitchCfg = twitch?.twitch as Record<string, unknown> | undefined;
const accountMap = (twitchCfg?.accounts as Record<string, unknown> | undefined) ?? {};
const resolvedAccountId =
Object.entries(accountMap).find(([, value]) => value === account)?.[0] ??
DEFAULT_ACCOUNT_ID;
const tokenResolution = resolveTwitchToken(cfg, { accountId: resolvedAccountId });
return {
accountId: resolvedAccountId,
enabled: account?.enabled !== false,
configured: isAccountConfigured(account, tokenResolution.token),
running: runtime?.running ?? false,
lastStartAt: runtime?.lastStartAt ?? null,
lastStopAt: runtime?.lastStopAt ?? null,
lastError: runtime?.lastError ?? null,
probe,
};
},
/** Collect status issues for all accounts */
collectStatusIssues: collectTwitchStatusIssues,
},
/** Gateway adapter for connection lifecycle */
gateway: {
/** Start an account connection */
startAccount: async (ctx): Promise<void> => {
const account = ctx.account;
const accountId = ctx.accountId;
ctx.setStatus?.({
accountId,
running: true,
lastStartAt: Date.now(),
lastError: null,
});
ctx.log?.info(`Starting Twitch connection for ${account.username}`);
// Lazy import: the monitor pulls the reply pipeline; avoid ESM init cycles.
const { monitorTwitchProvider } = await import("./monitor.js");
await monitorTwitchProvider({
account,
accountId,
config: ctx.cfg,
runtime: ctx.runtime,
abortSignal: ctx.abortSignal,
});
},
/** Stop an account connection */
stopAccount: async (ctx): Promise<void> => {
const account = ctx.account;
const accountId = ctx.accountId;
// Disconnect and remove client manager from registry
await removeClientManager(accountId);
ctx.setStatus?.({
accountId,
running: false,
lastStopAt: Date.now(),
});
ctx.log?.info(`Stopped Twitch connection for ${account.username}`);
},
},
};
|