From 82cc42aee792140e0be5b3c1df7ffbb3664e5db0 Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Mon, 9 Nov 2026 14:06:30 +0800 Subject: [PATCH] fix(feishu): receive files attached to rich-text messages (#6604) Co-authored-by: zhang-li-cs --- nanobot/channels/feishu/runtime.py | 75 +++++++++++- .../feishu/tests/test_feishu_reply.py | 51 ++++++++ tests/channels/test_feishu_post_files.py | 110 ++++++++++++++++++ 3 files changed, 235 insertions(+), 1 deletion(-) create mode 100644 tests/channels/test_feishu_post_files.py diff --git a/nanobot/channels/feishu/runtime.py b/nanobot/channels/feishu/runtime.py index 002be93f9..9170fa77e 100644 --- a/nanobot/channels/feishu/runtime.py +++ b/nanobot/channels/feishu/runtime.py @@ -453,6 +453,64 @@ def _extract_post_content(content_json: dict[str, Any]) -> tuple[str, list[str]] return "", [] +def _extract_post_attachments( + content_json: dict[str, Any], +) -> tuple[list[dict[str, Any]], list[str]]: + """Extract file attachments from a Feishu post (rich text) message. + + Some Feishu ``post`` messages place a caption in ``content`` and + attachments in a ``files`` array that + ``_extract_post_content`` never reads, e.g.:: + + {"title": "", + "content": [[{"tag": "text", "text": "see attached"}]], + "files": [{"file_key": "file_v3_...", "file_name": "doc.pdf", + "is_folder": false}]} + + Handles the same three payload shapes as ``_extract_post_content``. + Returns ``(files, folders)``: entries with a usable ``file_key`` and + names of folders (``is_folder: true``), which are reported to the user + instead of attempting a file download. + """ + + def _files_in(block: Any) -> tuple[list[dict[str, Any]], list[str]] | None: + obj = _as_json_object(block) + if obj is None or "files" not in obj: + return None + files: list[dict[str, Any]] = [] + folders: list[str] = [] + for item in _as_json_list(obj.get("files")) or []: + entry = _as_json_object(item) + if entry is None: + continue + if entry.get("is_folder") is True: + name = entry.get("file_name") + folders.append(name if isinstance(name, str) and name else "folder") + elif isinstance(entry.get("file_key"), str) and entry["file_key"]: + files.append(entry) + return files, folders + + root = content_json + post = _as_json_object(root.get("post")) + if post is not None: + root = post + + found = _files_in(root) + if found is not None: + return found + + for key in ("zh_cn", "en_us", "ja_jp"): + found = _files_in(root.get(key)) + if found is not None: + return found + for val in root.values(): + found = _files_in(val) + if found is not None: + return found + + return [], [] + + _ONBOARD_ACCOUNTS_URLS = { "feishu": "https://accounts.feishu.cn", "lark": "https://accounts.larksuite.com", @@ -1775,7 +1833,8 @@ class FeishuChannel(BaseChannel): return None, f"[{msg_type}: download failed]" if not filename: - filename = fallback_filename + supplied_name = content_json.get("file_name") + filename = supplied_name if isinstance(supplied_name, str) and supplied_name else fallback_filename # Feishu voice messages are opus in OGG container. # Use .ogg extension for better Whisper compatibility. @@ -2584,6 +2643,20 @@ class FeishuChannel(BaseChannel): if file_path: media_paths.append(file_path) content_parts.append(content_text) + # Some posts include files alongside the text and images. + post_files, post_folders = _extract_post_attachments(content_json) + for folder_name in post_folders: + content_parts.append( + f"[folder: {folder_name} — folder attachments cannot be downloaded; " + "ask the user to send a zip archive]" + ) + for entry in post_files: + file_path, content_text = await self._download_and_save_media( + "file", entry, message_id + ) + if file_path: + media_paths.append(file_path) + content_parts.append(content_text) elif msg_type in ("image", "audio", "file", "media"): file_path, content_text = await self._download_and_save_media( diff --git a/nanobot/channels/feishu/tests/test_feishu_reply.py b/nanobot/channels/feishu/tests/test_feishu_reply.py index 5dd7c3c21..e70129010 100644 --- a/nanobot/channels/feishu/tests/test_feishu_reply.py +++ b/nanobot/channels/feishu/tests/test_feishu_reply.py @@ -761,6 +761,57 @@ async def test_on_message_keeps_longer_mention_key_that_shares_bot_prefix() -> N assert captured[0]["content"] == "@Alice (ou_alice) /new @nanobot (ou_bot)" +@pytest.mark.asyncio +async def test_post_files_download_and_reach_inbound_message(monkeypatch, tmp_path) -> None: + channel = _make_feishu_channel() + channel._processed_message_ids.clear() + channel._add_reaction = AsyncMock(return_value=None) + monkeypatch.setattr(feishu, "get_media_dir", lambda _channel: tmp_path) + channel._download_file_sync = MagicMock(return_value=(b"pdf content", None)) + payload = { + "content": [[{"tag": "text", "text": "Please read"}]], + "files": [{"file_key": "file_test", "file_name": "notice.pdf", "is_folder": False}], + } + + await channel._on_message(_make_feishu_event( + message_id="om_post_file", msg_type="post", content=json.dumps(payload), + )) + + inbound = await asyncio.wait_for(channel.bus.consume_inbound(), timeout=1) + saved = tmp_path / "notice.pdf" + channel._download_file_sync.assert_called_once_with("om_post_file", "file_test", "file") + assert saved.read_bytes() == b"pdf content" + assert inbound.media == [str(saved)] + assert "Please read" in inbound.content + assert str(saved) in inbound.content + + +@pytest.mark.asyncio +async def test_post_folder_and_failed_file_are_reported_without_media() -> None: + channel = _make_feishu_channel() + channel._processed_message_ids.clear() + channel._add_reaction = AsyncMock(return_value=None) + channel._download_file_sync = MagicMock(return_value=(None, None)) + payload = { + "content": [[{"tag": "text", "text": "Please read"}]], + "files": [ + {"file_name": "project", "is_folder": True}, + {"file_key": "file_bad", "file_name": "broken.pdf", "is_folder": False}, + ], + } + + await channel._on_message(_make_feishu_event( + message_id="om_post_failure", msg_type="post", content=json.dumps(payload), + )) + + inbound = await asyncio.wait_for(channel.bus.consume_inbound(), timeout=1) + channel._download_file_sync.assert_called_once_with("om_post_failure", "file_bad", "file") + assert inbound.media == [] + assert "project" in inbound.content + assert "zip" in inbound.content + assert "download failed" in inbound.content + + @pytest.mark.asyncio async def test_on_message_audio_publishes_downloaded_path_and_transcription() -> None: channel = _make_feishu_channel() diff --git a/tests/channels/test_feishu_post_files.py b/tests/channels/test_feishu_post_files.py new file mode 100644 index 000000000..c697dd21d --- /dev/null +++ b/tests/channels/test_feishu_post_files.py @@ -0,0 +1,110 @@ +from __future__ import annotations + +import json + +from nanobot.channels.feishu import runtime as feishu_runtime + +# Payloads captured from a real p2p chat (file keys replaced with +# placeholders). Sending text + a file together makes the Feishu client +# deliver ONE post message whose attachments live in a top-level "files" +# array; before this was handled the attachment was silently dropped. +_POST_WITH_FILE = json.loads( + '{"title": "",' + ' "content": [[{"tag": "text", "text": "see attached", "style": []}]],' + ' "content_v2": [[{"tag": "text", "text": "see attached", "style": []}]],' + ' "files": [{"file_key": "file_v3_00175_key",' + ' "file_name": "notice.pdf", "is_folder": false}]}' +) + +_POST_WITH_FOLDER = json.loads( + '{"title": "",' + ' "content": [[{"tag": "text", "text": "my project", "style": []}]],' + ' "files": [{"file_key": "file_v3_0116t_key",' + ' "file_name": "first-flask", "is_folder": true}]}' +) + +_POST_LOCALIZED = { + "zh_cn": { + "title": "", + "content": [[{"tag": "text", "text": "附件"}]], + "files": [ + {"file_key": "file_localized", "file_name": "成绩.pdf", "is_folder": False} + ], + } +} + +_POST_WRAPPED = { + "post": { + "zh_cn": { + "title": "", + "content": [[{"tag": "text", "text": "wrapped"}]], + "files": [ + {"file_key": "file_wrapped", "file_name": "a.txt", "is_folder": False} + ], + } + } +} + +_POST_WITHOUT_FILES = { + "title": "", + "content": [[{"tag": "text", "text": "plain text only"}]], +} + + +def test_extracts_file_from_direct_post_payload() -> None: + files, folders = feishu_runtime._extract_post_attachments(_POST_WITH_FILE) + assert folders == [] + assert len(files) == 1 + assert files[0]["file_key"] == "file_v3_00175_key" + assert files[0]["file_name"] == "notice.pdf" + + +def test_folder_is_reported_for_graceful_fallback_not_download() -> None: + files, folders = feishu_runtime._extract_post_attachments(_POST_WITH_FOLDER) + assert files == [] + assert folders == ["first-flask"] + + +def test_extracts_files_from_localized_payload() -> None: + files, folders = feishu_runtime._extract_post_attachments(_POST_LOCALIZED) + assert folders == [] + assert [f["file_key"] for f in files] == ["file_localized"] + + +def test_extracts_files_from_post_envelope_payload() -> None: + files, folders = feishu_runtime._extract_post_attachments(_POST_WRAPPED) + assert folders == [] + assert [f["file_key"] for f in files] == ["file_wrapped"] + + +def test_returns_empty_when_payload_has_no_files() -> None: + assert feishu_runtime._extract_post_attachments(_POST_WITHOUT_FILES) == ([], []) + assert feishu_runtime._extract_post_attachments({}) == ([], []) + + +def test_skips_entries_without_usable_file_key() -> None: + payload = { + "content": [], + "files": [ + {"file_name": "no-key.pdf", "is_folder": False}, + {"file_key": "", "is_folder": False}, + "not-a-dict", + {"file_key": "file_ok", "file_name": "ok.pdf", "is_folder": False}, + ], + } + files, folders = feishu_runtime._extract_post_attachments(payload) + assert folders == [] + assert [f["file_key"] for f in files] == ["file_ok"] + + +def test_folder_without_name_gets_placeholder() -> None: + payload = {"content": [], "files": [{"file_key": "file_f", "is_folder": True}]} + _, folders = feishu_runtime._extract_post_attachments(payload) + assert folders == ["folder"] + + +def test_caption_still_extracted_alongside_files() -> None: + """Regression guard: attachment handling must not break text/images.""" + text, images = feishu_runtime._extract_post_content(_POST_WITH_FILE) + assert text == "see attached" + assert images == []