fix(wecom): use SDK media upload API

This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-07 10:34:32 +08:00
1 parent a4fe3adf5c
commit 3f128505d0
4 files changed
+120 -333

No files matched your search

+1 -1
View File
@@ -19,6 +19,6 @@ PLUGIN = ChannelPlugin(
display_name="WeCom", display_name="WeCom",
runtime=f"{__package__}.runtime:WecomChannel", runtime=f"{__package__}.runtime:WecomChannel",
setup=SETUP_SPEC, setup=SETUP_SPEC,
dependencies=("wecom-aibot-sdk-python>=0.1.5",), dependencies=("wecom-aibot-sdk-python>=0.1.7,<0.2.0",),
webui="webui/index.ts", webui="webui/index.ts",
) )
+21 -135
View File
@@ -2,8 +2,6 @@
"""WeCom (Enterprise WeChat) channel implementation using wecom_aibot_sdk.""" """WeCom (Enterprise WeChat) channel implementation using wecom_aibot_sdk."""
import asyncio import asyncio
import base64
import hashlib
import importlib.util import importlib.util
import os import os
import re import re
@@ -23,8 +21,8 @@ from nanobot.config.schema import Base
WECOM_AVAILABLE = importlib.util.find_spec("wecom_aibot_sdk") is not None WECOM_AVAILABLE = importlib.util.find_spec("wecom_aibot_sdk") is not None
# Upload safety limits (matching QQ channel defaults) # Inbound media safety limit (matching QQ channel defaults)
WECOM_UPLOAD_MAX_BYTES = 1024 * 1024 * 200 # 200MB WECOM_DOWNLOAD_MAX_BYTES = 1024 * 1024 * 200 # 200MB
# Replace unsafe characters with "_", keep Chinese and common safe punctuation. # Replace unsafe characters with "_", keep Chinese and common safe punctuation.
_SAFE_NAME_RE = re.compile(r"[^\w.\-()\[\]()【】\u4e00-\u9fff]+", re.UNICODE) _SAFE_NAME_RE = re.compile(r"[^\w.\-()\[\]()【】\u4e00-\u9fff]+", re.UNICODE)
@@ -40,22 +38,6 @@ def _sanitize_filename(name: str, fallback: str = "unnamed") -> str:
return _clean(name) or _clean(fallback) or "unnamed" return _clean(name) or _clean(fallback) or "unnamed"
_IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"}
_VIDEO_EXTS = {".mp4", ".avi", ".mov"}
_AUDIO_EXTS = {".amr", ".mp3", ".wav", ".ogg"}
def _guess_wecom_media_type(filename: str) -> str:
"""Classify file extension as WeCom media_type string."""
ext = Path(filename).suffix.lower()
if ext in _IMAGE_EXTS:
return "image"
if ext in _VIDEO_EXTS:
return "video"
if ext in _AUDIO_EXTS:
return "voice"
return "file"
class WecomConfig(Base): class WecomConfig(Base):
"""WeCom (Enterprise WeChat) AI Bot channel configuration.""" """WeCom (Enterprise WeChat) AI Bot channel configuration."""
@@ -392,11 +374,11 @@ class WecomChannel(BaseChannel):
self.logger.warning("Failed to download media") self.logger.warning("Failed to download media")
return None return None
if len(data) > WECOM_UPLOAD_MAX_BYTES: if len(data) > WECOM_DOWNLOAD_MAX_BYTES:
self.logger.warning( self.logger.warning(
"inbound media too large: {} bytes (max {})", "inbound media too large: {} bytes (max {})",
len(data), len(data),
WECOM_UPLOAD_MAX_BYTES, WECOM_DOWNLOAD_MAX_BYTES,
) )
return None return None
@@ -413,102 +395,6 @@ class WecomChannel(BaseChannel):
self.logger.exception("Error downloading media") self.logger.exception("Error downloading media")
return None return None
async def _upload_media_ws(
self,
client: Any,
file_path: str,
) -> tuple[str, str] | tuple[None, None]:
"""Upload a local file to WeCom via WebSocket 3-step protocol (base64).
Uses the WeCom WebSocket upload commands directly via
``client._ws_manager.send_reply()``:
``aibot_upload_media_init`` → upload_id
``aibot_upload_media_chunk`` × N (≤512 KB raw per chunk, base64)
``aibot_upload_media_finish`` → media_id
Returns (media_id, media_type) on success, (None, None) on failure.
"""
from wecom_aibot_sdk.utils import generate_req_id as _gen_req_id
try:
fname = os.path.basename(file_path)
media_type = _guess_wecom_media_type(fname)
# Read file size and data in a thread to avoid blocking the event loop
def _read_file() -> tuple[int, bytes]:
file_size = os.path.getsize(file_path)
if file_size > WECOM_UPLOAD_MAX_BYTES:
raise ValueError(
f"File too large: {file_size} bytes (max {WECOM_UPLOAD_MAX_BYTES})"
)
with open(file_path, "rb") as f:
return file_size, f.read()
file_size, data = await asyncio.to_thread(_read_file)
# MD5 is used for file integrity only, not cryptographic security
md5_hash = hashlib.md5(data).hexdigest()
chunk_size = 512 * 1024 # 512 KB raw (before base64)
mv = memoryview(data)
chunk_list = [bytes(mv[i : i + chunk_size]) for i in range(0, file_size, chunk_size)]
n_chunks = len(chunk_list)
del mv, data
# Step 1: init
req_id = _gen_req_id("upload_init")
resp = await client._ws_manager.send_reply(req_id, {
"type": media_type,
"filename": fname,
"total_size": file_size,
"total_chunks": n_chunks,
"md5": md5_hash,
}, "aibot_upload_media_init")
if resp.errcode != 0:
self.logger.warning("upload init failed ({}): {}", resp.errcode, resp.errmsg)
return None, None
upload_id = resp.body.get("upload_id") if resp.body else None
if not upload_id:
self.logger.warning("upload init: no upload_id in response")
return None, None
# Step 2: send chunks
for i, chunk in enumerate(chunk_list):
req_id = _gen_req_id("upload_chunk")
resp = await client._ws_manager.send_reply(req_id, {
"upload_id": upload_id,
"chunk_index": i,
"base64_data": base64.b64encode(chunk).decode(),
}, "aibot_upload_media_chunk")
if resp.errcode != 0:
self.logger.warning("upload chunk {} failed ({}): {}", i, resp.errcode, resp.errmsg)
return None, None
# Step 3: finish
req_id = _gen_req_id("upload_finish")
resp = await client._ws_manager.send_reply(req_id, {
"upload_id": upload_id,
}, "aibot_upload_media_finish")
if resp.errcode != 0:
self.logger.warning("upload finish failed ({}): {}", resp.errcode, resp.errmsg)
return None, None
media_id = resp.body.get("media_id") if resp.body else None
if not media_id:
self.logger.warning("upload finish: no media_id in response body={}", resp.body)
return None, None
suffix = "..." if len(media_id) > 16 else ""
self.logger.debug("uploaded {} ({}) → media_id={}", fname, media_type, media_id[:16] + suffix)
return media_id, media_type
except ValueError as e:
self.logger.warning("upload skipped for {}: {}", file_path, e)
return None, None
except Exception:
self.logger.exception("_upload_media_ws error for {}", file_path)
return None, None
async def send(self, msg: OutboundMessage) -> None: async def send(self, msg: OutboundMessage) -> None:
"""Send a message through WeCom.""" """Send a message through WeCom."""
if not self._client: if not self._client:
@@ -526,29 +412,29 @@ class WecomChannel(BaseChannel):
if not os.path.isfile(file_path): if not os.path.isfile(file_path):
self.logger.warning("media file not found: {}", file_path) self.logger.warning("media file not found: {}", file_path)
continue continue
media_id, media_type = await self._upload_media_ws(self._client, file_path) try:
if media_id: upload = await self._client.upload_media(file_path)
if frame: except Exception:
await self._client.reply(frame, { self.logger.exception("media upload failed for {}", file_path)
"msgtype": media_type,
media_type: {"media_id": media_id},
})
else:
await self._client.send_message(msg.chat_id, {
"msgtype": media_type,
media_type: {"media_id": media_id},
})
self.logger.debug("sent {} → {}", media_type, msg.chat_id)
else:
content += f"\n[file upload failed: {os.path.basename(file_path)}]" content += f"\n[file upload failed: {os.path.basename(file_path)}]"
continue
media_type = upload.media_type
media_body = {
"msgtype": media_type,
media_type: {"media_id": upload.media_id},
}
if frame:
await self._client.reply(frame, media_body)
else:
await self._client.send_message(msg.chat_id, media_body)
self.logger.debug("sent {} → {}", media_type, msg.chat_id)
if not content: if not content:
return return
if frame: if frame:
# Both progress and final messages must use reply_stream (cmd="aibot_respond_msg"). # Keep progress and final updates on the SDK's serialized streaming reply path.
# The plain reply() uses cmd="reply" which does not support "text" msgtype
# and causes errcode=40008 from WeCom API.
generate_req_id = self._generate_req_id generate_req_id = self._generate_req_id
if generate_req_id is None: if generate_req_id is None:
raise RuntimeError("WeCom request-id generator is not initialized") raise RuntimeError("WeCom request-id generator is not initialized")
@@ -3,7 +3,7 @@
import os import os
import tempfile import tempfile
from pathlib import Path from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch from unittest.mock import AsyncMock, patch
import pytest import pytest
@@ -17,50 +17,17 @@ except ImportError:
if not WECOM_AVAILABLE: if not WECOM_AVAILABLE:
pytest.skip("WeCom dependencies not installed (wecom_aibot_sdk)", allow_module_level=True) pytest.skip("WeCom dependencies not installed (wecom_aibot_sdk)", allow_module_level=True)
from wecom_aibot_sdk import UploadResult, WSClient
from nanobot.bus.events import OutboundMessage from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ProgressEvent from nanobot.bus.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.channels.wecom.runtime import ( from nanobot.channels.wecom.runtime import (
WecomChannel, WecomChannel,
WecomConfig, WecomConfig,
_guess_wecom_media_type,
_sanitize_filename, _sanitize_filename,
) )
# Try to import the real response class; fall back to a stub if unavailable.
try:
from wecom_aibot_sdk.utils import WsResponse
_RealWsResponse = WsResponse
except ImportError:
_RealWsResponse = None
class _FakeResponse:
"""Minimal stand-in for wecom_aibot_sdk WsResponse."""
def __init__(self, errcode: int = 0, body: dict | None = None, errmsg: str = "ok"):
self.errcode = errcode
self.errmsg = errmsg
self.body = body or {}
class _FakeWsManager:
"""Tracks send_reply calls and returns configurable responses."""
def __init__(self, responses: list[_FakeResponse] | None = None):
self.responses = responses or []
self.calls: list[tuple[str, dict, str]] = []
self._idx = 0
async def send_reply(self, req_id: str, data: dict, cmd: str) -> _FakeResponse:
self.calls.append((req_id, data, cmd))
if self._idx < len(self.responses):
resp = self.responses[self._idx]
self._idx += 1
return resp
return _FakeResponse()
class _FakeFrame: class _FakeFrame:
"""Minimal frame object with a body dict.""" """Minimal frame object with a body dict."""
@@ -72,16 +39,23 @@ class _FakeFrame:
class _FakeWeComClient: class _FakeWeComClient:
"""Fake WeCom client with mock methods.""" """Fake WeCom client with mock methods."""
def __init__(self, ws_responses: list[_FakeResponse] | None = None): def __init__(self):
self._ws_manager = _FakeWsManager(ws_responses)
self.download_file = AsyncMock(return_value=(None, None)) self.download_file = AsyncMock(return_value=(None, None))
self.upload_media = AsyncMock(
return_value=UploadResult(media_id="media_123", media_type="image")
)
self.reply = AsyncMock() self.reply = AsyncMock()
self.reply_stream = AsyncMock() self.reply_stream = AsyncMock()
self.send_message = AsyncMock() self.send_message = AsyncMock()
self.reply_welcome = AsyncMock() self.reply_welcome = AsyncMock()
# ── Helper function tests (pure, no async) ────────────────────────── # ── SDK contract and helper function tests ─────────────────────────
def test_sdk_exposes_media_upload_api() -> None:
"""The declared SDK version provides the public API used by this channel."""
assert callable(WSClient.upload_media)
def test_sanitize_filename_strips_path_traversal() -> None: def test_sanitize_filename_strips_path_traversal() -> None:
@@ -103,31 +77,6 @@ def test_sanitize_filename_empty_or_dots_fallback() -> None:
assert _sanitize_filename("") == "unnamed" assert _sanitize_filename("") == "unnamed"
def test_guess_wecom_media_type_image() -> None:
for ext in (".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"):
assert _guess_wecom_media_type(f"photo{ext}") == "image"
def test_guess_wecom_media_type_video() -> None:
for ext in (".mp4", ".avi", ".mov"):
assert _guess_wecom_media_type(f"video{ext}") == "video"
def test_guess_wecom_media_type_voice() -> None:
for ext in (".amr", ".mp3", ".wav", ".ogg"):
assert _guess_wecom_media_type(f"audio{ext}") == "voice"
def test_guess_wecom_media_type_file_fallback() -> None:
for ext in (".pdf", ".doc", ".xlsx", ".zip"):
assert _guess_wecom_media_type(f"doc{ext}") == "file"
def test_guess_wecom_media_type_case_insensitive() -> None:
assert _guess_wecom_media_type("photo.PNG") == "image"
assert _guess_wecom_media_type("photo.Jpg") == "image"
# ── _download_and_save_media() ────────────────────────────────────── # ── _download_and_save_media() ──────────────────────────────────────
@@ -203,125 +152,6 @@ async def test_download_and_save_failure() -> None:
assert result is None assert result is None
# ── _upload_media_ws() ──────────────────────────────────────────────
@pytest.mark.asyncio
async def test_upload_media_ws_success() -> None:
"""Happy path: init → chunk → finish → returns (media_id, media_type)."""
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
f.write(b"\x89PNG\r\n")
tmp = f.name
try:
responses = [
_FakeResponse(errcode=0, body={"upload_id": "up_1"}),
_FakeResponse(errcode=0, body={}),
_FakeResponse(errcode=0, body={"media_id": "media_abc"}),
]
client = _FakeWeComClient(responses)
channel = WecomChannel(WecomConfig(bot_id="b", secret="s", allow_from=["*"]), MessageBus())
channel._client = client
with patch("wecom_aibot_sdk.utils.generate_req_id", side_effect=lambda x: f"req_{x}"):
media_id, media_type = await channel._upload_media_ws(client, tmp)
assert media_id == "media_abc"
assert media_type == "image"
finally:
os.unlink(tmp)
@pytest.mark.asyncio
async def test_upload_media_ws_oversized_file() -> None:
"""File >200MB triggers ValueError → returns (None, None)."""
# Instead of creating a real 200MB+ file, mock os.path.getsize and open
with patch("os.path.getsize", return_value=200 * 1024 * 1024 + 1), \
patch("builtins.open", MagicMock()):
client = _FakeWeComClient()
channel = WecomChannel(WecomConfig(bot_id="b", secret="s", allow_from=["*"]), MessageBus())
channel._client = client
result = await channel._upload_media_ws(client, "/fake/large.bin")
assert result == (None, None)
@pytest.mark.asyncio
async def test_upload_media_ws_init_failure() -> None:
"""Init step returns errcode != 0 → returns (None, None)."""
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f:
f.write(b"hello")
tmp = f.name
try:
responses = [
_FakeResponse(errcode=50001, errmsg="invalid"),
]
client = _FakeWeComClient(responses)
channel = WecomChannel(WecomConfig(bot_id="b", secret="s", allow_from=["*"]), MessageBus())
channel._client = client
with patch("wecom_aibot_sdk.utils.generate_req_id", side_effect=lambda x: f"req_{x}"):
result = await channel._upload_media_ws(client, tmp)
assert result == (None, None)
finally:
os.unlink(tmp)
@pytest.mark.asyncio
async def test_upload_media_ws_chunk_failure() -> None:
"""Chunk step returns errcode != 0 → returns (None, None)."""
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
f.write(b"\x89PNG\r\n")
tmp = f.name
try:
responses = [
_FakeResponse(errcode=0, body={"upload_id": "up_1"}),
_FakeResponse(errcode=50002, errmsg="chunk fail"),
]
client = _FakeWeComClient(responses)
channel = WecomChannel(WecomConfig(bot_id="b", secret="s", allow_from=["*"]), MessageBus())
channel._client = client
with patch("wecom_aibot_sdk.utils.generate_req_id", side_effect=lambda x: f"req_{x}"):
result = await channel._upload_media_ws(client, tmp)
assert result == (None, None)
finally:
os.unlink(tmp)
@pytest.mark.asyncio
async def test_upload_media_ws_finish_no_media_id() -> None:
"""Finish step returns empty media_id → returns (None, None)."""
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
f.write(b"\x89PNG\r\n")
tmp = f.name
try:
responses = [
_FakeResponse(errcode=0, body={"upload_id": "up_1"}),
_FakeResponse(errcode=0, body={}),
_FakeResponse(errcode=0, body={}), # no media_id
]
client = _FakeWeComClient(responses)
channel = WecomChannel(WecomConfig(bot_id="b", secret="s", allow_from=["*"]), MessageBus())
channel._client = client
with patch("wecom_aibot_sdk.utils.generate_req_id", side_effect=lambda x: f"req_{x}"):
result = await channel._upload_media_ws(client, tmp)
assert result == (None, None)
finally:
os.unlink(tmp)
# ── send() ────────────────────────────────────────────────────────── # ── send() ──────────────────────────────────────────────────────────
@@ -392,14 +222,69 @@ async def test_send_media_then_text() -> None:
tmp = f.name tmp = f.name
try: try:
responses = [
_FakeResponse(errcode=0, body={"upload_id": "up_1"}),
_FakeResponse(errcode=0, body={}),
_FakeResponse(errcode=0, body={"media_id": "media_123"}),
]
channel = WecomChannel(WecomConfig(bot_id="b", secret="s", allow_from=["*"]), MessageBus()) channel = WecomChannel(WecomConfig(bot_id="b", secret="s", allow_from=["*"]), MessageBus())
client = _FakeWeComClient(responses) client = _FakeWeComClient()
channel._client = client
channel._generate_req_id = lambda x: f"req_{x}"
frame = _FakeFrame()
channel._chat_frames["chat1"] = frame
await channel.send(
OutboundMessage(channel="wecom", chat_id="chat1", content="see image", media=[tmp])
)
client.upload_media.assert_awaited_once_with(tmp)
client.reply.assert_awaited_once_with(
frame,
{"msgtype": "image", "image": {"media_id": "media_123"}},
)
# Text should have been sent via reply_stream
client.reply_stream.assert_called_once()
finally:
os.unlink(tmp)
@pytest.mark.asyncio
async def test_send_proactive_media_uses_uploaded_media_id() -> None:
"""Proactive media uses the SDK upload result before sending text."""
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as f:
f.write(b"%PDF-1.4")
tmp = f.name
try:
channel = WecomChannel(WecomConfig(bot_id="b", secret="s", allow_from=["*"]), MessageBus())
client = _FakeWeComClient()
client.upload_media.return_value = UploadResult(media_id="media_file", media_type="file")
channel._client = client
await channel.send(
OutboundMessage(channel="wecom", chat_id="chat1", content="see file", media=[tmp])
)
client.upload_media.assert_awaited_once_with(tmp)
assert client.send_message.await_args_list[0].args == (
"chat1",
{"msgtype": "file", "file": {"media_id": "media_file"}},
)
assert client.send_message.await_args_list[1].args == (
"chat1",
{"msgtype": "markdown", "markdown": {"content": "see file"}},
)
finally:
os.unlink(tmp)
@pytest.mark.asyncio
async def test_send_media_upload_failure_falls_back_to_text() -> None:
"""Upload failures become a visible text marker without losing the reply."""
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
tmp = f.name
try:
channel = WecomChannel(WecomConfig(bot_id="b", secret="s", allow_from=["*"]), MessageBus())
client = _FakeWeComClient()
client.upload_media.side_effect = RuntimeError("upload failed")
channel._client = client channel._client = client
channel._generate_req_id = lambda x: f"req_{x}" channel._generate_req_id = lambda x: f"req_{x}"
channel._chat_frames["chat1"] = _FakeFrame() channel._chat_frames["chat1"] = _FakeFrame()
@@ -408,13 +293,29 @@ async def test_send_media_then_text() -> None:
OutboundMessage(channel="wecom", chat_id="chat1", content="see image", media=[tmp]) OutboundMessage(channel="wecom", chat_id="chat1", content="see image", media=[tmp])
) )
# Media should have been sent via reply assert "[file upload failed:" in client.reply_stream.await_args.args[2]
media_calls = [c for c in client.reply.call_args_list if c[0][1].get("msgtype") == "image"] assert "see image" in client.reply_stream.await_args.args[2]
assert len(media_calls) == 1 finally:
assert media_calls[0][0][1]["image"]["media_id"] == "media_123" os.unlink(tmp)
# Text should have been sent via reply_stream
client.reply_stream.assert_called_once() @pytest.mark.asyncio
async def test_send_media_delivery_failure_propagates_for_manager_retry() -> None:
"""A failed media reply still propagates after a successful upload."""
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
tmp = f.name
try:
channel = WecomChannel(WecomConfig(bot_id="b", secret="s", allow_from=["*"]), MessageBus())
client = _FakeWeComClient()
client.reply.side_effect = RuntimeError("media send failed")
channel._client = client
channel._chat_frames["chat1"] = _FakeFrame()
with pytest.raises(RuntimeError, match="media send failed"):
await channel.send(
OutboundMessage(channel="wecom", chat_id="chat1", content="", media=[tmp])
)
finally: finally:
os.unlink(tmp) os.unlink(tmp)
+1 -1
View File
@@ -2696,7 +2696,7 @@ def test_optional_dependency_metadata_for_enable():
"socksio>=1.0.0,<2.0.0", "socksio>=1.0.0,<2.0.0",
"python-socks[asyncio]>=2.8.0,<3.0.0; sys_platform != 'win32'", "python-socks[asyncio]>=2.8.0,<3.0.0; sys_platform != 'win32'",
), ),
"wecom": ("wecom-aibot-sdk-python>=0.1.5",), "wecom": ("wecom-aibot-sdk-python>=0.1.7,<0.2.0",),
"weixin": ("qrcode[pil]>=8.0", "pycryptodome>=3.20.0"), "weixin": ("qrcode[pil]>=8.0", "pycryptodome>=3.20.0"),
"whatsapp": ( "whatsapp": (
"neonize>=0.3.18.post0,<0.4.0", "neonize>=0.3.18.post0,<0.4.0",