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(feishu): 飞书频道支持发送图片和文件
terrenceeLeung0f5d93b2bc98
diff --git "a/docs/\351\242\221\351\201\223.md" "b/docs/\351\242\221\351\201\223.md"index 2048ae4418..c4ccab7198 100644--- "a/docs/\351\242\221\351\201\223.md"+++ "b/docs/\351\242\221\351\201\223.md"@@ -119,6 +119,7 @@ channels:1. 左侧选择**权限管理** -> **API权限**。2. 搜索并开通以下关键权限(用于收发消息):- `im:message` 相关:以应用的身份发消息、获取用户发给机器人的单聊消息、接收群聊中@机器人消息事件。+ - `im:resource`:上传图片和文件(用于发送图片/文件给用户)。- `contact:user.employee_id:readonly`:获取用户ID信息。- 也可以批量导入权限,参考火山引擎文档中的权限列表。diff --git a/jiuwenclaw/agentserver/tools/send_file_to_user.py b/jiuwenclaw/agentserver/tools/send_file_to_user.pyindex 01ff954ebc..f522da79e5 100644--- a/jiuwenclaw/agentserver/tools/send_file_to_user.py+++ b/jiuwenclaw/agentserver/tools/send_file_to_user.py@@ -81,14 +81,14 @@ class SendFileToolkit:"[SendFileToolkit] send_file 完成 session_id=%s",self.session_id,)- return f"成功发送 {len(abs_file_path_list)} 个文件"+ return f"已提交 {len(abs_file_path_list)} 个文件的发送请求"except Exception as e:logger.exception("[SendFileToolkit] send_file 失败 session_id=%s error=%s",self.session_id,str(e),)- return f"发送文件失败: {str(e)}"+ return f"提交文件失败: {str(e)}"def get_tools(self) -> List[Tool]:"""Return tools for registration in Runner.diff --git a/jiuwenclaw/channel/feishu.py b/jiuwenclaw/channel/feishu.pyindex 60e10dd1cf..9eb222a48f 100644--- a/jiuwenclaw/channel/feishu.py+++ b/jiuwenclaw/channel/feishu.py@@ -3,6 +3,7 @@import loggingimport asyncioimport concurrent.futures+import osimport typesimport jsonimport re@@ -39,6 +40,10 @@ class FeishuConfig(BaseModel):try:import lark_oapi as larkfrom lark_oapi.api.im.v1 import (+ CreateImageRequest,+ CreateImageRequestBody,+ CreateFileRequest,+ CreateFileRequestBody,CreateMessageRequest,CreateMessageRequestBody,CreateMessageReactionRequest,@@ -624,6 +629,33 @@ class FeishuChannel(BaseChannel):stream_key = str(getattr(msg, "id", "") or "")streaming_enabled = bool(self.config.enable_streaming)+ # P1: 处理 chat.file 事件 — 上传文件到飞书+ if event_name == "chat.file":+ files = payload.get("files", [])+ if not files:+ return+ receive_id, id_type = self._extract_receive_info(msg)+ for file_path in files:+ if not isinstance(file_path, str):+ continue+ if self._is_image_file(file_path):+ image_key = self._upload_image(file_path)+ if image_key:+ content = json.dumps({"image_key": image_key})+ await self._send_feishu_message(receive_id, id_type, content, msg.id, msg_type="image")+ else:+ fallback = self._build_card_content(f"[文件发送失败] {os.path.basename(file_path)}")+ await self._send_feishu_message(receive_id, id_type, fallback, msg.id)+ else:+ file_key = self._upload_file(file_path)+ if file_key:+ content = json.dumps({"file_key": file_key})+ await self._send_feishu_message(receive_id, id_type, content, msg.id, msg_type="file")+ else:+ fallback = self._build_card_content(f"[文件发送失败] {os.path.basename(file_path)}")+ await self._send_feishu_message(receive_id, id_type, fallback, msg.id)+ return+# 流式增量:先缓存;若开启流式则实时发送,否则仅缓存不发送。if event_name == "chat.delta":delta = self._extract_message_content(msg)@@ -918,6 +950,88 @@ class FeishuChannel(BaseChannel):return str(value)return str(value)+ _IMAGE_EXTENSIONS = frozenset({".jpg", ".jpeg", ".png", ".gif", ".bmp"})++ @staticmethod+ def _is_image_file(path: str) -> bool:+ """Check if file path has an image extension supported by Feishu."""+ ext = os.path.splitext(path)[1].lower()+ return ext in FeishuChannel._IMAGE_EXTENSIONS++ def _upload_image(self, abs_path: str) -> str | None:+ """Upload an image to Feishu and return the image_key, or None on failure."""+ if not self._api_client:+ return None+ try:+ with open(abs_path, "rb") as f:+ request = (+ CreateImageRequest.builder()+ .request_body(+ CreateImageRequestBody.builder()+ .image_type("message")+ .image(f)+ .build()+ )+ .build()+ )+ response = self._api_client.im.v1.image.create(request)++ if not response.success():+ logger.warning(+ "飞书图片上传失败: code=%s msg=%s path=%s",+ response.code, response.msg, abs_path,+ )+ return None++ image_key = getattr(response.data, "image_key", None)+ if image_key:+ logger.info("飞书图片上传成功: image_key=%s", image_key)+ return image_key+ except FileNotFoundError:+ logger.warning("飞书图片上传失败: 文件不存在 path=%s", abs_path)+ return None+ except Exception as e:+ logger.error("飞书图片上传异常: %s path=%s", e, abs_path)+ return None++ def _upload_file(self, abs_path: str) -> str | None:+ """Upload a file to Feishu and return the file_key, or None on failure."""+ if not self._api_client:+ return None+ try:+ file_name = os.path.basename(abs_path)+ with open(abs_path, "rb") as f:+ request = (+ CreateFileRequest.builder()+ .request_body(+ CreateFileRequestBody.builder()+ .file_type("stream")+ .file_name(file_name)+ .file(f)+ .build()+ )+ .build()+ )+ response = self._api_client.im.v1.file.create(request)++ if not response.success():+ logger.warning(+ "飞书文件上传失败: code=%s msg=%s path=%s",+ response.code, response.msg, abs_path,+ )+ return None++ file_key = getattr(response.data, "file_key", None)+ if file_key:+ logger.info("飞书文件上传成功: file_key=%s", file_key)+ return file_key+ except FileNotFoundError:+ logger.warning("飞书文件上传失败: 文件不存在 path=%s", abs_path)+ return None+ except Exception as e:+ logger.error("飞书文件上传异常: %s path=%s", e, abs_path)+ return None+def _build_card_content(self, content_str: str) -> str:"""构建飞书卡片内容。@@ -936,16 +1050,18 @@ class FeishuChannel(BaseChannel):return json.dumps(card, ensure_ascii=False)async def _send_feishu_message(- self, receive_id: str, id_type: str, card_content: str, msg_id: str- ) -> None:+ self, receive_id: str, id_type: str, content: str, msg_id: str,+ msg_type: str = "interactive",+ ) -> Any:"""发送飞书消息。Args:receive_id: 接收者IDid_type: ID类型- card_content: 卡片内容+ content: 消息内容(JSON字符串)msg_id: 发送消息ID(用于日志)+ msg_type: 消息类型(默认interactive,也支持image/file等)"""request = (CreateMessageRequest.builder()@@ -953,8 +1069,8 @@ class FeishuChannel(BaseChannel):.request_body(CreateMessageRequestBody.builder().receive_id(receive_id)- .msg_type("interactive")- .content(card_content)+ .msg_type(msg_type)+ .content(content).build()).build()@@ -967,8 +1083,10 @@ class FeishuChannel(BaseChannel):f"发送飞书消息失败: 错误码={response.code}, "f"消息={response.msg}, 日志ID={response.get_log_id()}")+ return Noneelse:logger.debug("已向 %s 发送飞书消息", msg_id)+ return responsedef _on_message_sync(self, data: "P2ImMessageReceiveV1") -> None:"""diff --git a/tests/unit/channel/__init__.py b/tests/unit/channel/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/unit/channel/test_feishu_upload.py b/tests/unit/channel/test_feishu_upload.pynew file mode 100644index 0000000000..5abb85be8f--- /dev/null+++ b/tests/unit/channel/test_feishu_upload.py@@ -0,0 +1,282 @@+# pylint: disable=protected-access+"""Tests for FeishuChannel media upload (P1)."""++import json+import os+import tempfile+from unittest.mock import MagicMock++import pytest++from jiuwenclaw.channel.feishu import FeishuChannel, FeishuConfig+from jiuwenclaw.channel.base import RobotMessageRouter+from jiuwenclaw.schema.message import Message, EventType+++def _make_channel() -> FeishuChannel:+ """Create a FeishuChannel with mocked dependencies."""+ config = FeishuConfig(+ enabled=True,+ app_id="test_app_id",+ app_secret="test_app_secret",+ )+ router = MagicMock(spec=RobotMessageRouter)+ ch = FeishuChannel(config, router)+ ch._api_client = MagicMock()+ return ch+++def _make_file_message(files: list[str], receive_id: str = "oc_test123") -> Message:+ """Create a chat.file Message."""+ return Message(+ id="req_001",+ type="event",+ channel_id="feishu",+ session_id="sess_001",+ params={},+ timestamp=1000.0,+ ok=True,+ payload={"event_type": "chat.file", "files": files},+ event_type=EventType.CHAT_FILE,+ metadata={"feishu_chat_id": receive_id},+ )+++# ---------------------------------------------------------------------------+# _is_image_file+# ---------------------------------------------------------------------------++def test_is_image_jpg():+ ch = _make_channel()+ assert ch._is_image_file("/path/to/photo.jpg") is True+++def test_is_image_jpeg():+ ch = _make_channel()+ assert ch._is_image_file("/path/to/photo.jpeg") is True+++def test_is_image_png():+ ch = _make_channel()+ assert ch._is_image_file("/path/to/screenshot.png") is True+++def test_is_image_gif():+ ch = _make_channel()+ assert ch._is_image_file("/path/to/anim.gif") is True+++def test_is_image_bmp():+ ch = _make_channel()+ assert ch._is_image_file("/path/to/img.bmp") is True+++def test_pdf_not_image():+ ch = _make_channel()+ assert ch._is_image_file("/path/to/doc.pdf") is False+++def test_txt_not_image():+ ch = _make_channel()+ assert ch._is_image_file("/path/to/notes.txt") is False+++def test_is_image_case_insensitive():+ ch = _make_channel()+ assert ch._is_image_file("/path/to/PHOTO.JPG") is True+++# ---------------------------------------------------------------------------+# _upload_image+# ---------------------------------------------------------------------------++def test_upload_image_success():+ ch = _make_channel()+ mock_response = MagicMock()+ mock_response.success.return_value = True+ mock_response.data = MagicMock()+ mock_response.data.image_key = "img_v2_test_key"+ ch._api_client.im.v1.image.create.return_value = mock_response++ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:+ f.write(b"fake png data")+ tmp_path = f.name++ try:+ result = ch._upload_image(tmp_path)+ assert result == "img_v2_test_key"+ ch._api_client.im.v1.image.create.assert_called_once()+ finally:+ os.unlink(tmp_path)+++def test_upload_image_failure():+ ch = _make_channel()+ mock_response = MagicMock()+ mock_response.success.return_value = False+ mock_response.code = 99999+ mock_response.msg = "upload failed"+ ch._api_client.im.v1.image.create.return_value = mock_response++ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:+ f.write(b"fake png data")+ tmp_path = f.name++ try:+ result = ch._upload_image(tmp_path)+ assert result is None+ finally:+ os.unlink(tmp_path)+++def test_upload_image_file_not_found():+ ch = _make_channel()+ result = ch._upload_image("/nonexistent/path/image.png")+ assert result is None+++# ---------------------------------------------------------------------------+# _upload_file+# ---------------------------------------------------------------------------++def test_upload_file_success():+ ch = _make_channel()+ mock_response = MagicMock()+ mock_response.success.return_value = True+ mock_response.data = MagicMock()+ mock_response.data.file_key = "file_v2_test_key"+ ch._api_client.im.v1.file.create.return_value = mock_response++ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as f:+ f.write(b"fake pdf data")+ tmp_path = f.name++ try:+ result = ch._upload_file(tmp_path)+ assert result == "file_v2_test_key"+ finally:+ os.unlink(tmp_path)+++def test_upload_file_failure():+ ch = _make_channel()+ mock_response = MagicMock()+ mock_response.success.return_value = False+ mock_response.code = 99999+ mock_response.msg = "upload failed"+ ch._api_client.im.v1.file.create.return_value = mock_response++ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as f:+ f.write(b"fake pdf data")+ tmp_path = f.name++ try:+ result = ch._upload_file(tmp_path)+ assert result is None+ finally:+ os.unlink(tmp_path)+++def test_upload_file_file_not_found():+ ch = _make_channel()+ result = ch._upload_file("/nonexistent/path/doc.pdf")+ assert result is None+++# ---------------------------------------------------------------------------+# send() with chat.file event+# ---------------------------------------------------------------------------++async def test_send_image_file():+ ch = _make_channel()++ upload_resp = MagicMock()+ upload_resp.success.return_value = True+ upload_resp.data = MagicMock()+ upload_resp.data.image_key = "img_v2_abc"+ ch._api_client.im.v1.image.create.return_value = upload_resp++ send_resp = MagicMock()+ send_resp.success.return_value = True+ ch._api_client.im.v1.message.create.return_value = send_resp++ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:+ f.write(b"fake png")+ tmp_path = f.name++ try:+ msg = _make_file_message([tmp_path])+ await ch.send(msg)++ call_args = ch._api_client.im.v1.message.create.call_args+ request_obj = call_args[0][0]+ body = request_obj.request_body+ assert body.msg_type == "image"+ content = json.loads(body.content)+ assert content["image_key"] == "img_v2_abc"+ finally:+ os.unlink(tmp_path)+++async def test_send_generic_file():+ ch = _make_channel()++ upload_resp = MagicMock()+ upload_resp.success.return_value = True+ upload_resp.data = MagicMock()+ upload_resp.data.file_key = "file_v2_xyz"+ ch._api_client.im.v1.file.create.return_value = upload_resp++ send_resp = MagicMock()+ send_resp.success.return_value = True+ ch._api_client.im.v1.message.create.return_value = send_resp++ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as f:+ f.write(b"fake pdf")+ tmp_path = f.name++ try:+ msg = _make_file_message([tmp_path])+ await ch.send(msg)++ call_args = ch._api_client.im.v1.message.create.call_args+ request_obj = call_args[0][0]+ body = request_obj.request_body+ assert body.msg_type == "file"+ content = json.loads(body.content)+ assert content["file_key"] == "file_v2_xyz"+ finally:+ os.unlink(tmp_path)+++async def test_send_file_upload_failure_sends_text_fallback():+ ch = _make_channel()++ upload_resp = MagicMock()+ upload_resp.success.return_value = False+ upload_resp.code = 99999+ upload_resp.msg = "fail"+ ch._api_client.im.v1.image.create.return_value = upload_resp++ send_resp = MagicMock()+ send_resp.success.return_value = True+ ch._api_client.im.v1.message.create.return_value = send_resp++ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:+ f.write(b"fake png")+ tmp_path = f.name++ try:+ msg = _make_file_message([tmp_path])+ await ch.send(msg)++ # Should fall back to interactive card with error text+ call_args = ch._api_client.im.v1.message.create.call_args+ request_obj = call_args[0][0]+ body = request_obj.request_body+ assert body.msg_type == "interactive"+ finally:+ os.unlink(tmp_path)