From c0321a2472c08b6b4e9cf176fa663acc422458d8 Mon Sep 17 00:00:00 2001 From: Yufeng He <40085740+he-yufeng@users.noreply.github.com> Date: Tue, 13 Oct 2026 05:23:16 +0800 Subject: [PATCH 1/2] fix(qqofficial): keep markdown-rejected sends as passive replies When the QQ official API refuses a native markdown payload, the fallback used to drop msg_id and resend through the active-message interface, which runs into the 304049 active-message rate limit and loses the reply threading. Reorder the fallback so a rejected markdown degrades to a plain content reply that keeps msg_id (passive reply, msg_type reset from 2 to 0, stream trailing newline restored). The stream newline repair retry also keeps msg_id. Only errors that are not markdown rejections take the active-send fallback, and if the active retry itself hits the markdown rejection (the passive failure was unrelated, e.g. an expired msg_id) it downgrades to plain content too instead of losing the message. Fallback raises are chained so the original rejection stays visible in logs. --- .../qqofficial/qqofficial_message_event.py | 99 +++++++++----- tests/test_qqofficial_group_message_create.py | 122 ++++++++++++++++++ 2 files changed, 187 insertions(+), 34 deletions(-) diff --git a/astrbot/core/platform/sources/qqofficial/qqofficial_message_event.py b/astrbot/core/platform/sources/qqofficial/qqofficial_message_event.py index 274932d09e0..13bbee4f475 100644 --- a/astrbot/core/platform/sources/qqofficial/qqofficial_message_event.py +++ b/astrbot/core/platform/sources/qqofficial/qqofficial_message_event.py @@ -679,25 +679,36 @@ async def _send_with_markdown_fallback( try: return await send_func(payload) except _QQOFFICIAL_SEND_API_ERRORS as err: - logger.info("[QQOfficial] 回复消息失败: %s, 尝试使用主动发送接口。", err) - if payload.get("msg_id"): + # markdown 被服务端拒绝(50056)时,保留 msg_id 退化为纯 content + # 被动回复。先去掉 msg_id 会把被动回复变成主动消息,既烧主动 + # 配额也可能直接失败(如 304049 主动消息限频)。 + if ( + isinstance(err, botpy.errors.ServerError) + and QQOfficialMessageEvent.MARKDOWN_NOT_ALLOWED_ERROR in str(err) + and payload.get("markdown") + and plain_text + ): + logger.warning( + "[QQOfficial] markdown 发送被拒绝,回退到 content 模式重试。" + ) fallback_payload = payload.copy() - fallback_payload.pop("msg_id", None) - try: - ret = await send_func(fallback_payload) - logger.info("[QQOfficial] 使用主动发送接口发送成功。") - return ret - except _QQOFFICIAL_SEND_API_ERRORS as fallback_err: - err = fallback_err - payload = fallback_payload - - if not isinstance(err, botpy.errors.ServerError): - raise + fallback_payload.pop("markdown", None) + fallback_payload["content"] = plain_text + if fallback_payload.get("msg_type") == 2: + fallback_payload["msg_type"] = 0 + if stream: + fallback_content = cast(str, fallback_payload.get("content") or "") + if fallback_content and not fallback_content.endswith("\n"): + fallback_payload["content"] = fallback_content + "\n" + return await send_func(fallback_payload) # QQ 流式 markdown 分片校验:内容必须以换行结尾。 # 某些边界场景服务端仍可能判定失败,这里做一次修正重试。 - if stream and QQOfficialMessageEvent.STREAM_MARKDOWN_NEWLINE_ERROR in str( - err + # 与消息 id 无关,保留 msg_id 继续走被动回复。 + if ( + stream + and isinstance(err, botpy.errors.ServerError) + and QQOfficialMessageEvent.STREAM_MARKDOWN_NEWLINE_ERROR in str(err) ): retry_payload = payload.copy() @@ -716,26 +727,46 @@ async def _send_with_markdown_fallback( ) return await send_func(retry_payload) - if ( - QQOfficialMessageEvent.MARKDOWN_NOT_ALLOWED_ERROR not in str(err) - or not payload.get("markdown") - or not plain_text - ): - raise + # 其余发送错误(如 msg_id 过期)才去 msg_id 走主动接口兜底。 + logger.info("[QQOfficial] 回复消息失败: %s, 尝试使用主动发送接口。", err) + if payload.get("msg_id"): + fallback_payload = payload.copy() + fallback_payload.pop("msg_id", None) + try: + ret = await send_func(fallback_payload) + logger.info("[QQOfficial] 使用主动发送接口发送成功。") + return ret + except _QQOFFICIAL_SEND_API_ERRORS as fallback_err: + # 被动发送的失败可能本就与 markdown 无关(如 msg_id 过期), + # 主动重试仍可能撞上 markdown 拒绝,这里同样降级为纯 + # content,否则消息整条丢失。 + if ( + isinstance(fallback_err, botpy.errors.ServerError) + and QQOfficialMessageEvent.MARKDOWN_NOT_ALLOWED_ERROR + in str(fallback_err) + and fallback_payload.get("markdown") + and plain_text + ): + logger.warning( + "[QQOfficial] 主动发送 markdown 同样被拒绝,降级为纯 content 重试。" + ) + downgrade_payload = fallback_payload.copy() + downgrade_payload.pop("markdown", None) + downgrade_payload["content"] = plain_text + if downgrade_payload.get("msg_type") == 2: + downgrade_payload["msg_type"] = 0 + if stream: + downgrade_content = cast( + str, downgrade_payload.get("content") or "" + ) + if downgrade_content and not downgrade_content.endswith( + "\n" + ): + downgrade_payload["content"] = downgrade_content + "\n" + return await send_func(downgrade_payload) + raise fallback_err from err - logger.warning( - "[QQOfficial] markdown 发送被拒绝,回退到 content 模式重试。" - ) - fallback_payload = payload.copy() - fallback_payload.pop("markdown", None) - fallback_payload["content"] = plain_text - if fallback_payload.get("msg_type") == 2: - fallback_payload["msg_type"] = 0 - if stream: - fallback_content = cast(str, fallback_payload.get("content") or "") - if fallback_content and not fallback_content.endswith("\n"): - fallback_payload["content"] = fallback_content + "\n" - return await send_func(fallback_payload) + raise async def upload_group_and_c2c_image( self, diff --git a/tests/test_qqofficial_group_message_create.py b/tests/test_qqofficial_group_message_create.py index 59ed22e0f5d..f6d7dc861e0 100644 --- a/tests/test_qqofficial_group_message_create.py +++ b/tests/test_qqofficial_group_message_create.py @@ -995,3 +995,125 @@ async def test_webhook_send_by_session_use_markdown_config_false_sends_content() assert kwargs["content"] == "webhook plain content" assert "markdown" not in kwargs assert "msg_type" not in kwargs + + +@pytest.mark.asyncio +async def test_markdown_rejected_keeps_msg_id_and_degrades_to_content(): + # Regression test for #10420: a markdown rejection (50056) must degrade to + # a plain-content passive reply with msg_id intact, not drop msg_id and + # become a proactive message (which hits the proactive quota, e.g. 304049). + calls = [] + + async def fake_send(payload): + calls.append(dict(payload)) + if len(calls) == 1: + raise botpy.errors.ServerError("不允许发送原生 markdown") + return {"id": "sent-content"} + + payload = { + "markdown": {"content": "**bold** text"}, + "msg_type": 2, + "msg_id": "passive-1", + } + ret = await QQOfficialMessageEvent._send_with_markdown_fallback( + fake_send, payload, "**bold** text" + ) + + assert ret == {"id": "sent-content"} + assert len(calls) == 2 + assert calls[1]["msg_id"] == "passive-1" + assert "markdown" not in calls[1] + assert calls[1]["content"] == "**bold** text" + assert calls[1]["msg_type"] == 0 + + +@pytest.mark.asyncio +async def test_non_markdown_error_still_falls_back_to_active_send(): + # Errors unrelated to the payload content (stale msg_id and the like) + # keep the old behavior: retry once without msg_id as a proactive message. + calls = [] + + async def fake_send(payload): + calls.append(dict(payload)) + if len(calls) == 1: + raise botpy.errors.NotFoundError("msg_id expired") + return {"id": "sent-active"} + + payload = { + "markdown": {"content": "**bold** text"}, + "msg_type": 2, + "msg_id": "passive-1", + } + ret = await QQOfficialMessageEvent._send_with_markdown_fallback( + fake_send, payload, "**bold** text" + ) + + assert ret == {"id": "sent-active"} + assert len(calls) == 2 + assert "msg_id" not in calls[1] + + +@pytest.mark.asyncio +async def test_stream_newline_retry_keeps_msg_id(): + # The stream markdown newline fix is a content correction, not an id + # problem, so the retry must stay a passive reply with msg_id. + calls = [] + + async def fake_send(payload): + calls.append(dict(payload)) + if len(calls) == 1: + raise botpy.errors.ServerError("流式消息md分片需要\\n结束") + return {"id": "sent-newline"} + + payload = { + "markdown": {"content": "partial chunk"}, + "msg_type": 2, + "msg_id": "passive-1", + } + ret = await QQOfficialMessageEvent._send_with_markdown_fallback( + fake_send, payload, "partial chunk", stream={"msg_seq": 1} + ) + + assert ret == {"id": "sent-newline"} + assert len(calls) == 2 + assert calls[1]["msg_id"] == "passive-1" + assert calls[1]["markdown"]["content"] == "partial chunk\n" + + +@pytest.mark.asyncio +async def test_markdown_fallback_active_retry_markdown_rejected_downgrades_to_plain_content(): + # The passive send can fail for a non-markdown reason (expired msg_id) and + # the active retry then hit the markdown rejection. The downgrade must + # cover the active path too, otherwise the message is lost entirely. + calls = [] + + async def send_func(payload): + calls.append(dict(payload)) + if len(calls) == 1: + raise botpy.errors.ServerError("msg_id expired") + if len(calls) == 2: + raise botpy.errors.ServerError( + f"50056 {QQOfficialMessageEvent.MARKDOWN_NOT_ALLOWED_ERROR}" + ) + return {"id": "sent-ok"} + + payload = { + "msg_id": "expired-msg", + "msg_type": 2, + "markdown": {"content": "**md**"}, + "message_reference": {"message_id": "quoted-1"}, + } + + ret = await QQOfficialMessageEvent._send_with_markdown_fallback( + send_func, payload, "plain fallback" + ) + + assert ret == {"id": "sent-ok"} + assert len(calls) == 3 + assert calls[0]["msg_id"] == "expired-msg" + assert "msg_id" not in calls[1] + assert calls[1]["markdown"] == {"content": "**md**"} + assert "markdown" not in calls[2] + assert calls[2]["content"] == "plain fallback" + assert calls[2]["msg_type"] == 0 + assert calls[2]["message_reference"] == {"message_id": "quoted-1"} From b36222b7e5951f8da22573966dde9d2febd69df1 Mon Sep 17 00:00:00 2001 From: Yufeng He <40085740+he-yufeng@users.noreply.github.com> Date: Tue, 3 Nov 2026 08:54:32 +0800 Subject: [PATCH 2/2] fix(qqofficial): keep stream newline retries passive --- .../qqofficial/qqofficial_message_event.py | 38 ++++++++++--------- 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/astrbot/core/platform/sources/qqofficial/qqofficial_message_event.py b/astrbot/core/platform/sources/qqofficial/qqofficial_message_event.py index fdf6ebf320a..ecf1fabc714 100644 --- a/astrbot/core/platform/sources/qqofficial/qqofficial_message_event.py +++ b/astrbot/core/platform/sources/qqofficial/qqofficial_message_event.py @@ -759,26 +759,12 @@ async def _send_with_markdown_fallback( fallback_payload["content"] = fallback_content + "\n" return await send_func(fallback_payload) - logger.info("[QQOfficial] 回复消息失败: %s, 尝试使用主动发送接口。", err) - if payload.get("msg_id") or payload.get("event_id"): - fallback_payload = payload.copy() - fallback_payload.pop("msg_id", None) - fallback_payload.pop("event_id", None) - try: - ret = await send_func(fallback_payload) - logger.info("[QQOfficial] 使用主动发送接口发送成功。") - return ret - except _QQOFFICIAL_SEND_API_ERRORS as fallback_err: - err = fallback_err - payload = fallback_payload - - if not isinstance(err, botpy.errors.ServerError): - raise - # QQ 流式 markdown 分片校验:内容必须以换行结尾。 # 某些边界场景服务端仍可能判定失败,这里做一次修正重试。 - if stream and QQOfficialMessageEvent.STREAM_MARKDOWN_NEWLINE_ERROR in str( - err + if ( + isinstance(err, botpy.errors.ServerError) + and stream + and QQOfficialMessageEvent.STREAM_MARKDOWN_NEWLINE_ERROR in str(err) ): retry_payload = payload.copy() @@ -797,6 +783,22 @@ async def _send_with_markdown_fallback( ) return await send_func(retry_payload) + logger.info("[QQOfficial] 回复消息失败: %s, 尝试使用主动发送接口。", err) + if payload.get("msg_id") or payload.get("event_id"): + fallback_payload = payload.copy() + fallback_payload.pop("msg_id", None) + fallback_payload.pop("event_id", None) + try: + ret = await send_func(fallback_payload) + logger.info("[QQOfficial] 使用主动发送接口发送成功。") + return ret + except _QQOFFICIAL_SEND_API_ERRORS as fallback_err: + err = fallback_err + payload = fallback_payload + + if not isinstance(err, botpy.errors.ServerError): + raise + if ( QQOfficialMessageEvent.MARKDOWN_NOT_ALLOWED_ERROR not in str(err) or not payload.get("markdown")