Skip to content

Commit d2fb912

Browse files
wcqqq1214Soulter
andauthored
fix: prevent Discord self-reply loops (#10425)
Co-authored-by: Soulter <[email protected]>
1 parent 03ce652 commit d2fb912

2 files changed

Lines changed: 39 additions & 0 deletions

File tree

‎astrbot/core/platform/sources/discord/client.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,9 @@ def _create_interaction_data(self, interaction: discord.Interaction) -> dict:
9898

9999
async def on_message(self, message: discord.Message) -> None:
100100
"""当接收到消息时触发"""
101+
if self.user is not None and message.author.id == self.user.id:
102+
return
103+
101104
if message.author.bot and not self.allow_bot_messages:
102105
return
103106

‎tests/test_discord_adapter.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
discord_platform_adapter,
1313
discord_platform_event,
1414
)
15+
from astrbot.core.platform.sources.discord.client import DiscordBotClient
1516
from astrbot.core.platform.sources.discord.discord_platform_adapter import (
1617
DiscordPlatformAdapter,
1718
)
@@ -26,6 +27,41 @@
2627
_WAV_PATH = "/tmp/discord_voice.wav"
2728

2829

30+
@pytest.mark.asyncio
31+
@pytest.mark.parametrize("allow_bot_messages", [False, True])
32+
@pytest.mark.parametrize(("author_id", "is_bot"), [(1, True), (2, True), (3, False)])
33+
async def test_discord_filters_self_messages(allow_bot_messages, author_id, is_bot):
34+
"""Reject self messages while preserving the other-bot setting.
35+
36+
Args:
37+
allow_bot_messages: Whether messages from other bots are enabled.
38+
author_id: The sender ID; 1 is the connected bot.
39+
is_bot: Whether the sender is a bot.
40+
"""
41+
client = DiscordBotClient(token="test", allow_bot_messages=allow_bot_messages)
42+
client._connection.user = SimpleNamespace(id=1)
43+
client.on_message_received = AsyncMock()
44+
message = SimpleNamespace(
45+
id=42,
46+
author=SimpleNamespace(
47+
id=author_id, bot=is_bot, name="tester", display_name="tester"
48+
),
49+
content="hello",
50+
clean_content="hello",
51+
channel=SimpleNamespace(id=123),
52+
guild=None,
53+
mentions=[],
54+
)
55+
56+
await client.on_message(message)
57+
58+
if author_id == 1 or (is_bot and not allow_bot_messages):
59+
client.on_message_received.assert_not_awaited()
60+
else:
61+
client.on_message_received.assert_awaited_once()
62+
assert client.on_message_received.call_args.args[0]["message"] is message
63+
64+
2965
@pytest.mark.asyncio
3066
@pytest.mark.parametrize("component_type", ["video", "video_url", "file"])
3167
@pytest.mark.parametrize("with_text", [False, True])

0 commit comments

Comments
 (0)