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:钉钉通道支持文件上传与下载
liubuyu1e737d58c5a01
diff --git a/jiuwenclaw/channel/dingding.py b/jiuwenclaw/channel/dingding.pyindex d79b4fff2e..ffc4699f9a 100644--- a/jiuwenclaw/channel/dingding.py+++ b/jiuwenclaw/channel/dingding.py@@ -1,7 +1,12 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+import asyncioimport jsonimport logging+import os+import reimport time+from dataclasses import dataclassfrom typing import Any, Callablefrom pydantic import BaseModel, Field@@ -9,6 +14,7 @@ import httpxfrom jiuwenclaw.channel.base import RobotMessageRouter, BaseChannel+from jiuwenclaw.channel.dingtalk_file_service import DingTalkFileServicefrom jiuwenclaw.schema.message import Message, ReqMethodlogger = logging.getLogger(__name__)@@ -20,6 +26,72 @@ class DingTalkConfig(BaseModel):client_id: str = "" # 应用IDclient_secret: str = "" # 应用密钥allow_from: list[str] = Field(default_factory=list) # 允许的员工ID+ # 文件处理配置+ 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 = "" # 工作空间目录+++@dataclass+class DingTalkInboundMessage:+ """钉钉入站消息载体,避免参数列表持续膨胀。"""++ content: str+ sender_id: str+ sender_name: str+ conversation_id: str+ conversation_type: str+ files: list[dict] | None = None+++@dataclass+class DingTalkMessageSendRequest:+ """钉钉消息发送请求参数封装。"""++ token: str+ chat_id: str+ conversation_type: str+ open_conversation_id: str+ file_path: str+ file_name: str+++@dataclass+class DingTalkFileNotificationRequest:+ """钉钉文件通知请求参数封装。"""++ token: str+ chat_id: str+ conversation_type: str+ open_conversation_id: str+ file_path: str+ file_name: str+ error_msg: str = ""+++@dataclass+class DingTalkMediaMessageRequest:+ """钉钉媒体消息发送请求参数封装。"""++ token: str+ chat_id: str+ conversation_type: str+ open_conversation_id: str+ msg_key: str+ msg_param: str+++@dataclass+class DingTalkImageSendRequest:+ """钉钉图片发送请求参数封装。"""++ token: str+ chat_id: str+ conversation_type: str+ open_conversation_id: str+ file_path: strtry:@@ -51,7 +123,7 @@ class DingTalkHandler(CallbackHandler):super().__init__()self.channel = channel- def _extract_message_content(self, chatbot_msg: ChatbotMessage, raw_data: dict) -> str:+ def _extract_text_content(self, chatbot_msg: ChatbotMessage, raw_data: dict) -> str:"""从消息对象中提取文本内容"""content = ""if chatbot_msg.text:@@ -72,11 +144,10 @@ class DingTalkHandler(CallbackHandler):conversation_type = chatbot_msg.conversation_type or "1" # 1: 单聊;2:群聊return conversation_id, conversation_type- def _create_message_task(self, content: str, sender_id: str, sender_name: str,- conversation_id: str, conversation_type: str) -> None:+ def _create_message_task(self, message: DingTalkInboundMessage) -> None:"""创建异步任务处理消息"""task = asyncio.create_task(- self.channel._on_message(content, sender_id, sender_name, conversation_id, conversation_type)+ self.channel.handle_incoming_message(message))self.channel._background_tasks.add(task)task.add_done_callback(self.channel._background_tasks.discard)@@ -86,15 +157,8 @@ class DingTalkHandler(CallbackHandler):try:# 使用SDK的ChatbotMessage进行健壮解析chatbot_msg = ChatbotMessage.from_dict(message.data)-- # 提取文本内容- content = self._extract_message_content(chatbot_msg, message.data)-- if not content:- logger.warning(- f"收到空或不支持的消息类型: {chatbot_msg.message_type}"- )- return AckMessage.STATUS_OK, "OK"+ raw_data = message.data+ msg_type = raw_data.get("msgtype", "text")# 提取发送者信息sender_id, sender_name = self._extract_sender_info(chatbot_msg)@@ -102,12 +166,56 @@ class DingTalkHandler(CallbackHandler):# 提取会话信息conversation_id, conversation_type = self._extract_conversation_info(chatbot_msg)+ # 权限检查(所有消息类型)+ if not self.channel.is_allowed(sender_id):+ logger.warning(f"发送者 {sender_id} 未被允许使用此机器人")+ return AckMessage.STATUS_OK, "OK"++ # 根据消息类型处理+ content = ""+ files = None++ if msg_type == "text":+ content = self._extract_text_content(chatbot_msg, raw_data)+ elif msg_type == "picture":+ content, files = await self.channel.handle_picture_message(+ raw_data, sender_id, conversation_id, conversation_type+ )+ elif msg_type == "file":+ content, files = await self.channel.handle_file_message(+ raw_data, sender_id, conversation_id, conversation_type+ )+ elif msg_type == "audio" or msg_type == "voice":+ content, files = await self.channel.handle_audio_message(+ raw_data, sender_id, conversation_id, conversation_type+ )+ elif msg_type == "video":+ content, files = await self.channel.handle_video_message(+ raw_data, sender_id, conversation_id, conversation_type+ )+ else:+ content = f"[不支持的消息类型: {msg_type}]"+ logger.warning(f"收到不支持的消息类型: {msg_type}")++ if not content and not files:+ logger.warning(f"收到空消息: {msg_type}")+ return AckMessage.STATUS_OK, "OK"+logger.info(- f"收到来自 {sender_name} ({sender_id}) 的钉钉消息: {content} (会话ID: {conversation_id})"+ f"收到来自 {sender_name} ({sender_id}) 的钉钉消息: {content[:50]}... (会话ID: {conversation_id})")# 转发到通道(非阻塞)- self._create_message_task(content, sender_id, sender_name, conversation_id, conversation_type)+ self._create_message_task(+ DingTalkInboundMessage(+ content=content,+ sender_id=sender_id,+ sender_name=sender_name,+ conversation_id=conversation_id,+ conversation_type=conversation_type,+ files=files,+ )+ )return AckMessage.STATUS_OK, "OK"@@ -140,6 +248,11 @@ class DingTalkChannel(BaseChannel):self._gateway_callback: Callable[[Message], None] | None = Noneself._stream_task: asyncio.Task | None = None # 用于跟踪 SDK start() 任务+ # 文件服务+ self._file_service: DingTalkFileService | None = None+ # 按 request_id 记录已发送文件路径,避免重复发送+ self._sent_file_paths_by_req: dict[str, set[str]] = {}+@propertydef channel_id(self) -> str:"""返回通道的唯一标识"""@@ -173,16 +286,20 @@ class DingTalkChannel(BaseChannel):def _build_user_message(self, chat_id: str, sender_id: str, content: str,conversation_id: str, conversation_type: str,- metadata: dict[str, Any] | None = None) -> Message:+ metadata: dict[str, Any] | None = None,+ files: list[dict] | None = None) -> Message:"""构建用户消息对象"""metadata = metadata or {}metadata.update({"conversation_id": conversation_id, "conversation_type": conversation_type})+ params = {"content": content, "query": content}+ if files:+ params["files"] = filesreturn Message(id=chat_id,type="req",channel_id=self.name,session_id=str(chat_id),- params={"content": content, "query": content},+ params=params,timestamp=time.time(),ok=True,req_method=ReqMethod.CHAT_SEND,@@ -190,9 +307,10 @@ class DingTalkChannel(BaseChannel):)async def _process_incoming_message(self, chat_id: str, sender_id: str, content: str, conversation_id: str,- conversation_type: str, metadata: dict[str, Any] | None = None) -> None:+ conversation_type: str, metadata: dict[str, Any] | None = None,+ files: list[dict] | None = None) -> None:"""处理来自钉钉通道的传入消息"""- msg = self._build_user_message(chat_id, sender_id, content, conversation_id, conversation_type, metadata)+ msg = self._build_user_message(chat_id, sender_id, content, conversation_id, conversation_type, metadata, files)if self._gateway_callback:@@ -237,6 +355,17 @@ class DingTalkChannel(BaseChannel):self._running = Trueself._http = httpx.AsyncClient()+ # 初始化文件服务+ workspace_dir = self.config.workspace_dir or os.path.expanduser("~/.jiuwenclaw/agent/workspace")+ self._file_service = DingTalkFileService(+ client_id=self.config.client_id,+ get_token_func=self._get_access_token,+ http_client=self._http,+ max_download_size=self.config.max_download_size,+ download_timeout=self.config.download_timeout,+ workspace_dir=workspace_dir,+ )+self._initialize_stream_client()# 将 SDK start() 作为独立任务运行,便于在 stop() 时取消@@ -432,6 +561,15 @@ class DingTalkChannel(BaseChannel):if not token: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+# 提取内容content = self._extract_message_content(msg)if not content:@@ -453,25 +591,533 @@ class DingTalkChannel(BaseChannel):# 发送HTTP请求await self._send_http_request(url, data, token, chat_id)- async def _on_message(self, content: str, sender_id: str, sender_name: str, conversation_id: str,- conversation_type: str) -> None:+ # chat.final 兜底文件发送+ if event_type == "chat.final":+ await self._send_fallback_files(msg, content)++ # ==================== 文件下载处理方法 ====================++ async def handle_picture_message(+ self, raw_data: dict, sender_id: str, conversation_id: str, conversation_type: str+ ) -> tuple[str, list[dict] | None]:+ """处理图片消息"""+ if not self.config.enable_file_download:+ return "[图片: 文件下载功能已禁用]", None++ if not self._file_service:+ return "[图片: 文件服务未初始化]", None++ content = raw_data.get("content", {})+ download_code = content.get("downloadCode", "")+ message_id = raw_data.get("msgId", sender_id)++ if not download_code:+ return "[图片: 缺少下载码]", None++ file_info = await self._file_service.download_image(download_code, message_id)+ if not file_info:+ return "[图片: 下载失败]", None++ return "[图片]", [file_info]++ async def handle_file_message(+ self, raw_data: dict, sender_id: str, conversation_id: str, conversation_type: str+ ) -> tuple[str, list[dict] | None]:+ """处理文件消息"""+ if not self.config.enable_file_download:+ return "[文件: 文件下载功能已禁用]", None++ if not self._file_service:+ return "[文件: 文件服务未初始化]", None++ content = raw_data.get("content", {})+ download_code = content.get("downloadCode", "")+ file_name = content.get("fileName", "unknown_file")+ file_size = content.get("fileSize", 0)+ message_id = raw_data.get("msgId", sender_id)++ if not download_code:+ return "[文件: 缺少下载码]", None++ # 检查文件大小(仅当文件大小已知且过大时跳过)+ # 注意:钉钉消息可能不包含 fileSize 字段,所以只在已知大小时检查+ if file_size > 0 and file_size > self.config.max_download_size:+ return f"[文件过大: {file_name}]", None++ file_info = await self._file_service.download_file(download_code, message_id, file_name)+ if not file_info:+ return f"[文件: {file_name} 下载失败]", None++ # 下载后检查实际文件大小+ if file_info.get("size", 0) == 0:+ logger.warning(f"下载的文件为空: {file_name}")+ return "[空文件]", None++ return f"[文件: {file_name}]", [file_info]++ async def handle_audio_message(+ self, raw_data: dict, sender_id: str, conversation_id: str, conversation_type: str+ ) -> tuple[str, list[dict] | None]:+ """处理音频消息"""+ if not self.config.enable_file_download:+ return "[音频: 文件下载功能已禁用]", None++ if not self._file_service:+ return "[音频: 文件服务未初始化]", None++ content = raw_data.get("content", {})+ download_code = content.get("downloadCode", "")+ duration = content.get("duration", 0)+ message_id = raw_data.get("msgId", sender_id)++ if not download_code:+ return "[音频: 缺少下载码]", None++ file_info = await self._file_service.download_audio(download_code, message_id)+ if not file_info:+ return "[音频: 下载失败]", None++ duration_str = f" {duration / 1000:.1f}s" if duration else ""+ return f"[音频{duration_str}]", [file_info]++ async def handle_video_message(+ self, raw_data: dict, sender_id: str, conversation_id: str, conversation_type: str+ ) -> tuple[str, list[dict] | None]:+ """处理视频消息"""+ if not self.config.enable_file_download:+ return "[视频: 文件下载功能已禁用]", None++ if not self._file_service:+ return "[视频: 文件服务未初始化]", None++ content = raw_data.get("content", {})+ download_code = content.get("downloadCode", "")+ duration = content.get("duration", 0)+ message_id = raw_data.get("msgId", sender_id)++ if not download_code:+ return "[视频: 缺少下载码]", None++ file_info = await self._file_service.download_video(download_code, message_id)+ if not file_info:+ return "[视频: 下载失败]", None++ duration_str = f" {duration / 1000:.1f}s" if duration else ""+ return f"[视频{duration_str}]", [file_info]++ async def handle_incoming_message(self, message: DingTalkInboundMessage) -> None:"""处理传入消息(由DingTalkHandler调用)委托给 _process_incoming_message(),该方法在发布到总线之前执行 allow_from权限检查。"""try:- logger.info(f"钉钉入站消息: {content} 来自 {sender_name}")+ logger.info(f"钉钉入站消息: {message.content} 来自 {message.sender_name}")await self._process_incoming_message(- chat_id=sender_id,- sender_id=sender_id, # 对于私聊,chat_id == sender_id- content=str(content),- conversation_id=conversation_id,- conversation_type=conversation_type,+ chat_id=message.sender_id,+ sender_id=message.sender_id,+ content=str(message.content),+ conversation_id=message.conversation_id,+ conversation_type=message.conversation_type,metadata={- "sender_name": sender_name,+ "sender_name": message.sender_name,"platform": "dingtalk",+ "dingtalk_chat_id": message.conversation_id,+ "dingtalk_sender_id": message.sender_id,},+ files=message.files,)except Exception as e:- logger.error(f"发布钉钉消息时出错: {e}")\ No newline at end of file+ logger.error(f"发布钉钉消息时出错: {e}")++ # ==================== 文件发送方法 ====================++ def _extract_receive_info(self, msg: Message) -> tuple[str, str, str]:+ """从消息中提取接收者信息。++ Returns:+ (chat_id, conversation_type, open_conversation_id)+ """+ metadata = msg.metadata or {}+ conversation_type = metadata.get("conversation_type", "1")+ open_conversation_id = metadata.get("conversation_id", "")++ # 根据会话类型选择正确的 chat_id:+ # - 私聊 (type=1): Robot API userIds 需要员工ID (sender_staff_id)+ # - 群聊 (type=2): Robot API openConversationId 需要 conversation_id+ if conversation_type == "2":+ # 群聊:使用 conversation_id+ chat_id = metadata.get("dingtalk_chat_id") or metadata.get("dingtalk_sender_id") or ""+ else:+ # 私聊:使用 sender_staff_id(员工ID)+ chat_id = metadata.get("dingtalk_sender_id") or metadata.get("dingtalk_chat_id") or ""++ # 回退到 session_id+ if not chat_id:+ chat_id = getattr(msg, "session_id", "") or msg.id or ""++ return chat_id, conversation_type, open_conversation_id++ async def _send_file_message(self, msg: Message) -> None:+ """发送文件消息"""+ if not self._file_service or not self.config.send_file_allowed:+ logger.warning("钉钉文件发送功能未启用")+ return++ payload = msg.payload if isinstance(msg.payload, dict) else {}+ files = payload.get("files", [])+ if not files:+ return++ chat_id, conversation_type, open_conversation_id = self._extract_receive_info(msg)+ if not chat_id:+ logger.warning("钉钉文件发送: 未找到接收者")+ 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()++ token = await self._get_access_token()+ if not token:+ logger.error("钉钉文件发送: 无法获取 access_token")+ return++ for file_info in files:+ file_path = file_info.get("path", "")+ if not file_path or not os.path.isfile(file_path):+ logger.warning(f"钉钉文件发送: 文件不存在 {file_path}")+ continue++ # 检查是否已发送+ if file_path in self._sent_file_paths_by_req[request_id]:+ continue++ # 根据文件类型选择发送方法+ ext = os.path.splitext(file_path)[1].lower()+ file_name = os.path.basename(file_path)++ try:+ if ext in {'.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'}:+ await self._send_image(+ DingTalkImageSendRequest(+ token=token,+ chat_id=chat_id,+ conversation_type=conversation_type,+ open_conversation_id=open_conversation_id,+ file_path=file_path,+ )+ )+ elif ext in {'.mp3', '.wav', '.aac', '.ogg', '.flac', '.m4a'}:+ await self._send_audio(+ DingTalkMessageSendRequest(+ token=token,+ chat_id=chat_id,+ conversation_type=conversation_type,+ open_conversation_id=open_conversation_id,+ file_path=file_path,+ file_name=file_name,+ )+ )+ elif ext in {'.mp4', '.mov', '.avi', '.mkv', '.flv', '.webm'}:+ await self._send_video(+ DingTalkMessageSendRequest(+ token=token,+ chat_id=chat_id,+ conversation_type=conversation_type,+ open_conversation_id=open_conversation_id,+ file_path=file_path,+ file_name=file_name,+ )+ )+ else:+ await self._send_file(+ DingTalkMessageSendRequest(+ token=token,+ chat_id=chat_id,+ conversation_type=conversation_type,+ open_conversation_id=open_conversation_id,+ file_path=file_path,+ file_name=file_name,+ )+ )++ self._sent_file_paths_by_req[request_id].add(file_path)+ logger.info(f"钉钉文件已发送: {file_name}")++ except Exception as e:+ logger.error(f"钉钉文件发送失败: {file_name} - {e}")+ # 发送失败时通知用户+ await self._send_file_notification(+ DingTalkFileNotificationRequest(+ token=token,+ chat_id=chat_id,+ conversation_type=conversation_type,+ open_conversation_id=open_conversation_id,+ file_path=file_path,+ file_name=file_name,+ error_msg=str(e),+ )+ )++ # 清理过期的发送记录+ if len(self._sent_file_paths_by_req) > 100:+ 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]++ async def _send_image(self, request: DingTalkImageSendRequest) -> None:+ """发送图片消息"""+ media_id = await self._file_service.upload_media(request.file_path, "image")+ if not media_id:+ raise Exception("图片上传失败")++ msg_param = json.dumps({"photoURL": media_id})+ await self._send_media_message(+ DingTalkMediaMessageRequest(+ token=request.token,+ chat_id=request.chat_id,+ conversation_type=request.conversation_type,+ open_conversation_id=request.open_conversation_id,+ msg_key="sampleImageMsg",+ msg_param=msg_param,+ )+ )++ async def _send_audio(self, request: DingTalkMessageSendRequest) -> None:+ """发送音频消息"""+ media_id = await self._file_service.upload_media(request.file_path, "voice")+ if not media_id:+ raise Exception("音频上传失败")++ msg_param = json.dumps({"mediaId": media_id})+ await self._send_media_message(+ DingTalkMediaMessageRequest(+ token=request.token,+ chat_id=request.chat_id,+ conversation_type=request.conversation_type,+ open_conversation_id=request.open_conversation_id,+ msg_key="sampleAudio",+ msg_param=msg_param,+ )+ )++ async def _send_video(self, request: DingTalkMessageSendRequest) -> None:+ """发送视频消息"""+ media_id = await self._file_service.upload_media(request.file_path, "video")+ if not media_id:+ raise Exception("视频上传失败")++ msg_param = json.dumps({"mediaId": media_id})+ await self._send_media_message(+ DingTalkMediaMessageRequest(+ token=request.token,+ chat_id=request.chat_id,+ conversation_type=request.conversation_type,+ open_conversation_id=request.open_conversation_id,+ msg_key="sampleVideo",+ msg_param=msg_param,+ )+ )++ async def _send_file(self, request: DingTalkMessageSendRequest) -> None:+ """发送文件消息++ 使用机器人消息 API 发送文件消息,msgKey 为 sampleFile。+ 支持各种文件类型:音频、视频、PPT、Excel、PDF、压缩包等。++ 参考:https://open.dingtalk.com/document/orgapp/chatbots-send-one-on-one-chat-messages-in-batches+ """+ # 上传文件获取 mediaId+ media_id = await self._file_service.upload_media(request.file_path, "file")+ if not media_id:+ raise Exception("文件上传失败")++ # 获取文件扩展名用于 fileType+ ext = os.path.splitext(request.file_name)[1].lower().lstrip('.')+ if not ext:+ ext = "stream"++ # 使用机器人 API 发送文件消息+ # msgKey: sampleFile+ # msgParam: {"mediaId": "xxx", "fileName": "xxx", "fileType": "xxx"}+ msg_param = json.dumps({+ "mediaId": media_id,+ "fileName": request.file_name,+ "fileType": ext,+ })++ await self._send_media_message(+ DingTalkMediaMessageRequest(+ token=request.token,+ chat_id=request.chat_id,+ conversation_type=request.conversation_type,+ open_conversation_id=request.open_conversation_id,+ msg_key="sampleFile",+ msg_param=msg_param,+ )+ )+ logger.info(f"[DingTalk] 文件发送成功: {request.file_name} -> {request.chat_id}")++ async def _send_file_notification(self, request: DingTalkFileNotificationRequest) -> None:+ """发送文件通知(Markdown 消息),用于文件发送失败时的备用通知。"""+ # 获取文件大小+ try:+ file_size = os.path.getsize(request.file_path)+ if file_size < 1024:+ size_str = f"{file_size} B"+ elif file_size < 1024 * 1024:+ size_str = f"{file_size / 1024:.1f} KB"+ else:+ size_str = f"{file_size / (1024 * 1024):.1f} MB"+ except Exception:+ size_str = "未知大小"++ if request.error_msg:+ markdown_content = (+ f"### 文件发送失败\n\n"+ f"**文件名**: {request.file_name}\n\n"+ f"**大小**: {size_str}\n\n"+ f"**错误**: {request.error_msg}\n\n"+ f"**路径**: `{request.file_path}`"+ )+ else:+ markdown_content = (+ f"### 文件已生成\n\n"+ f"**文件名**: {request.file_name}\n\n"+ f"**大小**: {size_str}\n\n"+ f"**路径**: `{request.file_path}`"+ )++ msg_param = json.dumps({+ "title": "文件通知",+ "text": markdown_content,+ })+ await self._send_media_message(+ DingTalkMediaMessageRequest(+ token=request.token,+ chat_id=request.chat_id,+ conversation_type=request.conversation_type,+ open_conversation_id=request.open_conversation_id,+ msg_key="sampleMarkdown",+ msg_param=msg_param,+ )+ )++ async def _send_media_message(self, request: DingTalkMediaMessageRequest) -> None:+ """发送媒体消息"""+ if request.conversation_type == "2":+ # 群聊+ url = "https://api.dingtalk.com/v1.0/robot/groupMessages/send"+ data = {+ "robotCode": self.config.client_id,+ "openConversationId": request.open_conversation_id,+ "msgKey": request.msg_key,+ "msgParam": request.msg_param,+ }+ else:+ # 私聊+ url = "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend"+ data = {+ "robotCode": self.config.client_id,+ "userIds": [request.chat_id],+ "msgKey": request.msg_key,+ "msgParam": request.msg_param,+ }++ headers = {"x-acs-dingtalk-access-token": request.token}++ if not self._http:+ raise Exception("HTTP 客户端未初始化")++ response = await self._http.post(url, json=data, headers=headers)+ if response.status_code != 200:+ raise Exception(f"发送失败: {response.text}")++ # ==================== 兜底文件发送 ====================++ def _detect_workspace_files(self, text: str, workspace_dir: str) -> list[str]:+ """检测文本中提到的 workspace 文件路径。++ 支持两种模式:+ 1. 完整绝对路径匹配+ 2. 从引号/书名号中提取文件名,在 workspace 下查找++ Args:+ text: 消息文本+ workspace_dir: 工作空间目录++ Returns:+ 存在的文件路径列表+ """+ if not workspace_dir or not text:+ return []++ found_files = []++ # 模式1:完整绝对路径匹配+ # 匹配类似 /home/xxx/.jiuwenclaw/agent/workspace/xxx.ext 的路径+ path_pattern = re.compile(+ r'(?:^|["\'「「【《\s])(' + re.escape(workspace_dir) + r'[^\s"\'」」】》]+\.\w{1,10})(?:$|["\'」」】》\s])',+ re.MULTILINE+ )+ for match in path_pattern.finditer(text):+ path = match.group(1).strip()+ if os.path.isfile(path):+ found_files.append(path)++ # 模式2:从引号/书名号中提取文件名+ # 匹配 "filename.ext"、'filename.ext'、「filename.ext」、《filename.ext》+ filename_pattern = re.compile(+ r'["\'「「【《]([^"\'」」】》]+\.\w{1,10})["\'」」】》]'+ )+ for match in filename_pattern.finditer(text):+ filename = match.group(1).strip()+ # 在 workspace 下查找同名文件+ potential_path = os.path.join(workspace_dir, filename)+ if os.path.isfile(potential_path) and potential_path not in found_files:+ found_files.append(potential_path)++ return found_files++ async def _send_fallback_files(self, msg: Message, content: str) -> None:+ """chat.final 兜底文件发送。++ 当 LLM 未调用 send_file_to_user 但在回复中提到了文件时,+ 自动检测并发送这些文件。+ """+ if not self._file_service or not self.config.send_file_allowed:+ return++ workspace_dir = self.config.workspace_dir or os.path.expanduser("~/.jiuwenclaw/agent/workspace")+ if not os.path.isdir(workspace_dir):+ return++ # 检测文件路径+ file_paths = self._detect_workspace_files(content, workspace_dir)+ if not file_paths:+ return++ # 获取当前 request_id 用于去重+ request_id = getattr(msg, "id", "") or ""+ sent_paths = self._sent_file_paths_by_req.get(request_id, set())++ # 过滤已发送的文件+ new_files = [p for p in file_paths if p not in sent_paths]+ if not new_files:+ return++ logger.info(f"钉钉兜底文件发送: 检测到 {len(new_files)} 个未发送文件")++ # 构造文件消息并发送+ files_payload = [{"path": p, "name": os.path.basename(p)} for p in new_files]+ fallback_msg = Message(+ id=msg.id,+ type=msg.type,+ channel_id=self.name,+ session_id=msg.session_id,+ payload={"event_type": "chat.file", "files": files_payload},+ metadata=msg.metadata,+ )+ await self._send_file_message(fallback_msg)\ No newline at end of filediff --git a/jiuwenclaw/channel/dingtalk_file_service.py b/jiuwenclaw/channel/dingtalk_file_service.pynew file mode 100644index 0000000000..f30715a96b--- /dev/null+++ b/jiuwenclaw/channel/dingtalk_file_service.py@@ -0,0 +1,475 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""DingTalk File Service++提供钉钉文件的下载和上传功能。+"""++from __future__ import annotations++import asyncio+import os+import re+from typing import Any, Callable++import httpx+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 DingTalkFileService:+ """钉钉文件服务,处理文件下载和上传。"""++ def __init__(+ self,+ client_id: str,+ get_token_func: Callable[[], asyncio.coroutines.Coroutine[Any, Any, str | None]],+ http_client: httpx.AsyncClient,+ max_download_size: int = 100 * 1024 * 1024,+ download_timeout: int = 60,+ workspace_dir: str = "",+ ):+ """初始化文件服务。++ Args:+ client_id: 钉钉应用 client_id(robotCode)+ get_token_func: 获取 access_token 的异步函数+ http_client: HTTP 客户端+ max_download_size: 最大下载文件大小(字节)+ download_timeout: 下载超时时间(秒)+ workspace_dir: 工作空间目录+ """+ self._client_id = client_id+ self._get_token = get_token_func+ self._http = http_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, "dingtalk_files", "downloads", file_category)+ os.makedirs(base_dir, exist_ok=True)+ return base_dir++ @classmethod+ def _safe_filename(cls, name: str) -> str:+ """生成安全的文件名。"""+ # 移除或替换不安全字符+ safe = re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', name)+ return safe[:100] # 限制长度++ async def _download_with_retry(+ self,+ download_code: str,+ file_type: str,+ max_retries: int = 3,+ ) -> bytes | None:+ """带重试的文件下载。++ Args:+ download_code: 文件下载码+ file_type: 文件类型(image/file/voice/video)+ max_retries: 最大重试次数++ Returns:+ 文件内容,失败返回 None+ """+ token = await self._get_token()+ if not token:+ logger.error("[DingTalkFileService] 无法获取 access_token")+ return None++ url = "https://api.dingtalk.com/v1.0/robot/messageFiles/download"+ # 钉钉下载 API 使用 POST 方法,参数放在请求体中+ body = {+ "downloadCode": download_code,+ "robotCode": self._client_id,+ }+ headers = {+ "x-acs-dingtalk-access-token": token,+ "Content-Type": "application/json",+ }++ for attempt in range(max_retries):+ try:+ async with self._download_semaphore:+ # 第一步:POST 请求获取 downloadUrl+ response = await asyncio.wait_for(+ self._http.post(url, json=body, headers=headers),+ timeout=self._download_timeout,+ )++ if response.status_code != 200:+ logger.warning(+ f"[DingTalkFileService] 获取下载链接失败 status={response.status_code} "+ f"attempt={attempt + 1}/{max_retries} response={response.text}"+ )+ if attempt < max_retries - 1:+ await asyncio.sleep(2 ** attempt)+ continue++ # 解析响应获取 downloadUrl+ result = response.json()+ download_url = result.get("downloadUrl")+ if not download_url:+ logger.warning(+ f"[DingTalkFileService] 响应缺少 downloadUrl: {result}"+ )+ if attempt < max_retries - 1:+ await asyncio.sleep(2 ** attempt)+ continue++ # 第二步:GET 请求下载实际文件内容+ download_response = await asyncio.wait_for(+ self._http.get(download_url),+ timeout=self._download_timeout,+ )++ if download_response.status_code != 200:+ logger.warning(+ f"[DingTalkFileService] 下载文件失败 status={download_response.status_code} "+ f"attempt={attempt + 1}/{max_retries}"+ )+ if attempt < max_retries - 1:+ await asyncio.sleep(2 ** attempt)+ continue++ content = download_response.content+ if not content:+ logger.warning(+ f"[DingTalkFileService] 下载内容为空 attempt={attempt + 1}/{max_retries}"+ )+ if attempt < max_retries - 1:+ await asyncio.sleep(2 ** attempt)+ continue++ if len(content) > self._max_download_size:+ logger.warning(+ f"[DingTalkFileService] 文件大小 {len(content)} 超过限制 {self._max_download_size},跳过下载"+ )+ return None++ return content++ except asyncio.TimeoutError:+ logger.warning(+ f"[DingTalkFileService] 下载超时 attempt={attempt + 1}/{max_retries}"+ )+ if attempt < max_retries - 1:+ await asyncio.sleep(2 ** (attempt + 1))+ except Exception as e:+ logger.error(f"[DingTalkFileService] 下载异常: {e}")+ if attempt < max_retries - 1:+ await asyncio.sleep(2 ** attempt)++ return None++ async def download_image(self, download_code: str, message_id: str) -> dict | None:+ """下载图片文件。++ Args:+ download_code: 图片下载码+ message_id: 消息 ID++ Returns:+ 文件信息字典,失败返回 None+ """+ content = await self._download_with_retry(download_code, "image")+ if not content:+ return None++ # 检测文件格式+ ext = detect_file_extension(content)+ if not ext:+ ext = '.png' # 默认 PNG++ # 生成文件名+ safe_code = self._safe_filename(download_code[:20])+ filename = f"{message_id}_{safe_code}{ext}"++ # 保存文件+ download_dir = self._get_download_dir("images")+ file_path = os.path.join(download_dir, filename)++ try:+ with open(file_path, 'wb') as f:+ f.write(content)++ return {+ "path": file_path,+ "name": filename,+ "size": len(content),+ "mime_type": get_mime_type(ext),+ "download_code": download_code,+ "file_category": "image",+ }+ except Exception as e:+ logger.error(f"[DingTalkFileService] 保存图片失败: {e}")+ return None++ async def download_file(self, download_code: str, message_id: str, original_name: str = "") -> dict | None:+ """下载普通文件。++ Args:+ download_code: 文件下载码+ message_id: 消息 ID+ original_name: 原始文件名++ Returns:+ 文件信息字典,失败返回 None+ """+ content = await self._download_with_retry(download_code, "file")+ if not content:+ return None++ # 确定扩展名+ if original_name:+ ext = os.path.splitext(original_name)[1].lower()+ else:+ ext = detect_file_extension(content) or '.bin'++ # 生成文件名+ safe_code = self._safe_filename(download_code[:20])+ if original_name:+ filename = self._safe_filename(original_name)+ else:+ filename = f"{message_id}_{safe_code}{ext}"++ # 保存文件+ download_dir = self._get_download_dir("files")+ file_path = os.path.join(download_dir, filename)++ try:+ with open(file_path, 'wb') as f:+ f.write(content)++ return {+ "path": file_path,+ "name": filename,+ "size": len(content),+ "mime_type": get_mime_type(ext),+ "download_code": download_code,+ "file_category": "file",+ }+ except Exception as e:+ logger.error(f"[DingTalkFileService] 保存文件失败: {e}")+ return None++ async def download_audio(self, download_code: str, message_id: str) -> dict | None:+ """下载音频文件。++ Args:+ download_code: 音频下载码+ message_id: 消息 ID++ Returns:+ 文件信息字典,失败返回 None+ """+ content = await self._download_with_retry(download_code, "voice")+ if not content:+ return None++ # 检测文件格式+ ext = detect_file_extension(content)+ if not ext:+ ext = '.mp3' # 默认 MP3++ # 生成文件名+ safe_code = self._safe_filename(download_code[:20])+ filename = f"{message_id}_{safe_code}{ext}"++ # 保存文件+ download_dir = self._get_download_dir("audio")+ file_path = os.path.join(download_dir, filename)++ try:+ with open(file_path, 'wb') as f:+ f.write(content)++ return {+ "path": file_path,+ "name": filename,+ "size": len(content),+ "mime_type": get_mime_type(ext),+ "download_code": download_code,+ "file_category": "audio",+ }+ except Exception as e:+ logger.error(f"[DingTalkFileService] 保存音频失败: {e}")+ return None++ async def download_video(self, download_code: str, message_id: str) -> dict | None:+ """下载视频文件。++ Args:+ download_code: 视频下载码+ message_id: 消息 ID++ Returns:+ 文件信息字典,失败返回 None+ """+ content = await self._download_with_retry(download_code, "video")+ if not content:+ return None++ # 检测文件格式+ ext = detect_file_extension(content)+ if not ext:+ ext = '.mp4' # 默认 MP4++ # 生成文件名+ safe_code = self._safe_filename(download_code[:20])+ filename = f"{message_id}_{safe_code}{ext}"++ # 保存文件+ download_dir = self._get_download_dir("video")+ file_path = os.path.join(download_dir, filename)++ try:+ with open(file_path, 'wb') as f:+ f.write(content)++ return {+ "path": file_path,+ "name": filename,+ "size": len(content),+ "mime_type": get_mime_type(ext),+ "download_code": download_code,+ "file_category": "video",+ }+ except Exception as e:+ logger.error(f"[DingTalkFileService] 保存视频失败: {e}")+ return None++ async def upload_media(self, file_path: str, file_type: str) -> str | None:+ """上传媒体文件到钉钉。++ Args:+ file_path: 本地文件路径+ file_type: 文件类型(image/file/voice/video)++ Returns:+ mediaId,失败返回 None+ """+ if not os.path.isfile(file_path):+ logger.warning(f"[DingTalkFileService] 文件不存在: {file_path}")+ return None++ token = await self._get_token()+ if not token:+ logger.error("[DingTalkFileService] 无法获取 access_token")+ return None++ # 使用钉钉旧版 API(与 dingtalk-stream SDK 一致)+ from urllib.parse import quote_plus+ url = f"https://oapi.dingtalk.com/media/upload?access_token={quote_plus(token)}"++ try:+ filename = os.path.basename(file_path)+ mime_type = get_mime_type(os.path.splitext(file_path)[1])+ with open(file_path, 'rb') as f:+ files = {+ "media": (filename, f.read(), mime_type),+ }+ data = {+ "type": file_type,+ }+ response = await self._http.post(url, data=data, files=files)++ if response.status_code != 200:+ logger.error(f"[DingTalkFileService] 上传失败: {response.text}")+ return None++ result = response.json()+ # 旧版 API 返回 media_id(下划线)+ media_id = result.get("media_id")+ if not media_id:+ logger.error(f"[DingTalkFileService] 上传响应缺少 media_id: {result}")+ return None++ logger.debug(f"[DingTalkFileService] 上传成功: {filename} -> {media_id}")+ return media_id++ except Exception as e:+ logger.error(f"[DingTalkFileService] 上传异常: {e}")+ return None+diff --git a/jiuwenclaw/resources/config.yaml b/jiuwenclaw/resources/config.yamlindex ecdd58d377..3bb17f08a8 100644--- a/jiuwenclaw/resources/config.yaml+++ b/jiuwenclaw/resources/config.yaml@@ -189,6 +189,7 @@ channels:client_secret:allow_from: []enabled: false+ send_file_allowed: truetelegram:# Telegram Bot 配置# 从 @BotFather 获取 bot_tokendiff --git a/tests/unit/channel/test_dingtalk_file.py b/tests/unit/channel/test_dingtalk_file.pynew file mode 100644index 0000000000..ae4479e558--- /dev/null+++ b/tests/unit/channel/test_dingtalk_file.py@@ -0,0 +1,195 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Tests for DingTalkChannel file upload and download functionality."""++import json+import os+import tempfile+from unittest.mock import AsyncMock, MagicMock++import pytest+import httpx++from jiuwenclaw.channel.dingding import (+ DingTalkChannel,+ DingTalkConfig,+)+from jiuwenclaw.channel.dingtalk_file_service import DingTalkFileService+from jiuwenclaw.channel.base import RobotMessageRouter+from jiuwenclaw.schema.message import Message, EventType+++# ---------------------------------------------------------------------------+# Helper Functions+# ---------------------------------------------------------------------------++def _make_channel() -> DingTalkChannel:+ """Create a DingTalkChannel instance for testing."""+ config = DingTalkConfig(+ enabled=True,+ client_id="test_client_id",+ client_secret="test_client_secret",+ allow_from=["test_user"],+ enable_file_upload=True,+ enable_file_download=True,+ max_download_size=20 * 1024 * 1024,+ download_timeout=60,+ workspace_dir="",+ )+ router = MagicMock(spec=RobotMessageRouter)+ ch = DingTalkChannel(config, router)+ setattr(ch, '_http', MagicMock(spec=httpx.AsyncClient))+ setattr(ch, '_file_service', MagicMock(spec=DingTalkFileService))+ setattr(ch, '_access_token', "test_token")+ return ch+++def _make_file_message(file_paths: list[str]) -> Message:+ """Create a file message for testing."""+ files = [{"path": path, "name": os.path.basename(path)} for path in file_paths]+ return Message(+ id="test_request_id",+ type="req",+ channel_id="dingtalk",+ session_id="test_session",+ params={},+ payload={"event_type": "chat.file", "files": files},+ metadata={+ "dingtalk_sender_id": "test_user",+ "dingtalk_chat_id": "test_chat",+ "conversation_type": "1",+ "conversation_id": "test_conv",+ },+ timestamp=0,+ ok=True,+ req_method="chat_send",+ )+++# ---------------------------------------------------------------------------+# Test 1: File Upload Success+# ---------------------------------------------------------------------------++async def test_send_image_file_success():+ """Test successful image file upload and send."""+ ch = _make_channel()++ file_service = getattr(ch, '_file_service')+ http_client = getattr(ch, '_http')++ file_service.upload_media = AsyncMock(return_value="test_media_id_123")++ # Mock HTTP client response+ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.text = '{"errcode": 0}'+ http_client.post = AsyncMock(return_value=mock_response)++ # Create temporary image file+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:+ f.write(b"\x89PNG\r\n\x1a\n") # PNG magic number+ tmp_path = f.name++ try:+ msg = _make_file_message([tmp_path])+ await ch.send(msg)++ # Verify upload was called+ file_service.upload_media.assert_called_once()++ # Verify HTTP POST was called+ assert http_client.post.call_count == 3+ call_args = http_client.post.call_args+ assert call_args[0][0] == "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend"++ # Verify request body+ request_data = call_args[1]["json"]+ assert request_data["robotCode"] == "test_client_id"+ assert request_data["msgKey"] == "sampleImageMsg"++ msg_param = json.loads(request_data["msgParam"])+ assert msg_param["photoURL"] == "test_media_id_123"++ finally:+ os.unlink(tmp_path)+++# ---------------------------------------------------------------------------+# Test 2: File Download Success+# ---------------------------------------------------------------------------++async def test_handle_picture_message_success():+ """Test successful picture message download."""+ ch = _make_channel()++ file_service = getattr(ch, '_file_service')+ file_service.download_image = AsyncMock(return_value={+ "path": "/tmp/test_image.png",+ "name": "test_image.png",+ "size": 1024,+ "mime_type": "image/png",+ "download_code": "test_download_code",+ "file_category": "image",+})++ raw_data = {+ "content": {+ "downloadCode": "test_download_code",+ },+ "msgId": "test_msg_id",+ }++ content, files = await ch.handle_picture_message(+ raw_data, "test_user", "test_conv", "1"+ )++ # Verify download was called+ file_service.download_image.assert_called_once_with(+ "test_download_code", "test_msg_id"+ )++ # Verify return values+ assert content == "[图片]"+ assert files is not None+ assert len(files) == 1+ assert files[0]["name"] == "test_image.png"+ assert files[0]["mime_type"] == "image/png"+++# ---------------------------------------------------------------------------+# Test 3: File Download Disabled+# ---------------------------------------------------------------------------++async def test_handle_picture_message_disabled():+ """Test picture message handling when download is disabled."""+ config = DingTalkConfig(+ enabled=True,+ client_id="test_client_id",+ client_secret="test_client_secret",+ allow_from=["test_user"],+ enable_file_download=False, # Download disabled+ )+ router = MagicMock(spec=RobotMessageRouter)+ ch = DingTalkChannel(config, router)++ raw_data = {+ "content": {+ "downloadCode": "test_download_code",+ },+ "msgId": "test_msg_id",+ }++ content, files = await ch.handle_picture_message(+ raw_data, "test_user", "test_conv", "1"+ )++ # Verify no download was attempted+ assert content == "[图片: 文件下载功能已禁用]"+ assert files is None+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])\ No newline at end of file