refactor: 适配新的微信机器人版本

This commit is contained in:
hp0912 2026-11-15 20:35:52 +08:00
parent 888c1ce49e
commit 666c6d8b8c
16 changed files with 291 additions and 104 deletions

View File

@ -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_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_ID: 机器人实例 ID
- ROBOT_CODE: 机器人实例编码 - ROBOT_CODE: 机器人实例编码
@ -44,12 +46,14 @@ npm run check
- ROBOT_REF_MESSAGE_ID: 如果是引用消息,则是引用的消息的 ID - ROBOT_REF_MESSAGE_ID: 如果是引用消息,则是引用的消息的 ID
**发送图片的时候可以调用 Agent 接口** **发送图片和 GIF**
`send-image` 支持本地和远程图片,包括 GIF。发送静态原图时传 `send_original: true`,默认值为 `false`。
1. 发送远程图片地址 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: 请求体 Body:
@ -63,19 +67,22 @@ npm run check
2. 发送本地图片路径 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: 请求体 Body:
{ {
"to_wxid": "{{ROBOT_FROM_WX_ID}}", "to_wxid": "{{ROBOT_FROM_WX_ID}}",
"file_path": "{{file_path}}" "file_path": "{{file_path}}",
"send_original": true
} }
``` ```
**发送视频的时候可以调用 Agent 接口** **发送视频的时候可以调用 Agent 接口**
`video-generation` 生成视频后使用下方接口。可选的布尔字段 `send_original` 控制是否附带原片。省略时使用客户端的默认设置。
``` ```
[POST] http://127.0.0.1:{ROBOT_WECHAT_CLIENT_PORT}/api/v1/robot/message/send/video/url [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 发送表情消息接口** **Agent 发送表情消息接口**
`send-emoji` 按内置名称查找微信已有表情的 `Md5` 和 `TotalLen`。给定 GIF 路径或 URL 时使用上方图片接口。
``` ```
[POST] http://127.0.0.1:{ROBOT_WECHAT_CLIENT_PORT}/api/v1/robot/message/send/emoji [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, // 表情长度 "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` 数组 |

View File

@ -65,14 +65,15 @@ def send_image(image_url: str) -> bool:
try: try:
with urllib.request.urlopen(request, timeout=10) as response: with urllib.request.urlopen(request, timeout=10) as response:
if 200 <= response.status < 300:
return True
payload = json.load(response) payload = json.load(response)
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError): except (urllib.error.URLError, TimeoutError, json.JSONDecodeError):
return False return False
code = payload.get("code") return (
return code == 200 or code == 0 isinstance(payload, dict)
and payload.get("code") == 200
and payload.get("data") == [f"成功: {image_url}"]
)
def main() -> int: def main() -> int:

View File

@ -26,7 +26,6 @@ except ImportError: # pragma: no cover - Python 3.8 fallback
sys.stderr = sys.stdout sys.stderr = sys.stdout
MAX_EXPORT_ROWS = 50_000 MAX_EXPORT_ROWS = 50_000
MAX_EXCEL_FILE_SIZE = 25 * 1024 * 1024
EXCEL_CELL_MAX_LENGTH = 32_767 EXCEL_CELL_MAX_LENGTH = 32_767
ILLEGAL_XML_CHARACTERS = re.compile( ILLEGAL_XML_CHARACTERS = re.compile(
r"[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F-\x84\x86-\x9F]" r"[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F-\x84\x86-\x9F]"
@ -512,8 +511,6 @@ def _build_workbook(
) )
try: try:
workbook.save(temporary_path) workbook.save(temporary_path)
if temporary_path.stat().st_size > MAX_EXCEL_FILE_SIZE:
raise ValueError("生成的 Excel 文件超过 25MB,请缩短导出时间范围")
temporary_path.replace(output_path) temporary_path.replace(output_path)
finally: finally:
temporary_path.unlink(missing_ok=True) temporary_path.unlink(missing_ok=True)
@ -521,7 +518,9 @@ def _build_workbook(
def _raise_for_client_error(payload: dict[str, Any]) -> None: def _raise_for_client_error(payload: dict[str, Any]) -> None:
code = payload.get("code") 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}") message = str(payload.get("message") or f"客户端返回错误码 {code}")
raise RuntimeError(message) 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: except urllib.error.URLError as exc:
raise RuntimeError(f"发送 Excel 失败: {exc.reason}") from exc raise RuntimeError(f"发送 Excel 失败: {exc.reason}") from exc
if not response_text.strip():
return
try: try:
payload = json.loads(response_text) payload = json.loads(response_text)
except json.JSONDecodeError as exc: except json.JSONDecodeError as exc:

View File

@ -343,6 +343,23 @@ def _is_remote_image_url(value: str) -> bool:
return urllib.parse.urlparse(value).scheme in {"http", "https"} 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: 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)] 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)] 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, timeout=300,
) )
_debug_response("send image url response", response) _debug_response("send image url response", response)
_raise_for_client_error(response, len(remote_urls))
for file_path in local_paths: for file_path in local_paths:
send_url = f"http://127.0.0.1:{client_port}/api/v1/robot/message/send/image/local" 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, timeout=300,
) )
_debug_response("send image local response", response) _debug_response("send image local response", response)
_raise_for_client_error(response)
def _cleanup_openai_temp_files(image_outputs: list[str]) -> None: def _cleanup_openai_temp_files(image_outputs: list[str]) -> None:

View File

@ -1,13 +1,13 @@
--- ---
name: send-emoji name: send-emoji
description: "发送微信表情技能。使用表情包聊天可以活跃气氛,也可以缓解尴尬,你可以在适当的时候发送表情包活跃聊天氛围,也可以在遇到不方便回答或者不想回答的问题时发送一个表情包来巧妙地回避。" description: "按名称发送内置微信表情,例如 [开心]。用户说「发个表情」或聊天时适合用表情活跃气氛、缓解尴尬、回应不方便回答的问题时使用。用户给出 GIF 文件或链接时使用 send-image。"
--- ---
# Send Emoji Skill # Send Emoji Skill
## 描述 ## 描述
这是一个向当前微信会话发送表情的技能。 这个技能发送名称表中已有的微信表情。用户要求把某个本地或网络 GIF 当表情发时,将路径或 URL 交给 `send-image`。
技能脚本位于 `scripts/send_emoji.py`,内部维护了表情名称到微信表情标识(Md5 / TotalLen)的映射表,对 AI 模型完全透明——模型只需传入表情名称(如 `[开心]`),脚本自动查找对应的 Md5 和 TotalLen 并调用客户端接口发送。 技能脚本位于 `scripts/send_emoji.py`,内部维护了表情名称到微信表情标识(Md5 / TotalLen)的映射表,对 AI 模型完全透明——模型只需传入表情名称(如 `[开心]`),脚本自动查找对应的 Md5 和 TotalLen 并调用客户端接口发送。
@ -32,7 +32,7 @@ description: "发送微信表情技能。使用表情包聊天可以活跃气氛
## 触发条件 ## 触发条件
- Agent 根据上下文判断需要用表情回应时,从可用表情列表中选取合适的。 - Agent 根据上下文判断需要用表情回应时,从可用表情列表中选取合适的。
- 用户要求发送某个微信表情。 - 用户按名称要求发送某个内置微信表情。
- 用户说「发个表情」「来个表情包」「发个 xxx 表情」。 - 用户说「发个表情」「来个表情包」「发个 xxx 表情」。
## 入参规范 ## 入参规范
@ -43,7 +43,7 @@ description: "发送微信表情技能。使用表情包聊天可以活跃气氛
"properties": { "properties": {
"name": { "name": {
"type": "string", "type": "string",
"description": "表情名称,如 [开心]、[快乐]。必须是可用表情列表中的名称。" "description": "表情名称,如 [开心]、[爱心]。必须是可用表情列表中的名称。"
}, },
"names": { "names": {
"type": "array", "type": "array",
@ -65,7 +65,7 @@ description: "发送微信表情技能。使用表情包聊天可以活跃气氛
对应命令行参数: 对应命令行参数:
- `--name <表情名称>` 必填或可重复传入,如 `--name '[开心]'` - `--name <表情名称>` 必填或可重复传入,如 `--name '[开心]'`
- `--names <JSON数组>` 可选,用于一次传入多个名称,如 `--names '["[开心]", "[快乐]"]'` - `--names <JSON数组>` 可选,用于一次传入多个名称,如 `--names '["[开心]", "[爱心]"]'`
- `--ended` 可选标志 - `--ended` 可选标志
```bash ```bash
@ -75,7 +75,7 @@ python3 scripts/send_emoji.py --name '[开心]'
发送多个表情: 发送多个表情:
```bash ```bash
python3 scripts/send_emoji.py --name '[开心]' --name '[快乐]' python3 scripts/send_emoji.py --name '[开心]' --name '[爱心]'
``` ```
当 Agent 认为任务已完成、对话可以结束时,加上 `--ended` 标志: 当 Agent 认为任务已完成、对话可以结束时,加上 `--ended` 标志:
@ -84,7 +84,7 @@ python3 scripts/send_emoji.py --name '[开心]' --name '[快乐]'
python3 scripts/send_emoji.py --name '[开心]' --ended 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 智能体再做额外处理。 - 成功时,脚本输出「表情发送成功」,表示表情已通过客户端接口直接发送,无需 AI 智能体再做额外处理。
- 如果传入 `--ended`,输出末尾会追加 `ended`,Agent 会自动结束对话。 - 如果传入 `--ended`,输出末尾会追加 `ended`,Agent 会自动结束对话。
- 不要发送`表情发送成功啦` `已经发送表情啦` `工具调用成功` 这类无意义的回复,如果你只有这类话要说,请在输出末尾加上 `ended`,让 Agent 结束对话。 - 不要发送`表情发送成功啦` `已经发送表情啦` `工具调用成功` 这类无意义的回复,如果你只有这类话要说,请在输出末尾加上 `ended`,让 Agent 结束对话。
- 失败时,返回脚本输出的具体错误信息(含可用表情列表)。 - 失败时返回脚本输出的具体原因。名称未知时会列出可用表情。

View File

@ -66,7 +66,7 @@ def _client_private_token() -> str:
return os.environ.get("ROBOT_CLIENT_PRIVATE_TOKEN", "").strip() 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") data = json.dumps(body).encode("utf-8")
req = urllib.request.Request( req = urllib.request.Request(
url, url,
@ -78,10 +78,11 @@ def _http_post_json(url: str, body: dict, timeout: int = 300) -> dict:
method="POST", method="POST",
) )
with urllib.request.urlopen(req, timeout=timeout) as resp: with urllib.request.urlopen(req, timeout=timeout) as resp:
text = resp.read().decode("utf-8") response = json.load(resp)
if not text.strip(): if not isinstance(response, dict) or "code" not in response:
return {} raise RuntimeError("客户端返回的发送结果无效")
return json.loads(text) 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]: def _expand_json_array_values(values: list[str], label: str) -> list[str]:

View File

@ -1,6 +1,6 @@
--- ---
name: send-file 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。 - 至少提供一个非空本地路径或远程 URL。
- 本地路径必须指向已存在、非空且不超过 25MB 的文件,不能把 URL 作为本地路径传入。 - 本地路径必须指向已存在且非空的文件。
- 远程 URL 必须包含有效的 `http` 或 `https` 协议及主机名;客户端下载后的文件也不能超过 25MB。 - 远程 URL 必须包含有效的 `http` 或 `https` 协议及主机名。
- 脚本按首次出现顺序去重;所有参数通过校验后,单个发送失败时会继续尝试其余文件,最终返回全部失败原因。 - 脚本按首次出现顺序去重;所有参数通过校验后,单个发送失败时会继续尝试其余文件,最终返回全部失败原因。
## 输出 ## 输出

View File

@ -12,34 +12,28 @@ from pathlib import Path
sys.stderr = sys.stdout sys.stderr = sys.stdout
MAX_FILE_SIZE = 25 * 1024 * 1024
def _client_private_token() -> str: def _client_private_token() -> str:
return os.environ.get("ROBOT_CLIENT_PRIVATE_TOKEN", "").strip() return os.environ.get("ROBOT_CLIENT_PRIVATE_TOKEN", "").strip()
def _raise_for_client_error(response: dict) -> None: def _raise_for_client_error(response: object, url_count: int) -> None:
if not response: if not isinstance(response, dict) or "code" not in response:
return raise RuntimeError("客户端返回的发送结果无效")
if response["code"] != 200:
code = response.get("code") raise RuntimeError(response.get("message") or f"客户端返回错误码 {response['code']}")
if code is not None and str(code) != "200": if url_count:
message = str(response.get("message") or f"客户端返回错误码 {code}") results = response.get("data")
raise RuntimeError(message) if not isinstance(results, list) or len(results) != url_count:
raise RuntimeError("客户端返回的逐项发送结果不完整")
data = response.get("data")
if isinstance(data, list):
failures = [ failures = [
item.strip() str(item) for item in results
for item in data if not isinstance(item, str) or not item.startswith("成功: ")
if isinstance(item, str) and item.lstrip().startswith("失败:")
] ]
if failures: if failures:
raise RuntimeError(";".join(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") data = json.dumps(body).encode("utf-8")
req = urllib.request.Request( req = urllib.request.Request(
url, url,
@ -51,15 +45,8 @@ def _http_post_json(url: str, body: dict, timeout: int = 300) -> dict:
method="POST", method="POST",
) )
with urllib.request.urlopen(req, timeout=timeout) as resp: with urllib.request.urlopen(req, timeout=timeout) as resp:
text = resp.read().decode("utf-8") response = json.load(resp)
if not text.strip(): _raise_for_client_error(response, len(body.get("file_urls", [])))
return {}
response = json.loads(text)
if not isinstance(response, dict):
raise RuntimeError("客户端返回格式不正确")
_raise_for_client_error(response)
return response
def _expand_json_array_values(values: list[str], label: str) -> list[str]: 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(): if not path.is_file():
raise ValueError(f"本地文件不存在: {value}") raise ValueError(f"本地文件不存在: {value}")
file_size = path.stat().st_size if path.stat().st_size <= 0:
if file_size <= 0:
raise ValueError(f"本地文件不能为空: {value}") raise ValueError(f"本地文件不能为空: {value}")
if file_size > MAX_FILE_SIZE:
raise ValueError(f"本地文件大小不能超过 25MB: {value}")
return str(path.resolve()) return str(path.resolve())

View File

@ -1,12 +1,14 @@
--- ---
name: send-image name: send-image
description: "发送本地或远程图片到当前微信会话。比如,其他技能产出了需要发送的本地图片路径时使用。" description: "将本地图片文件或远程图片链接发送到当前微信会话,支持静态原图。用户给出 GIF 路径或链接,要求发动态图或把这个 GIF 当表情发时,使用本技能。"
--- ---
# 发送图片 # 发送图片
使用 `scripts/send_image.py` 调用机器人客户端接口,将一个或多个本地图片文件、远程图片 URL 发送到当前微信会话。 使用 `scripts/send_image.py` 调用机器人客户端接口,将一个或多个本地图片文件、远程图片 URL 发送到当前微信会话。
用户给出 GIF 文件路径或链接时,使用本技能。按名称发送内置表情时使用 `send-emoji`。用户明确要求发送可下载的 GIF 附件时使用 `send-file`。
## 入参 ## 入参
```json ```json
@ -34,6 +36,11 @@ description: "发送本地或远程图片到当前微信会话。比如,其他
"type": "string" "type": "string"
}, },
"description": "要发送的多个远程图片 URL。" "description": "要发送的多个远程图片 URL。"
},
"send_original": {
"type": "boolean",
"default": false,
"description": "是否以原图发送本次请求中的静态图片。"
} }
}, },
"anyOf": [ "anyOf": [
@ -52,6 +59,7 @@ description: "发送本地或远程图片到当前微信会话。比如,其他
- `--file_paths <JSON数组>`:一次传入多个本地图片路径。 - `--file_paths <JSON数组>`:一次传入多个本地图片路径。
- `--image_url <远程图片URL>`:可重复传入。 - `--image_url <远程图片URL>`:可重复传入。
- `--image_urls <JSON数组>`:一次传入多个远程图片 URL。 - `--image_urls <JSON数组>`:一次传入多个远程图片 URL。
- `--send_original` 请求发送静态原图,也可以显式传 `--send_original true` 或 `--send_original false`。
## 执行 ## 执行
@ -61,6 +69,13 @@ description: "发送本地或远程图片到当前微信会话。比如,其他
python3 scripts/send_image.py --file_path '/tmp/example.png' 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 ```bash

View File

@ -1,4 +1,4 @@
interface: interface:
display_name: "发送图片" display_name: "发送图片"
short_description: "将一个或多个本地图片文件或远程图片链接发送到当前微信会话" short_description: "将本地图片或远程图片链接发送到当前微信会话,支持静态原图和 GIF"
default_prompt: "使用 $send-image 将这些本地图片或远程图片发送到当前微信会话。" default_prompt: "使用 $send-image 将这些本地图片或远程图片发送到当前微信会话。"

View File

@ -17,27 +17,24 @@ def _client_private_token() -> str:
return os.environ.get("ROBOT_CLIENT_PRIVATE_TOKEN", "").strip() return os.environ.get("ROBOT_CLIENT_PRIVATE_TOKEN", "").strip()
def _raise_for_client_error(response: dict) -> None: def _raise_for_client_error(response: object, url_count: int) -> None:
if not response: if not isinstance(response, dict) or "code" not in response:
return raise RuntimeError("客户端返回的发送结果无效")
if response["code"] != 200:
code = response.get("code") raise RuntimeError(response.get("message") or f"客户端返回错误码 {response['code']}")
if code is not None and str(code) != "200": if url_count:
message = str(response.get("message") or f"客户端返回错误码 {code}") results = response.get("data")
raise RuntimeError(message) if not isinstance(results, list) or len(results) != url_count:
raise RuntimeError("客户端返回的逐项发送结果不完整")
data = response.get("data")
if isinstance(data, list):
failures = [ failures = [
item.strip() str(item) for item in results
for item in data if not isinstance(item, str) or not item.startswith("成功: ")
if isinstance(item, str) and item.lstrip().startswith("失败:")
] ]
if failures: if failures:
raise RuntimeError(";".join(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") data = json.dumps(body).encode("utf-8")
req = urllib.request.Request( req = urllib.request.Request(
url, url,
@ -49,15 +46,8 @@ def _http_post_json(url: str, body: dict, timeout: int = 300) -> dict:
method="POST", method="POST",
) )
with urllib.request.urlopen(req, timeout=timeout) as resp: with urllib.request.urlopen(req, timeout=timeout) as resp:
text = resp.read().decode("utf-8") response = json.load(resp)
if not text.strip(): _raise_for_client_error(response, len(body.get("image_urls", [])))
return {}
response = json.loads(text)
if not isinstance(response, dict):
raise RuntimeError("客户端返回格式不正确")
_raise_for_client_error(response)
return response
def _expand_json_array_values(values: list[str], label: str) -> list[str]: 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 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 = argparse.ArgumentParser(add_help=False)
parser.add_argument("--file_path", action="append", default=[]) parser.add_argument("--file_path", action="append", default=[])
parser.add_argument("--file_paths", action="append", default=[]) parser.add_argument("--file_paths", action="append", default=[])
parser.add_argument("--image_url", action="append", default=[]) parser.add_argument("--image_url", action="append", default=[])
parser.add_argument("--image_urls", 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) namespace, unknown = parser.parse_known_args(argv)
if unknown: if unknown:
@ -105,7 +96,7 @@ def _parse_cli_params(argv: list[str]) -> tuple[list[str], list[str]]:
image_urls = _expand_json_array_values( image_urls = _expand_json_array_values(
namespace.image_url + namespace.image_urls, "image_urls" 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: def _is_remote_url(value: str) -> bool:
@ -131,18 +122,24 @@ def _validate_remote_image_url(value: str) -> str:
return value 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 = ( send_url = (
f"http://127.0.0.1:{client_port}/api/v1/robot/message/send/image/local" 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( 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: ) -> None:
send_url = f"http://127.0.0.1:{client_port}/api/v1/robot/message/send/image/url" 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: def main() -> int:
@ -151,7 +148,7 @@ def main() -> int:
return 1 return 1
try: 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: if not raw_file_paths and not raw_image_urls:
sys.stdout.write("缺少本地图片路径或远程图片 URL\n") sys.stdout.write("缺少本地图片路径或远程图片 URL\n")
return 1 return 1
@ -178,13 +175,13 @@ def main() -> int:
failures: list[str] = [] failures: list[str] = []
for file_path in file_paths: for file_path in file_paths:
try: 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: except Exception as exc:
failures.append(f"本地图片 {file_path}: {exc}") failures.append(f"本地图片 {file_path}: {exc}")
if image_urls: if image_urls:
try: 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: except Exception as exc:
failures.append(f"远程图片: {exc}") failures.append(f"远程图片: {exc}")

View File

@ -354,6 +354,23 @@ def _is_remote_image_url(value: str) -> bool:
return urllib.parse.urlparse(value).scheme in {"http", "https"} 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: 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)] 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)] 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, timeout=300,
) )
_debug_response("send image url response", response) _debug_response("send image url response", response)
_raise_for_client_error(response, len(remote_urls))
for file_path in local_paths: for file_path in local_paths:
send_url = f"http://127.0.0.1:{client_port}/api/v1/robot/message/send/image/local" 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, timeout=300,
) )
_debug_response("send image local response", response) _debug_response("send image local response", response)
_raise_for_client_error(response)
def _cleanup_openai_temp_files(image_outputs: list[str]) -> None: def _cleanup_openai_temp_files(image_outputs: list[str]) -> None:

View File

@ -67,6 +67,10 @@ description: "AI 视频生成工具。当用户想生成视频、文生视频、
"type": "integer", "type": "integer",
"description": "视频时长,单位秒,可选,默认 5。", "description": "视频时长,单位秒,可选,默认 5。",
"default": 5 "default": 5
},
"send_original": {
"type": "boolean",
"description": "发送生成的视频时是否附带原片。省略时使用客户端的默认设置。"
} }
}, },
"required": ["prompt"], "required": ["prompt"],
@ -82,6 +86,7 @@ description: "AI 视频生成工具。当用户想生成视频、文生视频、
- `--ratio <比例>` 可选 - `--ratio <比例>` 可选
- `--resolution <分辨率>` 可选 - `--resolution <分辨率>` 可选
- `--duration <秒数>` 可选 - `--duration <秒数>` 可选
- `--send_original` 或 `--send_original true` 表示附带原片,`--send_original false` 表示只发播放版本。
## 依赖安装 ## 依赖安装
@ -94,13 +99,13 @@ description: "AI 视频生成工具。当用户想生成视频、文生视频、
2. 从用户输入中提取 `prompt`,不要改写提示词本身。 2. 从用户输入中提取 `prompt`,不要改写提示词本身。
3. 根据上下文可选提取 `model`、`file_paths`、`ratio`、`resolution`、`duration`。 3. 根据上下文可选提取 `model`、`file_paths`、`ratio`、`resolution`、`duration`。
4. 如果用户没有明确指定模型,默认使用 `jimeng-video-3.0-fast`。 4. 如果用户没有明确指定模型,默认使用 `jimeng-video-3.0-fast`。
5. 在仓库根目录执行脚本,例如: 5. 在技能目录执行脚本,例如
```bash ```bash
python3 scripts/video_generation.py --prompt '海边日落,镜头缓慢推进' --file_paths 'https://example.com/start.jpg' 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`,其中一条失败就返回具体原因。
## 校验规则 ## 校验规则

View File

@ -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")) 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() client_port = os.environ.get("ROBOT_WECHAT_CLIENT_PORT", "").strip()
if not client_port: if not client_port:
raise RuntimeError("环境变量 ROBOT_WECHAT_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_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, "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_url,
send_body, send_body,
{ {
@ -206,6 +225,7 @@ def send_videos(from_wx_id: str, video_urls: list[str]) -> None:
}, },
timeout=60, timeout=60,
) )
_raise_for_client_error(response, len(video_urls))
def call_jimeng_video( def call_jimeng_video(
@ -262,6 +282,7 @@ def _parse_cli_params(argv: list[str]) -> dict:
parser.add_argument("--ratio", default="") parser.add_argument("--ratio", default="")
parser.add_argument("--resolution", default="") parser.add_argument("--resolution", default="")
parser.add_argument("--duration", type=int, default=0) 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) namespace, unknown = parser.parse_known_args(argv)
if unknown: if unknown:
@ -274,6 +295,7 @@ def _parse_cli_params(argv: list[str]) -> dict:
"ratio": namespace.ratio, "ratio": namespace.ratio,
"resolution": namespace.resolution, "resolution": namespace.resolution,
"duration": namespace.duration, "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 return 1
try: try:
send_videos(from_wx_id, video_urls) send_videos(from_wx_id, video_urls, params["send_original"])
sys.stdout.write("ended") sys.stdout.write("ended")
except Exception as exc: except Exception as exc:
sys.stdout.write(f"发送视频失败: {exc}\n") sys.stdout.write(f"发送视频失败: {exc}\n")

View File

@ -1760,11 +1760,18 @@ async function maybeSendScreenshot(
return false; return false;
} }
const sendUrl = `http://127.0.0.1:${clientPort}/api/v1/robot/message/send/image/local`; const sendUrl = `http://127.0.0.1:${clientPort}/api/v1/robot/message/send/image/local`;
await postJson( const text = await postJson(
sendUrl, sendUrl,
{ to_wxid: toWxid, file_path: filePath }, { to_wxid: toWxid, file_path: filePath },
params.timeoutMs, 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; return true;
} }

102
tests/test_send_media.py Normal file
View File

@ -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)