remove duplicate log tags + log received messages

This commit is contained in:
jaydenfyi 2026-01-25 19:15:42 +08:00
parent 80fc5babd1
commit 5a155697fa
6 changed files with 58 additions and 58 deletions

View File

@ -52,7 +52,7 @@ export function getOrCreateClientManager(
createdAt: Date.now(), createdAt: Date.now(),
}); });
logger.info(`[twitch] Registered client manager for account: ${accountId}`); logger.info(`Registered client manager for account: ${accountId}`);
return manager; return manager;
} }
@ -83,7 +83,7 @@ export async function removeClientManager(accountId: string): Promise<void> {
// Remove from registry // Remove from registry
registry.delete(accountId); registry.delete(accountId);
entry.logger.info(`[twitch] Unregistered client manager for account: ${accountId}`); entry.logger.info(`Unregistered client manager for account: ${accountId}`);
} }
/** /**

View File

@ -95,7 +95,7 @@ async function processTwitchMessage(params: {
sessionKey: ctxPayload.SessionKey ?? route.sessionKey, sessionKey: ctxPayload.SessionKey ?? route.sessionKey,
ctx: ctxPayload, ctx: ctxPayload,
onRecordError: (err) => { onRecordError: (err) => {
runtime.error?.(`[twitch] Failed updating session meta: ${String(err)}`); runtime.error?.(`Failed updating session meta: ${String(err)}`);
}, },
}); });
@ -144,10 +144,10 @@ async function deliverTwitchReply(params: {
try { try {
const clientManager = getOrCreateClientManager(accountId, { const clientManager = getOrCreateClientManager(accountId, {
info: (msg) => runtime.log?.(`[twitch] ${msg}`), info: (msg) => runtime.log?.(msg),
warn: (msg) => runtime.log?.(`[twitch] ${msg}`), warn: (msg) => runtime.log?.(msg),
error: (msg) => runtime.error?.(`[twitch] ${msg}`), error: (msg) => runtime.error?.(msg),
debug: (msg) => runtime.log?.(`[twitch] ${msg}`), debug: (msg) => runtime.log?.(msg),
}); });
const client = await clientManager.getClient( const client = await clientManager.getClient(
@ -156,19 +156,19 @@ async function deliverTwitchReply(params: {
accountId, accountId,
); );
if (!client) { if (!client) {
runtime.error?.(`[twitch] No client available for sending reply`); runtime.error?.(`No client available for sending reply`);
return; return;
} }
// Send the reply // Send the reply
if (!payload.text) { if (!payload.text) {
runtime.error?.(`[twitch] No text to send in reply payload`); runtime.error?.(`No text to send in reply payload`);
return; return;
} }
await client.say(channel, payload.text); await client.say(channel, payload.text);
statusSink?.({ lastOutboundAt: Date.now() }); statusSink?.({ lastOutboundAt: Date.now() });
} catch (err) { } catch (err) {
runtime.error?.(`[twitch] Failed to send reply: ${String(err)}`); runtime.error?.(`Failed to send reply: ${String(err)}`);
} }
} }
@ -186,10 +186,10 @@ export async function monitorTwitchProvider(
let stopped = false; let stopped = false;
const logger = { const logger = {
info: (msg: string) => runtime.log?.(`[twitch] ${msg}`), info: (msg: string) => runtime.log?.(msg),
warn: (msg: string) => runtime.log?.(`[twitch] ${msg}`), warn: (msg: string) => runtime.log?.(msg),
error: (msg: string) => runtime.error?.(`[twitch] ${msg}`), error: (msg: string) => runtime.error?.(msg),
debug: (msg: string) => runtime.log?.(`[twitch] ${msg}`), debug: (msg: string) => runtime.log?.(msg),
}; };
const clientManager = getOrCreateClientManager(accountId, logger); const clientManager = getOrCreateClientManager(accountId, logger);
@ -200,10 +200,10 @@ export async function monitorTwitchProvider(
config as Parameters<typeof clientManager.getClient>[1], config as Parameters<typeof clientManager.getClient>[1],
accountId, accountId,
); );
runtime.log?.(`[twitch] Connected to Twitch as ${account.username}`); runtime.log?.(`Connected to Twitch as ${account.username}`);
} catch (error) { } catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error); const errorMsg = error instanceof Error ? error.message : String(error);
runtime.error?.(`[twitch] Failed to connect: ${errorMsg}`); runtime.error?.(`Failed to connect: ${errorMsg}`);
throw error; throw error;
} }
@ -223,9 +223,7 @@ export async function monitorTwitchProvider(
}); });
if (!access.allowed) { if (!access.allowed) {
runtime.log?.( runtime.log?.(`Ignored message from ${message.username}: ${access.reason ?? "blocked"}`);
`[twitch] Ignored message from ${message.username}: ${access.reason ?? "blocked"}`,
);
return; return;
} }
@ -242,7 +240,7 @@ export async function monitorTwitchProvider(
statusSink, statusSink,
}); });
} catch (err) { } catch (err) {
runtime.error?.(`[twitch] Message processing failed: ${String(err)}`); runtime.error?.(`Message processing failed: ${String(err)}`);
} }
}); });

View File

@ -60,9 +60,7 @@ export const twitchPlugin: ChannelPlugin<TwitchAccountConfig> = {
notifyApproval: async ({ id }) => { notifyApproval: async ({ id }) => {
// Note: Twitch doesn't support DMs from bots, so pairing approval is limited // Note: Twitch doesn't support DMs from bots, so pairing approval is limited
// We'll log the approval instead // We'll log the approval instead
console.warn( console.warn(`Pairing approved for user ${id} (notification sent via chat if possible)`);
`[twitch] Pairing approved for user ${id} (notification sent via chat if possible)`,
);
}, },
}, },
@ -243,7 +241,7 @@ export const twitchPlugin: ChannelPlugin<TwitchAccountConfig> = {
lastError: null, lastError: null,
}); });
ctx.log?.info(`[twitch] Starting Twitch connection for ${account.username}`); ctx.log?.info(`Starting Twitch connection for ${account.username}`);
// Lazy import: the monitor pulls the reply pipeline; avoid ESM init cycles. // Lazy import: the monitor pulls the reply pipeline; avoid ESM init cycles.
const { monitorTwitchProvider } = await import("./monitor.js"); const { monitorTwitchProvider } = await import("./monitor.js");
@ -270,7 +268,7 @@ export const twitchPlugin: ChannelPlugin<TwitchAccountConfig> = {
lastStopAt: Date.now(), lastStopAt: Date.now(),
}); });
ctx.log?.info(`[twitch] Stopped Twitch connection for ${account.username}`); ctx.log?.info(`Stopped Twitch connection for ${account.username}`);
}, },
}, },
}; };

View File

@ -27,10 +27,10 @@ function normalizeUsername(input: string): string {
*/ */
function createLogger(logger?: ChannelLogSink): ChannelLogSink { function createLogger(logger?: ChannelLogSink): ChannelLogSink {
return { return {
info: (msg: string) => logger?.info(`[twitch] ${msg}`), info: (msg: string) => logger?.info(msg),
warn: (msg: string) => logger?.warn(`[twitch] ${msg}`), warn: (msg: string) => logger?.warn(msg),
error: (msg: string) => logger?.error(`[twitch] ${msg}`), error: (msg: string) => logger?.error(msg),
debug: (msg: string) => logger?.debug?.(`[twitch] ${msg}`) ?? (() => {}), debug: (msg: string) => logger?.debug?.(msg) ?? (() => {}),
}; };
} }

View File

@ -126,7 +126,7 @@ export async function sendMessageTwitchInternal(
}; };
} catch (error) { } catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error); const errorMsg = error instanceof Error ? error.message : String(error);
logger.error(`[twitch] Failed to send message: ${errorMsg}`); logger.error(`Failed to send message: ${errorMsg}`);
return { return {
ok: false, ok: false,
messageId: generateMessageId(), messageId: generateMessageId(),

View File

@ -40,40 +40,34 @@ export class TwitchClientManager {
}) })
.then((userId) => { .then((userId) => {
this.logger.info( this.logger.info(
`[twitch] Added user ${userId} to RefreshingAuthProvider for ${account.username}`, `Added user ${userId} to RefreshingAuthProvider for ${account.username}`,
); );
}) })
.catch((err) => { .catch((err) => {
this.logger.error( this.logger.error(
`[twitch] Failed to add user to RefreshingAuthProvider: ${err instanceof Error ? err.message : String(err)}`, `Failed to add user to RefreshingAuthProvider: ${err instanceof Error ? err.message : String(err)}`,
); );
}); });
authProvider.onRefresh((userId, token) => { authProvider.onRefresh((userId, token) => {
this.logger.info( this.logger.info(
`[twitch] Access token refreshed for user ${userId} (expires in ${token.expiresIn ? `${token.expiresIn}s` : "unknown"})`, `Access token refreshed for user ${userId} (expires in ${token.expiresIn ? `${token.expiresIn}s` : "unknown"})`,
); );
}); });
authProvider.onRefreshFailure((userId, error) => { authProvider.onRefreshFailure((userId, error) => {
this.logger.error( this.logger.error(`Failed to refresh access token for user ${userId}: ${error.message}`);
`[twitch] Failed to refresh access token for user ${userId}: ${error.message}`,
);
}); });
const refreshStatus = account.refreshToken const refreshStatus = account.refreshToken
? "automatic token refresh enabled" ? "automatic token refresh enabled"
: "token refresh disabled (no refresh token)"; : "token refresh disabled (no refresh token)";
this.logger.info( this.logger.info(`Using RefreshingAuthProvider for ${account.username} (${refreshStatus})`);
`[twitch] Using RefreshingAuthProvider for ${account.username} (${refreshStatus})`,
);
return authProvider; return authProvider;
} }
this.logger.info( this.logger.info(`Using StaticAuthProvider for ${account.username} (no clientSecret provided)`);
`[twitch] Using StaticAuthProvider for ${account.username} (no clientSecret provided)`,
);
return new StaticAuthProvider(account.clientId, normalizedToken); return new StaticAuthProvider(account.clientId, normalizedToken);
} }
@ -98,17 +92,15 @@ export class TwitchClientManager {
if (!tokenResolution.token) { if (!tokenResolution.token) {
this.logger.error( this.logger.error(
`[twitch] Missing Twitch token for account ${account.username} (set channels.twitch.accounts.${account.username}.token or CLAWDBOT_TWITCH_ACCESS_TOKEN for default)`, `Missing Twitch token for account ${account.username} (set channels.twitch.accounts.${account.username}.token or CLAWDBOT_TWITCH_ACCESS_TOKEN for default)`,
); );
throw new Error("Missing Twitch token"); throw new Error("Missing Twitch token");
} }
this.logger.debug?.( this.logger.debug?.(`Using ${tokenResolution.source} token source for ${account.username}`);
`[twitch] Using ${tokenResolution.source} token source for ${account.username}`,
);
if (!account.clientId) { if (!account.clientId) {
this.logger.error(`[twitch] Missing Twitch client ID for account ${account.username}`); this.logger.error(`Missing Twitch client ID for account ${account.username}`);
throw new Error("Missing Twitch client ID"); throw new Error("Missing Twitch client ID");
} }
@ -127,22 +119,22 @@ export class TwitchClientManager {
log: (level, message) => { log: (level, message) => {
switch (level) { switch (level) {
case LogLevel.CRITICAL: case LogLevel.CRITICAL:
this.logger.error(`[twitch] ${message}`); this.logger.error(`${message}`);
break; break;
case LogLevel.ERROR: case LogLevel.ERROR:
this.logger.error(`[twitch] ${message}`); this.logger.error(`${message}`);
break; break;
case LogLevel.WARNING: case LogLevel.WARNING:
this.logger.warn(`[twitch] ${message}`); this.logger.warn(`${message}`);
break; break;
case LogLevel.INFO: case LogLevel.INFO:
this.logger.info(`[twitch] ${message}`); this.logger.info(`${message}`);
break; break;
case LogLevel.DEBUG: case LogLevel.DEBUG:
this.logger.debug?.(`[twitch] ${message}`); this.logger.debug?.(`${message}`);
break; break;
case LogLevel.TRACE: case LogLevel.TRACE:
this.logger.debug?.(`[twitch] ${message}`); this.logger.debug?.(`${message}`);
break; break;
} }
}, },
@ -155,7 +147,7 @@ export class TwitchClientManager {
client.connect(); client.connect();
this.clients.set(key, client); this.clients.set(key, client);
this.logger.info(`[twitch] Connected to Twitch as ${account.username}`); this.logger.info(`Connected to Twitch as ${account.username}`);
return client; return client;
} }
@ -171,6 +163,12 @@ export class TwitchClientManager {
const handler = this.messageHandlers.get(key); const handler = this.messageHandlers.get(key);
if (handler) { if (handler) {
const normalizedChannel = channelName.startsWith("#") ? channelName.slice(1) : channelName; const normalizedChannel = channelName.startsWith("#") ? channelName.slice(1) : channelName;
const from = `twitch:${msg.userInfo.userName}`;
const preview = messageText.slice(0, 100).replace(/\n/g, "\\n");
this.logger.debug?.(
`twitch inbound: channel=${normalizedChannel} from=${from} len=${messageText.length} preview="${preview}"`,
);
handler({ handler({
username: msg.userInfo.userName, username: msg.userInfo.userName,
displayName: msg.userInfo.displayName, displayName: msg.userInfo.displayName,
@ -192,6 +190,12 @@ export class TwitchClientManager {
client.onWhisper((_user, messageText, msg) => { client.onWhisper((_user, messageText, msg) => {
const handler = this.messageHandlers.get(key); const handler = this.messageHandlers.get(key);
if (handler) { if (handler) {
const from = `twitch:${msg.userInfo.userName}`;
const preview = messageText.slice(0, 100).replace(/\n/g, "\\n");
this.logger.debug?.(
`twitch inbound: whisper from=${from} len=${messageText.length} preview="${preview}"`,
);
handler({ handler({
username: msg.userInfo.userName, username: msg.userInfo.userName,
displayName: msg.userInfo.displayName, displayName: msg.userInfo.displayName,
@ -209,7 +213,7 @@ export class TwitchClientManager {
} }
}); });
this.logger.info(`[twitch] Set up handlers for ${key}`); this.logger.info(`Set up handlers for ${key}`);
} }
/** /**
@ -238,7 +242,7 @@ export class TwitchClientManager {
client.quit(); client.quit();
this.clients.delete(key); this.clients.delete(key);
this.messageHandlers.delete(key); this.messageHandlers.delete(key);
this.logger.info(`[twitch] Disconnected ${key}`); this.logger.info(`Disconnected ${key}`);
} }
} }
@ -249,7 +253,7 @@ export class TwitchClientManager {
this.clients.forEach((client) => client.quit()); this.clients.forEach((client) => client.quit());
this.clients.clear(); this.clients.clear();
this.messageHandlers.clear(); this.messageHandlers.clear();
this.logger.info("[twitch] Disconnected all clients"); this.logger.info(" Disconnected all clients");
} }
/** /**
@ -274,7 +278,7 @@ export class TwitchClientManager {
return { ok: true, messageId }; return { ok: true, messageId };
} catch (error) { } catch (error) {
this.logger.error( this.logger.error(
`[twitch] Failed to send message: ${error instanceof Error ? error.message : String(error)}`, `Failed to send message: ${error instanceof Error ? error.message : String(error)}`,
); );
return { return {
ok: false, ok: false,