Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(discord): flag uninstalled bot, intent off, app ID mismatch in test connection (#22178)

Rdmclin2162ba635d809
diff --git a/apps/server/src/services/bot/platforms/discord/client.ts b/apps/server/src/services/bot/platforms/discord/client.ts
index 6b51001b59c..b369166ae1f 100644
--- a/apps/server/src/services/bot/platforms/discord/client.ts
+++ b/apps/server/src/services/bot/platforms/discord/client.ts
@@ -26,7 +26,6 @@ import {
import { formatUsageStats } from '../utils';
import { DiscordApi } from './api';
import { isSoloDiscordBotThread } from './chatComposition';
-import { DISCORD_BOT_TOKEN_PATTERN, DISCORD_PUBLIC_KEY_PATTERN } from './const';
import {
collectDiscordMentionNames,
resolveDiscordMentions,
@@ -38,6 +37,7 @@ import {
patchDiscordMessageEdits,
} from './patch';
import { batchDiscordFiles, materializeAttachmentsForDiscord } from './sendAttachments';
+import { validateDiscordCredentials } from './validateCredentials';
const log = debug('bot-platform:discord:bot');
@@ -662,42 +662,11 @@ export class DiscordClientFactory extends ClientFactory {
return new DiscordGatewayClient(config, context);
}
- async validateCredentials(credentials: Record<string, string>): Promise<ValidationResult> {
- const errors: Array<{ field: string; message: string }> = [];
-
- if (!credentials.botToken) errors.push({ field: 'botToken', message: 'Bot Token is required' });
- if (!credentials.publicKey)
- errors.push({ field: 'publicKey', message: 'Public Key is required' });
-
- if (errors.length > 0) return { errors, valid: false };
-
- // Name the actual problem before spending a round-trip on it — a
- // malformed public key can't be caught by the API call at all, and a
- // malformed token would come back as a generic auth failure.
- if (!new RegExp(DISCORD_PUBLIC_KEY_PATTERN).test(credentials.publicKey))
- errors.push({
- field: 'publicKey',
- message: 'Public Key must be a 64-character hex string',
- });
- if (!new RegExp(DISCORD_BOT_TOKEN_PATTERN).test(credentials.botToken))
- errors.push({
- field: 'botToken',
- message: 'Bot Token must be three dot-separated segments, as shown in the Discord portal',
- });
-
- if (errors.length > 0) return { errors, valid: false };
-
- try {
- const res = await fetch('https://discord.com/api/v10/users/@me', {
- headers: { Authorization: `Bot ${credentials.botToken}` },
- });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- return { valid: true };
- } catch {
- return {
- errors: [{ field: 'botToken', message: 'Failed to authenticate with Discord API' }],
- valid: false,
- };
- }
+ async validateCredentials(
+ credentials: Record<string, string>,
+ _settings?: Record<string, unknown>,
+ applicationId?: string,
+ ): Promise<ValidationResult> {
+ return validateDiscordCredentials(credentials, applicationId);
}
}
diff --git a/apps/server/src/services/bot/platforms/discord/validateCredentials.test.ts b/apps/server/src/services/bot/platforms/discord/validateCredentials.test.ts
new file mode 100644
index 00000000000..2ff8d5541e0
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/discord/validateCredentials.test.ts
@@ -0,0 +1,144 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { DiscordClientFactory } from './client';
+import { validateDiscordCredentials } from './validateCredentials';
+
+const APP_ID = '123456789012345678';
+const credentials = {
+ botToken: `${'a'.repeat(24)}.${'b'.repeat(6)}.${'c'.repeat(27)}`,
+ publicKey: 'f'.repeat(64),
+};
+
+const MESSAGE_CONTENT = 1 << 19;
+const MESSAGE_CONTENT_LIMITED = 1 << 18;
+
+type Route = { body?: unknown; status?: number } | 'network-error';
+
+const mockDiscord = (routes: Record<string, Route>) => {
+ const fetchMock = vi.fn(async (input: string | URL) => {
+ const path = String(input).replace('https://discord.com/api/v10', '');
+ const route = routes[path];
+ if (!route || route === 'network-error') throw new Error('network down');
+ const status = route.status ?? 200;
+ return new Response(JSON.stringify(route.body ?? {}), { status });
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ return fetchMock;
+};
+
+const healthyRoutes = (): Record<string, Route> => ({
+ '/applications/@me': { body: { flags: MESSAGE_CONTENT_LIMITED, id: APP_ID } },
+ '/users/@me': { body: { id: APP_ID } },
+ '/users/@me/guilds?limit=1': { body: [{ id: '1' }] },
+});
+
+const codes = (result: Awaited<ReturnType<typeof validateDiscordCredentials>>) =>
+ result.errors?.map((e) => e.code);
+
+describe('validateDiscordCredentials', () => {
+ beforeEach(() => {
+ vi.unstubAllGlobals();
+ });
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('passes a bot that is installed and can read message content', async () => {
+ mockDiscord(healthyRoutes());
+
+ await expect(validateDiscordCredentials(credentials, APP_ID)).resolves.toEqual({ valid: true });
+ });
+
+ it('accepts the full (verified-app) Message Content flag too', async () => {
+ mockDiscord({
+ ...healthyRoutes(),
+ '/applications/@me': { body: { flags: MESSAGE_CONTENT, id: APP_ID } },
+ });
+
+ await expect(validateDiscordCredentials(credentials, APP_ID)).resolves.toEqual({ valid: true });
+ });
+
+ it('reports a bot that has not been added to any server', async () => {
+ mockDiscord({ ...healthyRoutes(), '/users/@me/guilds?limit=1': { body: [] } });
+
+ const result = await validateDiscordCredentials(credentials, APP_ID);
+
+ expect(result.valid).toBe(false);
+ expect(codes(result)).toEqual(['bot_not_installed']);
+ });
+
+ it('reports Message Content Intent being off', async () => {
+ mockDiscord({
+ ...healthyRoutes(),
+ '/applications/@me': { body: { flags: 0, id: APP_ID } },
+ });
+
+ const result = await validateDiscordCredentials(credentials, APP_ID);
+
+ expect(result.valid).toBe(false);
+ expect(codes(result)).toEqual(['message_content_intent_disabled']);
+ });
+
+ it('reports an Application ID that belongs to another app', async () => {
+ mockDiscord(healthyRoutes());
+
+ const result = await validateDiscordCredentials(credentials, '999999999999999999');
+
+ expect(result.valid).toBe(false);
+ expect(codes(result)).toEqual(['application_mismatch']);
+ expect(result.errors?.[0].field).toBe('applicationId');
+ });
+
+ it('reports every setup gap at once', async () => {
+ mockDiscord({
+ ...healthyRoutes(),
+ '/applications/@me': { body: { flags: 0, id: APP_ID } },
+ '/users/@me/guilds?limit=1': { body: [] },
+ });
+
+ const result = await validateDiscordCredentials(credentials, APP_ID);
+
+ expect(codes(result)).toEqual(['message_content_intent_disabled', 'bot_not_installed']);
+ });
+
+ it('marks a rejected token as invalid credentials and skips follow-up checks', async () => {
+ const fetchMock = mockDiscord({ '/users/@me': { status: 401 } });
+
+ const result = await validateDiscordCredentials(credentials, APP_ID);
+
+ expect(codes(result)).toEqual(['invalid_credentials']);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not fail the bot when a follow-up lookup itself fails', async () => {
+ mockDiscord({
+ '/applications/@me': 'network-error',
+ '/users/@me': { body: { id: APP_ID } },
+ '/users/@me/guilds?limit=1': { status: 500 },
+ });
+
+ await expect(validateDiscordCredentials(credentials, APP_ID)).resolves.toEqual({ valid: true });
+ });
+
+ it('rejects malformed values before calling Discord', async () => {
+ const fetchMock = mockDiscord({});
+
+ const result = await validateDiscordCredentials({ botToken: 'nope', publicKey: 'xyz' }, APP_ID);
+
+ expect(result.errors?.map((e) => e.field)).toEqual(['publicKey', 'botToken']);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('is what DiscordClientFactory.validateCredentials runs, with the application ID', async () => {
+ mockDiscord({ ...healthyRoutes(), '/users/@me/guilds?limit=1': { body: [] } });
+
+ const result = await new DiscordClientFactory().validateCredentials(
+ credentials,
+ {},
+ APP_ID,
+ 'discord',
+ );
+
+ expect(codes(result)).toEqual(['bot_not_installed']);
+ });
+});
diff --git a/apps/server/src/services/bot/platforms/discord/validateCredentials.ts b/apps/server/src/services/bot/platforms/discord/validateCredentials.ts
new file mode 100644
index 00000000000..e02357e0d68
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/discord/validateCredentials.ts
@@ -0,0 +1,137 @@
+import type { BotCredentialErrorCode, ValidationError, ValidationResult } from '../types';
+import { DISCORD_BOT_TOKEN_PATTERN, DISCORD_PUBLIC_KEY_PATTERN } from './const';
+
+const DISCORD_API_BASE = 'https://discord.com/api/v10';
+
+/**
+ * Application flags that mean the Message Content privileged intent is on.
+ * `_LIMITED` is what an unverified app (under 100 servers) gets when the
+ * toggle in the Developer Portal's Bot page is enabled.
+ * https://discord.com/developers/docs/resources/application#application-object-application-flags
+ */
+const GATEWAY_MESSAGE_CONTENT = 1 << 19;
+const GATEWAY_MESSAGE_CONTENT_LIMITED = 1 << 18;
+
+const codeForStatus = (status: number): BotCredentialErrorCode | undefined => {
+ if (status === 401) return 'invalid_credentials';
+ if (status === 403) return 'permission_denied';
+ if (status === 429) return 'rate_limited';
+ if (status >= 500) return 'upstream_unavailable';
+};
+
+const getJson = async <T>(path: string, botToken: string): Promise<T | undefined> => {
+ try {
+ const res = await fetch(`${DISCORD_API_BASE}${path}`, {
+ headers: { Authorization: `Bot ${botToken}` },
+ });
+ if (!res.ok) return undefined;
+ return (await res.json()) as T;
+ } catch {
+ return undefined;
+ }
+};
+
+/**
+ * Check a Discord bot's credentials the way the bot will actually be used.
+ *
+ * A valid token alone is not a working bot: the most common reasons a
+ * "connected" Discord bot never answers are that it was never added to a
+ * server, that Message Content Intent is off, or that the Application ID
+ * belongs to another app. Each is reported with its own code so the form can
+ * say what to fix. The follow-up checks only report what Discord answered
+ * definitely; a failed lookup is not treated as a failure of the bot.
+ */
+export const validateDiscordCredentials = async (
+ credentials: Record<string, string>,
+ applicationId?: string,
+): Promise<ValidationResult> => {
+ const errors: ValidationError[] = [];
+
+ if (!credentials.botToken) errors.push({ field: 'botToken', message: 'Bot Token is required' });
+ if (!credentials.publicKey)
+ errors.push({ field: 'publicKey', message: 'Public Key is required' });
+
+ if (errors.length > 0) return { errors, valid: false };
+
+ // Name the actual problem before spending a round-trip on it — a
+ // malformed public key can't be caught by the API call at all, and a
+ // malformed token would come back as a generic auth failure.
+ if (!new RegExp(DISCORD_PUBLIC_KEY_PATTERN).test(credentials.publicKey))
+ errors.push({
+ field: 'publicKey',
+ message: 'Public Key must be a 64-character hex string',
+ });
+ if (!new RegExp(DISCORD_BOT_TOKEN_PATTERN).test(credentials.botToken))
+ errors.push({
+ field: 'botToken',
+ message: 'Bot Token must be three dot-separated segments, as shown in the Discord portal',
+ });
+
+ if (errors.length > 0) return { errors, valid: false };
+
+ const { botToken } = credentials;
+
+ try {
+ const res = await fetch(`${DISCORD_API_BASE}/users/@me`, {
+ headers: { Authorization: `Bot ${botToken}` },
+ });
+ if (!res.ok) {
+ return {
+ errors: [
+ {
+ code: codeForStatus(res.status),
+ field: 'botToken',
+ message: `Failed to authenticate with Discord API (HTTP ${res.status})`,
+ },
+ ],
+ valid: false,
+ };
+ }
+ } catch {
+ return {
+ errors: [
+ {
+ code: 'upstream_unavailable',
+ field: 'botToken',
+ message: 'Failed to authenticate with Discord API',
+ },
+ ],
+ valid: false,
+ };
+ }
+
+ const [application, guilds] = await Promise.all([
+ getJson<{ flags?: number; id?: string }>('/applications/@me', botToken),
+ getJson<unknown[]>('/users/@me/guilds?limit=1', botToken),
+ ]);
+
+ if (application?.id && applicationId && application.id !== applicationId) {
+ errors.push({
+ code: 'application_mismatch',
+ field: 'applicationId',
+ message: `The bot token belongs to application ${application.id}, not ${applicationId}`,
+ });
+ }
+
+ if (
+ application &&
+ typeof application.flags === 'number' &&
+ (application.flags & (GATEWAY_MESSAGE_CONTENT | GATEWAY_MESSAGE_CONTENT_LIMITED)) === 0
+ ) {
+ errors.push({
+ code: 'message_content_intent_disabled',
+ field: 'botToken',
+ message: 'Message Content Intent is not enabled for this application',
+ });
+ }
+
+ if (Array.isArray(guilds) && guilds.length === 0) {
+ errors.push({
+ code: 'bot_not_installed',
+ field: 'applicationId',
+ message: 'The bot has not been added to any server yet',
+ });
+ }
+
+ return errors.length > 0 ? { errors, valid: false } : { valid: true };
+};
diff --git a/apps/server/src/services/bot/platforms/types.ts b/apps/server/src/services/bot/platforms/types.ts
index 65ce38752b7..fb1fad11e66 100644
--- a/apps/server/src/services/bot/platforms/types.ts
+++ b/apps/server/src/services/bot/platforms/types.ts
@@ -569,8 +569,11 @@ export interface BotPlatformRuntimeContext {
* `agent` locale namespace, shared with the runtime-status error codes.
*/
export type BotCredentialErrorCode =
+ | 'application_mismatch'
| 'application_not_found'
+ | 'bot_not_installed'
| 'invalid_credentials'
+ | 'message_content_intent_disabled'
| 'missing_credentials'
| 'permission_denied'
| 'rate_limited'
diff --git a/docs/usage/channels/discord.mdx b/docs/usage/channels/discord.mdx
index f2b207e212e..724daf7c9ea 100644
--- a/docs/usage/channels/discord.mdx
+++ b/docs/usage/channels/discord.mdx
@@ -91,6 +91,8 @@ By connecting a Discord channel to your LobeHub agent, users can interact with t
## Step 3: Invite the Bot to Your Server
+The bot can only receive messages from a server it has been added to, so do this before testing the connection. Saving the configuration in LobeHub does not add the bot to any server.
+
<Steps>
### Generate an Invite URL
@@ -118,12 +120,19 @@ By connecting a Discord channel to your LobeHub agent, users can interact with t
Copy the generated URL, open it in your browser, select the server you want to add the bot to, and click **Authorize**.
- > **Private channels need explicit access.** Server-level authorization only grants the bot category/server defaults. If a channel is marked **Private Channel**, Discord ignores the bot's server-wide role and the bot won't receive any events there — including @mentions — until you open the channel's **Settings → Permissions** and add the bot (or a role it has) under **Members and roles**. You can also click **Sync Now** to make the channel inherit its category's permissions.
+ > **Private channels need explicit access.** Server-level authorization only grants the bot category/server defaults. If a channel is marked **Private Channel**, Discord ignores the bot's server-wide role and the bot won't receive any events there — including @mentions — until you open the channel's **Settings → Permissions** and add the bot (or a role it has) under **Members and roles**, with at least **View Channel**, **Send Messages**, **Read Message History** and **Send Messages in Threads** allowed. You can also click **Sync Now** to make the channel inherit its category's permissions.
</Steps>
## Step 4: Test the Connection
-Back in LobeHub's channel settings for Discord, click **Test Connection** to verify everything is configured correctly. Then send a message to your bot on Discord to confirm it responds.
+Back in LobeHub's channel settings for Discord, click **Test Connection**. It checks that:
+
+- the bot token is valid;
+- the Application ID belongs to the same app as the bot token;
+- **Message Content Intent** is turned on;
+- the bot has been added to at least one server.
+
+Then @mention your bot in a server channel on Discord to confirm it responds. Test Connection cannot see channel-level permissions, so if the bot answers in one channel but not another, see the private channel note in Step 3.
## Step 5: Set Your Platform Identity (Recommended)
@@ -195,4 +204,7 @@ See the [Channels overview](/docs/usage/channels/overview#direct-message-policy)
- **Bot not responding in server:** Confirm the bot has been invited to the server with the correct permissions, and Message Content Intent is enabled. If **Group Policy** is `Disabled` or `Allowlist`, double-check the channel is in **Allowed Channel IDs**. If **Allowed User IDs** is set, the sender's user ID must be in it.
- **@mention doesn't reach the bot in one specific channel:** The channel is likely a **Private Channel**. Discord drops every event for users/bots not explicitly listed in that channel's permissions, no matter what server-wide role they have. Open the channel's **Settings → Permissions**, click **Add members or roles**, and add the bot (or a role it has). Alternatively click **Sync Now** to inherit the parent category's permissions. A quick visual check: if the bot's name renders without an underline/link styling when you type `@<botname>`, Discord thinks it has no access to that channel.
- **Bot not responding to DMs:** Open **Advanced Settings** and confirm **DM Policy** is not set to `Disabled`. If **Allowed User IDs** is set, make sure the sender's Discord user ID is in it.
-- **Test Connection failed:** Double-check the Application ID, Bot Token, and Public Key are correct.
+- **Test Connection says the bot isn't in any server:** You haven't finished Step 3. Open the invite link, pick the server, and click **Authorize**, then test again.
+- **Test Connection says Message Content Intent is off:** In the Developer Portal, open **Bot → Privileged Gateway Intents**, turn on **Message Content Intent**, and click **Save Changes**.
+- **Test Connection says the Application ID doesn't match the bot token:** The two values come from different apps. Copy the Application ID from **General Information** and the token from **Bot** of the same app.
+- **Test Connection failed for another reason:** Double-check the Application ID, Bot Token, and Public Key are correct.
diff --git a/docs/usage/channels/discord.zh-CN.mdx b/docs/usage/channels/discord.zh-CN.mdx
index 1405401ce28..51f0a1d1d8c 100644
--- a/docs/usage/channels/discord.zh-CN.mdx
+++ b/docs/usage/channels/discord.zh-CN.mdx
@@ -90,6 +90,8 @@ tags:
## 第三步:邀请机器人加入您的服务器
+机器人只能收到它已加入的服务器里的消息,所以请在测试连接之前完成这一步。在 LobeHub 中保存配置并不会把机器人加入任何服务器。
+
<Steps>
### 生成邀请链接
@@ -117,12 +119,19 @@ tags:
复制生成的链接,在浏览器中打开,选择您希望添加机器人的服务器,然后点击 **授权**。
- > **私有频道需要单独授权。** 服务器层级的授权只会给机器人分类 / 服务器的默认权限。如果某个频道开启了 **Private Channel(私有频道)**,Discord 会忽略机器人在服务器层级的角色,机器人在该频道收不到任何事件(包括 @提及),直到你在频道的 **设置 → Permissions(权限)** 中点击 **Add members or roles**,把机器人本身或它持有的角色加进来。也可以直接点 **Sync Now** 让频道继承分类的权限。
+ > **私有频道需要单独授权。** 服务器层级的授权只会给机器人分类 / 服务器的默认权限。如果某个频道开启了 **Private Channel(私有频道)**,Discord 会忽略机器人在服务器层级的角色,机器人在该频道收不到任何事件(包括 @提及),直到你在频道的 **设置 → Permissions(权限)** 中点击 **Add members or roles**,把机器人本身或它持有的角色加进来,并至少允许 **查看频道**、**发送消息**、**阅读消息历史记录** 和 **在子区内发送消息**。也可以直接点 **Sync Now** 让频道继承分类的权限。
</Steps>
## 第四步:测试连接
-返回 LobeHub 的 Discord 渠道设置,点击 **测试连接** 以验证配置是否正确。然后在 Discord 中向您的机器人发送消息,确认其是否响应。
+返回 LobeHub 的 Discord 渠道设置,点击 **测试连接**。它会检查:
+
+- 机器人令牌是否有效;
+- 应用程序 ID 与机器人令牌是否属于同一个应用;
+- 是否开启了 **消息内容意图**;
+- 机器人是否已加入至少一个服务器。
+
+然后在 Discord 的服务器频道里 @您的机器人,确认其是否响应。测试连接看不到频道级权限,如果机器人在某个频道能回复、在另一个频道不能,请参考第三步中关于私有频道的说明。
## 第五步:填写你的平台身份(推荐)
@@ -194,4 +203,7 @@ LobeHub 通过三层叠加配置控制入站消息,全部位于 **高级设置
- **机器人未在服务器中响应:** 确认机器人已被邀请到服务器并拥有正确的权限,同时启用了消息内容意图。如果 **群组策略** 是 `Disabled` 或 `Allowlist`,确认目标频道在 **允许的频道 ID** 列表里。如果 **允许的用户 ID** 已填,发送者的用户 ID 必须在列表里。
- **某个频道里 @不到机器人:** 通常是因为该频道是 **Private Channel(私有频道)**。Discord 会丢弃所有未被显式加入频道权限列表的用户 / 机器人的事件,无论他们在服务器层级是什么角色。打开该频道的 **设置 → Permissions(权限)**,点击 **Add members or roles**,把机器人或它持有的角色加进来;或者点 **Sync Now** 让频道继承父分类的权限。一个快速肉眼判断:输入 `@<机器人名>` 时如果出现的机器人名字没有下划线 / 链接样式,说明 Discord 认为它无权访问该频道。
- **机器人不回私信:** 打开 **高级设置**,确认 **私信策略** 不是 `Disabled`。如果 **允许的用户 ID** 已填,确认发起方的 Discord 用户 ID 在列表里。
-- **测试连接失败:** 仔细检查应用程序 ID、机器人令牌和公钥是否正确。
+- **测试连接提示机器人未加入任何服务器:** 第三步还没完成。打开邀请链接,选择服务器并点击 **授权**,然后重新测试。
+- **测试连接提示未开启 Message Content Intent:** 在开发者门户打开 **机器人 → 特权网关意图**,开启 **消息内容意图** 并点击 **保存更改**。
+- **测试连接提示应用程序 ID 与机器人令牌不匹配:** 两个值来自不同的应用。请从同一个应用的 **常规信息** 复制应用程序 ID、从 **机器人** 页面复制令牌。
+- **测试连接因其他原因失败:** 仔细检查应用程序 ID、机器人令牌和公钥是否正确。
diff --git a/docs/usage/messenger/discord.mdx b/docs/usage/messenger/discord.mdx
index 21255ebf281..602054d4345 100644
--- a/docs/usage/messenger/discord.mdx
+++ b/docs/usage/messenger/discord.mdx
@@ -99,6 +99,7 @@ You can re-add the bot to a server (or re-link personally) at any time by repeat
- **"Server already connected"** — Another LobeHub user already added the bot to this server. DM the LobeHub bot on Discord to link your personal account; you do not need to add the bot again.
- **Discord install failed (`<reason>`)** — Common reasons: authorisation cancelled, install session expired (re-open the modal and try again), Discord returned incomplete data (retry; if persistent, contact support).
- **Bot is in the server but doesn't reply** — Check that you have a personal link under **Settings → Messenger → Discord**. The bot only answers users with a confirmed personal link.
+- **Bot replies in some channels but not in a private one** — Discord only delivers a private channel's messages to members listed in its permissions. Open the channel's **Settings → Permissions**, click **Add members or roles**, and add the LobeHub bot with **View Channel**, **Send Messages**, **Read Message History** and **Send Messages in Threads** allowed.
- **Removed the audit row but the bot is still in my server** — That's expected. Disconnecting in LobeHub only removes the audit entry; a Discord server admin must kick the bot from Discord itself.
- **"This link is already used"** — One-time confirmation links expire after one use. DM the bot again to get a new link.
- **"This account is already linked"** — Your Discord account is bound to a different LobeHub account. Sign in to that LobeHub account to manage the link, or unlink there before retrying.
diff --git a/docs/usage/messenger/discord.zh-CN.mdx b/docs/usage/messenger/discord.zh-CN.mdx
index e45948a2053..db77387c00d 100644
--- a/docs/usage/messenger/discord.zh-CN.mdx
+++ b/docs/usage/messenger/discord.zh-CN.mdx
@@ -98,6 +98,7 @@ Discord 也有两种含义不同的断开操作,有一处和 Slack 不同需
- **"Server already connected"(服务器已连接)** —— 服务器已被另一位 LobeHub 用户加过机器人。直接在 Discord 私聊 LobeHub 机器人完成个人关联即可,无需重新添加。
- **Discord 安装失败(`<原因>`)** —— 常见原因:用户取消授权、安装会话过期(重新打开弹窗再试)、Discord 返回的数据不完整(重试;持续失败请联系支持)。
- **机器人在服务器但不回我消息** —— 检查 **设置 → Messenger → Discord** 下你是否有个人关联。机器人只回复完成了个人关联的用户。
+- **机器人在其他频道能回复,在某个私有频道不回复** —— Discord 只会把私有频道的消息发给其权限列表里的成员。打开该频道的 **设置 → Permissions(权限)**,点击 **Add members or roles**,把 LobeHub 机器人加进来,并允许 **查看频道**、**发送消息**、**阅读消息历史记录** 和 **在子区内发送消息**。
- **断开了审计行,但机器人还在服务器里** —— 这是预期行为。在 LobeHub 里断开只移除审计记录,需要 Discord 服务器管理员手动从 Discord 那边把机器人踢出。
- **"This link is already used"** —— 一次性确认链接只能用一次,给机器人再发一条消息获取新链接。
- **"This account is already linked"** —— 这个 Discord 账号已绑定到另一个 LobeHub 账号。请用那个 LobeHub 账号登录管理,或先在那边解绑。
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index db49d784927..6b02fb78eaa 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -152,9 +152,12 @@
"channel.connectSuccess": "Bot connected successfully",
"channel.connecting": "Connecting...",
"channel.connectionConfig": "Connection Configuration",
+ "channel.connectionError.application_mismatch": "The Application ID doesn't match the bot token. Copy both from the same app in the Discord Developer Portal.",
"channel.connectionError.application_not_found": "The bot application does not exist. Check the application ID in the platform console.",
+ "channel.connectionError.bot_not_installed": "The bot isn't in any server yet. Open the invite link in the setup steps, add the bot to your server, then test again.",
"channel.connectionError.connection_closed": "The platform connection was interrupted. LobeHub will try to reconnect automatically.",
"channel.connectionError.invalid_credentials": "The bot credentials are invalid. Check the application ID, secret, and access tokens.",
+ "channel.connectionError.message_content_intent_disabled": "Message Content Intent is off, so the bot can't read messages. Turn it on under Bot → Privileged Gateway Intents in the Discord Developer Portal and save.",
"channel.connectionError.missing_credentials": "Required bot credentials are missing. Complete the bot configuration and try again.",
"channel.connectionError.permission_denied": "The platform denied access. Check the bot's permissions and enabled capabilities.",
"channel.connectionError.rate_limited": "The platform is rate limiting this bot. Wait a moment and try again.",
@@ -360,7 +363,7 @@
"channel.quickSetup.discord.create.title": "Create an application",
"channel.quickSetup.discord.credentials.desc": "Both are on General Information.",
"channel.quickSetup.discord.credentials.title": "Copy the Application ID and Public Key",
- "channel.quickSetup.discord.invite.desc": "The invite link already carries the permissions the bot needs.",
+ "channel.quickSetup.discord.invite.desc": "The invite link already carries the permissions the bot needs. For a private channel, also add the bot in that channel's Settings → Permissions.",
"channel.quickSetup.discord.invite.title": "Invite the bot to your server",
"channel.quickSetup.feishu.bot.desc": "Under App Capabilities, add Bot.",
"channel.quickSetup.feishu.bot.title": "Turn on the bot",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index ddc3ffa44d7..93c3a053b56 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -152,9 +152,12 @@
"channel.connectSuccess": "Bot 连接成功",
"channel.connecting": "连接中...",
"channel.connectionConfig": "连接配置",
+ "channel.connectionError.application_mismatch": "应用 ID 与 Bot Token 不属于同一个应用。请从 Discord 开发者后台的同一个应用中复制这两项。",
"channel.connectionError.application_not_found": "机器人应用不存在,请检查平台控制台中的应用 ID。",
+ "channel.connectionError.bot_not_installed": "机器人还没有加入任何服务器。请用接入步骤里的邀请链接把机器人添加到服务器,然后重新测试。",
"channel.connectionError.connection_closed": "平台连接已中断,LobeHub 将自动尝试重连。",
"channel.connectionError.invalid_credentials": "机器人凭据无效,请检查应用 ID、密钥和访问令牌。",
+ "channel.connectionError.message_content_intent_disabled": "未开启 Message Content Intent,机器人读不到消息内容。请在 Discord 开发者后台的 Bot → Privileged Gateway Intents 中开启并保存。",
"channel.connectionError.missing_credentials": "缺少必要的机器人凭据,请补全 Bot 配置后重试。",
"channel.connectionError.permission_denied": "平台拒绝了访问,请检查机器人的权限和已启用能力。",
"channel.connectionError.rate_limited": "平台正在限制该机器人的请求频率,请稍后重试。",
@@ -360,7 +363,7 @@
"channel.quickSetup.discord.create.title": "创建应用",
"channel.quickSetup.discord.credentials.desc": "都在 General Information 页面。",
"channel.quickSetup.discord.credentials.title": "复制 Application ID 和 Public Key",
- "channel.quickSetup.discord.invite.desc": "邀请链接已包含机器人需要的权限。",
+ "channel.quickSetup.discord.invite.desc": "邀请链接已包含机器人需要的权限。私有频道还需在该频道的设置 → 权限中添加机器人。",
"channel.quickSetup.discord.invite.title": "邀请机器人进服务器",
"channel.quickSetup.feishu.bot.desc": "在「应用能力」中添加「机器人」。",
"channel.quickSetup.feishu.bot.title": "开启机器人能力",
diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.ts
index 0f56cf708ad..bca8e6348fb 100644
--- a/packages/locales/src/default/agent.ts
+++ b/packages/locales/src/default/agent.ts
@@ -66,7 +66,7 @@ export default {
'On the Bot page, Reset Token and copy it, then turn on Message Content Intent.',
'channel.quickSetup.discord.invite.title': 'Invite the bot to your server',
'channel.quickSetup.discord.invite.desc':
- 'The invite link already carries the permissions the bot needs.',
+ "The invite link already carries the permissions the bot needs. For a private channel, also add the bot in that channel's Settings → Permissions.",
'channel.quickSetup.telegram.botfather.title': 'Create a bot with BotFather',
'channel.quickSetup.telegram.botfather.desc': 'Send /newbot and pick a name and username.',
'channel.quickSetup.telegram.token.title': 'Copy the token',
@@ -191,12 +191,18 @@ export default {
'channel.connectStarting': 'Bot is starting. Please wait a moment.',
'channel.connectSuccess': 'Bot connected successfully',
'channel.connecting': 'Connecting...',
+ 'channel.connectionError.application_mismatch':
+ "The Application ID doesn't match the bot token. Copy both from the same app in the Discord Developer Portal.",
'channel.connectionError.application_not_found':
'The bot application does not exist. Check the application ID in the platform console.',
+ 'channel.connectionError.bot_not_installed':
+ "The bot isn't in any server yet. Open the invite link in the setup steps, add the bot to your server, then test again.",
'channel.connectionError.connection_closed':
'The platform connection was interrupted. LobeHub will try to reconnect automatically.',
'channel.connectionError.invalid_credentials':
'The bot credentials are invalid. Check the application ID, secret, and access tokens.',
+ 'channel.connectionError.message_content_intent_disabled':
+ "Message Content Intent is off, so the bot can't read messages. Turn it on under Bot → Privileged Gateway Intents in the Discord Developer Portal and save.",
'channel.connectionError.missing_credentials':
'Required bot credentials are missing. Complete the bot configuration and try again.',
'channel.connectionError.permission_denied':
diff --git a/src/features/AgentChannel/quickSetup/guides.ts b/src/features/AgentChannel/quickSetup/guides.ts
index e9d4a4101d7..603a8b33285 100644
--- a/src/features/AgentChannel/quickSetup/guides.ts
+++ b/src/features/AgentChannel/quickSetup/guides.ts
@@ -24,6 +24,11 @@ export type SetupLinkLabel =
| 'openSlackApp';
export interface SetupStep {
+ /**
+ * Done before "save and connect" even though it asks for no credential: Discord's
+ * invite only needs the app ID, and a bot in no server fails the connection test.
+ */
+ beforeConnect?: boolean;
/**
* Keys of the credential fields this step is about (`applicationId`, or a key
* under `credentials`; `extras` is the platform's helper under them). While a bot is being set up they are filled in right
@@ -122,6 +127,7 @@ export const getSetupGuide = (
},
},
{
+ beforeConnect: true,
key: 'invite',
link: appId ? { href: buildDiscordInviteUrl(appId), label: 'inviteBot' } : undefined,
needsApplicationId: !appId,
@@ -186,11 +192,12 @@ export const getInlineFieldKeys = (platformId: string): Set<string> =>
);
/**
- * Where the "save and connect" step goes: right after the last step that asks for a credential,
- * since everything after it (inviting the bot, turning on a webhook, subscribing to events) needs
- * the bot to be saved and running. A guide whose steps ask for nothing gets it at the end.
+ * Where the "save and connect" step goes: right after the last step that asks for a credential
+ * or is marked `beforeConnect`, since everything after it (turning on a webhook, subscribing to
+ * events) needs the bot to be saved and running. A guide whose steps ask for nothing gets it at
+ * the end.
*/
export const connectStepIndex = (steps: SetupStep[]): number => {
- const last = steps.findLastIndex((step) => (step.fields?.length ?? 0) > 0);
+ const last = steps.findLastIndex((step) => step.beforeConnect || (step.fields?.length ?? 0) > 0);
return last === -1 ? steps.length : last + 1;
};
diff --git a/src/features/AgentChannel/quickSetup/quickSetup.test.ts b/src/features/AgentChannel/quickSetup/quickSetup.test.ts
index 9e8e250405c..9f1973cdc79 100644
--- a/src/features/AgentChannel/quickSetup/quickSetup.test.ts
+++ b/src/features/AgentChannel/quickSetup/quickSetup.test.ts
@@ -183,9 +183,17 @@ describe('getSetupGuide', () => {
return steps.map((step) => step.key).toSpliced(connectStepIndex(steps), 0, 'connect');
};
- expect(at('discord')).toEqual(['create', 'credentials', 'bot', 'connect', 'invite']);
+ // Discord's invite needs only the app ID, and a bot in no server fails the connection test.
+ expect(at('discord')).toEqual(['create', 'credentials', 'bot', 'invite', 'connect']);
expect(at('telegram')).toEqual(['botfather', 'token', 'connect', 'privacy']);
expect(at('line')).toEqual(['account', 'messagingApi', 'credentials', 'connect', 'webhook']);
expect(connectStepIndex([{ key: 'only' }])).toBe(1);
+ expect(
+ connectStepIndex([
+ { fields: ['token'], key: 'token' },
+ { beforeConnect: true, key: 'invite' },
+ { key: 'webhook' },
+ ]),
+ ).toBe(2);
});
});