diff --git a/app/modules/wechat/__init__.py b/app/modules/wechat/__init__.py index b817fe599..c9664e6ed 100644 --- a/app/modules/wechat/__init__.py +++ b/app/modules/wechat/__init__.py @@ -335,7 +335,7 @@ class WechatModule(_MessageChannelModuleBase[WeChat | WeChatBot]): def post_message(self, message: Message, **kwargs: object) -> None: """ - 向符合通知规则的实例发送文本、图文或语音。 + 向符合通知规则的实例发送文本、图文、原生图片或语音。 :param message: 通知内容及接收对象;语音发送失败时回退到文本或图文 :param kwargs: 兼容模块分发的附加参数,当前不使用 @@ -347,6 +347,10 @@ class WechatModule(_MessageChannelModuleBase[WeChat | WeChatBot]): client = self.get_instance(conf.name) if client: text = message.channel_text(NotificationChannel.Wechat, conf.config) or message.text + if message.native_image and message.image and isinstance(client, WeChat): + client.send_msg(title=message.title, text=text, image=message.image, + userid=userid, link=message.link, native_image=True) + continue if message.voice_path and hasattr(client, "send_voice"): sent = client.send_voice( voice_path=message.voice_path, diff --git a/app/modules/wechat/wechat.py b/app/modules/wechat/wechat.py index 4653cbb02..568cdcea6 100644 --- a/app/modules/wechat/wechat.py +++ b/app/modules/wechat/wechat.py @@ -22,6 +22,9 @@ from app.runtime.log import logger lock = threading.Lock() +# 企业微信临时图片素材上限为 10 MiB,仅接受 JPG、PNG。 +_IMAGE_MAX_BYTES = 10 * 1024 * 1024 + class RetryException(Exception): """ @@ -284,15 +287,17 @@ class WeChat: return False def send_msg(self, title: Optional[str], text: Optional[str] = None, image: Optional[str] = None, - userid: Optional[str] = None, link: Optional[str] = None) -> Optional[bool]: + userid: Optional[str] = None, link: Optional[str] = None, *, + native_image: bool = False) -> Optional[bool]: """ - 获取访问令牌后发送文本或图文消息。 + 获取访问令牌后发送文本、图文或显式指定的原生图片消息。 :param title: 消息标题 :param text: 消息正文 - :param image: 封面地址;非空时使用图文消息,否则使用文本 + :param image: 图片地址;默认作为图文封面,原生图片还支持 Base64 数据地址 :param userid: 企业微信用户标识;为空时发送给全体应用成员 :param link: 消息跳转地址 + :param native_image: 有图片时上传并发送原生图片;标题和正文另发文本,忽略跳转地址 :return: 接口接受消息时返回 True;发送失败返回 False;无访问令牌返回 None """ try: @@ -300,6 +305,8 @@ class WeChat: logger.error("获取微信access_token失败,请检查参数配置") return None + if image and native_image: + return self._send_native_image(image=image, title=title, text=text, userid=userid) if image: ret_code = self.__send_image_message(title=title, text=text, image_url=image, userid=userid, link=link) else: @@ -310,6 +317,90 @@ class WeChat: logger.error(f"发送消息失败:{e}") return False + @staticmethod + def _load_native_image(image: str) -> Optional[bytes]: + """ + 读取原生图片并限制下载量,不在磁盘或图片缓存中保存二维码。 + + :param image: HTTP(S) 图片地址或 JPG/PNG 的 Base64 数据地址 + :return: 大于 5 字节且不超过 10 MiB 的 JPG/PNG 内容;来源、格式或大小无效返回 None + """ + content: Optional[bytes] + if image.startswith("data:image/"): + try: + header, encoded = image.split(",", 1) + if not header.endswith(";base64") or len(encoded) > ((_IMAGE_MAX_BYTES + 2) // 3) * 4: + logger.error("企业微信原生图片数据地址无效或超过 10MB") + return None + content = base64.b64decode(encoded, validate=True) + except ValueError: + logger.error("企业微信原生图片 Base64 数据无效") + return None + elif image.startswith(("https://", "http://")): + content = WeChat._download_native_image(image) + else: + logger.error("企业微信原生图片仅支持 HTTP(S) 或 Base64 数据地址") + return None + + if not content or not 5 < len(content) <= _IMAGE_MAX_BYTES or WeChat._guess_mime_type(content, "") not in { + "image/jpeg", "image/png", + }: + logger.error("企业微信原生图片必须为大于 5 字节且不超过 10MB 的 JPG/PNG") + return None + return content + + @staticmethod + def _download_native_image(image: str) -> Optional[bytes]: + """ + 有界读取图片响应,并在成功、拒绝或读取异常时关闭连接。 + + :param image: 插件显式指定的 HTTP(S) 图片地址 + :return: 下载得到的原始字节;无响应、非 200 响应或超过 10 MiB 时返回 None + """ + response = RequestUtils(timeout=30).get_res(image, stream=True) + if response is None: + return None + try: + if response.status_code != 200: + logger.error(f"下载企业微信原生图片失败,HTTP 状态码:{response.status_code}") + return None + chunks = bytearray() + for chunk in response.iter_content(chunk_size=64 * 1024): + if len(chunks) + len(chunk) > _IMAGE_MAX_BYTES: + logger.error("企业微信原生图片超过 10MB") + return None + chunks.extend(chunk) + return bytes(chunks) + finally: + response.close() + + def _send_native_image(self, image: str, title: Optional[str], text: Optional[str], + userid: Optional[str]) -> bool: + """ + 上传原图并发送图片消息,附带文字独立发送且不使用图文卡片。 + + :param image: HTTP(S) 或 Base64 图片地址 + :param title: 可选的说明标题 + :param text: 可选的说明正文 + :param userid: 企业微信用户标识;为空时发送给全体应用成员 + :return: 图片及附带文字均发送成功时返回 True;任一步骤失败返回 False + """ + content = self._load_native_image(image) + if content is None: + return False + suffix = ".png" if content.startswith(b"\x89PNG\r\n\x1a\n") else ".jpg" + media_id = self._upload_temp_media(Path(f"image{suffix}"), media_type="image", content=content) + if not media_id: + return False + if (title or text) and not self.__send_message(title=title, text=text, userid=userid): + return False + return self.__post_request(self._send_msg_url, { + "touser": userid or "@all", + "msgtype": "image", + "agentid": self._appid, + "image": {"media_id": media_id}, + }) + @staticmethod def _guess_mime_type(content: bytes, default: str = "image/jpeg") -> str: """ @@ -457,12 +548,14 @@ class WeChat: return None return dst_path - def _upload_temp_media(self, media_path: Path, media_type: str = "voice") -> Optional[str]: + def _upload_temp_media(self, media_path: Path, media_type: str = "voice", *, + content: Optional[bytes] = None) -> Optional[str]: """ 上传临时素材并取得企业微信媒体标识。 - :param media_path: 需要完整读入内存的本地素材路径 + :param media_path: 本地素材路径;传入 content 时仅使用文件名,不读取磁盘 :param media_type: 企业微信素材类型,默认 voice + :param content: 可直接上传的素材字节;为空时从 media_path 读取,保留语音调用兼容性 :return: 上传成功的 media_id;读取、请求或响应解析失败返回 None """ access_token = self.__get_access_token() @@ -474,8 +567,12 @@ class WeChat: ) try: # 先读入字节并关闭文件,避免上传过程持有文件句柄 - with media_path.open("rb") as media_file: - file_content = media_file.read() + if content is None: + content = media_path.read_bytes() + + mime_type = "voice/amr" if media_type == "voice" else "application/octet-stream" + if media_type == "image": + mime_type = self._guess_mime_type(content) # 只声明响应格式,让请求库按文件上传内容生成 Content-Type response = RequestUtils(timeout=60).request( @@ -485,8 +582,8 @@ class WeChat: files={ "media": ( media_path.name, - file_content, - "voice/amr" if media_type == "voice" else "application/octet-stream", + content, + mime_type, ) }, ) diff --git a/app/schemas/message.py b/app/schemas/message.py index a640e2778..4eb164987 100644 --- a/app/schemas/message.py +++ b/app/schemas/message.py @@ -275,6 +275,7 @@ class Message(BaseModel): title: Optional[str] = Field(default=None, description="标题") text: Optional[str] = Field(default=None, description="文本内容") image: Optional[str] = Field(default=None, description="图片") + native_image: bool = Field(default=False, description="是否发送原生图片;企业微信自建应用支持,默认沿用图文消息") poster: Optional[str] = Field(default=None, description="独立媒体海报,不使用背景图回退") voice_path: Optional[str] = Field(default=None, description="语音文件路径") file_path: Optional[str] = Field(default=None, description="本地文件路径") diff --git a/app/sdk/plugin/base.py b/app/sdk/plugin/base.py index bb29a6257..e78c108b7 100644 --- a/app/sdk/plugin/base.py +++ b/app/sdk/plugin/base.py @@ -432,6 +432,7 @@ class _PluginBase(metaclass=ABCMeta): 发送消息,沿用宿主通知开关和收件人路由。 :param kwargs: 可传 rich_content 通用结构化通知;宿主按渠道能力排版,text 保留为纯文本回退。 + 传 native_image=True 可让企业微信自建应用发送完整原图,默认仍发送图文卡片。 """ if not link: link = settings.MP_DOMAIN(f"#/plugins?tab=installed&id={self.__class__.__name__}") diff --git a/docs/mcp-api.md b/docs/mcp-api.md index 7b955431b..9f0172017 100644 --- a/docs/mcp-api.md +++ b/docs/mcp-api.md @@ -315,6 +315,12 @@ Web 会话沿用当前用户;无渠道调用不携带收件人,插件回执 新通知从已有媒体上下文提取海报;`image` 继续保留原有渠道图片语义。 旧通知及没有海报的通知返回 `poster: null`,客户端不应将背景图裁切成海报。 +插件通过 `post_message(image=..., native_image=True)` 可请求企业微信自建应用发送完整原图, +适用于二维码和截图。`image` 支持 HTTP(S) 或 Base64 JPG/PNG 数据地址,内容须大于 5 字节且 +不超过 10 MiB;有标题或正文时另发文本,`link`(包括插件默认详情链接)不会用于原生图片。 +下载、上传或发送失败会记录错误,不回退为图文卡片。省略开关时仍使用图文,机器人模式和其他渠道 +保持原有行为;此开关不改变通知权限与收件人路由。 + `POST /api/v1/notification/config` 保存通知渠道时要求名称和稳定 `id` 各自唯一。 改名应保留原 `id`;复制为新的渠道实例应使用新的 `id`,避免共享登录凭据。 通过消息渠道发起普通重启时,完成回执保留发起时的 `source` 配置。 diff --git a/skills/create-moviepilot-plugin/SKILL.md b/skills/create-moviepilot-plugin/SKILL.md index 3145f3567..3752b8f9e 100644 --- a/skills/create-moviepilot-plugin/SKILL.md +++ b/skills/create-moviepilot-plugin/SKILL.md @@ -372,7 +372,12 @@ Use only the extension points the requested plugin actually needs: `init_plugin()` reads config; `update_config()` persists internal changes. - Data: use `save_data()`, `get_data()`, `del_data()`, and `get_data_path()`. - Notification: use `post_message()` instead of directly calling message - modules. + modules. For QR codes or screenshots sent through a WeCom custom application, + pass `image=, native_image=True`. + This uploads and sends a native image with any title/text sent separately; + the link (including the default plugin-page link) is ignored. Images must be + larger than 5 bytes and at most 10 MiB. The default remains a news card; + other channels and WeCom bot mode keep their existing behavior. - APIs: return route definitions from `get_api()`; default auth is `apikey` when `auth` is omitted. Vue component APIs should normally use `auth: "bear"` and be called through the `api` prop passed by the frontend. diff --git a/tests/test_wechat_native_image.py b/tests/test_wechat_native_image.py new file mode 100644 index 000000000..fe8ca425c --- /dev/null +++ b/tests/test_wechat_native_image.py @@ -0,0 +1,354 @@ +""" +验证企业微信显式原生图片通知的 SDK 透传、素材上传及默认图文兼容性。 +""" + +import base64 +import json +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +from app.modules.wechat import WechatModule +from app.modules.wechat import wechat as wechat_client +from app.modules.wechat.wechat import WeChat +from app.modules.wechat.wechatbot import WeChatBot +from app.schemas.message import Message +from app.schemas.types import NotificationChannel +from app.sdk.plugin import base as plugin_base +from app.sdk.plugin.base import _PluginBase + +_PNG = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jYH0AAAAASUVORK5CYII=" +) +_PNG_DATA_URL = f"data:image/png;base64,{base64.b64encode(_PNG).decode()}" +_IMAGE_URL = "https://images.example/login.png?token=private" +_SEND_URL = "https://wecom.example/cgi-bin/message/send?access_token={access_token}" +_UPLOAD_URL = "https://wecom.example/cgi-bin/media/upload?access_token={access_token}&type={media_type}" + + +@pytest.fixture +def http(monkeypatch: pytest.MonkeyPatch) -> Mock: + """ + 替换图片下载、临时素材上传和消息发送,禁止真实网络请求。 + """ + request_utils = Mock() + transport = request_utils.return_value + transport.get_res.return_value.status_code = 200 + transport.get_res.return_value.iter_content.return_value = [_PNG[:8], _PNG[8:]] + transport.request.return_value.json.return_value = {"errcode": 0, "media_id": "image-media"} + transport.post.return_value.status_code = 200 + transport.post.return_value.json.return_value = {"errcode": 0} + monkeypatch.setattr(wechat_client, "RequestUtils", request_utils) + return transport + + +@pytest.fixture +def client(monkeypatch: pytest.MonkeyPatch) -> WeChat: + """ + 提供无初始化网络请求、令牌固定且不影响其他实例的自建应用客户端。 + """ + result = WeChat.__new__(WeChat) + result._appid = "1000002" + result._send_msg_url = _SEND_URL + result._upload_media_url = _UPLOAD_URL + monkeypatch.setattr(result, "_WeChat__get_access_token", Mock(return_value="access-token")) + return result + + +def _payloads(http: Mock) -> list[dict]: + """ + 解码消息发送请求,按发送顺序保留载荷。 + """ + return [json.loads(call.kwargs["data"]) for call in http.post.call_args_list] + + +@pytest.mark.parametrize("image", [_IMAGE_URL, _PNG_DATA_URL]) +@pytest.mark.parametrize("userid", [None, "member-1"]) +def test_native_image_uploads_original_bytes_and_sends_caption_separately( + client: WeChat, http: Mock, image: str, userid: str | None, +) -> None: + """ + 图片先上传原始字节,说明文字和图片分别发送且不夹带插件详情链接。 + """ + assert client.send_msg( + title="扫码登录", text="请在过期前扫描二维码", image=image, userid=userid, + link="https://moviepilot.example/#/plugins?id=Login", native_image=True, + ) is True + + upload = http.request.call_args.kwargs + assert upload["url"] == "https://wecom.example/cgi-bin/media/upload?access_token=access-token&type=image" + assert upload["headers"] == {"Accept": "application/json"} + assert upload["files"] == {"media": ("image.png", _PNG, "image/png")} + sent = _payloads(http) + assert [payload["msgtype"] for payload in sent] == ["text", "image"] + assert "扫码登录" in sent[0]["text"]["content"] + assert "请在过期前扫描二维码" in sent[0]["text"]["content"] + assert "moviepilot.example" not in sent[0]["text"]["content"] + assert sent[1] == { + "touser": userid or "@all", "msgtype": "image", "agentid": "1000002", + "image": {"media_id": "image-media"}, + } + if image == _IMAGE_URL: + http.get_res.assert_called_once_with(_IMAGE_URL, stream=True) + http.get_res.return_value.close.assert_called_once_with() + else: + http.get_res.assert_not_called() + + +def test_native_image_without_caption_sends_only_image(client: WeChat, http: Mock) -> None: + """ + 纯图片通知只发送一条原生图片,不额外发送空文本。 + """ + assert client.send_msg(title=None, image=_PNG_DATA_URL, native_image=True) is True + assert [payload["msgtype"] for payload in _payloads(http)] == ["image"] + + +def test_native_jpeg_uses_jpeg_filename_and_mime_type(client: WeChat, http: Mock) -> None: + """ + JPG 素材保留原始内容,并使用匹配的文件名与 MIME 类型。 + """ + image = b"\xff\xd8\xfforiginal-jpeg" + data_url = f"data:image/jpeg;base64,{base64.b64encode(image).decode()}" + + assert client.send_msg(title=None, image=data_url, native_image=True) is True + assert http.request.call_args.kwargs["files"] == {"media": ("image.jpg", image, "image/jpeg")} + + +@pytest.mark.parametrize("native_image", [False, True]) +def test_missing_image_keeps_text_delivery(client: WeChat, http: Mock, native_image: bool) -> None: + """ + 没有图片时保持原有文本投递,不因原生图片开关请求上传。 + """ + assert client.send_msg(title="标题", text="正文", native_image=native_image) is True + assert [payload["msgtype"] for payload in _payloads(http)] == ["text"] + http.get_res.assert_not_called() + http.request.assert_not_called() + + +def test_default_image_keeps_news_card(client: WeChat, http: Mock) -> None: + """ + 未显式启用时仍发送包含封面和跳转地址的图文卡片,不下载图片。 + """ + assert client.send_msg(title="新增媒体", text="已入库", image=_IMAGE_URL, link="https://detail.example") is True + article = _payloads(http)[0]["news"]["articles"][0] + assert article == { + "title": "新增媒体", "description": "已入库", "picurl": _IMAGE_URL, "url": "https://detail.example", + } + http.get_res.assert_not_called() + http.request.assert_not_called() + + +@pytest.mark.parametrize("image", [ + "file:///private/image.png", "/local/image.png", "data:image/png;base64,!!!", + "data:image/png,unencoded", "data:image/png;base64,YWJjZA==", + "data:image/gif;base64,R0lGODlhZ2lm", "data:image/png;base64,aHRtbCBub3QgaW1hZ2U=", +]) +def test_invalid_native_images_do_not_upload_or_send(client: WeChat, http: Mock, image: str) -> None: + """ + 拒绝本地路径、无效 Base64、过短内容以及不支持的格式,不回退为裁切图文。 + """ + assert client.send_msg(title="扫码登录", image=image, native_image=True) is False + http.get_res.assert_not_called() + http.request.assert_not_called() + http.post.assert_not_called() + + +def test_oversized_data_url_is_rejected_before_decode( + client: WeChat, http: Mock, monkeypatch: pytest.MonkeyPatch, +) -> None: + """ + Base64 数据超过原图预算时直接拒绝,不解码或上传。 + """ + monkeypatch.setattr(wechat_client, "_IMAGE_MAX_BYTES", 6) + decode = Mock(side_effect=AssertionError("不应解码超限图片")) + monkeypatch.setattr(wechat_client.base64, "b64decode", decode) + + assert client.send_msg(title=None, image=_PNG_DATA_URL, native_image=True) is False + decode.assert_not_called() + http.request.assert_not_called() + + +@pytest.mark.parametrize("status_code, chunks", [ + (404, [_PNG]), (200, [b"error"]), (200, [b""]), (200, [_PNG, b"too-large"]), +]) +def test_failed_or_invalid_download_closes_response_and_sends_nothing( + client: WeChat, http: Mock, monkeypatch: pytest.MonkeyPatch, status_code: int, chunks: list[bytes], +) -> None: + """ + HTTP 错误、空响应、错误格式和超限下载均关闭连接且不发送消息。 + """ + monkeypatch.setattr(wechat_client, "_IMAGE_MAX_BYTES", len(_PNG)) + response = http.get_res.return_value + response.status_code = status_code + response.iter_content.return_value = chunks + + assert client.send_msg(title="扫码登录", image=_IMAGE_URL, native_image=True) is False + response.close.assert_called_once_with() + http.request.assert_not_called() + http.post.assert_not_called() + + +def test_failed_stream_closes_response(client: WeChat, http: Mock) -> None: + """ + 读取中途抛出异常时也释放 HTTP 响应,不发送不完整图片。 + """ + http.get_res.return_value.iter_content.side_effect = OSError("读取失败") + + assert client.send_msg(title=None, image=_IMAGE_URL, native_image=True) is False + http.get_res.return_value.close.assert_called_once_with() + http.request.assert_not_called() + http.post.assert_not_called() + + +@pytest.mark.parametrize("payload", [{"errcode": 40005}, {"errcode": 0}, {"errcode": 0, "media_id": 3}]) +def test_failed_upload_does_not_send_caption_or_news(client: WeChat, http: Mock, payload: dict) -> None: + """ + 上传失败或缺少有效素材 ID 时停止发送,避免产生空通知或回退图文。 + """ + http.request.return_value.json.return_value = payload + + assert client.send_msg(title="扫码登录", image=_PNG_DATA_URL, native_image=True) is False + http.post.assert_not_called() + + +@pytest.mark.parametrize("response_target", ["request", "get_res"]) +def test_missing_http_response_fails_without_sending( + client: WeChat, http: Mock, response_target: str, +) -> None: + """ + 下载或上传无响应时返回失败,不继续投递通知。 + """ + getattr(http, response_target).return_value = None + + assert client.send_msg(title="扫码登录", image=_IMAGE_URL, native_image=True) is False + http.post.assert_not_called() + + +def test_invalid_upload_json_does_not_send(client: WeChat, http: Mock) -> None: + """ + 素材接口返回无法解析的响应时停止发送,不暴露为发送成功。 + """ + http.request.return_value.json.side_effect = ValueError("无效 JSON") + + assert client.send_msg(title="扫码登录", image=_PNG_DATA_URL, native_image=True) is False + http.post.assert_not_called() + + +def test_missing_access_token_does_not_load_image( + client: WeChat, http: Mock, monkeypatch: pytest.MonkeyPatch, +) -> None: + """ + 没有访问令牌时沿用原返回值,不下载或上传图片。 + """ + monkeypatch.setattr(client, "_WeChat__get_access_token", Mock(return_value=None)) + + assert client.send_msg(title=None, image=_IMAGE_URL, native_image=True) is None + http.get_res.assert_not_called() + http.request.assert_not_called() + http.post.assert_not_called() + + +@pytest.mark.parametrize("title", [None, "扫码登录"]) +def test_send_error_is_reported(client: WeChat, http: Mock, title: str | None) -> None: + """ + 企业微信拒绝说明文字或图片时返回失败,不声称发送成功。 + """ + http.post.return_value.json.return_value = {"errcode": 40003} + + assert client.send_msg(title=title, image=_PNG_DATA_URL, native_image=True) is False + assert len(_payloads(http)) == 1 + + +def test_voice_upload_still_reads_local_file(client: WeChat, http: Mock, tmp_path: Path) -> None: + """ + 复用上传方法后,现有语音路径仍读取本地文件并声明 AMR 类型。 + """ + voice_path = tmp_path / "voice.amr" + voice_path.write_bytes(b"#!AMR\nvoice") + + assert client._upload_temp_media(voice_path) == "image-media" + upload = http.request.call_args.kwargs + assert upload["url"].endswith("&type=voice") + assert upload["files"] == {"media": ("voice.amr", b"#!AMR\nvoice", "voice/amr")} + assert voice_path.exists() + + +def _route_to_client(monkeypatch: pytest.MonkeyPatch, client: WeChat | WeChatBot) -> WechatModule: + """ + 为单个实例装配通知路由,接收对象由现有宿主方法提供。 + """ + module = WechatModule() + conf = SimpleNamespace(name="wechat-test", config={}) + monkeypatch.setattr(module, "get_configs", lambda: {conf.name: conf}) + monkeypatch.setattr(module, "get_instance", lambda _: client) + monkeypatch.setattr(module, "check_message", lambda *_: True) + monkeypatch.setattr(module, "get_notification_userid", lambda *_: "member-1") + return module + + +def test_plugin_native_image_survives_default_link_and_message_roundtrip( + client: WeChat, http: Mock, monkeypatch: pytest.MonkeyPatch, +) -> None: + """ + 插件默认详情链接、消息序列化与模块转发不会把显式原图变回图文卡片。 + """ + monkeypatch.setattr(plugin_base, "settings", SimpleNamespace(MP_DOMAIN=lambda path: f"https://mp.example/{path}")) + plugin = SimpleNamespace(chain=Mock()) + _PluginBase.post_message( + plugin, channel=NotificationChannel.Wechat, title="扫码登录", image=_PNG_DATA_URL, native_image=True, + ) + message = plugin.chain.post_message.call_args.args[0] + assert "#/plugins?tab=installed&id=" in message.link + assert message.native_image is True + module = _route_to_client(monkeypatch, client) + + module.post_message(Message.model_validate(message.model_dump())) + + sent = _payloads(http) + assert [payload["msgtype"] for payload in sent] == ["text", "image"] + assert all(payload["touser"] == "member-1" for payload in sent) + assert "#/plugins" not in sent[0]["text"]["content"] + + +@pytest.mark.parametrize("native_image", [False, True]) +def test_bot_mode_does_not_receive_app_only_keyword( + monkeypatch: pytest.MonkeyPatch, native_image: bool, +) -> None: + """ + 机器人模式继续使用原有发送参数,不接收仅自建应用支持的开关。 + """ + bot = WeChatBot.__new__(WeChatBot) + send = Mock() + monkeypatch.setattr(bot, "send_msg", send) + module = _route_to_client(monkeypatch, bot) + message = Message(title="标题", image=_IMAGE_URL, link="https://detail.example", native_image=native_image) + + module.post_message(message) + + send.assert_called_once_with(title="标题", text=None, image=_IMAGE_URL, + userid="member-1", link="https://detail.example") + + +def test_native_image_respects_notification_filter( + client: WeChat, http: Mock, monkeypatch: pytest.MonkeyPatch, +) -> None: + """ + 显式原生图片不能绕过通知实例过滤规则。 + """ + module = _route_to_client(monkeypatch, client) + monkeypatch.setattr(module, "check_message", lambda *_: False) + + module.post_message(Message(image=_PNG_DATA_URL, native_image=True)) + + http.request.assert_not_called() + http.post.assert_not_called() + + +def test_default_message_does_not_enable_native_image() -> None: + """ + 旧调用及其序列化数据默认保持图文行为。 + """ + assert Message(image=_IMAGE_URL).native_image is False + assert Message.model_validate({"image": _IMAGE_URL}).native_image is False