Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat:企业微信通道支持文件上传下载

liubuyu1c8096ad758d8
diff --git a/jiuwenclaw/agentserver/tools/send_file_to_user.py b/jiuwenclaw/agentserver/tools/send_file_to_user.py
index c293004a69..8e534db414 100644
--- a/jiuwenclaw/agentserver/tools/send_file_to_user.py
+++ b/jiuwenclaw/agentserver/tools/send_file_to_user.py
@@ -56,45 +56,69 @@ class SendFileToolkit:
"""
if isinstance(abs_file_path_list, str):
try:
- abs_file_path_list = json.loads(abs_file_path_list)
- except json.decoder.JSONDecodeError as e:
- logger.info(f"send_file args error: {e}")
- raise TypeError(f"[SendFileToolkit] send_file args error.") from e
-
- not_exist_files = [
- f for f in abs_file_path_list if not self.check_file_exists(f)
- ]
- if not_exist_files:
- logger.warning(
- "[SendFileToolkit] send_file 文件不存在 session_id=%s files=%s",
- self.session_id,
- not_exist_files,
- )
- return f"发送文件失败,以下文件不存在: {not_exist_files}"
+ parsed = json.loads(abs_file_path_list)
+ if isinstance(parsed, list):
+ abs_file_path_list = parsed
+ elif isinstance(parsed, str):
+ abs_file_path_list = [parsed]
+ else:
+ abs_file_path_list = [abs_file_path_list]
+ except (TypeError, ValueError):
+ abs_file_path_list = [abs_file_path_list]
+
+ if not isinstance(abs_file_path_list, list):
+ abs_file_path_list = [str(abs_file_path_list)]
+
+ valid_files = []
+ missing_files = []
+ for fp in abs_file_path_list:
+ fp = str(fp).strip()
+ if not fp:
+ continue
+ if os.path.isfile(fp):
+ valid_files.append(fp)
+ else:
+ missing_files.append(fp)
+ logger.warning("[SendFileToolkit] 文件不存在: %s", fp)
+
+ if not valid_files:
+ msg_parts = ["发送文件失败:所有文件均不存在"]
+ for mf in missing_files:
+ msg_parts.append(f" - {mf}")
+ return "\n".join(msg_parts)
logger.info(
- "[SendFileToolkit] send_file 开始 session_id=%s 文件数=%d",
+ "[SendFileToolkit] send_file 开始 session_id=%s 有效文件=%d 缺失=%d",
self.session_id,
- len(abs_file_path_list),
+ len(valid_files),
+ len(missing_files),
)
try:
server = AgentWebSocketServer.get_instance()
+ files_payload = [
+ {
+ "path": file_path,
+ "name": os.path.basename(file_path),
+ }
+ for file_path in valid_files
+ ]
msg = {
"request_id": self.request_id,
"channel_id": self.channel_id,
"payload": {
"event_type": "chat.file",
- "files": abs_file_path_list,
+ "files": files_payload,
},
"is_complete": False,
}
await server.send_push(msg)
- logger.info(
- "[SendFileToolkit] send_file 完成 session_id=%s",
- self.session_id,
- )
- return f"已提交 {len(abs_file_path_list)} 个文件的发送请求"
+ result_parts = [f"成功发送 {len(valid_files)} 个文件"]
+ if missing_files:
+ result_parts.append("以下文件不存在,未发送:")
+ for mf in missing_files:
+ result_parts.append(f" - {mf}")
+ return "\n".join(result_parts)
except Exception as e:
logger.exception(
"[SendFileToolkit] send_file 失败 session_id=%s error=%s",
@@ -103,41 +127,6 @@ class SendFileToolkit:
)
return f"提交文件失败: {str(e)}"
- @staticmethod
- def check_file_exists(self, file_path: str) -> bool:
- """Check if a file exists at the given path.
-
- Args:
- file_path: Absolute path of the file to check.
-
- Returns:
- True if file exists and is a valid file, False otherwise.
- """
- if not file_path:
- return False
-
- if not os.path.exists(file_path):
- logger.warning(
- "[SendFileToolkit] check_file_exists 文件不存在 path=%s",
- file_path,
- )
- return False
-
- if not os.path.isfile(file_path):
- logger.warning(
- "[SendFileToolkit] check_file_exists 路径不是文件 path=%s",
- file_path,
- )
- return False
-
- file_size = os.path.getsize(file_path)
- logger.info(
- "[SendFileToolkit] check_file_exists 文件存在 path=%s size=%d",
- file_path,
- file_size,
- )
- return True
-
def get_tools(self) -> List[Tool]:
"""Return tools for registration in Runner.
diff --git a/jiuwenclaw/channel/wecom_channel.py b/jiuwenclaw/channel/wecom_channel.py
index 747dd92f9f..85c70d63c2 100644
--- a/jiuwenclaw/channel/wecom_channel.py
+++ b/jiuwenclaw/channel/wecom_channel.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import logging
import asyncio
+import os
import re
import time
from typing import Any, Callable
@@ -38,6 +39,12 @@ class WecomConfig(BaseModel):
allow_from: list[str] = Field(default_factory=list)
enable_streaming: bool = True
send_thinking_message: bool = True
+ # 文件处理配置
+ max_download_size: int = 100 * 1024 * 1024 # 最大下载文件大小(默认 100MB)
+ download_timeout: int = 60 # 下载超时时间(秒)
+ send_file_allowed: bool = True # 是否启用文件上传功能
+ enable_file_download: bool = True # 是否启用文件下载功能
+ workspace_dir: str = "" # 工作空间目录
class WecomChannel(BaseChannel):
@@ -58,6 +65,10 @@ class WecomChannel(BaseChannel):
self._connect_task: asyncio.Task | None = None
# 流式回复:wecom_req_id -> {frame, stream_id, accumulated_content}
self._pending_streams: dict[str, dict[str, Any]] = {}
+ # 文件服务
+ self._file_service: Any = None
+ # 按 request_id 记录已发送文件路径,避免重复发送
+ self._sent_file_paths_by_req: dict[str, set[str]] = {}
@property
def channel_id(self) -> str:
@@ -327,6 +338,15 @@ class WecomChannel(BaseChannel):
if msg.event_type == EventType.CHAT_PROCESSING_STATUS:
return
+ # 提取事件类型
+ payload = msg.payload if isinstance(msg.payload, dict) else {}
+ event_type = getattr(msg.event_type, "value", None) or payload.get("event_type") or ""
+
+ # 处理文件发送事件(chat.media 与 chat.file 统一走文件发送路径)
+ if event_type in ("chat.file", "chat.media"):
+ await self._send_file_message(msg)
+ return
+
# 心跳/系统事件
if msg.event_type == EventType.HEARTBEAT_RELAY:
chatid = self._extract_chatid(msg)
@@ -441,10 +461,45 @@ class WecomChannel(BaseChannel):
async def on_text(frame: dict) -> None:
await self._handle_incoming_message(frame)
+ async def on_image(frame: dict) -> None:
+ await self._handle_image_message(frame)
+
+ async def on_file(frame: dict) -> None:
+ await self._handle_file_message(frame)
+
+ async def on_voice(frame: dict) -> None:
+ await self._handle_voice_message(frame)
+
+ async def on_video(frame: dict) -> None:
+ await self._handle_video_message(frame)
+
+ async def on_mixed(frame: dict) -> None:
+ await self._handle_mixed_message(frame)
+
client.on("message.text", on_text)
+ client.on("message.image", on_image)
+ client.on("message.file", on_file)
+ client.on("message.voice", on_voice)
+ client.on("message.video", on_video)
+ client.on("message.mixed", on_mixed)
self._ws_client = client
+ # 初始化文件服务
+ try:
+ from jiuwenclaw.channel.wecom_file_service import WecomFileService
+ workspace_dir = self.config.workspace_dir or os.path.expanduser("~/.jiuwenclaw/agent/workspace")
+ self._file_service = WecomFileService(
+ ws_client=client,
+ max_download_size=self.config.max_download_size,
+ download_timeout=self.config.download_timeout,
+ workspace_dir=workspace_dir,
+ )
+ logger.info("WecomChannel 文件服务已初始化")
+ except Exception as e:
+ logger.warning(f"WecomChannel 文件服务初始化失败: {e}")
+ self._file_service = None
+
try:
await client.connect()
logger.info("WecomChannel WebSocket 已连接")
@@ -509,6 +564,345 @@ class WecomChannel(BaseChannel):
logger.info("WecomChannel 已停止")
+ # ==================== 文件消息处理方法 ====================
+
+ async def _handle_image_message(self, frame: dict) -> None:
+ """处理图片消息"""
+ if not self.config.enable_file_download:
+ logger.debug("WecomChannel 文件下载功能已禁用")
+ return
+
+ if not self._file_service:
+ logger.warning("WecomChannel 文件服务未初始化")
+ return
+
+ body = frame.get("body", {})
+ image_data = body.get("image", {})
+ url = image_data.get("url", "")
+ aes_key = image_data.get("aeskey", "")
+
+ if not url or not aes_key:
+ logger.warning("WecomChannel 图片消息缺少 url 或 aeskey")
+ return
+
+ # 提取消息信息
+ chatid, req_id, _ = self._extract_frame_info(frame)
+ message_id = req_id or f"img_{int(time.time() * 1000)}"
+
+ # 下载图片
+ file_info = await self._file_service.download_file(
+ url=url,
+ aes_key=aes_key,
+ message_id=message_id,
+ file_category="images",
+ )
+
+ if not file_info:
+ content = "[图片: 下载失败]"
+ else:
+ content = "[图片]"
+ logger.info(f"WecomChannel 图片下载成功: {file_info['path']}")
+
+ # 构建消息并发送
+ await self._send_file_message_to_handler(frame, content, [file_info] if file_info else None)
+
+ async def _handle_file_message(self, frame: dict) -> None:
+ """处理文件消息"""
+ if not self.config.enable_file_download:
+ logger.debug("WecomChannel 文件下载功能已禁用")
+ return
+
+ if not self._file_service:
+ logger.warning("WecomChannel 文件服务未初始化")
+ return
+
+ body = frame.get("body", {})
+ file_data = body.get("file", {})
+ url = file_data.get("url", "")
+ aes_key = file_data.get("aeskey", "")
+ filename = file_data.get("filename", "unknown_file")
+
+ if not url or not aes_key:
+ logger.warning("WecomChannel 文件消息缺少 url 或 aeskey")
+ return
+
+ # 提取消息信息
+ chatid, req_id, _ = self._extract_frame_info(frame)
+ message_id = req_id or f"file_{int(time.time() * 1000)}"
+
+ # 下载文件
+ file_info = await self._file_service.download_file(
+ url=url,
+ aes_key=aes_key,
+ message_id=message_id,
+ file_category="files",
+ filename=filename,
+ )
+
+ if not file_info:
+ content = f"[文件: {filename} 下载失败]"
+ else:
+ content = f"[文件: {filename}]"
+ logger.info(f"WecomChannel 文件下载成功: {file_info['path']}")
+
+ # 构建消息并发送
+ await self._send_file_message_to_handler(frame, content, [file_info] if file_info else None)
+
+ async def _handle_voice_message(self, frame: dict) -> None:
+ """处理语音消息"""
+ if not self.config.enable_file_download:
+ logger.debug("WecomChannel 文件下载功能已禁用")
+ return
+
+ if not self._file_service:
+ logger.warning("WecomChannel 文件服务未初始化")
+ return
+
+ body = frame.get("body", {})
+ voice_data = body.get("voice", {})
+ url = voice_data.get("url", "")
+ aes_key = voice_data.get("aeskey", "")
+
+ if not url or not aes_key:
+ logger.warning("WecomChannel 语音消息缺少 url 或 aeskey")
+ return
+
+ # 提取消息信息
+ chatid, req_id, _ = self._extract_frame_info(frame)
+ message_id = req_id or f"voice_{int(time.time() * 1000)}"
+
+ # 下载语音
+ file_info = await self._file_service.download_file(
+ url=url,
+ aes_key=aes_key,
+ message_id=message_id,
+ file_category="voice",
+ )
+
+ if not file_info:
+ content = "[语音: 下载失败]"
+ else:
+ content = "[语音]"
+ logger.info(f"WecomChannel 语音下载成功: {file_info['path']}")
+
+ # 构建消息并发送
+ await self._send_file_message_to_handler(frame, content, [file_info] if file_info else None)
+
+ async def _handle_video_message(self, frame: dict) -> None:
+ """处理视频消息"""
+ if not self.config.enable_file_download:
+ logger.debug("WecomChannel 文件下载功能已禁用")
+ return
+
+ if not self._file_service:
+ logger.warning("WecomChannel 文件服务未初始化")
+ return
+
+ body = frame.get("body", {})
+ video_data = body.get("video", {})
+ url = video_data.get("url", "")
+ aes_key = video_data.get("aeskey", "")
+
+ if not url or not aes_key:
+ logger.warning("WecomChannel 视频消息缺少 url 或 aeskey")
+ return
+
+ # 提取消息信息
+ chatid, req_id, _ = self._extract_frame_info(frame)
+ message_id = req_id or f"video_{int(time.time() * 1000)}"
+
+ # 下载视频
+ file_info = await self._file_service.download_file(
+ url=url,
+ aes_key=aes_key,
+ message_id=message_id,
+ file_category="video",
+ )
+
+ if not file_info:
+ content = "[视频: 下载失败]"
+ else:
+ content = "[视频]"
+ logger.info(f"WecomChannel 视频下载成功: {file_info['path']}")
+
+ # 构建消息并发送
+ await self._send_file_message_to_handler(frame, content, [file_info] if file_info else None)
+
+ async def _handle_mixed_message(self, frame: dict) -> None:
+ """处理图文混排消息"""
+ if not self.config.enable_file_download:
+ logger.debug("WecomChannel 文件下载功能已禁用")
+ # 仍然处理文本部分
+ await self._handle_incoming_message(frame)
+ return
+
+ if not self._file_service:
+ logger.warning("WecomChannel 文件服务未初始化")
+ await self._handle_incoming_message(frame)
+ return
+
+ body = frame.get("body", {})
+ mixed_data = body.get("mixed", {})
+ msg_items = mixed_data.get("msgitem", [])
+
+ if not msg_items:
+ await self._handle_incoming_message(frame)
+ return
+
+ # 提取文本和图片
+ text_parts = []
+ file_infos = []
+
+ chatid, req_id, _ = self._extract_frame_info(frame)
+ message_id = req_id or f"mixed_{int(time.time() * 1000)}"
+
+ for idx, item in enumerate(msg_items):
+ item_type = item.get("msgtype", "")
+
+ if item_type == "text":
+ text_content = item.get("text", {}).get("content", "")
+ if text_content:
+ text_parts.append(text_content)
+
+ elif item_type == "image":
+ image_data = item.get("image", {})
+ url = image_data.get("url", "")
+ aes_key = image_data.get("aeskey", "")
+
+ if url and aes_key:
+ file_info = await self._file_service.download_file(
+ url=url,
+ aes_key=aes_key,
+ message_id=f"{message_id}_{idx}",
+ file_category="images",
+ )
+ if file_info:
+ file_infos.append(file_info)
+
+ # 合并文本
+ content = " ".join(text_parts) if text_parts else "[图文混排]"
+
+ # 构建消息并发送
+ await self._send_file_message_to_handler(frame, content, file_infos if file_infos else None)
+
+ async def _send_file_message_to_handler(
+ self, frame: dict, content: str, files: list[dict] | None
+ ) -> None:
+ """将文件消息发送到消息处理器"""
+ chatid, req_id, _ = self._extract_frame_info(frame)
+
+ if not chatid:
+ logger.warning("WecomChannel 无法从 frame 提取 chatid,跳过文件消息")
+ return
+
+ # 权限检查
+ if not self.is_allowed(chatid):
+ logger.warning("WecomChannel 发送者 %s 未被允许", chatid)
+ return
+
+ logger.info("WecomChannel 收到文件消息: chatid=%s content=%s", chatid, content[:50])
+
+ req_id_final = req_id or f"wecom_{int(time.time() * 1000)}"
+
+ # 构建消息
+ params = {"content": content, "query": content}
+ if files:
+ params["files"] = files
+
+ msg = Message(
+ id=req_id_final,
+ type="req",
+ channel_id=self.name,
+ session_id=chatid,
+ params=params,
+ timestamp=time.time(),
+ ok=True,
+ req_method=ReqMethod.CHAT_SEND,
+ is_stream=True,
+ metadata={
+ "wecom_chat_id": chatid,
+ "wecom_req_id": req_id_final,
+ },
+ )
+
+ if self._message_callback:
+ self._message_callback(msg)
+ else:
+ await self.bus.route_user_message(msg)
+
+ # ==================== 文件发送方法 ====================
+
+ async def _send_file_message(self, msg: Message) -> None:
+ """发送文件消息"""
+ if not self._file_service or not self.config.send_file_allowed:
+ logger.warning("WecomChannel 文件发送功能未启用")
+ return
+
+ if not self._ws_client or not getattr(self._ws_client, "is_connected", False):
+ logger.warning("WecomChannel 未连接,跳过文件发送")
+ return
+
+ payload = msg.payload if isinstance(msg.payload, dict) else {}
+ files = payload.get("files", [])
+ if not files:
+ return
+
+ # 提取 chatid
+ metadata = msg.metadata or {}
+ chatid = metadata.get("wecom_chat_id") or ""
+ if not chatid:
+ chatid = getattr(msg, "session_id", None) or msg.id or ""
+
+ if not chatid:
+ logger.warning("WecomChannel 文件发送: 未找到接收者")
+ return
+
+ # 获取当前 request_id 用于去重
+ request_id = getattr(msg, "id", "") or ""
+ if request_id not in self._sent_file_paths_by_req:
+ self._sent_file_paths_by_req[request_id] = set()
+
+ for file_info in files:
+ file_path = file_info if isinstance(file_info, str) else file_info.get("path", "")
+ if not file_path or not os.path.isfile(file_path):
+ logger.warning(f"WecomChannel 文件发送: 文件不存在 {file_path}")
+ continue
+
+ # 检查是否已发送
+ if file_path in self._sent_file_paths_by_req[request_id]:
+ continue
+
+ # 确定媒体类型
+ media_type = self._file_service.get_media_type_for_file(file_path)
+
+ try:
+ # 上传文件
+ media_id = await self._file_service.upload_file(file_path, media_type)
+ if not media_id:
+ logger.error(f"WecomChannel 文件上传失败: {file_path}")
+ continue
+
+ # 发送媒体消息
+ await self._ws_client.send_media_message(
+ chatid=chatid,
+ media_type=media_type,
+ media_id=media_id,
+ )
+
+ # 记录已发送
+ self._sent_file_paths_by_req[request_id].add(file_path)
+ logger.info(f"WecomChannel 文件发送成功: {file_path} -> {chatid}")
+
+ except Exception as e:
+ logger.error(f"WecomChannel 文件发送失败: {file_path}, error: {e}")
+
+ # 清理过期的去重记录
+ if len(self._sent_file_paths_by_req) > 100:
+ # 删除最早的 50 个
+ keys_to_remove = list(self._sent_file_paths_by_req.keys())[:50]
+ for key in keys_to_remove:
+ del self._sent_file_paths_by_req[key]
+
def get_metadata(self) -> ChannelMetadata:
return ChannelMetadata(
channel_id=self.channel_id,
diff --git a/jiuwenclaw/channel/wecom_file_service.py b/jiuwenclaw/channel/wecom_file_service.py
new file mode 100644
index 0000000000..037d7734ed
--- /dev/null
+++ b/jiuwenclaw/channel/wecom_file_service.py
@@ -0,0 +1,298 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""WecomFileService - 企业微信文件服务
+
+提供企业微信文件的下载和上传功能。
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import re
+import time
+from typing import Any
+
+from loguru import logger
+
+
+# 文件魔数映射(用于格式检测)
+FILE_SIGNATURES = {
+ # 图片
+ b'\x89PNG': '.png',
+ b'\xff\xd8\xff': '.jpg',
+ b'GIF8': '.gif',
+ b'RIFF': '.webp', # 需要进一步检查 WEBP 标识
+ # 音频
+ b'ID3': '.mp3',
+ b'\xff\xfb': '.mp3',
+ b'\xff\xfa': '.mp3',
+ b'fLaC': '.flac',
+ b'OggS': '.ogg',
+ # 视频
+ b'ftyp': '.mp4',
+ b'moof': '.mp4',
+ b'moov': '.mp4',
+ b'\x1a\x45\xdf\xa3': '.mkv',
+ b'FLV': '.flv',
+}
+
+# MIME 类型映射
+MIME_TYPES = {
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.gif': 'image/gif',
+ '.webp': 'image/webp',
+ '.mp3': 'audio/mpeg',
+ '.wav': 'audio/wav',
+ '.ogg': 'audio/ogg',
+ '.flac': 'audio/flac',
+ '.mp4': 'video/mp4',
+ '.mkv': 'video/x-matroska',
+ '.flv': 'video/x-flv',
+ '.pdf': 'application/pdf',
+ '.doc': 'application/msword',
+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ '.xls': 'application/vnd.ms-excel',
+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ '.ppt': 'application/vnd.ms-powerpoint',
+ '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ '.txt': 'text/plain',
+ '.zip': 'application/zip',
+ '.json': 'application/json',
+}
+
+
+def detect_file_extension(content: bytes) -> str:
+ """通过文件头魔数检测文件扩展名。"""
+ if len(content) < 12:
+ return ''
+
+ # 检查 WEBP(RIFF....WEBP)
+ if content[:4] == b'RIFF' and content[8:12] == b'WEBP':
+ return '.webp'
+
+ # 检查 WAV(RIFF....WAVE)
+ if content[:4] == b'RIFF' and content[8:12] == b'WAVE':
+ return '.wav'
+
+ # 检查 MP4(ftyp/moof/moov)
+ if content[4:8] in (b'ftyp', b'moof', b'moov'):
+ return '.mp4'
+
+ # 检查其他格式
+ for signature, ext in FILE_SIGNATURES.items():
+ if content.startswith(signature):
+ return ext
+
+ return ''
+
+
+def get_mime_type(extension: str) -> str:
+ """获取文件扩展名对应的 MIME 类型。"""
+ return MIME_TYPES.get(extension.lower(), 'application/octet-stream')
+
+
+class WecomFileService:
+ """企业微信文件服务,处理文件下载和上传。"""
+
+ def __init__(
+ self,
+ ws_client: Any,
+ max_download_size: int = 100 * 1024 * 1024,
+ download_timeout: int = 60,
+ workspace_dir: str = "",
+ ):
+ """初始化文件服务。
+
+ Args:
+ ws_client: 企业微信 WebSocket 客户端(WSClient 实例)
+ max_download_size: 最大下载文件大小(字节)
+ download_timeout: 下载超时时间(秒)
+ workspace_dir: 工作空间目录
+ """
+ self._ws_client = ws_client
+ self.max_download_size = max_download_size
+ self.download_timeout = download_timeout
+ self.workspace_dir = workspace_dir
+ self._download_semaphore = asyncio.Semaphore(3)
+
+ def _get_download_dir(self, file_category: str) -> str:
+ """获取下载目录路径。"""
+ base_dir = os.path.join(self.workspace_dir, "wecom_files", "downloads", file_category)
+ os.makedirs(base_dir, exist_ok=True)
+ return base_dir
+
+ @staticmethod
+ def _safe_filename(name: str) -> str:
+ """生成安全的文件名。"""
+ # 移除或替换不安全字符
+ safe = re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', name)
+ return safe[:100] # 限制长度
+
+ async def download_file(
+ self,
+ url: str,
+ aes_key: str,
+ message_id: str,
+ file_category: str = "file",
+ filename: str | None = None,
+ ) -> dict | None:
+ """下载文件并保存到本地。
+
+ Args:
+ url: 文件下载地址
+ aes_key: AES 解密密钥(Base64 编码)
+ message_id: 消息 ID(用于生成文件名)
+ file_category: 文件类别(image/file/voice/video)
+ filename: 原始文件名(可选)
+
+ Returns:
+ 文件信息字典,失败返回 None
+ """
+ try:
+ # 使用 SDK 的 download_file 方法(自动处理 AES 解密)
+ async with self._download_semaphore:
+ result = await asyncio.wait_for(
+ self._ws_client.download_file(url, aes_key),
+ timeout=self.download_timeout,
+ )
+
+ if not result or "buffer" not in result:
+ logger.error("[WecomFileService] 下载文件失败:无返回数据")
+ return None
+
+ file_data = result["buffer"]
+ original_filename = result.get("filename") or filename
+
+ # 检查文件大小
+ if len(file_data) > self.max_download_size:
+ logger.warning(
+ f"[WecomFileService] 文件过大: {len(file_data)} > {self.max_download_size}"
+ )
+ return None
+
+ # 检查空文件
+ if len(file_data) == 0:
+ logger.warning("[WecomFileService] 下载的文件为空")
+ return None
+
+ # 检测文件扩展名
+ extension = detect_file_extension(file_data)
+ if not extension and original_filename:
+ # 从原始文件名提取扩展名
+ _, ext = os.path.splitext(original_filename)
+ if ext:
+ extension = ext
+
+ # 生成文件名
+ timestamp = int(time.time() * 1000)
+ if not extension:
+ extension = ".bin"
+
+ if file_category == "file" and original_filename:
+ # 普通文件保留原始文件名
+ safe_name = self._safe_filename(original_filename)
+ local_filename = f"{message_id}_{timestamp}_{safe_name}"
+ else:
+ # 图片/语音/视频使用时间戳命名
+ local_filename = f"{message_id}_{timestamp}{extension}"
+
+ # 保存文件
+ download_dir = self._get_download_dir(file_category)
+ file_path = os.path.join(download_dir, local_filename)
+
+ with open(file_path, 'wb') as f:
+ f.write(file_data)
+
+ # 构建文件信息
+ file_info = {
+ "path": file_path,
+ "name": original_filename or local_filename,
+ "size": len(file_data),
+ "mime_type": get_mime_type(extension),
+ "file_category": file_category,
+ }
+
+ logger.info(
+ f"[WecomFileService] 文件下载成功: {file_category}/{local_filename} "
+ f"size={len(file_data)}"
+ )
+ return file_info
+
+ except asyncio.TimeoutError:
+ logger.error(f"[WecomFileService] 下载文件超时: {url}")
+ return None
+ except Exception as e:
+ logger.error(f"[WecomFileService] 下载文件失败: {e}")
+ return None
+
+ async def upload_file(
+ self,
+ file_path: str,
+ media_type: str,
+ ) -> str | None:
+ """上传文件到企业微信。
+
+ Args:
+ file_path: 本地文件路径
+ media_type: 媒体类型(file/image/voice/video)
+
+ Returns:
+ media_id,失败返回 None
+ """
+ try:
+ # 读取文件
+ with open(file_path, 'rb') as f:
+ file_data = f.read()
+
+ filename = os.path.basename(file_path)
+
+ # 使用 SDK 的 upload_media 方法
+ result = await self._ws_client.upload_media(
+ file_data,
+ type=media_type,
+ filename=filename,
+ )
+
+ if not result or "media_id" not in result:
+ logger.error(f"[WecomFileService] 上传文件失败:无 media_id 返回")
+ return None
+
+ media_id = result["media_id"]
+ logger.info(
+ f"[WecomFileService] 文件上传成功: {filename} -> {media_id}"
+ )
+ return media_id
+
+ except Exception as e:
+ logger.error(f"[WecomFileService] 上传文件失败: {e}")
+ return None
+
+ @classmethod
+ def get_media_type_for_file(cls, file_path: str) -> str:
+ """根据文件扩展名确定媒体类型。
+
+ Args:
+ file_path: 文件路径
+
+ Returns:
+ 媒体类型(file/image/voice/video)
+ """
+ ext = os.path.splitext(file_path)[1].lower()
+
+ # 图片
+ if ext in {'.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'}:
+ return 'image'
+
+ # 语音
+ if ext in {'.mp3', '.wav', '.aac', '.ogg', '.flac', '.m4a'}:
+ return 'voice'
+
+ # 视频
+ if ext in {'.mp4', '.mov', '.avi', '.mkv', '.flv', '.webm'}:
+ return 'video'
+
+ # 其他文件
+ return 'file'
diff --git a/jiuwenclaw/gateway/message_handler.py b/jiuwenclaw/gateway/message_handler.py
index f3b29e7a33..3216d9466b 100644
--- a/jiuwenclaw/gateway/message_handler.py
+++ b/jiuwenclaw/gateway/message_handler.py
@@ -403,9 +403,33 @@ class MessageHandler(ABC):
@staticmethod
- def _response_to_message(resp: "AgentResponse", session_id: str | None) -> "Message":
+ def _merge_agent_metadata(
+ request_metadata: dict[str, Any] | None,
+ response_metadata: dict[str, Any] | None,
+ ) -> dict[str, Any] | None:
+ """合并 Agent 响应 metadata 与网关请求 metadata。
+
+ send_push / 工具链返回的响应常不带 metadata,通道(如钉钉 batchSend)需要
+ 请求侧的 dingtalk_sender_id、conversation_type 等;响应中有同名字段时优先响应。
+ """
+ req_md = request_metadata or {}
+ resp_md = response_metadata or {}
+ if not req_md and not resp_md:
+ return None
+ merged: dict[str, Any] = {**req_md, **resp_md}
+ return merged
+
+ @staticmethod
+ def _response_to_message(
+ resp: "AgentResponse",
+ session_id: str | None,
+ *,
+ request_metadata: dict[str, Any] | None = None,
+ ) -> "Message":
from jiuwenclaw.schema.message import Message, EventType
+ metadata = MessageHandler._merge_agent_metadata(request_metadata, resp.metadata)
+
# 检查 payload 中是否包含 event_type,如果包含则创建事件消息
event_type = None
if resp.payload and isinstance(resp.payload, dict):
@@ -424,7 +448,7 @@ class MessageHandler(ABC):
ok=True,
payload=resp.payload,
event_type=event_type,
- metadata=resp.metadata,
+ metadata=metadata,
)
except ValueError:
# 不是有效的 EventType,继续作为普通响应处理
@@ -440,7 +464,7 @@ class MessageHandler(ABC):
timestamp=time.time(),
ok=resp.ok,
payload=resp.payload,
- metadata=resp.metadata,
+ metadata=metadata,
)
@staticmethod
@@ -500,7 +524,9 @@ class MessageHandler(ABC):
"""执行单次非流式 Agent 请求并将结果写入 robot_messages(供串行或后台任务复用)。"""
try:
resp = await self._agent_client.send_request(req)
- out = self._response_to_message(resp, session_id=msg.session_id)
+ out = self._response_to_message(
+ resp, session_id=msg.session_id, request_metadata=req.metadata
+ )
await self.publish_robot_messages(out)
logger.info(
"[MessageHandler] Agent 响应已写入 robot_messages: request_id=%s channel_id=%s",
@@ -695,6 +721,7 @@ class MessageHandler(ABC):
这个方法被包装为 Task,在后台运行,可以被随时取消。
"""
cancelled = False
+ has_processing_status_false = False # 追踪 AgentServer 是否已发送 processing_status=false
try:
async for chunk in self._agent_client.send_request_stream(req):
# 跳过终止 chunk(仅作为流结束信号,不含实际数据)
@@ -705,6 +732,13 @@ class MessageHandler(ABC):
)
continue
# 携带 request metadata,供 Feishu/Xiaoyi 用平台身份回发
+ # 检查是否是 processing_status=false 事件
+ payload = chunk.payload or {}
+ if isinstance(payload, dict):
+ if payload.get("event_type") == "chat.processing_status":
+ if payload.get("is_processing") is False:
+ has_processing_status_false = True
+
out = self._chunk_to_message(
chunk, session_id=session_id, metadata=req.metadata
)
@@ -733,7 +767,8 @@ class MessageHandler(ABC):
req.request_id,
)
# 所有流式任务正常结束后,通知前端全部处理完成
- if not cancelled and not self._stream_tasks:
+ # 只有当 AgentServer 没有发送过 processing_status=false 时才发送
+ if not cancelled and not self._stream_tasks and not has_processing_status_false:
await self._send_processing_status(
req.request_id, session_id, req.channel_id, is_processing=False,
)
diff --git a/jiuwenclaw/resources/config.yaml b/jiuwenclaw/resources/config.yaml
index e59c766adf..ecdd58d377 100644
--- a/jiuwenclaw/resources/config.yaml
+++ b/jiuwenclaw/resources/config.yaml
@@ -249,6 +249,7 @@ channels:
enable_streaming: true
send_thinking_message: false
enabled: false
+ send_file_allowed: true
# ========== 细粒度权限管控 ==========
#
diff --git a/pyproject.toml b/pyproject.toml
index 6168b07cb7..ed641ad7f1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -26,7 +26,7 @@ dependencies = [
"python-telegram-bot>=20.0",
"discord.py>=2.4.0",
"dingtalk-stream>=0.24.3",
- "wecom-aibot-sdk>=1.0.0",
+ "wecom-aibot-sdk>=1.0.5",
"python-socks>=2.8.1",
"greenlet>=3.3.2",
"skillnet-ai==0.0.16",
diff --git a/tests/unit/channel/test_wecom_file.py b/tests/unit/channel/test_wecom_file.py
new file mode 100644
index 0000000000..3a4cde33b0
--- /dev/null
+++ b/tests/unit/channel/test_wecom_file.py
@@ -0,0 +1,140 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Tests for WecomChannel file functionality."""
+
+from unittest.mock import MagicMock, AsyncMock, patch
+import pytest
+from jiuwenclaw.channel.wecom_channel import WecomChannel, WecomConfig
+from jiuwenclaw.channel.wecom_file_service import WecomFileService, detect_file_extension, get_mime_type
+from jiuwenclaw.channel.base import RobotMessageRouter
+
+
+# ---------------------------------------------------------------------------
+# Test: File Extension Detection
+# ---------------------------------------------------------------------------
+
+def test_detect_file_extension_png():
+ """Test PNG file detection."""
+ # PNG 文件头:89 50 4E 47
+ content = b'\x89PNG\r\n\x1a\n' + b'\x00' * 100
+ assert detect_file_extension(content) == '.png'
+
+
+def test_detect_file_extension_jpg():
+ """Test JPG file detection."""
+ # JPG 文件头:FF D8 FF
+ content = b'\xff\xd8\xff\xe0' + b'\x00' * 100
+ assert detect_file_extension(content) == '.jpg'
+
+
+def test_detect_file_extension_mp4():
+ """Test MP4 file detection."""
+ # MP4 文件头:ftyp at offset 4
+ content = b'\x00\x00\x00\x20ftypisom' + b'\x00' * 100
+ assert detect_file_extension(content) == '.mp4'
+
+
+def test_detect_file_extension_unknown():
+ """Test unknown file detection."""
+ content = b'unknown file content'
+ assert detect_file_extension(content) == ''
+
+
+# ---------------------------------------------------------------------------
+# Test: MIME Type
+# ---------------------------------------------------------------------------
+
+def test_get_mime_type():
+ """Test MIME type mapping."""
+ assert get_mime_type('.png') == 'image/png'
+ assert get_mime_type('.jpg') == 'image/jpeg'
+ assert get_mime_type('.mp4') == 'video/mp4'
+ assert get_mime_type('.pdf') == 'application/pdf'
+ assert get_mime_type('.unknown') == 'application/octet-stream'
+
+
+# ---------------------------------------------------------------------------
+# Test: WecomFileService
+# ---------------------------------------------------------------------------
+
+def test_wecom_file_service_init():
+ """Test WecomFileService initialization."""
+ ws_client = MagicMock()
+ service = WecomFileService(
+ ws_client=ws_client,
+ max_download_size=10 * 1024 * 1024,
+ download_timeout=30,
+ workspace_dir="/tmp/test",
+ )
+
+ assert service.max_download_size == 10 * 1024 * 1024
+ assert service.download_timeout == 30
+ assert service.workspace_dir == "/tmp/test"
+
+
+def test_get_media_type_for_file():
+ """Test media type detection for files."""
+ ws_client = MagicMock()
+ service = WecomFileService(ws_client=ws_client)
+
+ # 图片
+ assert service.get_media_type_for_file("/path/to/image.jpg") == 'image'
+ assert service.get_media_type_for_file("/path/to/image.png") == 'image'
+
+ # 语音
+ assert service.get_media_type_for_file("/path/to/audio.mp3") == 'voice'
+ assert service.get_media_type_for_file("/path/to/audio.wav") == 'voice'
+
+ # 视频
+ assert service.get_media_type_for_file("/path/to/video.mp4") == 'video'
+ assert service.get_media_type_for_file("/path/to/video.mov") == 'video'
+
+ # 其他文件
+ assert service.get_media_type_for_file("/path/to/document.pdf") == 'file'
+ assert service.get_media_type_for_file("/path/to/document.docx") == 'file'
+
+
+# ---------------------------------------------------------------------------
+# Test: WecomConfig
+# ---------------------------------------------------------------------------
+
+def test_wecom_config_defaults():
+ """Test WecomConfig default values."""
+ config = WecomConfig()
+
+ assert config.enabled is False
+ assert config.bot_id == ""
+ assert config.secret == ""
+ assert config.max_download_size == 100 * 1024 * 1024
+ assert config.download_timeout == 60
+ assert config.send_file_allowed is True
+ assert config.enable_file_download is True
+ assert config.workspace_dir == ""
+
+
+# ---------------------------------------------------------------------------
+# Test: WecomChannel File Handling
+# ---------------------------------------------------------------------------
+
+async def test_wecom_channel_file_service_initialization():
+ """Test that WecomChannel initializes file service."""
+ config = WecomConfig(
+ enabled=True,
+ bot_id="test_bot_id",
+ secret="test_secret",
+ workspace_dir="/tmp/test_workspace",
+ )
+ router = MagicMock(spec=RobotMessageRouter)
+
+ with patch('jiuwenclaw.channel.wecom_channel.WECOM_AVAILABLE', True):
+ with patch('jiuwenclaw.channel.wecom_channel.WSClient'):
+ channel = WecomChannel(config, router)
+
+ # 验证文件服务相关属性已初始化
+ assert hasattr(channel, '_file_service')
+ assert hasattr(channel, '_sent_file_paths_by_req')
+
+
+if __name__ == "__main__":
+ pytest.main([__file__, "-v"])