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(bot): let Discord replies actually @-mention people (#21736)

Arvin Xue86c0f189e39
diff --git a/apps/server/src/services/bot/platforms/discord/client.test.ts b/apps/server/src/services/bot/platforms/discord/client.test.ts
index 5094a027c15..dc0a2f2eb90 100644
--- a/apps/server/src/services/bot/platforms/discord/client.test.ts
+++ b/apps/server/src/services/bot/platforms/discord/client.test.ts
@@ -362,7 +362,7 @@ describe('DiscordGatewayClient', () => {
it('names every mention and only strips the leading self mention', () => {
const client = createNumericClient();
expect(client.sanitizeUserInput!('<@111> 我搞了个 <@2000> 来抢你的活', { raw } as any)).toBe(
- '@Shadow Arvin 我搞了个 @Lobo 来抢你的活',
+ '@Shadow Arvin (<@111>) 我搞了个 @Lobo 来抢你的活',
);
expect(client.sanitizeUserInput!('<@2000> /new', { raw } as any)).toBe('/new');
});
@@ -370,7 +370,7 @@ describe('DiscordGatewayClient', () => {
it('resolveMentions keeps the self mention as a name', () => {
const client = createNumericClient();
expect(client.resolveMentions!('<@2000> hi <@111>', { raw } as any)).toBe(
- '@Lobo hi @Shadow Arvin',
+ '@Lobo hi @Shadow Arvin (<@111>)',
);
});
});
diff --git a/apps/server/src/services/bot/platforms/discord/client.ts b/apps/server/src/services/bot/platforms/discord/client.ts
index 24ba339f091..75aa5dead94 100644
--- a/apps/server/src/services/bot/platforms/discord/client.ts
+++ b/apps/server/src/services/bot/platforms/discord/client.ts
@@ -486,7 +486,7 @@ class DiscordGatewayClient implements PlatformClient {
}
resolveMentions(text: string, message?: unknown): string {
- return resolveDiscordMentions(text, collectDiscordMentionNames(message));
+ return resolveDiscordMentions(text, collectDiscordMentionNames(message), this.applicationId);
}
sanitizeUserInput(text: string, message?: unknown): string {
diff --git a/apps/server/src/services/bot/platforms/discord/mentions.test.ts b/apps/server/src/services/bot/platforms/discord/mentions.test.ts
index 1b231e26d8a..c8343d86032 100644
--- a/apps/server/src/services/bot/platforms/discord/mentions.test.ts
+++ b/apps/server/src/services/bot/platforms/discord/mentions.test.ts
@@ -63,9 +63,16 @@ describe('collectDiscordMentionNames', () => {
describe('resolveDiscordMentions', () => {
const names = new Map([[SHADOW, 'Shadow Arvin']]);
- it('replaces <@id> and <@!id> with @name', () => {
+ it('replaces <@id> and <@!id> with @name, keeping the token to mention them back', () => {
expect(resolveDiscordMentions(`<@${SHADOW}> hi <@!${SHADOW}>`, names)).toBe(
- '@Shadow Arvin hi @Shadow Arvin',
+ `@Shadow Arvin (<@${SHADOW}>) hi @Shadow Arvin (<@${SHADOW}>)`,
+ );
+ });
+
+ it('names the bot itself without its token', () => {
+ const withSelf = new Map([...names, [ME, 'Lobo']]);
+ expect(resolveDiscordMentions(`<@${ME}> 和 <@${SHADOW}>`, withSelf, ME)).toBe(
+ `@Lobo 和 @Shadow Arvin (<@${SHADOW}>)`,
);
});
@@ -87,7 +94,7 @@ describe('sanitizeDiscordUserInput', () => {
it('keeps the other bot and the self mention mid-sentence readable', () => {
const text = `<@${SHADOW}> 我搞了个 <@${ME}> 来抢你的活,你怎么说`;
expect(sanitizeDiscordUserInput(text, ME, makeMessage(mentionsRaw))).toBe(
- '@Shadow Arvin 我搞了个 @Lobo 来抢你的活,你怎么说',
+ `@Shadow Arvin (<@${SHADOW}>) 我搞了个 @Lobo 来抢你的活,你怎么说`,
);
});
@@ -103,6 +110,18 @@ describe('sanitizeDiscordUserInput', () => {
expect(sanitizeDiscordUserInput(`hello <@${ME}> there`, ME)).toBe('hello there');
});
+ it('keeps a third person addressable when the bot is asked to hand something to them', () => {
+ const raw = {
+ mentions: [
+ { bot: true, global_name: null, id: ME, username: 'Lobo' },
+ { global_name: 'Arvin Xu', id: SHADOW, username: 'arvinxx' },
+ ],
+ };
+ expect(
+ sanitizeDiscordUserInput(`<@${ME}> 汇总一下给到<@${SHADOW}>`, ME, makeMessage(raw)),
+ ).toBe(`汇总一下给到@Arvin Xu (<@${SHADOW}>)`);
+ });
+
it('leaves other unresolvable mentions in place instead of dropping them', () => {
expect(sanitizeDiscordUserInput(`<@${ME}> ping <@${SHADOW}>`, ME)).toBe(`ping <@${SHADOW}>`);
});
diff --git a/apps/server/src/services/bot/platforms/discord/mentions.ts b/apps/server/src/services/bot/platforms/discord/mentions.ts
index 5700e473d06..288c98e6018 100644
--- a/apps/server/src/services/bot/platforms/discord/mentions.ts
+++ b/apps/server/src/services/bot/platforms/discord/mentions.ts
@@ -59,14 +59,22 @@ export const collectDiscordMentionNames = (message?: unknown): Map<string, strin
};
/**
- * Rewrite `<@id>` tokens to `@Display Name` so the model reads who was
- * addressed instead of an opaque snowflake. Unknown ids are left untouched
+ * Rewrite `<@id>` tokens to `@Display Name (<@id>)` so the model reads who was
+ * addressed instead of an opaque snowflake, while keeping the token it must
+ * write back to notify that person: a bare `@Name` in a reply is plain text on
+ * Discord and pings nobody. The bot's own mention (`selfId`) is named only —
+ * there is no reason for the bot to ping itself. Unknown ids are left untouched
* rather than dropped — a raw id still tells the model *someone* was tagged.
*/
-export const resolveDiscordMentions = (text: string, names: Map<string, string>): string =>
+export const resolveDiscordMentions = (
+ text: string,
+ names: Map<string, string>,
+ selfId?: string,
+): string =>
text.replaceAll(USER_MENTION_RE, (token, id: string) => {
const name = names.get(id);
- return name ? `@${name}` : token;
+ if (!name) return token;
+ return id === selfId ? `@${name}` : `@${name} (<@${id}>)`;
});
/**
@@ -85,7 +93,8 @@ export const stripLeadingBotMention = (text: string, applicationId: string): str
* model sees the full message — not just the leading part, which it used to
* misread as another bot trying to take over:
* 1. strip the leading self-mention prefix;
- * 2. resolve every remaining user mention to `@name` via the message payload;
+ * 2. resolve every remaining user mention to `@name (<@id>)` via the message
+ * payload (the bot's own to `@name`);
* 3. drop self mentions that could not be named (Gateway path, no `mentions`)
* so the model never sees its own raw id.
*/
@@ -95,6 +104,10 @@ export const sanitizeDiscordUserInput = (
message?: unknown,
): string => {
const stripped = stripLeadingBotMention(text, applicationId);
- const resolved = resolveDiscordMentions(stripped, collectDiscordMentionNames(message));
+ const resolved = resolveDiscordMentions(
+ stripped,
+ collectDiscordMentionNames(message),
+ applicationId,
+ );
return resolved.replaceAll(new RegExp(`\\s*<@!?${applicationId}>`, 'g'), '').trim();
};
diff --git a/packages/context-engine/src/providers/__tests__/DiscordContextProvider.test.ts b/packages/context-engine/src/providers/__tests__/DiscordContextProvider.test.ts
index 8097e47e97d..8352a5234e8 100644
--- a/packages/context-engine/src/providers/__tests__/DiscordContextProvider.test.ts
+++ b/packages/context-engine/src/providers/__tests__/DiscordContextProvider.test.ts
@@ -3,6 +3,9 @@ import { describe, expect, it } from 'vitest';
import type { PipelineContext } from '../../types';
import { DiscordContextProvider } from '../DiscordContextProvider';
+const MENTION_SYNTAX =
+ ' <mention_syntax>To @-mention (notify) someone, write <@USER_ID> with their numeric Discord user id. A plain "@Name" is only text and notifies nobody. Mentions in incoming messages appear as "@Name (<@USER_ID>)": copy the <@USER_ID> part; the id of whoever wrote a message is the `id` on their <speaker> tag. Never invent an id; if you do not know it, write the name without "@".</mention_syntax>';
+
describe('DiscordContextProvider', () => {
const createContext = (messages: any[]): PipelineContext => ({
initialState: { messages: [] },
@@ -38,6 +41,7 @@ describe('DiscordContextProvider', () => {
expect(getInjectedContent(result, 1)).toBe(`<discord_context>
<guild id="123456" />
<channel id="789" name="general" type="0" topic="General discussion" />
+${MENTION_SYNTAX}
</discord_context>`);
expect(result.messages[2].content).toBe('Hello');
});
@@ -57,6 +61,7 @@ describe('DiscordContextProvider', () => {
expect(getInjectedContent(result)).toBe(`<discord_context>
<guild id="123" name="My Server" />
<channel id="789" name="dev" />
+${MENTION_SYNTAX}
</discord_context>`);
});
@@ -111,6 +116,7 @@ describe('DiscordContextProvider', () => {
expect(result.messages).toHaveLength(2);
expect(getInjectedContent(result)).toBe(`<discord_context>
<guild id="123" name="Server" />
+${MENTION_SYNTAX}
</discord_context>`);
});
@@ -126,6 +132,7 @@ describe('DiscordContextProvider', () => {
expect(result.messages).toHaveLength(2);
expect(getInjectedContent(result)).toBe(`<discord_context>
<channel id="789" name="general" type="0" />
+${MENTION_SYNTAX}
</discord_context>`);
});
@@ -144,6 +151,7 @@ describe('DiscordContextProvider', () => {
expect(getInjectedContent(result)).toBe(`<discord_context>
<guild id="123" />
<channel id="789" />
+${MENTION_SYNTAX}
</discord_context>`);
});
});
@@ -164,6 +172,7 @@ describe('DiscordContextProvider', () => {
expect(getInjectedContent(result)).toBe(`<discord_context>
<guild id="123" />
<channel id="789" topic="Bug reports only" />
+${MENTION_SYNTAX}
</discord_context>`);
});
@@ -182,6 +191,7 @@ describe('DiscordContextProvider', () => {
expect(getInjectedContent(result)).toBe(`<discord_context>
<guild id="123" />
<channel id="789" type="0" />
+${MENTION_SYNTAX}
</discord_context>`);
});
});
@@ -215,6 +225,7 @@ describe('DiscordContextProvider', () => {
<discord_context>
<guild id="123" />
<channel id="789" name="general" />
+${MENTION_SYNTAX}
</discord_context>`);
});
diff --git a/packages/prompts/src/prompts/discordContext/index.ts b/packages/prompts/src/prompts/discordContext/index.ts
index ac3d74fb323..62f46779b79 100644
--- a/packages/prompts/src/prompts/discordContext/index.ts
+++ b/packages/prompts/src/prompts/discordContext/index.ts
@@ -15,6 +15,14 @@ export interface DiscordThreadInfo {
name?: string;
}
+/**
+ * Discord only notifies a user for the `<@id>` token; a typed `@Name` renders
+ * as plain text. Inbound mentions reach the model as `@Name (<@id>)` (see the
+ * bot's `resolveDiscordMentions`), so it has the id to copy back.
+ */
+const MENTION_SYNTAX =
+ ' <mention_syntax>To @-mention (notify) someone, write <@USER_ID> with their numeric Discord user id. A plain "@Name" is only text and notifies nobody. Mentions in incoming messages appear as "@Name (<@USER_ID>)": copy the <@USER_ID> part; the id of whoever wrote a message is the `id` on their <speaker> tag. Never invent an id; if you do not know it, write the name without "@".</mention_syntax>';
+
export interface FormatDiscordContextOptions {
channel?: DiscordChannelInfo;
guild?: DiscordGuildInfo;
@@ -34,6 +42,7 @@ export interface FormatDiscordContextOptions {
* // <discord_context>
* // <guild id="123456" name="My Server" />
* // <channel id="789" name="general" type="0" topic="General discussion" />
+ * // <mention_syntax>...</mention_syntax>
* // </discord_context>
* ```
*/
@@ -64,5 +73,7 @@ export const formatDiscordContext = ({
parts.push(` <thread ${attrs.join(' ')} />`);
}
+ parts.push(MENTION_SYNTAX);
+
return `<discord_context>\n${parts.join('\n')}\n</discord_context>`;
};