Skip to content

Commit e99432c

Browse files
ztzproSoulter
andauthored
fix(qqofficial): restore @ mentions in group messages (#9705)
- serialize valid At components as <@openid> markup - send mention-bearing replies and proactive messages as Markdown - preserve payload compatibility for media and guild channel messages - support legacy and current incoming mention formats - add regression tests for QQ Official @ mentions Co-authored-by: Soulter <[email protected]>
1 parent ae5a155 commit e99432c

3 files changed

Lines changed: 119 additions & 12 deletions

File tree

‎astrbot/core/platform/sources/qqofficial/qqofficial_message_event.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727

2828
from astrbot.api import logger
2929
from astrbot.api.event import AstrMessageEvent, MessageChain
30-
from astrbot.api.message_components import File, Image, Plain, Record, Video
30+
from astrbot.api.message_components import At, File, Image, Plain, Record, Video
3131
from astrbot.api.platform import AstrBotMessage, Group, PlatformMetadata
3232
from astrbot.core.platform.sources.qqofficial.qqofficial_chunked_upload import (
3333
QQOFFICIAL_CHUNKED_UPLOAD_THRESHOLD,
@@ -919,6 +919,10 @@ async def _parse_to_qqofficial(message: MessageChain):
919919
for i in message.chain:
920920
if isinstance(i, Plain):
921921
plain_text += i.text
922+
elif isinstance(i, At):
923+
mention_id = str(i.qq) if i.qq else ""
924+
if mention_id and mention_id != "all":
925+
plain_text += f'<qqbot-at-user id="{mention_id}" />'
922926
elif isinstance(i, Image) and not image_base64:
923927
if not i.file:
924928
raise ValueError("Unsupported image file format")

‎astrbot/core/platform/sources/qqofficial/qqofficial_platform_adapter.py‎

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -754,6 +754,25 @@ def replace_face(match):
754754
# Match face tags: <faceType=...>
755755
return re.sub(r"<faceType=\d+[^>]*>", replace_face, content)
756756

757+
@staticmethod
758+
def _strip_bot_mention_markup(content: str | None, mention_id: str) -> str:
759+
"""Remove the current bot's QQ mention markup from incoming text.
760+
761+
Args:
762+
content: Raw QQ message content.
763+
mention_id: OpenID of the mentioned bot.
764+
765+
Returns:
766+
Message content with current and legacy bot mention markup removed.
767+
"""
768+
import re
769+
770+
escaped_id = re.escape(mention_id)
771+
markup_pattern = (
772+
rf'(?:<qqbot-at-user\s+id="{escaped_id}"\s*/>|<@!?{escaped_id}>)'
773+
)
774+
return re.sub(rf"(?:[ \t]*{markup_pattern}[ \t]*)+", " ", content or "")
775+
757776
@staticmethod
758777
async def _parse_from_qqofficial(
759778
message: botpy.message.Message
@@ -845,12 +864,11 @@ async def _parse_from_qqofficial(
845864
group_mentioned = bool(bot_mention_ids) or force_group_mention
846865
plain_content_raw = message.content or ""
847866
for mention_id in bot_mention_ids:
848-
plain_content_raw = plain_content_raw.replace(
849-
f"<@{mention_id}>",
850-
"",
851-
).replace(
852-
f"<@!{mention_id}>",
853-
"",
867+
plain_content_raw = (
868+
QQOfficialPlatformAdapter._strip_bot_mention_markup(
869+
plain_content_raw,
870+
mention_id,
871+
)
854872
)
855873
abm.message_str = QQOfficialPlatformAdapter._parse_face_message(
856874
plain_content_raw.strip()
@@ -887,9 +905,9 @@ async def _parse_from_qqofficial(
887905
abm.self_id = ""
888906

889907
plain_content = QQOfficialPlatformAdapter._parse_face_message(
890-
message.content.replace(
891-
"<@!" + str(abm.self_id) + ">",
892-
"",
908+
QQOfficialPlatformAdapter._strip_bot_mention_markup(
909+
message.content,
910+
str(abm.self_id),
893911
).strip()
894912
)
895913

‎tests/test_qqofficial_group_message_create.py‎

Lines changed: 87 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -173,11 +173,17 @@ async def test_parse_group_message_create_quoted_context():
173173
][-1] == "answer"
174174

175175

176+
@pytest.mark.parametrize(
177+
"mention_markup",
178+
["<@bot-123>", "<@!bot-123>", '<qqbot-at-user id="bot-123" />'],
179+
)
176180
@pytest.mark.asyncio
177-
async def test_parse_group_message_create_bot_mention_cleans_plain_text():
181+
async def test_parse_group_message_create_bot_mention_cleans_plain_text(
182+
mention_markup: str,
183+
):
178184
_, message = _dispatch_group_message(
179185
_make_group_payload(
180-
content="<@!bot-123> hello there",
186+
content=f"{mention_markup} hello there",
181187
mentions=[{"id": "bot-123", "is_you": True}],
182188
)
183189
)
@@ -197,6 +203,54 @@ async def test_parse_group_message_create_bot_mention_cleans_plain_text():
197203
assert abm.group_id == "group-1"
198204

199205

206+
@pytest.mark.parametrize(
207+
("content", "mention_id", "expected"),
208+
[
209+
("before<@bot-123>after", "bot-123", "before after"),
210+
("before <@bot-123><@!bot-123> after", "bot-123", "before after"),
211+
(
212+
'before<qqbot-at-user id="bot-123" />after',
213+
"bot-123",
214+
"before after",
215+
),
216+
("before<@other-user>after", "bot-123", "before<@other-user>after"),
217+
("before<@bot.123>after", "bot.123", "before after"),
218+
],
219+
)
220+
def test_strip_bot_mention_markup_preserves_word_boundaries(
221+
content: str,
222+
mention_id: str,
223+
expected: str,
224+
):
225+
normalized = QQOfficialPlatformAdapter._strip_bot_mention_markup(
226+
content,
227+
mention_id,
228+
)
229+
230+
assert normalized.strip() == expected
231+
232+
233+
@pytest.mark.asyncio
234+
async def test_parse_to_qqofficial_preserves_at_component_order():
235+
parsed = await QQOfficialMessageEvent._parse_to_qqofficial(
236+
MessageChain(chain=[At(qq="member-1"), Plain(" hello"), At(qq="all")])
237+
)
238+
239+
assert parsed[0] == '<qqbot-at-user id="member-1" /> hello'
240+
241+
242+
@pytest.mark.parametrize("qq", [None, ""])
243+
@pytest.mark.asyncio
244+
async def test_parse_to_qqofficial_ignores_empty_at_component(qq: str | None):
245+
mention = At(qq="placeholder")
246+
mention.qq = cast(Any, qq)
247+
chain = MessageChain(chain=[mention, Plain("hello")])
248+
249+
parsed = await QQOfficialMessageEvent._parse_to_qqofficial(chain)
250+
251+
assert parsed[0] == "hello"
252+
253+
200254
@pytest.mark.asyncio
201255
async def test_legacy_group_at_path_forces_bot_mention_when_mentions_missing():
202256
message = botpy.message.GroupMessage(
@@ -471,6 +525,37 @@ async def test_ws_group_send_by_session_with_cached_msg_id_still_omits_msg_id():
471525
assert "msg_seq" in kwargs
472526

473527

528+
@pytest.mark.asyncio
529+
async def test_ws_group_send_by_session_with_at_uses_text_chain_markup():
530+
adapter = QQOfficialPlatformAdapter(
531+
{
532+
"id": "qq-official-test",
533+
"appid": "123",
534+
"secret": "secret",
535+
"enable_group_c2c": True,
536+
"enable_guild_direct_message": False,
537+
},
538+
{},
539+
asyncio.Queue(),
540+
)
541+
adapter.client.api = SimpleNamespace(
542+
post_group_message=AsyncMock(return_value={"id": "sent-at"}),
543+
post_message=AsyncMock(),
544+
)
545+
adapter._session_scene["group-1"] = "group"
546+
chain = MessageChain(chain=[At(qq="member-1"), Plain(" hello")])
547+
chain.use_markdown(False)
548+
549+
await adapter.send_by_session(
550+
MessageSession("qq_official", MessageType.GROUP_MESSAGE, "group-1"),
551+
chain,
552+
)
553+
554+
kwargs = adapter.client.api.post_group_message.await_args.kwargs
555+
assert kwargs["content"] == '<qqbot-at-user id="member-1" /> hello'
556+
assert "markdown" not in kwargs
557+
558+
474559
@pytest.mark.asyncio
475560
async def test_media_upload_propagates_qq_api_error(monkeypatch):
476561
"""QQ upload errors propagate so callers cannot report a false success."""

0 commit comments

Comments
 (0)