Skip to content

Commit 9fd8dfe

Browse files
committed
fix(qqbot): add cause-specific setup guidance
1 parent f5add81 commit 9fd8dfe

10 files changed

Lines changed: 313 additions & 20 deletions

File tree

‎extensions/qqbot/src/engine/api/api-client.test.ts‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,78 @@ describe("ApiClient", () => {
9797
});
9898
});
9999

100+
it("adds network and whitelist guidance to DNS failures without suggesting credentials", async () => {
101+
fetchWithSsrFGuardMock.mockRejectedValueOnce(
102+
new Error("getaddrinfo ENOTFOUND api.sgroup.qq.com"),
103+
);
104+
105+
const client = new ApiClient({ baseUrl: "https://qqbot.test" });
106+
let error: unknown;
107+
try {
108+
await client.request("token-1", "GET", "/v2/users/@me");
109+
} catch (caught) {
110+
error = caught;
111+
}
112+
113+
const message = error instanceof Error ? error.message : String(error);
114+
expect(message).toContain("Network error [/v2/users/@me]");
115+
expect(message).toContain("network connectivity and DNS");
116+
expect(message).toContain("server IP whitelist");
117+
expect(message).not.toContain("appId");
118+
expect(message).not.toContain("clientSecret");
119+
});
120+
121+
it("adds credential guidance to structured HTTP 401 errors", async () => {
122+
const release = vi.fn(async () => {});
123+
fetchWithSsrFGuardMock.mockResolvedValueOnce({
124+
response: new Response('{"code":11241,"message":"invalid credentials"}', {
125+
status: 401,
126+
headers: { "content-type": "application/json" },
127+
}),
128+
release,
129+
});
130+
131+
const client = new ApiClient({ baseUrl: "https://qqbot.test" });
132+
let error: unknown;
133+
try {
134+
await client.request("token-1", "POST", "/v2/messages", { content: "hi" });
135+
} catch (caught) {
136+
error = caught;
137+
}
138+
139+
const message = error instanceof Error ? error.message : String(error);
140+
expect(message).toContain("API Error [/v2/messages]: invalid credentials");
141+
expect(message).toContain("QQBot account appId and clientSecret");
142+
expect(message).toContain("https://q.qq.com/");
143+
expect(release).toHaveBeenCalledTimes(1);
144+
});
145+
146+
it("keeps non-auth structured API guidance generic", async () => {
147+
const release = vi.fn(async () => {});
148+
fetchWithSsrFGuardMock.mockResolvedValueOnce({
149+
response: new Response('{"code":40034025,"message":"invalid event id"}', {
150+
status: 400,
151+
headers: { "content-type": "application/json" },
152+
}),
153+
release,
154+
});
155+
156+
const client = new ApiClient({ baseUrl: "https://qqbot.test" });
157+
let error: unknown;
158+
try {
159+
await client.request("token-1", "POST", "/v2/messages", { content: "hi" });
160+
} catch (caught) {
161+
error = caught;
162+
}
163+
164+
const message = error instanceof Error ? error.message : String(error);
165+
expect(message).toContain("API Error [/v2/messages]: invalid event id");
166+
expect(message).toContain("QQBot API troubleshooting");
167+
expect(message).not.toContain("appId");
168+
expect(message).not.toContain("clientSecret");
169+
expect(release).toHaveBeenCalledTimes(1);
170+
});
171+
100172
it("bounds successful response bodies without using response.text()", async () => {
101173
const release = vi.fn(async () => {});
102174
const streamed = createStreamingResponse({

‎extensions/qqbot/src/engine/api/api-client.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
} from "openclaw/plugin-sdk/provider-http";
1717
import { fetchWithSsrFGuard, type SsrFPolicy } from "openclaw/plugin-sdk/ssrf-runtime";
1818
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
19+
import { qqbotApiGuidance, qqbotNetworkGuidance } from "../config/setup-guidance.js";
1920
import { ApiError, type ApiClientConfig, type EngineLogger } from "../types.js";
2021

2122
const DEFAULT_BASE_URL = "https://api.sgroup.qq.com";
@@ -149,7 +150,11 @@ export class ApiClient {
149150
throw new ApiError(`Request timeout [${path}]: exceeded ${timeout}ms`, 0, path);
150151
}
151152
this.logger?.error?.(`[qqbot:api] <<< Network error: ${formatErrorMessage(err)}`);
152-
throw new ApiError(`Network error [${path}]: ${formatErrorMessage(err)}`, 0, path);
153+
throw new ApiError(
154+
`Network error [${path}]: ${formatErrorMessage(err)}. ${qqbotNetworkGuidance()}`,
155+
0,
156+
path,
157+
);
153158
}
154159

155160
const res = guarded.response;
@@ -206,7 +211,7 @@ export class ApiClient {
206211
};
207212
const bizCode = error.code ?? error.err_code;
208213
throw new ApiError(
209-
`API Error [${path}]: ${error.message ?? rawBody}`,
214+
`API Error [${path}]: ${error.message ?? rawBody}. ${qqbotApiGuidance(res.status)}`,
210215
res.status,
211216
path,
212217
bizCode,

‎extensions/qqbot/src/engine/api/token.test.ts‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,28 @@ describe("QQBot token manager", () => {
8989
expect(release).toHaveBeenCalledTimes(1);
9090
});
9191

92+
it("adds account-neutral credential guidance when the token endpoint omits access_token", async () => {
93+
const release = mockGuardedTokenResponse('{"code":4001,"message":"invalid app secret"}', {
94+
status: 200,
95+
headers: { "content-type": "application/json" },
96+
});
97+
98+
let error: unknown;
99+
try {
100+
await new TokenManager().getAccessToken("app-id", "secret");
101+
} catch (caught) {
102+
error = caught;
103+
}
104+
105+
const message = error instanceof Error ? error.message : String(error);
106+
expect(message).toContain("Failed to get QQBot access_token");
107+
expect(message).toContain("QQBot account appId and clientSecret");
108+
expect(message).toContain("https://q.qq.com/");
109+
expect(message).toContain('{"code":4001,"message":"invalid app secret"}');
110+
expect(message).not.toContain("QQBOT_APP_ID");
111+
expect(release).toHaveBeenCalledTimes(1);
112+
});
113+
92114
it("bounds access token responses without using response.text()", async () => {
93115
const logger = { debug: vi.fn(), info: vi.fn(), error: vi.fn() };
94116
const tracked = cancelTrackedResponse(`${"qqbot token unavailable ".repeat(1024)}tail`, {
@@ -230,7 +252,10 @@ describe("QQBot token manager", () => {
230252
}
231253
const timeoutError = firstOutcome.reason as Error;
232254
expect(timeoutError).toBe(secondOutcome.reason);
233-
expect(timeoutError.message).toBe("Network error getting access_token: request timed out");
255+
expect(timeoutError.message).toContain("Network error getting access_token: request timed out");
256+
expect(timeoutError.message).toContain("Check network connectivity and DNS");
257+
expect(timeoutError.message).toContain("server IP whitelist");
258+
expect(timeoutError.message).not.toContain("appId");
234259
expect(timeoutError.cause).toMatchObject({
235260
name: "TimeoutError",
236261
message: "request timed out",

‎extensions/qqbot/src/engine/api/token.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
import { readResponseTextLimited } from "openclaw/plugin-sdk/provider-http";
1717
import { sleepWithAbort } from "openclaw/plugin-sdk/runtime-env";
1818
import { fetchWithSsrFGuard, type SsrFPolicy } from "openclaw/plugin-sdk/ssrf-runtime";
19+
import { qqbotNetworkGuidance, qqbotTokenFailureMessage } from "../config/setup-guidance.js";
1920
import type { EngineLogger } from "../types.js";
2021

2122
const TOKEN_URL = "https://bots.qq.com/app/getAppAccessToken";
@@ -267,9 +268,10 @@ export class TokenManager {
267268
release = guarded.release;
268269
} catch (err) {
269270
this.logger?.error?.(`[qqbot:token:${appId}] Network error: ${formatErrorMessage(err)}`);
270-
throw new Error(`Network error getting access_token: ${formatErrorMessage(err)}`, {
271-
cause: err,
272-
});
271+
throw new Error(
272+
`Network error getting access_token: ${formatErrorMessage(err)}. ${qqbotNetworkGuidance()}`,
273+
{ cause: err },
274+
);
273275
}
274276

275277
try {
@@ -297,7 +299,7 @@ export class TokenManager {
297299
}
298300

299301
if (!data.access_token) {
300-
throw new Error(`Failed to get access_token: ${JSON.stringify(data)}`);
302+
throw new Error(qqbotTokenFailureMessage(JSON.stringify(data)));
301303
}
302304

303305
const nowMs = asDateTimestampMs(Date.now());
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import { describe, expect, it } from "vitest";
2+
import {
3+
qqbotApiGuidance,
4+
qqbotNetworkGuidance,
5+
qqbotNotConfiguredMessage,
6+
} from "./setup-guidance.js";
7+
8+
describe("QQBot setup guidance", () => {
9+
it("offers default-account config and environment variables", () => {
10+
const message = qqbotNotConfiguredMessage("default");
11+
12+
expect(message).toContain("channels.qqbot.appId");
13+
expect(message).toContain("QQBOT_APP_ID and QQBOT_CLIENT_SECRET");
14+
expect(message).toContain("https://docs.openclaw.ai/channels/qqbot");
15+
});
16+
17+
it("directs named accounts to account-scoped config without default-only environment variables", () => {
18+
const message = qqbotNotConfiguredMessage("operations");
19+
20+
expect(message).toContain("channels.qqbot.accounts.operations.appId");
21+
expect(message).toContain("clientSecret (or clientSecretFile)");
22+
expect(message).not.toContain("QQBOT_APP_ID");
23+
expect(message).not.toContain("QQBOT_CLIENT_SECRET");
24+
});
25+
26+
it("keeps authentication guidance account-neutral", () => {
27+
const message = qqbotApiGuidance(401);
28+
29+
expect(message).toContain("QQBot account appId");
30+
expect(message).toContain("https://q.qq.com/");
31+
expect(message).not.toContain("QQBOT_APP_ID");
32+
expect(message).not.toContain("QQBOT_CLIENT_SECRET");
33+
});
34+
35+
it("keeps network guidance cause-specific", () => {
36+
const message = qqbotNetworkGuidance();
37+
38+
expect(message).toContain("network connectivity and DNS");
39+
expect(message).toContain("server IP whitelist");
40+
expect(message).not.toContain("appId");
41+
expect(message).not.toContain("clientSecret");
42+
});
43+
44+
it("uses credential guidance only for HTTP 401 API failures", () => {
45+
expect(qqbotApiGuidance(401)).toContain("appId and clientSecret");
46+
expect(qqbotApiGuidance(403)).not.toContain("appId");
47+
expect(qqbotApiGuidance(429)).not.toContain("appId");
48+
});
49+
});
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { DEFAULT_ACCOUNT_ID } from "./resolve.js";
2+
3+
const QQBOT_DOCS_URL = "https://docs.openclaw.ai/channels/qqbot";
4+
const QQBOT_OPEN_PLATFORM_URL = "https://q.qq.com/";
5+
6+
function qqbotAuthGuidance(): string {
7+
return `Check the QQBot account appId and clientSecret (or clientSecretFile) in OpenClaw and verify the credentials in QQ Open Platform at ${QQBOT_OPEN_PLATFORM_URL}. See ${QQBOT_DOCS_URL}`;
8+
}
9+
10+
export function qqbotNetworkGuidance(): string {
11+
return `Check network connectivity and DNS, and verify the server IP whitelist in QQ Open Platform at ${QQBOT_OPEN_PLATFORM_URL}. See ${QQBOT_DOCS_URL}`;
12+
}
13+
14+
export function qqbotApiGuidance(httpStatus: number): string {
15+
return httpStatus === 401
16+
? qqbotAuthGuidance()
17+
: `See ${QQBOT_DOCS_URL} for QQBot API troubleshooting`;
18+
}
19+
20+
export function qqbotNotConfiguredMessage(accountId: string): string {
21+
const guidance =
22+
accountId === DEFAULT_ACCOUNT_ID
23+
? `Set channels.qqbot.appId and clientSecret (or clientSecretFile), or set QQBOT_APP_ID and QQBOT_CLIENT_SECRET. See ${QQBOT_DOCS_URL}`
24+
: `Set channels.qqbot.accounts.${accountId}.appId and clientSecret (or clientSecretFile). See ${QQBOT_DOCS_URL}`;
25+
return `QQBot not configured (missing appId or clientSecret). ${guidance}`;
26+
}
27+
28+
export function qqbotTokenFailureMessage(detail: string): string {
29+
return `Failed to get QQBot access_token. ${qqbotAuthGuidance()}. Open platform response: ${detail}`;
30+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { describe, expect, it } from "vitest";
2+
import { startGateway, type CoreGatewayContext } from "./gateway.js";
3+
4+
function makeContext(accountId: string): CoreGatewayContext {
5+
return {
6+
account: {
7+
accountId,
8+
appId: "",
9+
clientSecret: "",
10+
markdownSupport: false,
11+
config: {},
12+
},
13+
adapters: {
14+
commands: {},
15+
outboundAudio: {},
16+
},
17+
} as unknown as CoreGatewayContext;
18+
}
19+
20+
describe("QQBot gateway configuration guidance", () => {
21+
it("shows default-account recovery paths from the real gateway entry point", async () => {
22+
await expect(startGateway(makeContext("default"))).rejects.toThrow(
23+
/channels\.qqbot\.appId.*QQBOT_APP_ID and QQBOT_CLIENT_SECRET/,
24+
);
25+
});
26+
27+
it("shows account-scoped recovery without default-only env vars", async () => {
28+
let error: unknown;
29+
try {
30+
await startGateway(makeContext("operations"));
31+
} catch (caught) {
32+
error = caught;
33+
}
34+
35+
const message = error instanceof Error ? error.message : String(error);
36+
expect(message).toContain("channels.qqbot.accounts.operations.appId");
37+
expect(message).not.toContain("QQBOT_APP_ID");
38+
expect(message).not.toContain("QQBOT_CLIENT_SECRET");
39+
});
40+
});

‎extensions/qqbot/src/engine/gateway/gateway.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
} from "../commands/command-visibility.js";
88
import { initCommands } from "../commands/slash-commands-impl.js";
99
import { resolveGroupCommandLevelFromAccountConfig } from "../config/group.js";
10+
import { qqbotNotConfiguredMessage } from "../config/setup-guidance.js";
1011
import type { HistoryEntry } from "../group/history.js";
1112
import { claimMessageReply } from "../messaging/outbound-reply.js";
1213
import { setOutboundAudioPort } from "../messaging/outbound.js";
@@ -46,7 +47,7 @@ export async function startGateway(ctx: CoreGatewayContext): Promise<void> {
4647
initCommands(adapters.commands);
4748

4849
if (!account.appId || !account.clientSecret) {
49-
throw new Error("QQBot not configured (missing appId or clientSecret)");
50+
throw new Error(qqbotNotConfiguredMessage(account.accountId));
5051
}
5152

5253
const diag = await runDiagnostics();
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import { describe, expect, it } from "vitest";
2+
import type { GatewayAccount } from "../types.js";
3+
import { sendMedia, sendText } from "./outbound.js";
4+
5+
function makeAccount(accountId: string): GatewayAccount {
6+
return {
7+
accountId,
8+
appId: "",
9+
clientSecret: "",
10+
markdownSupport: false,
11+
config: {},
12+
};
13+
}
14+
15+
describe("QQBot outbound configuration guidance", () => {
16+
it("returns default-account recovery paths from sendText", async () => {
17+
const result = await sendText({
18+
account: makeAccount("default"),
19+
to: "user-openid",
20+
text: "hello",
21+
});
22+
23+
expect(result.error).toContain("channels.qqbot.appId");
24+
expect(result.error).toContain("QQBOT_APP_ID and QQBOT_CLIENT_SECRET");
25+
});
26+
27+
it("returns named-account recovery paths from sendMedia", async () => {
28+
const result = await sendMedia({
29+
account: makeAccount("operations"),
30+
accountId: "operations",
31+
to: "user-openid",
32+
text: "",
33+
mediaUrl: "https://example.com/image.png",
34+
});
35+
36+
expect(result.error).toContain("channels.qqbot.accounts.operations.appId");
37+
expect(result.error).not.toContain("QQBOT_APP_ID");
38+
expect(result.error).not.toContain("QQBOT_CLIENT_SECRET");
39+
});
40+
41+
it.each([
42+
["default", "<qqimg>https://example.com/image.png</qqimg>", "channels.qqbot.appId", true],
43+
[
44+
"operations",
45+
"report <qqfile>https://example.com/report.pdf</qqfile>",
46+
"channels.qqbot.accounts.operations.appId",
47+
false,
48+
],
49+
] as const)(
50+
"preflights tagged media for the %s account",
51+
async (accountId, text, expectedPath, expectsDefaultEnv) => {
52+
const result = await sendText({
53+
account: makeAccount(accountId),
54+
to: "user-openid",
55+
text,
56+
});
57+
58+
expect(result.error).toContain(expectedPath);
59+
if (expectsDefaultEnv) {
60+
expect(result.error).toContain("QQBOT_APP_ID and QQBOT_CLIENT_SECRET");
61+
} else {
62+
expect(result.error).not.toContain("QQBOT_APP_ID");
63+
expect(result.error).not.toContain("QQBOT_CLIENT_SECRET");
64+
}
65+
},
66+
);
67+
});

0 commit comments

Comments
 (0)