diff --git a/README.md b/README.md index 9ac83e4..903dcea 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,8 @@ npm run check - ROBOT_WECHAT_CLIENT_PORT: 机器人客户端服务端口,可用于在 SKILL 脚本直接调用客户端接口 `http://127.0.0.1:{ROBOT_WECHAT_CLIENT_PORT}/api/v1/xxxxx` +- `ROBOT_CLIENT_PRIVATE_TOKEN` 用于客户端接口的 `X-Private-Token` 请求头。 + - ROBOT_ID: 机器人实例 ID - ROBOT_CODE: 机器人实例编码 @@ -44,12 +46,14 @@ npm run check - ROBOT_REF_MESSAGE_ID: 如果是引用消息,则是引用的消息的 ID -**发送图片的时候可以调用 Agent 接口** +**发送图片和 GIF** + +`send-image` 支持本地和远程图片,包括 GIF。发送静态原图时传 `send_original: true`,默认值为 `false`。 1. 发送远程图片地址 ``` -[POST] http://127.0.0.1:{ROBOT_WECHAT_CLIENT_PORT}/api/v1//robot/message/send/image/url +[POST] http://127.0.0.1:{ROBOT_WECHAT_CLIENT_PORT}/api/v1/robot/message/send/image/url 请求体 Body: @@ -63,19 +67,22 @@ npm run check 2. 发送本地图片路径 ``` -[POST] http://127.0.0.1:{ROBOT_WECHAT_CLIENT_PORT}/api/v1//robot/message/send/image/local +[POST] http://127.0.0.1:{ROBOT_WECHAT_CLIENT_PORT}/api/v1/robot/message/send/image/local 请求体 Body: { "to_wxid": "{{ROBOT_FROM_WX_ID}}", - "file_path": "{{file_path}}" + "file_path": "{{file_path}}", + "send_original": true } ``` **发送视频的时候可以调用 Agent 接口** +`video-generation` 生成视频后使用下方接口。可选的布尔字段 `send_original` 控制是否附带原片。省略时使用客户端的默认设置。 + ``` [POST] http://127.0.0.1:{ROBOT_WECHAT_CLIENT_PORT}/api/v1/robot/message/send/video/url @@ -124,6 +131,8 @@ npm run check **Agent 发送表情消息接口** +`send-emoji` 按内置名称查找微信已有表情的 `Md5` 和 `TotalLen`。给定 GIF 路径或 URL 时使用上方图片接口。 + ``` [POST] http://127.0.0.1:{ROBOT_WECHAT_CLIENT_PORT}/api/v1/robot/message/send/emoji @@ -135,3 +144,12 @@ npm run check "TotalLen": 263, // 表情长度 } ``` + +**发送文件附件** + +`send-file` 用于发送可下载的附件,包括用户明确要求发送的 GIF 原文件。两个入口均使用 `POST`,接收方取自 `ROBOT_FROM_WX_ID`。 + +| 来源 | 客户端接口 | JSON 请求字段 | +| --- | --- | --- | +| 本地文件 | `/api/v1/robot/message/send/file/local` | `to_wxid`、`file_path` | +| 远程文件 | `/api/v1/robot/message/send/file/url` | `to_wxid`、`file_urls` 数组 | diff --git a/skills/beauty/scripts/beauty.py b/skills/beauty/scripts/beauty.py index 6acfbfd..9a86cd5 100644 --- a/skills/beauty/scripts/beauty.py +++ b/skills/beauty/scripts/beauty.py @@ -65,14 +65,15 @@ def send_image(image_url: str) -> bool: try: with urllib.request.urlopen(request, timeout=10) as response: - if 200 <= response.status < 300: - return True payload = json.load(response) except (urllib.error.URLError, TimeoutError, json.JSONDecodeError): return False - code = payload.get("code") - return code == 200 or code == 0 + return ( + isinstance(payload, dict) + and payload.get("code") == 200 + and payload.get("data") == [f"成功: {image_url}"] + ) def main() -> int: diff --git a/skills/export-chat-history/scripts/export_chat_history.py b/skills/export-chat-history/scripts/export_chat_history.py index c7ba3a4..234cfee 100644 --- a/skills/export-chat-history/scripts/export_chat_history.py +++ b/skills/export-chat-history/scripts/export_chat_history.py @@ -26,7 +26,6 @@ except ImportError: # pragma: no cover - Python 3.8 fallback sys.stderr = sys.stdout MAX_EXPORT_ROWS = 50_000 -MAX_EXCEL_FILE_SIZE = 25 * 1024 * 1024 EXCEL_CELL_MAX_LENGTH = 32_767 ILLEGAL_XML_CHARACTERS = re.compile( r"[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F-\x84\x86-\x9F]" @@ -512,8 +511,6 @@ def _build_workbook( ) try: workbook.save(temporary_path) - if temporary_path.stat().st_size > MAX_EXCEL_FILE_SIZE: - raise ValueError("生成的 Excel 文件超过 25MB,请缩短导出时间范围") temporary_path.replace(output_path) finally: temporary_path.unlink(missing_ok=True) @@ -521,7 +518,9 @@ def _build_workbook( def _raise_for_client_error(payload: dict[str, Any]) -> None: code = payload.get("code") - if code is not None and str(code) != "200": + if code is None: + raise RuntimeError("客户端返回的发送结果无效") + if code != 200: message = str(payload.get("message") or f"客户端返回错误码 {code}") raise RuntimeError(message) @@ -556,8 +555,6 @@ def _send_file(client_port: str, chat_room_id: str, path: Path) -> None: except urllib.error.URLError as exc: raise RuntimeError(f"发送 Excel 失败: {exc.reason}") from exc - if not response_text.strip(): - return try: payload = json.loads(response_text) except json.JSONDecodeError as exc: diff --git a/skills/image-to-image/scripts/image_to_image.py b/skills/image-to-image/scripts/image_to_image.py index 81f6730..86cecd8 100644 --- a/skills/image-to-image/scripts/image_to_image.py +++ b/skills/image-to-image/scripts/image_to_image.py @@ -343,6 +343,23 @@ def _is_remote_image_url(value: str) -> bool: return urllib.parse.urlparse(value).scheme in {"http", "https"} +def _raise_for_client_error(response: object, url_count: int = 0) -> None: + if not isinstance(response, dict) or "code" not in response: + raise RuntimeError("客户端返回的发送结果无效") + if response["code"] != 200: + raise RuntimeError(response.get("message") or f"客户端返回错误码 {response['code']}") + if url_count: + results = response.get("data") + if not isinstance(results, list) or len(results) != url_count: + raise RuntimeError("客户端返回的逐项发送结果不完整") + failures = [ + str(item) for item in results + if not isinstance(item, str) or not item.startswith("成功: ") + ] + if failures: + raise RuntimeError(";".join(failures)) + + def _send_image_outputs(client_port: str, from_wx_id: str, image_outputs: list[str]) -> None: remote_urls = [value for value in image_outputs if value and _is_remote_image_url(value)] local_paths = [value for value in image_outputs if value and not _is_remote_image_url(value)] @@ -363,6 +380,7 @@ def _send_image_outputs(client_port: str, from_wx_id: str, image_outputs: list[s timeout=300, ) _debug_response("send image url response", response) + _raise_for_client_error(response, len(remote_urls)) for file_path in local_paths: send_url = f"http://127.0.0.1:{client_port}/api/v1/robot/message/send/image/local" @@ -380,6 +398,7 @@ def _send_image_outputs(client_port: str, from_wx_id: str, image_outputs: list[s timeout=300, ) _debug_response("send image local response", response) + _raise_for_client_error(response) def _cleanup_openai_temp_files(image_outputs: list[str]) -> None: diff --git a/skills/send-emoji/SKILL.md b/skills/send-emoji/SKILL.md index 67905c2..0b31792 100644 --- a/skills/send-emoji/SKILL.md +++ b/skills/send-emoji/SKILL.md @@ -1,13 +1,13 @@ --- name: send-emoji -description: "发送微信表情技能。使用表情包聊天可以活跃气氛,也可以缓解尴尬,你可以在适当的时候发送表情包活跃聊天氛围,也可以在遇到不方便回答或者不想回答的问题时发送一个表情包来巧妙地回避。" +description: "按名称发送内置微信表情,例如 [开心]。用户说「发个表情」或聊天时适合用表情活跃气氛、缓解尴尬、回应不方便回答的问题时使用。用户给出 GIF 文件或链接时使用 send-image。" --- # Send Emoji Skill ## 描述 -这是一个向当前微信会话发送表情的技能。 +这个技能发送名称表中已有的微信表情。用户要求把某个本地或网络 GIF 当表情发时,将路径或 URL 交给 `send-image`。 技能脚本位于 `scripts/send_emoji.py`,内部维护了表情名称到微信表情标识(Md5 / TotalLen)的映射表,对 AI 模型完全透明——模型只需传入表情名称(如 `[开心]`),脚本自动查找对应的 Md5 和 TotalLen 并调用客户端接口发送。 @@ -32,7 +32,7 @@ description: "发送微信表情技能。使用表情包聊天可以活跃气氛 ## 触发条件 - Agent 根据上下文判断需要用表情回应时,从可用表情列表中选取合适的。 -- 用户要求发送某个微信表情。 +- 用户按名称要求发送某个内置微信表情。 - 用户说「发个表情」「来个表情包」「发个 xxx 表情」。 ## 入参规范 @@ -43,7 +43,7 @@ description: "发送微信表情技能。使用表情包聊天可以活跃气氛 "properties": { "name": { "type": "string", - "description": "表情名称,如 [开心]、[快乐]。必须是可用表情列表中的名称。" + "description": "表情名称,如 [开心]、[爱心]。必须是可用表情列表中的名称。" }, "names": { "type": "array", @@ -65,7 +65,7 @@ description: "发送微信表情技能。使用表情包聊天可以活跃气氛 对应命令行参数: - `--name <表情名称>` 必填或可重复传入,如 `--name '[开心]'` -- `--names ` 可选,用于一次传入多个名称,如 `--names '["[开心]", "[快乐]"]'` +- `--names ` 可选,用于一次传入多个名称,如 `--names '["[开心]", "[爱心]"]'` - `--ended` 可选标志 ```bash @@ -75,7 +75,7 @@ python3 scripts/send_emoji.py --name '[开心]' 发送多个表情: ```bash -python3 scripts/send_emoji.py --name '[开心]' --name '[快乐]' +python3 scripts/send_emoji.py --name '[开心]' --name '[爱心]' ``` 当 Agent 认为任务已完成、对话可以结束时,加上 `--ended` 标志: @@ -84,7 +84,7 @@ python3 scripts/send_emoji.py --name '[开心]' --name '[快乐]' python3 scripts/send_emoji.py --name '[开心]' --ended ``` -4. 脚本在内部查找 EMOJI_MAP,获取对应的 Md5 和 TotalLen,调用客户端接口 `POST http://127.0.0.1:{ROBOT_WECHAT_CLIENT_PORT}/api/v1/robot/message/send/emoji` 发送表情。 +脚本从 `EMOJI_MAP` 取出名称对应的 `Md5` 和 `TotalLen`,调用客户端接口 `POST /api/v1/robot/message/send/emoji`。所有表情都收到客户端成功回执后才输出发送成功。 ## 校验规则 @@ -101,4 +101,4 @@ python3 scripts/send_emoji.py --name '[开心]' --ended - 成功时,脚本输出「表情发送成功」,表示表情已通过客户端接口直接发送,无需 AI 智能体再做额外处理。 - 如果传入 `--ended`,输出末尾会追加 `ended`,Agent 会自动结束对话。 - 不要发送`表情发送成功啦` `已经发送表情啦` `工具调用成功` 这类无意义的回复,如果你只有这类话要说,请在输出末尾加上 `ended`,让 Agent 结束对话。 -- 失败时,返回脚本输出的具体错误信息(含可用表情列表)。 +- 失败时返回脚本输出的具体原因。名称未知时会列出可用表情。 diff --git a/skills/send-emoji/scripts/send_emoji.py b/skills/send-emoji/scripts/send_emoji.py index 790e07f..999f075 100644 --- a/skills/send-emoji/scripts/send_emoji.py +++ b/skills/send-emoji/scripts/send_emoji.py @@ -66,7 +66,7 @@ def _client_private_token() -> str: return os.environ.get("ROBOT_CLIENT_PRIVATE_TOKEN", "").strip() -def _http_post_json(url: str, body: dict, timeout: int = 300) -> dict: +def _http_post_json(url: str, body: dict, timeout: int = 300) -> None: data = json.dumps(body).encode("utf-8") req = urllib.request.Request( url, @@ -78,10 +78,11 @@ def _http_post_json(url: str, body: dict, timeout: int = 300) -> dict: method="POST", ) with urllib.request.urlopen(req, timeout=timeout) as resp: - text = resp.read().decode("utf-8") - if not text.strip(): - return {} - return json.loads(text) + response = json.load(resp) + if not isinstance(response, dict) or "code" not in response: + raise RuntimeError("客户端返回的发送结果无效") + if response["code"] != 200: + raise RuntimeError(response.get("message") or f"客户端返回错误码 {response['code']}") def _expand_json_array_values(values: list[str], label: str) -> list[str]: diff --git a/skills/send-file/SKILL.md b/skills/send-file/SKILL.md index ed0fc5d..7d13e62 100644 --- a/skills/send-file/SKILL.md +++ b/skills/send-file/SKILL.md @@ -1,6 +1,6 @@ --- name: send-file -description: "发送本地或远程文件到当前微信会话。比如,其他技能产出了需要发送的本地文件路径时使用。发送图片应优先使用 send-image 这个技能。" +description: "将本地文件或远程文件链接作为可下载的附件发送到当前微信会话,也适用于用户明确要求把 GIF 或图片原文件作为附件发送。发聊天图片或 GIF 动图时使用 send-image。" --- # 发送文件 @@ -72,8 +72,8 @@ python3 scripts/send_file.py --file_urls '["https://example.com/a.pdf","https:// ## 约束 - 至少提供一个非空本地路径或远程 URL。 -- 本地路径必须指向已存在、非空且不超过 25MB 的文件,不能把 URL 作为本地路径传入。 -- 远程 URL 必须包含有效的 `http` 或 `https` 协议及主机名;客户端下载后的文件也不能超过 25MB。 +- 本地路径必须指向已存在且非空的文件。 +- 远程 URL 必须包含有效的 `http` 或 `https` 协议及主机名。 - 脚本按首次出现顺序去重;所有参数通过校验后,单个发送失败时会继续尝试其余文件,最终返回全部失败原因。 ## 输出 diff --git a/skills/send-file/scripts/send_file.py b/skills/send-file/scripts/send_file.py index e9b5b20..dbd9568 100644 --- a/skills/send-file/scripts/send_file.py +++ b/skills/send-file/scripts/send_file.py @@ -12,34 +12,28 @@ from pathlib import Path sys.stderr = sys.stdout -MAX_FILE_SIZE = 25 * 1024 * 1024 - - def _client_private_token() -> str: return os.environ.get("ROBOT_CLIENT_PRIVATE_TOKEN", "").strip() -def _raise_for_client_error(response: dict) -> None: - if not response: - return - - code = response.get("code") - if code is not None and str(code) != "200": - message = str(response.get("message") or f"客户端返回错误码 {code}") - raise RuntimeError(message) - - data = response.get("data") - if isinstance(data, list): +def _raise_for_client_error(response: object, url_count: int) -> None: + if not isinstance(response, dict) or "code" not in response: + raise RuntimeError("客户端返回的发送结果无效") + if response["code"] != 200: + raise RuntimeError(response.get("message") or f"客户端返回错误码 {response['code']}") + if url_count: + results = response.get("data") + if not isinstance(results, list) or len(results) != url_count: + raise RuntimeError("客户端返回的逐项发送结果不完整") failures = [ - item.strip() - for item in data - if isinstance(item, str) and item.lstrip().startswith("失败:") + str(item) for item in results + if not isinstance(item, str) or not item.startswith("成功: ") ] if failures: raise RuntimeError(";".join(failures)) -def _http_post_json(url: str, body: dict, timeout: int = 300) -> dict: +def _http_post_json(url: str, body: dict, timeout: int = 300) -> None: data = json.dumps(body).encode("utf-8") req = urllib.request.Request( url, @@ -51,15 +45,8 @@ def _http_post_json(url: str, body: dict, timeout: int = 300) -> dict: method="POST", ) with urllib.request.urlopen(req, timeout=timeout) as resp: - text = resp.read().decode("utf-8") - if not text.strip(): - return {} - - response = json.loads(text) - if not isinstance(response, dict): - raise RuntimeError("客户端返回格式不正确") - _raise_for_client_error(response) - return response + response = json.load(resp) + _raise_for_client_error(response, len(body.get("file_urls", []))) def _expand_json_array_values(values: list[str], label: str) -> list[str]: @@ -122,11 +109,8 @@ def _normalize_local_file_path(value: str) -> str: if not path.is_file(): raise ValueError(f"本地文件不存在: {value}") - file_size = path.stat().st_size - if file_size <= 0: + if path.stat().st_size <= 0: raise ValueError(f"本地文件不能为空: {value}") - if file_size > MAX_FILE_SIZE: - raise ValueError(f"本地文件大小不能超过 25MB: {value}") return str(path.resolve()) diff --git a/skills/send-image/SKILL.md b/skills/send-image/SKILL.md index 32fd60c..09323b0 100644 --- a/skills/send-image/SKILL.md +++ b/skills/send-image/SKILL.md @@ -1,12 +1,14 @@ --- name: send-image -description: "发送本地或远程图片到当前微信会话。比如,其他技能产出了需要发送的本地图片路径时使用。" +description: "将本地图片文件或远程图片链接发送到当前微信会话,支持静态原图。用户给出 GIF 路径或链接,要求发动态图或把这个 GIF 当表情发时,使用本技能。" --- # 发送图片 使用 `scripts/send_image.py` 调用机器人客户端接口,将一个或多个本地图片文件、远程图片 URL 发送到当前微信会话。 +用户给出 GIF 文件路径或链接时,使用本技能。按名称发送内置表情时使用 `send-emoji`。用户明确要求发送可下载的 GIF 附件时使用 `send-file`。 + ## 入参 ```json @@ -34,6 +36,11 @@ description: "发送本地或远程图片到当前微信会话。比如,其他 "type": "string" }, "description": "要发送的多个远程图片 URL。" + }, + "send_original": { + "type": "boolean", + "default": false, + "description": "是否以原图发送本次请求中的静态图片。" } }, "anyOf": [ @@ -52,6 +59,7 @@ description: "发送本地或远程图片到当前微信会话。比如,其他 - `--file_paths `:一次传入多个本地图片路径。 - `--image_url <远程图片URL>`:可重复传入。 - `--image_urls `:一次传入多个远程图片 URL。 +- `--send_original` 请求发送静态原图,也可以显式传 `--send_original true` 或 `--send_original false`。 ## 执行 @@ -61,6 +69,13 @@ description: "发送本地或远程图片到当前微信会话。比如,其他 python3 scripts/send_image.py --file_path '/tmp/example.png' ``` +发送静态原图或本地 GIF 的示例 + +```bash +python3 scripts/send_image.py --file_path '/tmp/photo.jpg' --send_original +python3 scripts/send_image.py --file_path '/tmp/reaction.gif' +``` + 发送远程图片: ```bash diff --git a/skills/send-image/agents/openai.yaml b/skills/send-image/agents/openai.yaml index 081d003..3f0b394 100644 --- a/skills/send-image/agents/openai.yaml +++ b/skills/send-image/agents/openai.yaml @@ -1,4 +1,4 @@ interface: display_name: "发送图片" - short_description: "将一个或多个本地图片文件或远程图片链接发送到当前微信会话" + short_description: "将本地图片或远程图片链接发送到当前微信会话,支持静态原图和 GIF" default_prompt: "使用 $send-image 将这些本地图片或远程图片发送到当前微信会话。" diff --git a/skills/send-image/scripts/send_image.py b/skills/send-image/scripts/send_image.py index f491bd3..6c18f0e 100644 --- a/skills/send-image/scripts/send_image.py +++ b/skills/send-image/scripts/send_image.py @@ -17,27 +17,24 @@ def _client_private_token() -> str: return os.environ.get("ROBOT_CLIENT_PRIVATE_TOKEN", "").strip() -def _raise_for_client_error(response: dict) -> None: - if not response: - return - - code = response.get("code") - if code is not None and str(code) != "200": - message = str(response.get("message") or f"客户端返回错误码 {code}") - raise RuntimeError(message) - - data = response.get("data") - if isinstance(data, list): +def _raise_for_client_error(response: object, url_count: int) -> None: + if not isinstance(response, dict) or "code" not in response: + raise RuntimeError("客户端返回的发送结果无效") + if response["code"] != 200: + raise RuntimeError(response.get("message") or f"客户端返回错误码 {response['code']}") + if url_count: + results = response.get("data") + if not isinstance(results, list) or len(results) != url_count: + raise RuntimeError("客户端返回的逐项发送结果不完整") failures = [ - item.strip() - for item in data - if isinstance(item, str) and item.lstrip().startswith("失败:") + str(item) for item in results + if not isinstance(item, str) or not item.startswith("成功: ") ] if failures: raise RuntimeError(";".join(failures)) -def _http_post_json(url: str, body: dict, timeout: int = 300) -> dict: +def _http_post_json(url: str, body: dict, timeout: int = 300) -> None: data = json.dumps(body).encode("utf-8") req = urllib.request.Request( url, @@ -49,15 +46,8 @@ def _http_post_json(url: str, body: dict, timeout: int = 300) -> dict: method="POST", ) with urllib.request.urlopen(req, timeout=timeout) as resp: - text = resp.read().decode("utf-8") - if not text.strip(): - return {} - - response = json.loads(text) - if not isinstance(response, dict): - raise RuntimeError("客户端返回格式不正确") - _raise_for_client_error(response) - return response + response = json.load(resp) + _raise_for_client_error(response, len(body.get("image_urls", []))) def _expand_json_array_values(values: list[str], label: str) -> list[str]: @@ -88,12 +78,13 @@ def _dedupe(values: list[str]) -> list[str]: return deduped -def _parse_cli_params(argv: list[str]) -> tuple[list[str], list[str]]: +def _parse_cli_params(argv: list[str]) -> tuple[list[str], list[str], bool]: parser = argparse.ArgumentParser(add_help=False) parser.add_argument("--file_path", action="append", default=[]) parser.add_argument("--file_paths", action="append", default=[]) parser.add_argument("--image_url", action="append", default=[]) parser.add_argument("--image_urls", action="append", default=[]) + parser.add_argument("--send_original", nargs="?", const="true", choices=("true", "false")) namespace, unknown = parser.parse_known_args(argv) if unknown: @@ -105,7 +96,7 @@ def _parse_cli_params(argv: list[str]) -> tuple[list[str], list[str]]: image_urls = _expand_json_array_values( namespace.image_url + namespace.image_urls, "image_urls" ) - return _dedupe(file_paths), _dedupe(image_urls) + return _dedupe(file_paths), _dedupe(image_urls), namespace.send_original == "true" def _is_remote_url(value: str) -> bool: @@ -131,18 +122,24 @@ def _validate_remote_image_url(value: str) -> str: return value -def _send_local_image(client_port: str, to_wxid: str, file_path: str) -> None: +def _send_local_image(client_port: str, to_wxid: str, file_path: str, send_original: bool) -> None: send_url = ( f"http://127.0.0.1:{client_port}/api/v1/robot/message/send/image/local" ) - _http_post_json(send_url, {"to_wxid": to_wxid, "file_path": file_path}) + _http_post_json( + send_url, + {"to_wxid": to_wxid, "file_path": file_path, "send_original": send_original}, + ) def _send_remote_images( - client_port: str, to_wxid: str, image_urls: list[str] + client_port: str, to_wxid: str, image_urls: list[str], send_original: bool ) -> None: send_url = f"http://127.0.0.1:{client_port}/api/v1/robot/message/send/image/url" - _http_post_json(send_url, {"to_wxid": to_wxid, "image_urls": image_urls}) + _http_post_json( + send_url, + {"to_wxid": to_wxid, "image_urls": image_urls, "send_original": send_original}, + ) def main() -> int: @@ -151,7 +148,7 @@ def main() -> int: return 1 try: - raw_file_paths, raw_image_urls = _parse_cli_params(sys.argv[1:]) + raw_file_paths, raw_image_urls, send_original = _parse_cli_params(sys.argv[1:]) if not raw_file_paths and not raw_image_urls: sys.stdout.write("缺少本地图片路径或远程图片 URL\n") return 1 @@ -178,13 +175,13 @@ def main() -> int: failures: list[str] = [] for file_path in file_paths: try: - _send_local_image(client_port, to_wxid, file_path) + _send_local_image(client_port, to_wxid, file_path, send_original) except Exception as exc: failures.append(f"本地图片 {file_path}: {exc}") if image_urls: try: - _send_remote_images(client_port, to_wxid, image_urls) + _send_remote_images(client_port, to_wxid, image_urls, send_original) except Exception as exc: failures.append(f"远程图片: {exc}") diff --git a/skills/text-to-image/scripts/text_to_image.py b/skills/text-to-image/scripts/text_to_image.py index 289a440..1619f1c 100644 --- a/skills/text-to-image/scripts/text_to_image.py +++ b/skills/text-to-image/scripts/text_to_image.py @@ -354,6 +354,23 @@ def _is_remote_image_url(value: str) -> bool: return urllib.parse.urlparse(value).scheme in {"http", "https"} +def _raise_for_client_error(response: object, url_count: int = 0) -> None: + if not isinstance(response, dict) or "code" not in response: + raise RuntimeError("客户端返回的发送结果无效") + if response["code"] != 200: + raise RuntimeError(response.get("message") or f"客户端返回错误码 {response['code']}") + if url_count: + results = response.get("data") + if not isinstance(results, list) or len(results) != url_count: + raise RuntimeError("客户端返回的逐项发送结果不完整") + failures = [ + str(item) for item in results + if not isinstance(item, str) or not item.startswith("成功: ") + ] + if failures: + raise RuntimeError(";".join(failures)) + + def _send_image_outputs(client_port: str, from_wx_id: str, image_outputs: list[str]) -> None: remote_urls = [value for value in image_outputs if value and _is_remote_image_url(value)] local_paths = [value for value in image_outputs if value and not _is_remote_image_url(value)] @@ -374,6 +391,7 @@ def _send_image_outputs(client_port: str, from_wx_id: str, image_outputs: list[s timeout=300, ) _debug_response("send image url response", response) + _raise_for_client_error(response, len(remote_urls)) for file_path in local_paths: send_url = f"http://127.0.0.1:{client_port}/api/v1/robot/message/send/image/local" @@ -391,6 +409,7 @@ def _send_image_outputs(client_port: str, from_wx_id: str, image_outputs: list[s timeout=300, ) _debug_response("send image local response", response) + _raise_for_client_error(response) def _cleanup_openai_temp_files(image_outputs: list[str]) -> None: diff --git a/skills/video-generation/SKILL.md b/skills/video-generation/SKILL.md index d1182af..c0d3f5a 100644 --- a/skills/video-generation/SKILL.md +++ b/skills/video-generation/SKILL.md @@ -67,6 +67,10 @@ description: "AI 视频生成工具。当用户想生成视频、文生视频、 "type": "integer", "description": "视频时长,单位秒,可选,默认 5。", "default": 5 + }, + "send_original": { + "type": "boolean", + "description": "发送生成的视频时是否附带原片。省略时使用客户端的默认设置。" } }, "required": ["prompt"], @@ -82,6 +86,7 @@ description: "AI 视频生成工具。当用户想生成视频、文生视频、 - `--ratio <比例>` 可选 - `--resolution <分辨率>` 可选 - `--duration <秒数>` 可选 +- `--send_original` 或 `--send_original true` 表示附带原片,`--send_original false` 表示只发播放版本。 ## 依赖安装 @@ -94,13 +99,13 @@ description: "AI 视频生成工具。当用户想生成视频、文生视频、 2. 从用户输入中提取 `prompt`,不要改写提示词本身。 3. 根据上下文可选提取 `model`、`file_paths`、`ratio`、`resolution`、`duration`。 4. 如果用户没有明确指定模型,默认使用 `jimeng-video-3.0-fast`。 -5. 在仓库根目录执行脚本,例如: +5. 在技能目录执行脚本,例如 ```bash python3 scripts/video_generation.py --prompt '海边日落,镜头缓慢推进' --file_paths 'https://example.com/start.jpg' ``` -6. 脚本生成视频后会自动调用客户端接口 `POST http://127.0.0.1:{ROBOT_WECHAT_CLIENT_PORT}/api/v1/robot/message/send/video/url` 将视频发送给用户,成功时输出「ended」。 +6. 脚本生成视频后调用 `POST /api/v1/robot/message/send/video/url`。`send_original` 只影响发送阶段。所有视频都收到成功回执后输出 `ended`,其中一条失败就返回具体原因。 ## 校验规则 diff --git a/skills/video-generation/scripts/video_generation.py b/skills/video-generation/scripts/video_generation.py index edc5865..74ee850 100644 --- a/skills/video-generation/scripts/video_generation.py +++ b/skills/video-generation/scripts/video_generation.py @@ -187,17 +187,36 @@ def _http_post_json(url: str, body: dict, headers: dict, timeout: int = 300) -> return json.loads(resp.read().decode("utf-8")) -def send_videos(from_wx_id: str, video_urls: list[str]) -> None: +def _raise_for_client_error(response: object, url_count: int) -> None: + if not isinstance(response, dict) or "code" not in response: + raise RuntimeError("客户端返回的发送结果无效") + if response["code"] != 200: + raise RuntimeError(response.get("message") or f"客户端返回错误码 {response['code']}") + if url_count: + results = response.get("data") + if not isinstance(results, list) or len(results) != url_count: + raise RuntimeError("客户端返回的逐项发送结果不完整") + failures = [ + str(item) for item in results + if not isinstance(item, str) or not item.startswith("成功: ") + ] + if failures: + raise RuntimeError(";".join(failures)) + + +def send_videos(from_wx_id: str, video_urls: list[str], send_original: bool | None) -> None: client_port = os.environ.get("ROBOT_WECHAT_CLIENT_PORT", "").strip() if not client_port: raise RuntimeError("环境变量 ROBOT_WECHAT_CLIENT_PORT 未配置") send_url = f"http://127.0.0.1:{client_port}/api/v1/robot/message/send/video/url" - send_body = { + send_body: dict[str, object] = { "to_wxid": from_wx_id, - "video_urls": [url for url in video_urls if url], + "video_urls": video_urls, } - _http_post_json( + if send_original is not None: + send_body["send_original"] = send_original + response = _http_post_json( send_url, send_body, { @@ -206,6 +225,7 @@ def send_videos(from_wx_id: str, video_urls: list[str]) -> None: }, timeout=60, ) + _raise_for_client_error(response, len(video_urls)) def call_jimeng_video( @@ -262,6 +282,7 @@ def _parse_cli_params(argv: list[str]) -> dict: parser.add_argument("--ratio", default="") parser.add_argument("--resolution", default="") parser.add_argument("--duration", type=int, default=0) + parser.add_argument("--send_original", nargs="?", const="true", choices=("true", "false")) namespace, unknown = parser.parse_known_args(argv) if unknown: @@ -274,6 +295,7 @@ def _parse_cli_params(argv: list[str]) -> dict: "ratio": namespace.ratio, "resolution": namespace.resolution, "duration": namespace.duration, + "send_original": None if namespace.send_original is None else namespace.send_original == "true", } @@ -365,7 +387,7 @@ def main() -> int: return 1 try: - send_videos(from_wx_id, video_urls) + send_videos(from_wx_id, video_urls, params["send_original"]) sys.stdout.write("ended") except Exception as exc: sys.stdout.write(f"发送视频失败: {exc}\n") diff --git a/skills/web-page/scripts/web_page.ts b/skills/web-page/scripts/web_page.ts index c9fafd6..b4ed1ad 100644 --- a/skills/web-page/scripts/web_page.ts +++ b/skills/web-page/scripts/web_page.ts @@ -1760,11 +1760,18 @@ async function maybeSendScreenshot( return false; } const sendUrl = `http://127.0.0.1:${clientPort}/api/v1/robot/message/send/image/local`; - await postJson( + const text = await postJson( sendUrl, { to_wxid: toWxid, file_path: filePath }, params.timeoutMs, ); + const result: unknown = JSON.parse(text); + if (!isPlainObject(result) || typeof result.code !== "number") { + throw new Error("客户端返回的发送结果无效"); + } + if (result.code !== 200) { + throw new Error(String(result.message || `客户端返回错误码 ${result.code}`)); + } return true; } diff --git a/tests/test_send_media.py b/tests/test_send_media.py new file mode 100644 index 0000000..0eda882 --- /dev/null +++ b/tests/test_send_media.py @@ -0,0 +1,102 @@ +import contextlib +import io +import json +import os +import runpy +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + + +SKILLS = Path(__file__).resolve().parents[1] / "skills" +CLIENT_URL = "http://127.0.0.1:9876/api/v1/robot/message/send/" +SUCCESS = {"code": 200, "data": None} + + +class SendMediaTests(unittest.TestCase): + def run_sender(self, skill, args, replies): + script = SKILLS / skill / "scripts" / (skill.replace("-", "_") + ".py") + output = io.StringIO() + env = {"ROBOT_WECHAT_CLIENT_PORT": "9876", "ROBOT_FROM_WX_ID": "test-room"} + with ( + mock.patch.dict(os.environ, env), + mock.patch.object(sys, "argv", [str(script), *args]), + contextlib.redirect_stdout(output), + contextlib.redirect_stderr(output), + mock.patch("urllib.request.urlopen", side_effect=[ + io.BytesIO(json.dumps(reply).encode()) for reply in replies + ]) as post, + self.assertRaises(SystemExit) as stopped, + ): + runpy.run_path(str(script), run_name="__main__") + requests = [ + (request.full_url, json.loads(request.data)) + for (request,), _ in post.call_args_list + ] + return stopped.exception.code, output.getvalue(), requests + + def test_image_paths_and_urls_use_image_api_and_forward_original(self): + url = "https://example.test/reaction.gif" + with tempfile.TemporaryDirectory() as directory: + cases = [ + ("reaction.gif", [], False), + ("photo.jpg", ["--send_original"], True), + ("photo.png", ["--send_original", "false"], False), + ] + for filename, flags, original in cases: + with self.subTest(flags=flags): + path = Path(directory, filename).resolve() + path.write_bytes(b"image") + code, _, requests = self.run_sender( + "send-image", ["--file_path", str(path), "--image_url", url, *flags], + [SUCCESS, {"code": 200, "data": [f"成功: {url}"]}], + ) + self.assertEqual(code, 0) + common = {"to_wxid": "test-room", "send_original": original} + self.assertEqual(requests, [ + (CLIENT_URL + "image/local", {**common, "file_path": str(path)}), + (CLIENT_URL + "image/url", {**common, "image_urls": [url]}), + ]) + + def test_gif_as_an_attachment_and_large_files_use_file_api(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory, "reaction.gif").resolve() + with path.open("wb") as source: + source.truncate(30 * 1024 * 1024) + code, _, requests = self.run_sender("send-file", ["--file_path", str(path)], [SUCCESS]) + self.assertEqual(code, 0) + self.assertEqual(requests, [ + (CLIENT_URL + "file/local", {"to_wxid": "test-room", "file_path": str(path)}), + ]) + + def test_partial_url_failure_reports_the_client_reason(self): + urls = ["https://example.test/one", "https://example.test/two"] + failure = f"失败: {urls[1]} 错误: 上传失败" + for skill, field in (("send-image", "image_urls"), ("send-file", "file_urls")): + with self.subTest(skill=skill): + code, output, requests = self.run_sender( + skill, ["--" + field, json.dumps(urls)], + [{"code": 200, "data": [f"成功: {urls[0]}", failure]}], + ) + self.assertEqual(len(requests), 1) + self.assertNotEqual(code, 0) + self.assertIn(failure, output) + + def test_named_emoji_ends_only_on_client_success(self): + for reply, expected in ((SUCCESS, 0), ({"code": 500, "message": "表情素材不可用"}, 1)): + with self.subTest(reply=reply): + code, output, requests = self.run_sender( + "send-emoji", ["--name", "[开心]", "--ended"], [reply], + ) + self.assertEqual(code, expected) + body = { + "to_wxid": "test-room", + "Md5": "4aae9dbe27651859ed526bcaad5f1f34", + "TotalLen": 19788, + } + self.assertEqual(requests, [(CLIENT_URL + "emoji", body)]) + self.assertEqual(output.splitlines()[-1] == "ended", expected == 0) + if expected: + self.assertIn("表情素材不可用", output)