Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(backend/copilot-bot): let the Discord bot mention server members and roles, never everyone (#14331)

Bently07054888f797
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/base.py b/autogpt_platform/backend/backend/copilot/bot/adapters/base.py
index 71a0090be9..543af72d52 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/base.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/base.py
@@ -133,10 +133,13 @@ class MessageContext:
text: str # with bot mentions stripped
bot_mentioned: bool = False
thread_history: tuple[MessageHistoryEntry, ...] = ()
- # Users the bot is allowed to @-mention back in this turn — populated
- # from the inbound platform message's mentions (excluding the bot itself).
- # `(display_name, platform_user_id)` pairs. Anyone not in this list won't
- # get pinged even if the LLM produces `@theirname` in its output.
+ # Users the bot may @-mention back in this turn: the author and anyone
+ # mentioned in the inbound message (excluding the bot itself), as
+ # `(display_name, platform_user_id)` pairs. An adapter may widen this at
+ # send time to members and roles of the server it is posting in (Discord
+ # does, by looking up the names the model used); it must never widen it to
+ # everyone/here-style broadcasts. Names that resolve to nothing stay plain
+ # text.
mentionable_users: tuple[tuple[str, str], ...] = ()
# Other threads/channels the message linked or @-referenced, fetched by the
# bot up-front so the model has their content without web-fetching Discord.
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py
index 4cd447d770..10281af53a 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py
@@ -5,6 +5,7 @@ thread creation, typing, button rendering. All platform-agnostic logic lives
in the core handler. Slash commands live in commands.py.
"""
+import asyncio
import io
import logging
import re
@@ -70,6 +71,18 @@ REFERENCED_MESSAGE_CONTEXT = 15
# channel name in the proactive-post resolver (see ``looks_like_channel_id``).
_SNOWFLAKE = re.compile(r"^\d{15,21}$")
+# Marks a role in the shared ``(name, id)`` mention allowlist; users carry a
+# bare snowflake. Kept on the id so the platform-neutral resolver needs no
+# knowledge of Discord's two mention markups.
+ROLE_ID_PREFIX = "role:"
+
+# Send-time member lookup: at most this many distinct @names are queried per
+# message, each returning up to this many prefix matches.
+MENTION_QUERY_CAP = 8
+MENTION_QUERY_LIMIT = 20
+# First word after an @ that is not inside an email, URL or existing token.
+_MENTION_CANDIDATE = re.compile(r"(?<![\w@<])@([A-Za-z0-9_][\w'\-]{0,31})")
+
class DiscordAdapter(SocketAdapter):
def __init__(self, api: BotBackend):
@@ -151,7 +164,9 @@ class DiscordAdapter(SocketAdapter):
) -> None:
channel = await self._resolve_channel(channel_id)
if channel and isinstance(channel, discord.abc.Messageable):
- rendered, allowed = _resolve_mentions(text, mentionable_users)
+ rendered, allowed = _resolve_mentions(
+ text, await self._mentionables_for(channel, text, mentionable_users)
+ )
# tts=False is the default but we pin it explicitly — AutoPilot
# output is untrusted and should never blast through voice.
await channel.send(rendered, tts=False, allowed_mentions=allowed)
@@ -196,7 +211,9 @@ class DiscordAdapter(SocketAdapter):
channel = await self._resolve_channel(channel_id)
if not channel or not isinstance(channel, discord.abc.Messageable):
return
- rendered, allowed = _resolve_mentions(text, mentionable_users)
+ rendered, allowed = _resolve_mentions(
+ text, await self._mentionables_for(channel, text, mentionable_users)
+ )
try:
msg = await channel.fetch_message(int(reply_to_message_id))
except discord.HTTPException: # any fetch failure: NotFound, Forbidden, 5xx
@@ -349,10 +366,13 @@ class DiscordAdapter(SocketAdapter):
later-chunk failure stops the send and keeps the partial result rather
than discarding what already posted (a retry would duplicate it).
"""
+ rendered, allowed = _resolve_mentions(
+ text, await self._mentionables_for(channel, text, ())
+ )
first: Optional[discord.Message] = None
- for chunk in iter_chunks(text, config.CHUNK_FLUSH_AT):
+ for chunk in iter_chunks(rendered, config.CHUNK_FLUSH_AT):
try:
- msg = await channel.send(chunk, tts=False)
+ msg = await channel.send(chunk, tts=False, allowed_mentions=allowed)
except discord.HTTPException:
if first is None:
raise
@@ -659,18 +679,80 @@ class DiscordAdapter(SocketAdapter):
replacement = "" if user.id == bot_id else f"@{user.display_name}"
for token in raw_tokens:
text = text.replace(token, replacement)
+ for role in getattr(message, "role_mentions", None) or ():
+ text = text.replace(f"<@&{role.id}>", f"@{role.name}")
return text.strip()
def _collect_mentionable_users(
self, message: discord.Message
) -> tuple[tuple[str, str], ...]:
- """Users from the inbound message the bot may ping back this turn."""
+ """The author and anyone mentioned in the inbound message. Server
+ members and roles are looked up at send time from the names the bot
+ actually uses (see ``_mentionables_for``)."""
bot_id = self._client.user.id if self._client.user else None
- return tuple(
- (user.display_name, str(user.id))
- for user in message.mentions
- if user.id != bot_id
- )
+ pairs: list[tuple[str, str]] = []
+ for user in (message.author, *message.mentions):
+ if user.id == bot_id:
+ continue
+ pair = (user.display_name, str(user.id))
+ if pair not in pairs:
+ pairs.append(pair)
+ return tuple(pairs)
+
+ async def _mentionables_for(
+ self,
+ channel: discord.abc.Messageable,
+ text: str,
+ known: tuple[tuple[str, str], ...],
+ ) -> tuple[tuple[str, str], ...]:
+ """Everyone ``text`` may ping in ``channel``: ``known`` (author and
+ inbound mentions) plus, for a server channel, any member whose display
+ name or username matches an ``@Name`` in the text and any role by name.
+
+ Members are found with a gateway member query per name, which needs no
+ privileged intent and works on any server. ``@everyone`` and ``@here``
+ are never listed, so they stay plain text and the ping object keeps
+ them off regardless. A DM has no server, so only ``known`` applies.
+ """
+ guild = getattr(channel, "guild", None)
+ if not isinstance(guild, discord.Guild):
+ return known
+ bot_id = self._client.user.id if self._client.user else None
+ pairs: list[tuple[str, str]] = list(known)
+ seen: set[tuple[str, str]] = set(pairs)
+
+ def add(name: Optional[str], token_id: str) -> None:
+ if name and (name, token_id) not in seen:
+ seen.add((name, token_id))
+ pairs.append((name, token_id))
+
+ role_names: set[str] = set()
+ for role in guild.roles:
+ if role.id == guild.id or role.is_default():
+ continue
+ add(role.name, f"{ROLE_ID_PREFIX}{role.id}")
+ role_names.add(role.name.casefold())
+ for query in _mention_queries(text):
+ if query.casefold() in role_names:
+ continue
+ try:
+ members = await guild.query_members(
+ query=query, limit=MENTION_QUERY_LIMIT, cache=False
+ )
+ except (
+ asyncio.TimeoutError,
+ ValueError,
+ discord.ClientException,
+ discord.HTTPException,
+ ):
+ logger.warning("Member lookup for @%s failed", query, exc_info=True)
+ continue
+ for member in members:
+ if member.id == bot_id or member.bot:
+ continue
+ add(member.display_name, str(member.id))
+ add(member.name, str(member.id))
+ return tuple(pairs)
async def _thread_history(
self, message: discord.Message
@@ -827,20 +909,41 @@ def _resolve_mentions(
shared in ``text.resolve_mentions``; here we only supply Discord's mention
token and turn the pinged IDs into Discord's ping-safety object.
"""
- rendered, pinged = resolve_mentions(
- text, mentionable_users, lambda _name, uid: f"<@{uid}>"
- )
- pinged_ids: list[int] = []
- for uid in pinged:
+ rendered, pinged = resolve_mentions(text, mentionable_users, _mention_token)
+ user_ids: list[int] = []
+ role_ids: list[int] = []
+ for token_id in pinged:
+ is_role = token_id.startswith(ROLE_ID_PREFIX)
try:
- pinged_ids.append(int(uid))
+ numeric = int(token_id.removeprefix(ROLE_ID_PREFIX))
except ValueError:
continue
- if not pinged_ids:
+ (role_ids if is_role else user_ids).append(numeric)
+ if not user_ids and not role_ids:
return rendered, discord.AllowedMentions.none()
return rendered, discord.AllowedMentions(
everyone=False,
- users=[discord.Object(id=uid) for uid in pinged_ids],
- roles=False,
+ users=[discord.Object(id=uid) for uid in user_ids] or False,
+ roles=[discord.Object(id=rid) for rid in role_ids] or False,
replied_user=False,
)
+
+
+def _mention_token(_name: str, token_id: str) -> str:
+ if token_id.startswith(ROLE_ID_PREFIX):
+ return f"<@&{token_id.removeprefix(ROLE_ID_PREFIX)}>"
+ return f"<@{token_id}>"
+
+
+def _mention_queries(text: str) -> list[str]:
+ """The distinct first words following an ``@`` in ``text``, capped, used as
+ member-query prefixes. ``everyone`` and ``here`` are skipped outright."""
+ queries: list[str] = []
+ for match in _MENTION_CANDIDATE.finditer(text):
+ word = match.group(1).rstrip("'-")
+ if word.casefold() in ("everyone", "here") or word in queries:
+ continue
+ queries.append(word)
+ if len(queries) >= MENTION_QUERY_CAP:
+ break
+ return queries
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter_test.py
index df4452938d..4f719e2a44 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter_test.py
@@ -12,6 +12,7 @@ from backend.copilot.bot.adapters.discord.adapter import (
THREAD_HISTORY_CHAR_BUDGET,
THREAD_HISTORY_LIMIT,
DiscordAdapter,
+ _mention_queries,
_resolve_mentions,
)
@@ -38,13 +39,40 @@ def _mention(user_id: int, display_name: str) -> MagicMock:
return user
-def _message(content: str, mentions: list[MagicMock]) -> MagicMock:
+def _message(
+ content: str,
+ mentions: list[MagicMock],
+ guild: MagicMock | None = None,
+ author: MagicMock | None = None,
+) -> MagicMock:
msg = MagicMock()
msg.content = content
msg.mentions = mentions
+ msg.role_mentions = []
+ msg.guild = guild
+ msg.author = author or _mention(5000, "Asker")
return msg
+def _role(role_id: int, name: str) -> MagicMock:
+ role = MagicMock()
+ role.id = role_id
+ role.name = name
+ return role
+
+
+def _guild_with(members: list[MagicMock], roles: list[MagicMock]) -> MagicMock:
+ guild = MagicMock(spec=discord.Guild)
+ guild.id = 777
+ guild.members = members
+ everyone = _role(777, "@everyone")
+ everyone.is_default.return_value = True
+ for role in roles:
+ role.is_default.return_value = False
+ guild.roles = [everyone, *roles]
+ return guild
+
+
class _AsyncHistory:
def __init__(self, messages: list[MagicMock]):
self._messages = messages
@@ -657,6 +685,26 @@ class TestResolveMentions:
)
assert allowed.everyone is False
+ def test_resolves_role_to_role_markup_and_pings_the_role(self):
+ rendered, allowed = _resolve_mentions(
+ "Paging @Platform and @Sue",
+ (("Platform", "role:42"), ("Sue", "12345")),
+ )
+ assert rendered == "Paging <@&42> and <@12345>"
+ assert isinstance(allowed.roles, list)
+ assert [getattr(r, "id", None) for r in allowed.roles] == [42]
+ assert isinstance(allowed.users, list)
+ assert [getattr(u, "id", None) for u in allowed.users] == [12345]
+ assert allowed.everyone is False
+
+ def test_everyone_stays_plain_when_not_allowlisted(self):
+ rendered, allowed = _resolve_mentions(
+ "Heads up @everyone", (("Platform", "role:42"),)
+ )
+ assert rendered == "Heads up @everyone"
+ assert allowed.everyone is False
+ assert allowed.roles is False
+
def test_resolves_standalone_mention_alongside_email_in_same_message(self):
rendered, _ = _resolve_mentions(
"@Sue, can you check [email protected]?",
@@ -677,12 +725,75 @@ class TestCollectMentionableUsers:
],
)
result = adapter._collect_mentionable_users(msg)
- assert result == (("Sue", "2000"),)
+ assert result == (("Asker", "5000"), ("Sue", "2000"))
- def test_returns_empty_when_only_bot_mentioned(self):
+ def test_dm_lists_only_author_when_only_bot_mentioned(self):
adapter, _ = _bare_adapter(bot_id=1000)
msg = _message("<@1000> hi", mentions=[_mention(1000, "AutoGPT")])
- assert adapter._collect_mentionable_users(msg) == ()
+ assert adapter._collect_mentionable_users(msg) == (("Asker", "5000"),)
+
+ @pytest.mark.asyncio
+ async def test_send_time_lookup_finds_members_and_roles_but_never_everyone(
+ self,
+ ):
+ adapter, _ = _bare_adapter(bot_id=1000)
+ bently = _mention(3000, "Bently")
+ bently.name = "bentlybro"
+ bently.bot = False
+ bot_member = _mention(1000, "AutoGPT")
+ bot_member.bot = True
+ guild = _guild_with([], [_role(42, "Platform")])
+ guild.query_members = AsyncMock(return_value=[bently, bot_member])
+ channel = MagicMock(spec=discord.TextChannel)
+ channel.guild = guild
+
+ result = await adapter._mentionables_for(
+ channel, "Paging @Bently and @Platform, not @everyone", (("Nick", "2"),)
+ )
+
+ guild.query_members.assert_awaited_once_with(
+ query="Bently", limit=20, cache=False
+ )
+ assert ("Nick", "2") in result
+ assert ("Bently", "3000") in result
+ assert ("bentlybro", "3000") in result
+ assert ("Platform", "role:42") in result
+ assert not any(name == "@everyone" for name, _ in result)
+ assert not any(token == "1000" for _, token in result)
+
+ @pytest.mark.asyncio
+ async def test_send_time_lookup_in_a_dm_keeps_only_known_users(self):
+ adapter, _ = _bare_adapter(bot_id=1000)
+ channel = MagicMock(spec=discord.DMChannel)
+ result = await adapter._mentionables_for(
+ channel, "Hey @Bently", (("Nick", "2"),)
+ )
+ assert result == (("Nick", "2"),)
+
+ @pytest.mark.asyncio
+ async def test_send_time_lookup_survives_a_failed_member_query(self):
+ adapter, _ = _bare_adapter(bot_id=1000)
+ guild = _guild_with([], [_role(42, "Platform")])
+ guild.query_members = AsyncMock(side_effect=TimeoutError())
+ channel = MagicMock(spec=discord.TextChannel)
+ channel.guild = guild
+
+ result = await adapter._mentionables_for(channel, "Hey @Ghost", ())
+
+ assert result == (("Platform", "role:42"),)
+
+ def test_mention_queries_strip_punctuation_and_skip_everyone(self):
+ assert _mention_queries(
+ "cc @Bently, @Platform. and @everyone plus [email protected] <@123>"
+ ) == ["Bently", "Platform"]
+
+ def test_role_mentions_in_the_inbound_message_become_readable(self):
+ adapter, _ = _bare_adapter(bot_id=1000)
+ msg = _message(
+ "<@1000> ask <@&42> please", mentions=[_mention(1000, "AutoGPT")]
+ )
+ msg.role_mentions = [_role(42, "Platform")]
+ assert adapter._strip_mentions(msg) == "ask @Platform please"
def _bare_adapter_with_api() -> tuple[DiscordAdapter, MagicMock, MagicMock]: