11
This commit is contained in:
214
src/gateway.ts
214
src/gateway.ts
@@ -1,6 +1,6 @@
|
|||||||
import WebSocket from "ws";
|
import WebSocket from "ws";
|
||||||
import type { ResolvedQQBotAccount, WSPayload, C2CMessageEvent, GuildMessageEvent, GroupMessageEvent } from "./types.js";
|
import type { ResolvedQQBotAccount, WSPayload, C2CMessageEvent, GuildMessageEvent, GroupMessageEvent } from "./types.js";
|
||||||
import { getAccessToken, getGatewayUrl, sendC2CMessage, sendChannelMessage, sendGroupMessage } from "./api.js";
|
import { getAccessToken, getGatewayUrl, sendC2CMessage, sendChannelMessage, sendGroupMessage, clearTokenCache } from "./api.js";
|
||||||
import { getQQBotRuntime } from "./runtime.js";
|
import { getQQBotRuntime } from "./runtime.js";
|
||||||
|
|
||||||
// QQ Bot intents
|
// QQ Bot intents
|
||||||
@@ -10,6 +10,10 @@ const INTENTS = {
|
|||||||
GROUP_AND_C2C: 1 << 25, // 群聊和 C2C 私聊
|
GROUP_AND_C2C: 1 << 25, // 群聊和 C2C 私聊
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 重连配置
|
||||||
|
const RECONNECT_DELAYS = [1000, 2000, 5000, 10000, 30000, 60000]; // 递增延迟
|
||||||
|
const MAX_RECONNECT_ATTEMPTS = 100;
|
||||||
|
|
||||||
export interface GatewayContext {
|
export interface GatewayContext {
|
||||||
account: ResolvedQQBotAccount;
|
account: ResolvedQQBotAccount;
|
||||||
abortSignal: AbortSignal;
|
abortSignal: AbortSignal;
|
||||||
@@ -24,7 +28,7 @@ export interface GatewayContext {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 启动 Gateway WebSocket 连接
|
* 启动 Gateway WebSocket 连接(带自动重连)
|
||||||
*/
|
*/
|
||||||
export async function startGateway(ctx: GatewayContext): Promise<void> {
|
export async function startGateway(ctx: GatewayContext): Promise<void> {
|
||||||
const { account, abortSignal, cfg, onReady, onError, log } = ctx;
|
const { account, abortSignal, cfg, onReady, onError, log } = ctx;
|
||||||
@@ -33,27 +37,66 @@ export async function startGateway(ctx: GatewayContext): Promise<void> {
|
|||||||
throw new Error("QQBot not configured (missing appId or clientSecret)");
|
throw new Error("QQBot not configured (missing appId or clientSecret)");
|
||||||
}
|
}
|
||||||
|
|
||||||
const pluginRuntime = getQQBotRuntime();
|
let reconnectAttempts = 0;
|
||||||
const accessToken = await getAccessToken(account.appId, account.clientSecret);
|
let isAborted = false;
|
||||||
const gatewayUrl = await getGatewayUrl(accessToken);
|
let currentWs: WebSocket | null = null;
|
||||||
|
|
||||||
log?.info(`[qqbot:${account.accountId}] Connecting to ${gatewayUrl}`);
|
|
||||||
|
|
||||||
const ws = new WebSocket(gatewayUrl);
|
|
||||||
let heartbeatInterval: ReturnType<typeof setInterval> | null = null;
|
let heartbeatInterval: ReturnType<typeof setInterval> | null = null;
|
||||||
|
let sessionId: string | null = null;
|
||||||
let lastSeq: number | null = null;
|
let lastSeq: number | null = null;
|
||||||
|
|
||||||
|
abortSignal.addEventListener("abort", () => {
|
||||||
|
isAborted = true;
|
||||||
|
cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
const cleanup = () => {
|
const cleanup = () => {
|
||||||
if (heartbeatInterval) {
|
if (heartbeatInterval) {
|
||||||
clearInterval(heartbeatInterval);
|
clearInterval(heartbeatInterval);
|
||||||
heartbeatInterval = null;
|
heartbeatInterval = null;
|
||||||
}
|
}
|
||||||
if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
|
if (currentWs && (currentWs.readyState === WebSocket.OPEN || currentWs.readyState === WebSocket.CONNECTING)) {
|
||||||
ws.close();
|
currentWs.close();
|
||||||
}
|
}
|
||||||
|
currentWs = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
abortSignal.addEventListener("abort", cleanup);
|
const getReconnectDelay = () => {
|
||||||
|
const idx = Math.min(reconnectAttempts, RECONNECT_DELAYS.length - 1);
|
||||||
|
return RECONNECT_DELAYS[idx];
|
||||||
|
};
|
||||||
|
|
||||||
|
const scheduleReconnect = () => {
|
||||||
|
if (isAborted || reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
|
||||||
|
log?.error(`[qqbot:${account.accountId}] Max reconnect attempts reached or aborted`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const delay = getReconnectDelay();
|
||||||
|
reconnectAttempts++;
|
||||||
|
log?.info(`[qqbot:${account.accountId}] Reconnecting in ${delay}ms (attempt ${reconnectAttempts})`);
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!isAborted) {
|
||||||
|
connect();
|
||||||
|
}
|
||||||
|
}, delay);
|
||||||
|
};
|
||||||
|
|
||||||
|
const connect = async () => {
|
||||||
|
try {
|
||||||
|
cleanup();
|
||||||
|
|
||||||
|
// 刷新 token(可能过期了)
|
||||||
|
clearTokenCache();
|
||||||
|
const accessToken = await getAccessToken(account.appId, account.clientSecret);
|
||||||
|
const gatewayUrl = await getGatewayUrl(accessToken);
|
||||||
|
|
||||||
|
log?.info(`[qqbot:${account.accountId}] Connecting to ${gatewayUrl}`);
|
||||||
|
|
||||||
|
const ws = new WebSocket(gatewayUrl);
|
||||||
|
currentWs = ws;
|
||||||
|
|
||||||
|
const pluginRuntime = getQQBotRuntime();
|
||||||
|
|
||||||
// 处理收到的消息
|
// 处理收到的消息
|
||||||
const handleMessage = async (event: {
|
const handleMessage = async (event: {
|
||||||
@@ -127,32 +170,68 @@ export async function startGateway(ctx: GatewayContext): Promise<void> {
|
|||||||
Timestamp: new Date(event.timestamp).getTime(),
|
Timestamp: new Date(event.timestamp).getTime(),
|
||||||
OriginatingChannel: "qqbot",
|
OriginatingChannel: "qqbot",
|
||||||
OriginatingTo: toAddress,
|
OriginatingTo: toAddress,
|
||||||
// QQBot 特有字段
|
|
||||||
QQChannelId: event.channelId,
|
QQChannelId: event.channelId,
|
||||||
QQGuildId: event.guildId,
|
QQGuildId: event.guildId,
|
||||||
QQGroupOpenid: event.groupOpenid,
|
QQGroupOpenid: event.groupOpenid,
|
||||||
});
|
});
|
||||||
|
|
||||||
// 分发到 AI 系统
|
// 发送错误提示的辅助函数
|
||||||
|
const sendErrorMessage = async (errorText: string) => {
|
||||||
|
try {
|
||||||
|
const token = await getAccessToken(account.appId, account.clientSecret);
|
||||||
|
if (event.type === "c2c") {
|
||||||
|
await sendC2CMessage(token, event.senderId, errorText, event.messageId);
|
||||||
|
} else if (event.type === "group" && event.groupOpenid) {
|
||||||
|
await sendGroupMessage(token, event.groupOpenid, errorText, event.messageId);
|
||||||
|
} else if (event.channelId) {
|
||||||
|
await sendChannelMessage(token, event.channelId, errorText, event.messageId);
|
||||||
|
}
|
||||||
|
} catch (sendErr) {
|
||||||
|
log?.error(`[qqbot:${account.accountId}] Failed to send error message: ${sendErr}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const messagesConfig = pluginRuntime.channel.reply.resolveEffectiveMessagesConfig(cfg, route.agentId);
|
const messagesConfig = pluginRuntime.channel.reply.resolveEffectiveMessagesConfig(cfg, route.agentId);
|
||||||
|
|
||||||
await pluginRuntime.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
|
// 每次发消息前刷新 token
|
||||||
|
const freshToken = await getAccessToken(account.appId, account.clientSecret);
|
||||||
|
|
||||||
|
// 追踪是否有响应
|
||||||
|
let hasResponse = false;
|
||||||
|
const responseTimeout = 30000; // 30秒超时
|
||||||
|
let timeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
|
const timeoutPromise = new Promise<void>((_, reject) => {
|
||||||
|
timeoutId = setTimeout(() => {
|
||||||
|
if (!hasResponse) {
|
||||||
|
reject(new Error("Response timeout"));
|
||||||
|
}
|
||||||
|
}, responseTimeout);
|
||||||
|
});
|
||||||
|
|
||||||
|
const dispatchPromise = pluginRuntime.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
|
||||||
ctx: ctxPayload,
|
ctx: ctxPayload,
|
||||||
cfg,
|
cfg,
|
||||||
dispatcherOptions: {
|
dispatcherOptions: {
|
||||||
responsePrefix: messagesConfig.responsePrefix,
|
responsePrefix: messagesConfig.responsePrefix,
|
||||||
deliver: async (payload: { text?: string }) => {
|
deliver: async (payload: { text?: string }) => {
|
||||||
|
hasResponse = true;
|
||||||
|
if (timeoutId) {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
timeoutId = null;
|
||||||
|
}
|
||||||
|
|
||||||
const replyText = payload.text ?? "";
|
const replyText = payload.text ?? "";
|
||||||
if (!replyText.trim()) return;
|
if (!replyText.trim()) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (event.type === "c2c") {
|
if (event.type === "c2c") {
|
||||||
await sendC2CMessage(accessToken, event.senderId, replyText, event.messageId);
|
await sendC2CMessage(freshToken, event.senderId, replyText, event.messageId);
|
||||||
} else if (event.type === "group" && event.groupOpenid) {
|
} else if (event.type === "group" && event.groupOpenid) {
|
||||||
await sendGroupMessage(accessToken, event.groupOpenid, replyText, event.messageId);
|
await sendGroupMessage(freshToken, event.groupOpenid, replyText, event.messageId);
|
||||||
} else if (event.channelId) {
|
} else if (event.channelId) {
|
||||||
await sendChannelMessage(accessToken, event.channelId, replyText, event.messageId);
|
await sendChannelMessage(freshToken, event.channelId, replyText, event.messageId);
|
||||||
}
|
}
|
||||||
log?.info(`[qqbot:${account.accountId}] Sent reply`);
|
log?.info(`[qqbot:${account.accountId}] Sent reply`);
|
||||||
|
|
||||||
@@ -165,19 +244,46 @@ export async function startGateway(ctx: GatewayContext): Promise<void> {
|
|||||||
log?.error(`[qqbot:${account.accountId}] Send failed: ${err}`);
|
log?.error(`[qqbot:${account.accountId}] Send failed: ${err}`);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onError: (err: unknown) => {
|
onError: async (err: unknown) => {
|
||||||
log?.error(`[qqbot:${account.accountId}] Dispatch error: ${err}`);
|
log?.error(`[qqbot:${account.accountId}] Dispatch error: ${err}`);
|
||||||
|
hasResponse = true;
|
||||||
|
if (timeoutId) {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
timeoutId = null;
|
||||||
|
}
|
||||||
|
// 发送错误提示给用户
|
||||||
|
const errMsg = String(err);
|
||||||
|
if (errMsg.includes("401") || errMsg.includes("key") || errMsg.includes("auth")) {
|
||||||
|
await sendErrorMessage("[ClawdBot] 大模型 API Key 可能无效,请检查配置");
|
||||||
|
} else {
|
||||||
|
await sendErrorMessage(`[ClawdBot] 处理消息时出错: ${errMsg.slice(0, 100)}`);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
replyOptions: {},
|
replyOptions: {},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 等待分发完成或超时
|
||||||
|
try {
|
||||||
|
await Promise.race([dispatchPromise, timeoutPromise]);
|
||||||
|
} catch (err) {
|
||||||
|
if (timeoutId) {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
}
|
||||||
|
if (!hasResponse) {
|
||||||
|
log?.error(`[qqbot:${account.accountId}] No response within timeout`);
|
||||||
|
await sendErrorMessage("[ClawdBot] 未收到响应,请检查大模型 API Key 是否正确配置");
|
||||||
|
}
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
log?.error(`[qqbot:${account.accountId}] Message processing failed: ${err}`);
|
log?.error(`[qqbot:${account.accountId}] Message processing failed: ${err}`);
|
||||||
|
await sendErrorMessage(`[ClawdBot] 处理消息失败: ${String(err).slice(0, 100)}`);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
ws.on("open", () => {
|
ws.on("open", () => {
|
||||||
log?.info(`[qqbot:${account.accountId}] WebSocket connected`);
|
log?.info(`[qqbot:${account.accountId}] WebSocket connected`);
|
||||||
|
reconnectAttempts = 0; // 连接成功,重置重试计数
|
||||||
});
|
});
|
||||||
|
|
||||||
ws.on("message", async (data) => {
|
ws.on("message", async (data) => {
|
||||||
@@ -191,29 +297,50 @@ export async function startGateway(ctx: GatewayContext): Promise<void> {
|
|||||||
|
|
||||||
switch (op) {
|
switch (op) {
|
||||||
case 10: // Hello
|
case 10: // Hello
|
||||||
log?.info(`[qqbot:${account.accountId}] Hello received, starting heartbeat`);
|
log?.info(`[qqbot:${account.accountId}] Hello received`);
|
||||||
// Identify
|
|
||||||
ws.send(
|
// 如果有 session_id,尝试 Resume
|
||||||
JSON.stringify({
|
if (sessionId && lastSeq !== null) {
|
||||||
|
log?.info(`[qqbot:${account.accountId}] Attempting to resume session ${sessionId}`);
|
||||||
|
ws.send(JSON.stringify({
|
||||||
|
op: 6, // Resume
|
||||||
|
d: {
|
||||||
|
token: `QQBot ${accessToken}`,
|
||||||
|
session_id: sessionId,
|
||||||
|
seq: lastSeq,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
} else {
|
||||||
|
// 新连接,发送 Identify
|
||||||
|
ws.send(JSON.stringify({
|
||||||
op: 2,
|
op: 2,
|
||||||
d: {
|
d: {
|
||||||
token: `QQBot ${accessToken}`,
|
token: `QQBot ${accessToken}`,
|
||||||
intents: INTENTS.PUBLIC_GUILD_MESSAGES | INTENTS.DIRECT_MESSAGE | INTENTS.GROUP_AND_C2C,
|
intents: INTENTS.PUBLIC_GUILD_MESSAGES | INTENTS.DIRECT_MESSAGE | INTENTS.GROUP_AND_C2C,
|
||||||
shard: [0, 1],
|
shard: [0, 1],
|
||||||
},
|
},
|
||||||
})
|
}));
|
||||||
);
|
}
|
||||||
// Heartbeat
|
|
||||||
|
// 启动心跳
|
||||||
const interval = (d as { heartbeat_interval: number }).heartbeat_interval;
|
const interval = (d as { heartbeat_interval: number }).heartbeat_interval;
|
||||||
|
if (heartbeatInterval) clearInterval(heartbeatInterval);
|
||||||
heartbeatInterval = setInterval(() => {
|
heartbeatInterval = setInterval(() => {
|
||||||
|
if (ws.readyState === WebSocket.OPEN) {
|
||||||
ws.send(JSON.stringify({ op: 1, d: lastSeq }));
|
ws.send(JSON.stringify({ op: 1, d: lastSeq }));
|
||||||
|
log?.debug?.(`[qqbot:${account.accountId}] Heartbeat sent`);
|
||||||
|
}
|
||||||
}, interval);
|
}, interval);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 0: // Dispatch
|
case 0: // Dispatch
|
||||||
if (t === "READY") {
|
if (t === "READY") {
|
||||||
log?.info(`[qqbot:${account.accountId}] Ready`);
|
const readyData = d as { session_id: string };
|
||||||
|
sessionId = readyData.session_id;
|
||||||
|
log?.info(`[qqbot:${account.accountId}] Ready, session: ${sessionId}`);
|
||||||
onReady?.(d);
|
onReady?.(d);
|
||||||
|
} else if (t === "RESUMED") {
|
||||||
|
log?.info(`[qqbot:${account.accountId}] Session resumed`);
|
||||||
} else if (t === "C2C_MESSAGE_CREATE") {
|
} else if (t === "C2C_MESSAGE_CREATE") {
|
||||||
const event = d as C2CMessageEvent;
|
const event = d as C2CMessageEvent;
|
||||||
await handleMessage({
|
await handleMessage({
|
||||||
@@ -263,10 +390,21 @@ export async function startGateway(ctx: GatewayContext): Promise<void> {
|
|||||||
log?.debug?.(`[qqbot:${account.accountId}] Heartbeat ACK`);
|
log?.debug?.(`[qqbot:${account.accountId}] Heartbeat ACK`);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 9: // Invalid Session
|
case 7: // Reconnect
|
||||||
log?.error(`[qqbot:${account.accountId}] Invalid session`);
|
log?.info(`[qqbot:${account.accountId}] Server requested reconnect`);
|
||||||
onError?.(new Error("Invalid session"));
|
|
||||||
cleanup();
|
cleanup();
|
||||||
|
scheduleReconnect();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 9: // Invalid Session
|
||||||
|
const canResume = d as boolean;
|
||||||
|
log?.error(`[qqbot:${account.accountId}] Invalid session, can resume: ${canResume}`);
|
||||||
|
if (!canResume) {
|
||||||
|
sessionId = null;
|
||||||
|
lastSeq = null;
|
||||||
|
}
|
||||||
|
cleanup();
|
||||||
|
scheduleReconnect();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -275,8 +413,13 @@ export async function startGateway(ctx: GatewayContext): Promise<void> {
|
|||||||
});
|
});
|
||||||
|
|
||||||
ws.on("close", (code, reason) => {
|
ws.on("close", (code, reason) => {
|
||||||
log?.info(`[qqbot:${account.accountId}] WebSocket closed: ${code} ${reason}`);
|
log?.info(`[qqbot:${account.accountId}] WebSocket closed: ${code} ${reason.toString()}`);
|
||||||
cleanup();
|
cleanup();
|
||||||
|
|
||||||
|
// 非正常关闭则重连
|
||||||
|
if (!isAborted && code !== 1000) {
|
||||||
|
scheduleReconnect();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
ws.on("error", (err) => {
|
ws.on("error", (err) => {
|
||||||
@@ -284,6 +427,15 @@ export async function startGateway(ctx: GatewayContext): Promise<void> {
|
|||||||
onError?.(err);
|
onError?.(err);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
log?.error(`[qqbot:${account.accountId}] Connection failed: ${err}`);
|
||||||
|
scheduleReconnect();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 开始连接
|
||||||
|
await connect();
|
||||||
|
|
||||||
// 等待 abort 信号
|
// 等待 abort 信号
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
abortSignal.addEventListener("abort", () => resolve());
|
abortSignal.addEventListener("abort", () => resolve());
|
||||||
|
|||||||
Reference in New Issue
Block a user