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

特性:飞书通道支持文件上传和下载

liubuyu128d5db88f471
diff --git a/jiuwenclaw/channel/feishu.py b/jiuwenclaw/channel/feishu.py
index 0730575fad..78f545e16b 100644
--- a/jiuwenclaw/channel/feishu.py
+++ b/jiuwenclaw/channel/feishu.py
@@ -17,6 +17,12 @@ from pydantic import BaseModel, Field
from jiuwenclaw.channel.base import RobotMessageRouter, BaseChannel
from jiuwenclaw.schema.message import Message, ReqMethod, EventType
+from jiuwenclaw.channel.feishu_file_service import (
+ FeishuFileService,
+ is_image_file,
+ is_audio_file,
+ is_video_file,
+)
@@ -37,6 +43,12 @@ class FeishuConfig(BaseModel):
channel_id: str = "feishu" # ChannelManager 路由键,支持多实例
bot_key: str = "" # 企业飞书多 bot 配置键(仅 feishu_enterprise 使用)
+ # 文件处理配置
+ max_download_size: int = 100 * 1024 * 1024 # 最大下载文件大小(默认100MB)
+ download_timeout: int = 60 # 下载超时时间(秒)
+ enable_file_upload: bool = True # 是否启用文件上传功能
+ temp_file_dir: str = "" # 临时文件存储目录,默认使用工作空间
+
try:
import lark_oapi as lark
@@ -97,6 +109,19 @@ class FeishuInboundMessage:
user_id: str | None = None
bot_id: str | None = None
metadata: dict[str, Any] | None = None
+ params: dict[str, Any] | None = None
+
+
+@dataclass
+class FeishuMessageSendRequest:
+ """飞书消息发送请求参数封装。"""
+
+ receive_id: str
+ id_type: str
+ msg_type: str
+ content: str
+ log_label: str = ""
+ max_retries: int = 3
class FeishuChannel(BaseChannel):
@@ -140,6 +165,11 @@ class FeishuChannel(BaseChannel):
self._stopping = False
# 按 request_id 聚合 chat.delta,避免同一任务被拆分成多条消息发送到飞书。
self._stream_text_buffers: dict[str, str] = {}
+ # 文件服务(延迟初始化)
+ self._file_service: FeishuFileService | None = None
+ # 按 request_id 记录已通过 chat.file 发送的文件路径,用于兜底去重
+ # key=request_id, value=set of absolute file paths
+ self._sent_file_paths_by_req: dict[str, set[str]] = {}
@property
def channel_id(self) -> str:
@@ -171,12 +201,13 @@ class FeishuChannel(BaseChannel):
"""
# Message 的 id 必须全局唯一;多 bot 同群时飞书消息 message_id 相同,需加上 channel_id 防止冲突。
msg_id = f"{self.channel_id}:{inbound.message_id}"
+ params = {"content": inbound.content, "query": inbound.content} if inbound.params is None else inbound.params
msg = Message(
id=msg_id,
type="req",
channel_id=self.channel_id,
session_id=str(inbound.chat_id),
- params={"content": inbound.content, "query": inbound.content},
+ params=params,
timestamp=time.time(), ok=True,
provider=self.name,
chat_id=str(inbound.chat_id or ""),
@@ -229,6 +260,14 @@ class FeishuChannel(BaseChannel):
.log_level(lark.LogLevel.INFO)
.build()
)
+ # 初始化文件服务
+ from jiuwenclaw.utils import get_workspace_dir
+ workspace_dir = self.config.temp_file_dir or str(get_workspace_dir())
+ self._file_service = FeishuFileService(
+ api_client=self._api_client,
+ config=self.config,
+ workspace_dir=workspace_dir,
+ )
def _start_websocket_in_thread(self) -> None:
"""在独立线程中启动WebSocket客户端,避免事件循环冲突。"""
@@ -271,6 +310,7 @@ class FeishuChannel(BaseChannel):
config["verification_token"],
)
.register_p2_im_message_receive_v1(self._on_message_sync)
+ .register_p2_im_message_message_read_v1(self._on_message_read_event)
.build()
)
@@ -474,13 +514,17 @@ class FeishuChannel(BaseChannel):
Returns:
dict: 飞书表格元素,解析失败返回None
"""
- lines = [l.strip() for l in table_text.strip().split("\n") if l.strip()]
+ lines = [
+ line.strip() for line in table_text.strip().split("\n") if line.strip()
+ ]
if len(lines) < 3:
return None
- split = lambda l: [c.strip() for c in l.strip("|").split("|")]
- headers = split(lines[0])
- rows = [split(l) for l in lines[2:]]
+ def split_line(line):
+ return [c.strip() for c in line.strip("|").split("|")]
+
+ headers = split_line(lines[0])
+ rows = [split_line(line) for line in lines[2:]]
columns = [
{"tag": "column", "name": f"c{i}", "display_name": h, "width": "auto"}
@@ -643,31 +687,16 @@ 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)
+ # 处理文件消息
+ if msg.event_type == EventType.CHAT_FILE:
+ if self.config.enable_file_upload and self._file_service:
+ await self._send_file_message(msg)
+ return
+
+ # 处理媒体消息
+ if msg.event_type == EventType.CHAT_MEDIA:
+ if self.config.enable_file_upload and self._file_service:
+ await self._send_media_message(msg)
return
# 流式增量:先缓存;若开启流式则实时发送,否则仅缓存不发送。
@@ -727,12 +756,81 @@ class FeishuChannel(BaseChannel):
logger.warning("飞书发送:消息内容为空,跳过发送")
return
+ # 兜底:chat.final 中提到了 workspace 文件但 LLM 未调用 send_file_to_user 时,
+ # 自动提取文件路径并发送,避免用户收不到文件。
+ if (
+ event_name == "chat.final"
+ and self.config.enable_file_upload
+ and self._file_service
+ ):
+ req_id = str(getattr(msg, "id", "") or "")
+ already_sent = self._sent_file_paths_by_req.get(req_id, set())
+ detected_files = [
+ fp for fp in self._detect_workspace_files(content_str)
+ if os.path.abspath(fp) not in already_sent
+ ]
+ if detected_files:
+ logger.info(
+ "飞书兜底文件发送:从 chat.final 中检测到 %d 个未发送文件: %s",
+ len(detected_files),
+ detected_files,
+ )
+ for fp in detected_files:
+ try:
+ if is_image_file(fp):
+ await self._send_image_message(receive_id, id_type, fp)
+ elif is_audio_file(fp):
+ await self._send_audio_message(receive_id, id_type, fp, os.path.basename(fp))
+ elif is_video_file(fp):
+ await self._send_video_message(receive_id, id_type, fp, os.path.basename(fp))
+ else:
+ await self._send_file_card(receive_id, id_type, fp, os.path.basename(fp))
+ except Exception as file_err:
+ logger.error("飞书兜底文件发送失败: %s %s", fp, file_err)
+
card_content = self._build_card_content(content_str)
await self._send_feishu_message(receive_id, id_type, card_content, msg.id)
except Exception as e:
logger.error(f"发送飞书消息时发生异常: {e}")
+ def _detect_workspace_files(self, text: str) -> list[str]:
+ """从文本中提取 workspace 下实际存在的文件路径。
+
+ 用于兜底检测 LLM 提到但未通过 send_file_to_user 发送的文件。
+ 支持两种模式:
+ 1. 完整绝对路径:/home/xxx/.jiuwenclaw/agent/workspace/xxx.docx
+ 2. 仅文件名:'xxx.docx' 或 "xxx.docx"——在 workspace 目录下查找
+ """
+ from jiuwenclaw.utils import get_workspace_dir
+ workspace_dir = str(get_workspace_dir())
+
+ seen: set[str] = set()
+ result: list[str] = []
+
+ # 模式1:完整路径
+ abs_pattern = r"(/home/[^\s\[\]\"']+\.jiuwenclaw/agent/workspace/[^\s\[\]\"']+\.\w+)"
+ for m in re.findall(abs_pattern, text):
+ m = m.rstrip(".,;:!?)")
+ if m not in seen and os.path.isfile(m):
+ seen.add(m)
+ result.append(m)
+
+ # 模式2:从引号或书名号中提取文件名,在 workspace 下查找
+ # 匹配 '文件名.ext'、"文件名.ext"、《文件名.ext》
+ name_pattern = (
+ r"""['"'《]([^'"'》\n]+\."""
+ r"""(?:docx?|xlsx?|pptx?|pdf|csv|txt|md|zip|tar|gz|"""
+ r"""png|jpg|jpeg|gif|mp3|mp4|wav|opus))['"'》]"""
+ ) # noqa: E501
+ for fname in re.findall(name_pattern, text, re.IGNORECASE):
+ fpath = os.path.join(workspace_dir, fname)
+ if fpath not in seen and os.path.isfile(fpath):
+ seen.add(fpath)
+ result.append(fpath)
+
+ return result
+
@staticmethod
def _merge_stream_and_final_content(stream_text: str, final_text: str) -> str:
"""合并流式累积文本和 final 文本,优先保留信息更完整的一侧。"""
@@ -769,6 +867,7 @@ class FeishuChannel(BaseChannel):
# 1) 优先用 metadata 中的平台身份
feishu_chat_id = (meta.get("feishu_chat_id") or "").strip()
feishu_open_id = (meta.get("feishu_open_id") or "").strip()
+
if feishu_chat_id:
receive_id = feishu_chat_id
id_type = "chat_id" if feishu_chat_id.startswith("oc_") else "open_id"
@@ -777,8 +876,6 @@ class FeishuChannel(BaseChannel):
id_type = "open_id"
# 2) 若 metadata 中没有平台身份,则使用配置中的 chat_id 作为固定推送目标
- # print('this is in _extract_receive_info')
- logger.info('this is in _extract_receive_info, chat_id is %s', self.config.chat_id)
if not receive_id:
cfg_chat_id = getattr(self.config, "chat_id", "") or ""
cfg_chat_id = cfg_chat_id.strip()
@@ -793,6 +890,7 @@ class FeishuChannel(BaseChannel):
id_type = "chat_id"
else:
id_type = "open_id"
+ logger.warning(f"飞书回发未找到有效平台身份,使用回退值: {receive_id}")
return receive_id, id_type
@@ -1065,43 +1163,26 @@ class FeishuChannel(BaseChannel):
async def _send_feishu_message(
self, receive_id: str, id_type: str, content: str, msg_id: str,
- msg_type: str = "interactive",
) -> Any:
"""
- 发送飞书消息。
+ 发送飞书卡片消息(异步,在线程池中执行同步 SDK 调用)。
Args:
receive_id: 接收者ID
id_type: ID类型
content: 消息内容(JSON字符串)
msg_id: 发送消息ID(用于日志)
- msg_type: 消息类型(默认interactive,也支持image/file等)
"""
- request = (
- CreateMessageRequest.builder()
- .receive_id_type(id_type)
- .request_body(
- CreateMessageRequestBody.builder()
- .receive_id(receive_id)
- .msg_type(msg_type)
- .content(content)
- .build()
+ await self._create_and_send_message(
+ FeishuMessageSendRequest(
+ receive_id=receive_id,
+ id_type=id_type,
+ msg_type="interactive",
+ content=content,
+ log_label=msg_id,
)
- .build()
)
- response = self._api_client.im.v1.message.create(request)
-
- if not response.success():
- logger.warning(
- f"发送飞书消息失败: 错误码={response.code}, "
- f"消息={response.msg}, 日志ID={response.get_log_id()}"
- )
- return None
- else:
- logger.debug("已向 %s 发送飞书消息", msg_id)
- return response
-
def _on_message_sync(self, data: "P2ImMessageReceiveV1") -> None:
"""
传入消息的同步处理器(从WebSocket线程调用)。
@@ -1137,9 +1218,9 @@ class FeishuChannel(BaseChannel):
# 后台添加"已读"反应,不阻塞消息处理
asyncio.create_task(self._add_reaction(message.message_id, "THUMBSUP"))
- # 解析消息内容
- content = self._parse_message_content(message)
- if not content:
+ # 解析消息内容(支持文件类型)
+ content, file_info = await self._parse_message_content_with_file(message)
+ if not content and not file_info:
return
# 提取发送者open_id
@@ -1180,6 +1261,11 @@ class FeishuChannel(BaseChannel):
# 不影响正常收消息
pass
+ # 构建消息参数
+ params = {"content": content, "query": content}
+ if file_info:
+ params["files"] = [file_info]
+
# 处理消息:将平台身份写入 metadata,供回发时使用(与 session_id 解耦,\new_session 后仍可正确回发)
inbound = FeishuInboundMessage(
message_id=message.message_id,
@@ -1194,13 +1280,27 @@ class FeishuChannel(BaseChannel):
"open_id": open_id,
"feishu_open_id": open_id,
"feishu_chat_id": getattr(message, "chat_id", None) or "",
+ **({"file_info": file_info} if file_info else {}),
},
+ params=params,
)
await self._handle_message(inbound)
except Exception as e:
logger.error(f"处理飞书消息时发生异常: {e}")
+ def _on_message_read_event(self, data: Any) -> None:
+ """
+ 处理飞书消息已读事件(空处理器,仅用于消除 SDK 日志警告)。
+
+ 飞书会在用户阅读消息后推送 im.message.message_read_v1 事件,
+ 但当前场景不需要处理此事件,注册空处理器避免 SDK 打印 ERROR 日志。
+
+ Args:
+ data: 飞书消息已读事件数据(忽略)
+ """
+ pass # 不处理,仅用于消除日志警告
+
def _is_duplicate_message(self, message_id: str) -> bool:
"""
检查消息是否重复。
@@ -1241,3 +1341,464 @@ class FeishuChannel(BaseChannel):
return message.content or ""
else:
return MSG_TYPE_MAP.get(msg_type, f"[{msg_type}]")
+
+ async def _parse_message_content_with_file(
+ self,
+ message: Any,
+ ) -> tuple[str, dict | None]:
+ """
+ 解析消息内容,支持文件类型(异步版本)。
+
+ Args:
+ message: 飞书消息对象
+
+ Returns:
+ tuple: (文本内容, 文件信息字典或None)
+ """
+ if not self._file_service:
+ return self._parse_message_content(message), None
+
+ msg_type = message.message_type
+
+ # 文本消息
+ if msg_type == "text":
+ try:
+ return json.loads(message.content).get("text", ""), None
+ except json.JSONDecodeError:
+ return message.content or "", None
+
+ # 图片消息
+ if msg_type == "image":
+ return await self._handle_image_message(message)
+
+ # 文件消息
+ if msg_type == "file":
+ return await self._handle_file_message(message)
+
+ # 音频消息
+ if msg_type == "audio":
+ return await self._handle_audio_message(message)
+
+ # 视频/媒体消息
+ if msg_type == "media":
+ return await self._handle_media_message(message)
+
+ # 贴纸消息
+ if msg_type == "sticker":
+ return "[贴纸]", None
+
+ # 其他类型
+ return MSG_TYPE_MAP.get(msg_type, f"[{msg_type}]"), None
+
+ async def _handle_image_message(self, message: Any) -> tuple[str, dict | None]:
+ """处理图片消息。"""
+ try:
+ content = json.loads(message.content)
+ image_key = content.get("image_key")
+
+ if not image_key:
+ return "[图片]", None
+
+ # 下载图片
+ file_info = await self._file_service.download_image(
+ file_key=image_key,
+ message_id=message.message_id,
+ )
+
+ if file_info:
+ return "[图片]", file_info
+
+ return "[图片下载失败]", None
+
+ except Exception as e:
+ logger.error(f"处理图片消息失败: {e}")
+ return "[图片]", None
+
+ async def _handle_file_message(self, message: Any) -> tuple[str, dict | None]:
+ """处理文件消息。"""
+ try:
+ content = json.loads(message.content)
+ file_key = content.get("file_key")
+ file_name = content.get("file_name", "unknown")
+ file_size = content.get("file_size", 0)
+
+ logger.info(f"飞书文件消息: file_name={file_name}, file_size={file_size}, file_key={file_key}")
+
+ if not file_key:
+ return f"[文件: {file_name}]", None
+
+ # 检查文件大小限制
+ max_size = self.config.max_download_size
+ if file_size > max_size:
+ logger.warning(f"文件过大,跳过下载: {file_name} ({file_size} > {max_size})")
+ return f"[文件过大: {file_name}]", None
+
+ # 下载文件
+ logger.info(f"开始下载飞书文件: {file_name}")
+ file_info = await self._file_service.download_file_resource(
+ file_key=file_key,
+ message_id=message.message_id,
+ extra_info={"file_name": file_name, "file_size": file_size},
+ )
+
+ if file_info:
+ file_info["name"] = file_name
+ file_info["size"] = file_size
+ logger.info(f"飞书文件下载成功: {file_name}, path={file_info.get('path')}")
+ return f"[文件: {file_name}]", file_info
+
+ logger.warning(f"飞书文件下载失败: {file_name}")
+ return f"[文件下载失败: {file_name}]", None
+
+ except Exception as e:
+ logger.error(f"处理文件消息失败: {e}")
+ return "[文件]", None
+
+ async def _handle_audio_message(self, message: Any) -> tuple[str, dict | None]:
+ """处理音频消息。"""
+ try:
+ content = json.loads(message.content)
+ file_key = content.get("file_key")
+ duration = content.get("duration", 0)
+
+ if not file_key:
+ return "[音频]", None
+
+ # 下载音频
+ file_info = await self._file_service.download_audio(
+ file_key=file_key,
+ message_id=message.message_id,
+ )
+
+ if file_info:
+ duration_sec = duration / 1000
+ return f"[音频: {duration_sec:.1f}秒]", file_info
+
+ return "[音频下载失败]", None
+
+ except Exception as e:
+ logger.error(f"处理音频消息失败: {e}")
+ return "[音频]", None
+
+ async def _handle_media_message(self, message: Any) -> tuple[str, dict | None]:
+ """处理视频/媒体消息。"""
+ try:
+ content = json.loads(message.content)
+ file_key = content.get("file_key")
+ duration = content.get("duration", 0)
+
+ if not file_key:
+ return "[视频]", None
+
+ # 下载视频
+ file_info = await self._file_service.download_media(
+ file_key=file_key,
+ message_id=message.message_id,
+ )
+
+ if file_info:
+ duration_sec = duration / 1000
+ return f"[视频: {duration_sec:.1f}秒]", file_info
+
+ return "[视频下载失败]", None
+
+ except Exception as e:
+ logger.error(f"处理视频消息失败: {e}")
+ return "[视频]", None
+
+ def _extract_text_from_file(self, file_path: str, max_len: int = 50000) -> str | None:
+ """从文本文件中提取内容。"""
+ try:
+ with open(file_path, "r", encoding="utf-8") as f:
+ content = f.read(max_len + 1)
+ if len(content) > max_len:
+ content = content[:max_len] + "\n... [内容已截断]"
+ return content
+ except UnicodeDecodeError:
+ # 尝试其他编码
+ try:
+ with open(file_path, "r", encoding="gbk") as f:
+ content = f.read(max_len + 1)
+ if len(content) > max_len:
+ content = content[:max_len] + "\n... [内容已截断]"
+ return content
+ except Exception:
+ return None
+ except Exception as e:
+ logger.warning(f"提取文件内容失败: {e}")
+ return None
+
+ # ==================== 文件消息发送 ====================
+
+ async def _send_file_message(self, msg: Message) -> None:
+ """
+ 发送文件消息(支持图片/音频/视频/普通文件)。
+
+ Args:
+ msg: 包含文件信息的消息对象
+ """
+ payload = msg.payload if isinstance(msg.payload, dict) else {}
+ files = payload.get("files", [])
+
+ if not files:
+ logger.warning("飞书发送文件消息:无文件信息")
+ return
+
+ receive_id, id_type = self._extract_receive_info(msg)
+ logger.info(f"飞书发送文件消息: receive_id={receive_id}, id_type={id_type}")
+
+ for file_info in files:
+ # 支持两种格式:路径字符串 或 包含 path 字段的字典
+ if isinstance(file_info, dict):
+ file_path = file_info.get("path", "")
+ file_name = file_info.get("name", os.path.basename(file_path))
+ else:
+ file_path = str(file_info)
+ file_name = os.path.basename(file_path)
+
+ if not file_path or not os.path.exists(file_path):
+ logger.warning(f"飞书发送文件:文件不存在 {file_path}")
+ continue
+
+ req_id = str(getattr(msg, "id", "") or "")
+ if req_id:
+ self._sent_file_paths_by_req.setdefault(req_id, set()).add(
+ os.path.abspath(file_path)
+ )
+
+ if is_image_file(file_path):
+ await self._send_image_message(receive_id, id_type, file_path)
+ elif is_audio_file(file_path):
+ await self._send_audio_message(receive_id, id_type, file_path, file_name)
+ elif is_video_file(file_path):
+ await self._send_video_message(receive_id, id_type, file_path, file_name)
+ else:
+ await self._send_file_card(receive_id, id_type, file_path, file_name)
+
+ async def _create_and_send_message(
+ self,
+ request: FeishuMessageSendRequest,
+ ) -> None:
+ """构建并发送飞书消息(在线程池中执行同步 SDK 调用,支持重试)。"""
+ loop = asyncio.get_running_loop()
+
+ for attempt in range(request.max_retries):
+ try:
+ def _do_send():
+ req = (
+ CreateMessageRequest.builder()
+ .receive_id_type(request.id_type)
+ .request_body(
+ CreateMessageRequestBody.builder()
+ .receive_id(request.receive_id)
+ .msg_type(request.msg_type)
+ .content(request.content)
+ .build()
+ )
+ .build()
+ )
+ return self._api_client.im.v1.message.create(req)
+
+ response = await loop.run_in_executor(None, _do_send)
+
+ if not response.success():
+ logger.warning(
+ "飞书发送消息失败 (尝试 %d/%d, msg_type=%s%s): code=%s msg=%s",
+ attempt + 1, request.max_retries,
+ request.msg_type,
+ f" {request.log_label}" if request.log_label else "",
+ response.code,
+ response.msg,
+ )
+ if attempt < request.max_retries - 1:
+ await asyncio.sleep(1 * (attempt + 1))
+ continue
+ else:
+ logger.info("飞书消息发送成功: msg_type=%s%s", request.msg_type,
+ f" {request.log_label}" if request.log_label else "")
+ return
+
+ except Exception as e:
+ logger.warning(
+ "飞书发送消息异常 (尝试 %d/%d, msg_type=%s%s): %s",
+ attempt + 1, request.max_retries,
+ request.msg_type,
+ f" {request.log_label}" if request.log_label else "",
+ e,
+ )
+ if attempt < request.max_retries - 1:
+ await asyncio.sleep(1 * (attempt + 1))
+ continue
+ else:
+ logger.error("发送飞书消息异常: %s", e)
+
+ async def _send_image_message(
+ self,
+ receive_id: str,
+ id_type: str,
+ file_path: str,
+ ) -> None:
+ """
+ 发送图片消息。
+
+ 优先使用 image.create API(返回 image_key,发送 image 消息),
+ 失败时回退到 file.create API(发送 file 消息)。
+ """
+ try:
+ upload_result = await self._file_service.upload_image(file_path)
+ if not upload_result:
+ logger.error(f"飞书上传图片失败: {file_path}")
+ return
+
+ file_type = upload_result.get("file_type", "image")
+ image_key = upload_result.get("image_key")
+ file_key = upload_result.get("file_key")
+
+ if file_type == "image" and image_key:
+ content = json.dumps({"image_key": image_key}, ensure_ascii=False)
+ msg_type = "image"
+ elif file_key:
+ content = json.dumps({"file_key": file_key}, ensure_ascii=False)
+ msg_type = "file"
+ else:
+ logger.error(f"飞书上传图片返回无效: {upload_result}")
+ return
+
+ await self._create_and_send_message(
+ FeishuMessageSendRequest(
+ receive_id=receive_id,
+ id_type=id_type,
+ msg_type=msg_type,
+ content=content,
+ log_label=os.path.basename(file_path),
+ )
+ )
+
+ except Exception as e:
+ logger.error(f"发送飞书图片消息异常: {e}")
+
+ async def _send_audio_message(
+ self,
+ receive_id: str,
+ id_type: str,
+ file_path: str,
+ file_name: str,
+ ) -> None:
+ """
+ 发送音频消息。
+
+ 若文件为 .opus 格式(飞书原生),使用 msg_type=audio 发送(可在线播放);
+ 其他格式降级为普通文件消息。
+ """
+ try:
+ upload_result = await self._file_service.upload_file_resource(file_path)
+ if not upload_result:
+ logger.error(f"飞书上传音频失败: {file_path}")
+ return
+
+ file_key = upload_result.get("file_key")
+ if not file_key:
+ logger.error(f"飞书上传音频返回无效: {file_path}")
+ return
+
+ feishu_file_type = upload_result.get("file_type", "stream")
+
+ if feishu_file_type == "opus":
+ # opus 格式支持在线播放
+ content = json.dumps({"file_key": file_key}, ensure_ascii=False)
+ msg_type = "audio"
+ else:
+ # 其他音频格式作为普通文件发送
+ content = json.dumps({"file_key": file_key}, ensure_ascii=False)
+ msg_type = "file"
+
+ await self._create_and_send_message(
+ FeishuMessageSendRequest(
+ receive_id=receive_id,
+ id_type=id_type,
+ msg_type=msg_type,
+ content=content,
+ log_label=file_name,
+ )
+ )
+
+ except Exception as e:
+ logger.error(f"发送飞书音频消息异常: {e}")
+
+ async def _send_video_message(
+ self,
+ receive_id: str,
+ id_type: str,
+ file_path: str,
+ file_name: str,
+ ) -> None:
+ """
+ 发送视频消息(msg_type=media,支持在线播放)。
+
+ 飞书 media 消息内容:{"file_key": "..."}(thumbnail 可选,此处省略)
+ """
+ try:
+ upload_result = await self._file_service.upload_file_resource(file_path)
+ if not upload_result:
+ logger.error(f"飞书上传视频失败: {file_path}")
+ return
+
+ file_key = upload_result.get("file_key")
+ if not file_key:
+ logger.error(f"飞书上传视频返回无效: {file_path}")
+ return
+
+ content = json.dumps({"file_key": file_key}, ensure_ascii=False)
+
+ await self._create_and_send_message(
+ FeishuMessageSendRequest(
+ receive_id=receive_id,
+ id_type=id_type,
+ msg_type="media",
+ content=content,
+ log_label=file_name,
+ )
+ )
+
+ except Exception as e:
+ logger.error(f"发送飞书视频消息异常: {e}")
+
+ async def _send_file_card(
+ self,
+ receive_id: str,
+ id_type: str,
+ file_path: str,
+ file_name: str,
+ ) -> None:
+ """发送普通文件消息(msg_type=file)。"""
+ try:
+ upload_result = await self._file_service.upload_file_resource(file_path)
+ if not upload_result:
+ logger.error(f"飞书上传文件失败: {file_path}")
+ return
+
+ file_key = upload_result.get("file_key")
+ if not file_key:
+ logger.error(f"飞书上传文件返回无效: {file_path}")
+ return
+
+ content = json.dumps({"file_key": file_key}, ensure_ascii=False)
+
+ await self._create_and_send_message(
+ FeishuMessageSendRequest(
+ receive_id=receive_id,
+ id_type=id_type,
+ msg_type="file",
+ content=content,
+ log_label=file_name,
+ )
+ )
+
+ except Exception as e:
+ logger.error(f"发送飞书文件消息异常: {e}")
+
+ async def _send_media_message(self, msg: Message) -> None:
+ """
+ 发送媒体消息(video/audio)入口,与文件消息统一处理。
+ """
+ await self._send_file_message(msg)
\ No newline at end of file
diff --git a/jiuwenclaw/channel/feishu_file_service.py b/jiuwenclaw/channel/feishu_file_service.py
new file mode 100644
index 0000000000..6dddfe35e7
--- /dev/null
+++ b/jiuwenclaw/channel/feishu_file_service.py
@@ -0,0 +1,720 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""飞书文件服务,负责文件的下载与上传。"""
+
+import asyncio
+import mimetypes
+import os
+import re
+import time
+from typing import Any
+
+from jiuwenclaw.utils import logger
+
+# 类型别名,用于类型提示
+FeishuConfig = Any # 避免循环导入
+
+# ──────────────────────────────────────────────────────────────────────────────
+# 飞书 file.create API 支持的 file_type 枚举
+# https://open.feishu.cn/document/server-docs/im-v1/file/create
+# ──────────────────────────────────────────────────────────────────────────────
+_EXT_TO_FEISHU_FILE_TYPE: dict[str, str] = {
+ # 音频 —— 飞书原生格式为 opus,其他音频作为 stream(可下载,不可在线播放)
+ ".opus": "opus",
+ ".mp3": "stream",
+ ".wav": "stream",
+ ".flac": "stream",
+ ".ogg": "stream",
+ ".aac": "stream",
+ ".m4a": "stream",
+ # 视频
+ ".mp4": "mp4",
+ ".mov": "mp4",
+ ".avi": "mp4",
+ ".mkv": "mp4",
+ # 文档
+ ".pdf": "pdf",
+ ".doc": "doc",
+ ".docx": "doc",
+ ".xls": "xls",
+ ".xlsx": "stream",
+ ".ppt": "ppt",
+ ".pptx": "stream",
+}
+
+# 图片扩展名集合(走 image.create 接口,不走 file.create)
+_IMAGE_EXTENSIONS: frozenset[str] = frozenset(
+ {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", ".tiff", ".svg"}
+)
+
+# 音频扩展名集合(可尝试以 audio msg_type 发送)
+_AUDIO_EXTENSIONS: frozenset[str] = frozenset(
+ {".opus", ".mp3", ".wav", ".flac", ".ogg", ".aac", ".m4a"}
+)
+
+# 视频扩展名集合(以 media msg_type 发送)
+_VIDEO_EXTENSIONS: frozenset[str] = frozenset(
+ {".mp4", ".mov", ".avi", ".mkv", ".flv", ".wmv", ".webm"}
+)
+
+
+def get_feishu_file_type(file_path: str) -> str:
+ """根据文件扩展名返回飞书 file.create 所需的 file_type。"""
+ ext = os.path.splitext(file_path)[1].lower()
+ return _EXT_TO_FEISHU_FILE_TYPE.get(ext, "stream")
+
+
+def is_image_file(file_path: str) -> bool:
+ """判断是否为图片文件。"""
+ ext = os.path.splitext(file_path)[1].lower()
+ return ext in _IMAGE_EXTENSIONS
+
+
+def is_audio_file(file_path: str) -> bool:
+ """判断是否为音频文件。"""
+ ext = os.path.splitext(file_path)[1].lower()
+ return ext in _AUDIO_EXTENSIONS
+
+
+def is_video_file(file_path: str) -> bool:
+ """判断是否为视频文件。"""
+ ext = os.path.splitext(file_path)[1].lower()
+ return ext in _VIDEO_EXTENSIONS
+
+
+class FeishuFileService:
+ """
+ 飞书文件服务,负责文件的下载与上传。
+
+ 功能:
+ - 从飞书下载用户发送的文件(图片/音频/视频/普通文件)
+ - 上传文件到飞书用于发送
+ """
+
+ def __init__(
+ self,
+ api_client: Any,
+ config: FeishuConfig,
+ workspace_dir: str,
+ ):
+ """
+ 初始化文件服务。
+
+ Args:
+ api_client: 飞书 API 客户端(lark.Client 实例)
+ config: 飞书通道配置(FeishuConfig)
+ workspace_dir: 工作空间目录
+ """
+ self._api_client = api_client
+ self._config = config
+ self._workspace_dir = workspace_dir
+ self._download_semaphore = asyncio.Semaphore(3) # 限制并发下载数
+
+ # ──────────────────────────────────────────────────────────────────────────
+ # 工具方法
+ # ──────────────────────────────────────────────────────────────────────────
+ @classmethod
+ def _ensure_dir(cls, path: str) -> None:
+ """确保目录存在。"""
+ os.makedirs(path, exist_ok=True)
+
+ def _get_download_dir(self, file_type: str) -> str:
+ """获取下载目录路径,并确保目录存在。"""
+ base_dir = os.path.join(self._workspace_dir, "feishu_files", "downloads", file_type)
+ self._ensure_dir(base_dir)
+ return base_dir
+
+ @classmethod
+ def _generate_local_filename(
+ cls,
+ message_id: str,
+ file_key: str,
+ original_name: str = "",
+ extension: str = "",
+ ) -> str:
+ """
+ 生成本地文件名,确保唯一性。
+
+ 格式: {message_id}_{safe_file_key}{ext}
+ """
+ if not extension and original_name:
+ extension = os.path.splitext(original_name)[1]
+
+ # 清理 file_key 中的特殊字符,取前 20 位
+ safe_key = re.sub(r"[^\w\-]", "", file_key[:20])
+
+ return f"{message_id}_{safe_key}{extension}"
+
+ @classmethod
+ def _guess_mime_type(cls, file_name: str) -> str:
+ """根据文件名推断 MIME 类型。"""
+ mime_type, _ = mimetypes.guess_type(file_name)
+ return mime_type or "application/octet-stream"
+
+ def _get_download_timeout(self) -> int:
+ """获取下载超时时间(秒)。"""
+ return getattr(self._config, "download_timeout", 60)
+
+ # ──────────────────────────────────────────────────────────────────────────
+ # 文件下载(核心工具)
+ # ──────────────────────────────────────────────────────────────────────────
+
+ async def _download_with_retry(
+ self,
+ download_func: Any,
+ max_retries: int = 3,
+ ) -> bytes | None:
+ """
+ 带重试的文件下载(在线程池中执行同步 lark_oapi 调用)。
+
+ Args:
+ download_func: 无参可调用对象,执行后返回 lark_oapi response
+ max_retries: 最大重试次数
+
+ Returns:
+ 文件内容 bytes,失败返回 None
+ """
+ loop = asyncio.get_running_loop()
+ timeout = self._get_download_timeout()
+
+ for attempt in range(max_retries):
+ try:
+ # 在线程池执行同步 SDK 调用,并加超时控制
+ response = await asyncio.wait_for(
+ loop.run_in_executor(None, download_func),
+ timeout=timeout,
+ )
+
+ if not response.success():
+ logger.warning(
+ "飞书文件下载失败 (尝试 %d/%d): code=%s msg=%s",
+ attempt + 1, max_retries,
+ response.code, response.msg,
+ )
+ if attempt < max_retries - 1:
+ await asyncio.sleep(1 * (attempt + 1))
+ continue
+
+ # 兼容不同的响应结构(lark_oapi 各版本差异)
+ file_content: bytes | None = None
+ if hasattr(response, "file") and response.file:
+ file_content = response.file.read()
+ elif hasattr(response, "data") and response.data:
+ if hasattr(response.data, "file") and response.data.file:
+ file_content = response.data.file.read()
+
+ if file_content:
+ return file_content
+
+ # 响应成功但内容为空——视为可重试的瞬时错误
+ logger.warning(
+ "飞书文件下载响应中无文件内容 (尝试 %d/%d),稍后重试",
+ attempt + 1, max_retries,
+ )
+ if attempt < max_retries - 1:
+ await asyncio.sleep(1 * (attempt + 1))
+
+ except asyncio.TimeoutError:
+ logger.warning(
+ "飞书文件下载超时 %ds (尝试 %d/%d)",
+ timeout, attempt + 1, max_retries,
+ )
+ if attempt < max_retries - 1:
+ await asyncio.sleep(2 * (attempt + 1))
+ except Exception as e:
+ logger.error(
+ "飞书文件下载异常 (尝试 %d/%d): %s",
+ attempt + 1, max_retries, e,
+ )
+ if attempt < max_retries - 1:
+ await asyncio.sleep(1 * (attempt + 1))
+
+ return None
+
+ # ──────────────────────────────────────────────────────────────────────────
+ # 各类型下载实现
+ # ──────────────────────────────────────────────────────────────────────────
+
+ async def _download_image_internal(
+ self,
+ image_key: str,
+ message_id: str,
+ ) -> dict | None:
+ """
+ 下载图片文件。
+
+ 用户发送的图片必须通过 messageResource 接口下载(而非 image.get,
+ 后者仅支持应用自己上传的图片)。
+ """
+ try:
+ from lark_oapi.api.im.v1 import GetMessageResourceRequest
+
+ def _do_download():
+ request = (
+ GetMessageResourceRequest.builder()
+ .message_id(message_id)
+ .file_key(image_key)
+ .type("image")
+ .build()
+ )
+ return self._api_client.im.v1.message_resource.get(request)
+
+ file_content = await self._download_with_retry(_do_download)
+ if not file_content:
+ return None
+
+ # 通过文件头魔数推断图片格式
+ extension = self._detect_image_extension(file_content)
+
+ local_name = self._generate_local_filename(
+ message_id, image_key, extension=extension
+ )
+ download_dir = self._get_download_dir("images")
+ file_path = os.path.join(download_dir, local_name)
+
+ with open(file_path, "wb") as f:
+ f.write(file_content)
+
+ logger.info("飞书图片下载成功: %s", file_path)
+
+ return {
+ "path": file_path,
+ "name": local_name,
+ "size": len(file_content),
+ "mime_type": self._guess_mime_type(local_name),
+ "file_key": image_key,
+ "file_category": "image",
+ }
+
+ except Exception as e:
+ logger.error("下载飞书图片失败: %s", e)
+ return None
+
+ async def download_image(self, file_key: str, message_id: str) -> dict | None:
+ """下载图片文件(公开接口)。"""
+ return await self._download_image_internal(file_key, message_id)
+
+ async def _download_file_internal(
+ self,
+ file_key: str,
+ message_id: str,
+ extra_info: dict[str, Any] | None = None,
+ ) -> dict | None:
+ """
+ 下载普通文件。
+
+ 用户发送的文件通过 messageResource 接口下载。
+ """
+ try:
+ from lark_oapi.api.im.v1 import GetMessageResourceRequest
+
+ extra_info = extra_info or {}
+ original_name = extra_info.get("file_name", "")
+
+ # 尝试下载文件,即使文件大小为0(可能是飞书端显示问题)
+ def _do_download():
+ request = (
+ GetMessageResourceRequest.builder()
+ .message_id(message_id)
+ .file_key(file_key)
+ .type("file")
+ .build()
+ )
+ return self._api_client.im.v1.message_resource.get(request)
+
+ file_content = await self._download_with_retry(_do_download)
+ if not file_content:
+ return None
+
+ extension = os.path.splitext(original_name)[1] if original_name else ""
+ local_name = self._generate_local_filename(
+ message_id, file_key, original_name, extension
+ )
+ download_dir = self._get_download_dir("files")
+ file_path = os.path.join(download_dir, local_name)
+
+ # 处理文件名冲突
+ if os.path.exists(file_path):
+ base, ext = os.path.splitext(file_path)
+ file_path = f"{base}_{int(time.time())}{ext}"
+
+ with open(file_path, "wb") as f:
+ f.write(file_content)
+
+ logger.info("飞书文件下载成功: %s", file_path)
+
+ return {
+ "path": file_path,
+ "name": original_name or local_name,
+ "size": len(file_content),
+ "mime_type": self._guess_mime_type(original_name or local_name),
+ "file_key": file_key,
+ "file_category": "file",
+ }
+
+ except Exception as e:
+ logger.error("下载飞书文件失败: %s", e)
+ return None
+
+ async def download_file_resource(
+ self, file_key: str, message_id: str, extra_info: dict | None = None
+ ) -> dict | None:
+ """下载普通文件(公开接口)。"""
+ return await self._download_file_internal(file_key, message_id, extra_info)
+
+ async def _download_audio_internal(
+ self,
+ file_key: str,
+ message_id: str,
+ ) -> dict | None:
+ """
+ 下载音频文件。
+
+ 飞书音频消息的原生格式为 Opus,messageResource 返回的也是 opus 编码数据。
+ """
+ try:
+ from lark_oapi.api.im.v1 import GetMessageResourceRequest
+
+ def _do_download():
+ request = (
+ GetMessageResourceRequest.builder()
+ .message_id(message_id)
+ .file_key(file_key)
+ .type("audio")
+ .build()
+ )
+ return self._api_client.im.v1.message_resource.get(request)
+
+ file_content = await self._download_with_retry(_do_download)
+ if not file_content:
+ return None
+
+ # 飞书音频原生格式为 opus,通过文件头进一步确认
+ extension = self._detect_audio_extension(file_content)
+
+ local_name = self._generate_local_filename(
+ message_id, file_key, extension=extension
+ )
+ download_dir = self._get_download_dir("audio")
+ file_path = os.path.join(download_dir, local_name)
+
+ with open(file_path, "wb") as f:
+ f.write(file_content)
+
+ logger.info("飞书音频下载成功: %s", file_path)
+
+ return {
+ "path": file_path,
+ "name": local_name,
+ "size": len(file_content),
+ "mime_type": self._guess_mime_type(local_name),
+ "file_key": file_key,
+ "file_category": "audio",
+ }
+
+ except Exception as e:
+ logger.error("下载飞书音频失败: %s", e)
+ return None
+
+ async def download_audio(self, file_key: str, message_id: str) -> dict | None:
+ """下载音频文件(公开接口)。"""
+ return await self._download_audio_internal(file_key, message_id)
+
+ async def _download_media_internal(
+ self,
+ file_key: str,
+ message_id: str,
+ ) -> dict | None:
+ """
+ 下载视频/媒体文件。
+
+ 飞书视频消息通过 messageResource 接口下载。
+ """
+ try:
+ from lark_oapi.api.im.v1 import GetMessageResourceRequest
+
+ def _do_download():
+ request = (
+ GetMessageResourceRequest.builder()
+ .message_id(message_id)
+ .file_key(file_key)
+ .type("media")
+ .build()
+ )
+ return self._api_client.im.v1.message_resource.get(request)
+
+ file_content = await self._download_with_retry(_do_download)
+ if not file_content:
+ return None
+
+ extension = self._detect_video_extension(file_content)
+
+ local_name = self._generate_local_filename(
+ message_id, file_key, extension=extension
+ )
+ download_dir = self._get_download_dir("media")
+ file_path = os.path.join(download_dir, local_name)
+
+ with open(file_path, "wb") as f:
+ f.write(file_content)
+
+ logger.info("飞书视频下载成功: %s", file_path)
+
+ return {
+ "path": file_path,
+ "name": local_name,
+ "size": len(file_content),
+ "mime_type": self._guess_mime_type(local_name),
+ "file_key": file_key,
+ "file_category": "media",
+ }
+
+ except Exception as e:
+ logger.error("下载飞书视频失败: %s", e)
+ return None
+
+ async def download_media(self, file_key: str, message_id: str) -> dict | None:
+ """下载视频文件(公开接口)。"""
+ return await self._download_media_internal(file_key, message_id)
+
+ # ──────────────────────────────────────────────────────────────────────────
+ # 文件格式检测辅助方法
+ # ──────────────────────────────────────────────────────────────────────────
+
+ @staticmethod
+ def _detect_image_extension(data: bytes) -> str:
+ """通过文件头魔数推断图片扩展名,默认 .png。"""
+ if len(data) < 12:
+ return ".png"
+ header = data[:12]
+ if header[:4] == b"\x89PNG":
+ return ".png"
+ if header[:2] == b"\xff\xd8":
+ return ".jpg"
+ if header[:6] in (b"GIF87a", b"GIF89a"):
+ return ".gif"
+ if header[:4] == b"RIFF" and header[8:12] == b"WEBP":
+ return ".webp"
+ if header[:2] in (b"BM",):
+ return ".bmp"
+ return ".png"
+
+ @staticmethod
+ def _detect_audio_extension(data: bytes) -> str:
+ """
+ 通过文件头推断音频扩展名。
+
+ 飞书音频原生格式为 Opus(OggOpus 容器),默认返回 .opus。
+ """
+ if len(data) < 12:
+ return ".opus"
+ header = data[:12]
+ # OggS 容器(Opus/Vorbis)
+ if header[:4] == b"OggS":
+ return ".opus"
+ # FLAC
+ if header[:4] == b"fLaC":
+ return ".flac"
+ # WAVE
+ if header[:4] == b"RIFF" and header[8:12] == b"WAVE":
+ return ".wav"
+ # MP3 (ID3 tag or sync frame)
+ if header[:3] == b"ID3" or header[:2] == b"\xff\xfb":
+ return ".mp3"
+ # 默认为 opus(飞书原生格式)
+ return ".opus"
+
+ @staticmethod
+ def _detect_video_extension(data: bytes) -> str:
+ """通过文件头推断视频扩展名,默认 .mp4。"""
+ if len(data) < 12:
+ return ".mp4"
+ header = data[:12]
+ # MP4 / MOV (ftyp box)
+ if header[4:8] in (b"ftyp", b"moof", b"moov"):
+ return ".mp4"
+ # MKV / WebM (EBML header)
+ if header[:4] == b"\x1a\x45\xdf\xa3":
+ return ".mkv"
+ # FLV
+ if header[:3] == b"FLV":
+ return ".flv"
+ # AVI (RIFF ... AVI )
+ if header[:4] == b"RIFF" and header[8:12] == b"AVI ":
+ return ".avi"
+ return ".mp4"
+
+ # ──────────────────────────────────────────────────────────────────────────
+ # 文件上传
+ # ──────────────────────────────────────────────────────────────────────────
+
+ async def _upload_image_internal(self, file_path: str) -> dict | None:
+ """
+ 上传图片到飞书(图片 API,失败时回退到文件 API)。
+
+ 飞书图片限制:20 MB。
+ """
+ try:
+ from lark_oapi.api.im.v1 import CreateImageRequest, CreateImageRequestBody
+
+ file_size = os.path.getsize(file_path)
+ if file_size > 20 * 1024 * 1024:
+ logger.error("图片超过飞书限制 20MB: %s (%d)", file_path, file_size)
+ return None
+
+ loop = asyncio.get_running_loop()
+
+ def _do_upload():
+ file_obj = open(file_path, "rb")
+ try:
+ request = (
+ CreateImageRequest.builder()
+ .request_body(
+ CreateImageRequestBody.builder()
+ .image_type("message")
+ .image(file_obj)
+ .build()
+ )
+ .build()
+ )
+ return self._api_client.im.v1.image.create(request)
+ finally:
+ file_obj.close()
+
+ response = await loop.run_in_executor(None, _do_upload)
+
+ if response.success():
+ image_key = response.data.image_key
+ logger.info("飞书图片上传成功: %s → %s", file_path, image_key)
+ return {
+ "image_key": image_key,
+ "file_key": image_key,
+ "file_type": "image",
+ }
+
+ # 图片 API 失败,回退到文件 API
+ logger.warning(
+ "上传图片失败 (code=%s): %s,回退到文件 API", response.code, response.msg
+ )
+ return await self._upload_image_as_file(file_path)
+
+ except Exception as e:
+ logger.error("上传图片异常: %s", e)
+ return None
+
+ async def _upload_image_as_file(self, file_path: str) -> dict | None:
+ """使用文件 API 上传图片(图片 API 失败时的回退方案)。"""
+ try:
+ from lark_oapi.api.im.v1 import CreateFileRequest, CreateFileRequestBody
+
+ file_name = os.path.basename(file_path)
+ loop = asyncio.get_running_loop()
+
+ def _do_upload():
+ file_obj = open(file_path, "rb")
+ try:
+ request = (
+ CreateFileRequest.builder()
+ .request_body(
+ CreateFileRequestBody.builder()
+ .file_name(file_name)
+ .file_type("stream")
+ .file(file_obj)
+ .build()
+ )
+ .build()
+ )
+ return self._api_client.im.v1.file.create(request)
+ finally:
+ file_obj.close()
+
+ response = await loop.run_in_executor(None, _do_upload)
+
+ if not response.success():
+ logger.error(
+ "文件 API 上传图片失败: code=%s msg=%s", response.code, response.msg
+ )
+ return None
+
+ file_key = response.data.file_key
+ file_size = os.path.getsize(file_path)
+ logger.info("飞书文件 API 上传图片成功: %s → %s", file_path, file_key)
+ return {
+ "file_key": file_key,
+ "file_name": file_name,
+ "file_size": file_size,
+ "file_type": "file",
+ }
+
+ except Exception as e:
+ logger.error("文件 API 上传图片异常: %s", e)
+ return None
+
+ async def upload_image(self, file_path: str) -> dict | None:
+ """上传图片(公开接口)。"""
+ return await self._upload_image_internal(file_path)
+
+ async def _upload_file_internal(self, file_path: str) -> dict | None:
+ """
+ 上传普通文件到飞书(file.create 接口)。
+
+ 飞书文件限制:30 MB。
+ 根据文件扩展名自动选择合适的 file_type(如 opus/mp4/pdf/doc/xls/ppt/stream)。
+ """
+ try:
+ from lark_oapi.api.im.v1 import CreateFileRequest, CreateFileRequestBody
+
+ file_size = os.path.getsize(file_path)
+ if file_size > 30 * 1024 * 1024:
+ logger.error("文件超过飞书限制 30MB: %s (%d)", file_path, file_size)
+ return None
+
+ file_name = os.path.basename(file_path)
+ feishu_file_type = get_feishu_file_type(file_path)
+ loop = asyncio.get_running_loop()
+
+ def _do_upload():
+ file_obj = open(file_path, "rb")
+ try:
+ request = (
+ CreateFileRequest.builder()
+ .request_body(
+ CreateFileRequestBody.builder()
+ .file_name(file_name)
+ .file_type(feishu_file_type)
+ .file(file_obj)
+ .build()
+ )
+ .build()
+ )
+ return self._api_client.im.v1.file.create(request)
+ finally:
+ file_obj.close()
+
+ response = await loop.run_in_executor(None, _do_upload)
+
+ if not response.success():
+ logger.error("上传文件失败: code=%s msg=%s", response.code, response.msg)
+ return None
+
+ file_key = response.data.file_key
+ logger.info(
+ "飞书文件上传成功: %s → %s (file_type=%s)", file_path, file_key, feishu_file_type
+ )
+ return {
+ "file_key": file_key,
+ "file_name": file_name,
+ "file_size": file_size,
+ "file_type": feishu_file_type,
+ "file_category": "audio" if is_audio_file(file_path) else (
+ "media" if is_video_file(file_path) else "file"
+ ),
+ }
+
+ except Exception as e:
+ logger.error("上传文件异常: %s", e)
+ return None
+
+ async def upload_file_resource(self, file_path: str) -> dict | None:
+ """上传普通文件(公开接口)。"""
+ return await self._upload_file_internal(file_path)
diff --git a/tests/unit_tests/channel/test_feishu_upload.py b/tests/unit_tests/channel/test_feishu_upload.py
index 5abb85be8f..95833c763b 100644
--- a/tests/unit_tests/channel/test_feishu_upload.py
+++ b/tests/unit_tests/channel/test_feishu_upload.py
@@ -4,7 +4,7 @@
import json
import os
import tempfile
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, AsyncMock
import pytest
@@ -19,10 +19,15 @@ def _make_channel() -> FeishuChannel:
enabled=True,
app_id="test_app_id",
app_secret="test_app_secret",
+ enable_file_upload=True,
)
router = MagicMock(spec=RobotMessageRouter)
ch = FeishuChannel(config, router)
ch._api_client = MagicMock()
+ # Mock _file_service with async methods
+ ch._file_service = MagicMock()
+ ch._file_service.upload_image = AsyncMock()
+ ch._file_service.upload_file_resource = AsyncMock()
return ch
@@ -191,12 +196,13 @@ def test_upload_file_file_not_found():
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
+ # Mock upload_image to return image_key
+ ch._file_service.upload_image.return_value = {
+ "image_key": "img_v2_abc",
+ "file_type": "image",
+ }
+ # Mock message creation
send_resp = MagicMock()
send_resp.success.return_value = True
ch._api_client.im.v1.message.create.return_value = send_resp
@@ -209,12 +215,10 @@ async def test_send_image_file():
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"
+ # Verify upload_image was called
+ ch._file_service.upload_image.assert_called_once()
+ # Verify message.create was called
+ ch._api_client.im.v1.message.create.assert_called_once()
finally:
os.unlink(tmp_path)
@@ -223,12 +227,13 @@ async def test_send_image_file():
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
+ # Mock upload_file_resource to return file_key
+ ch._file_service.upload_file_resource.return_value = {
+ "file_key": "file_v2_xyz",
+ "file_type": "stream",
+ }
+ # Mock message creation
send_resp = MagicMock()
send_resp.success.return_value = True
ch._api_client.im.v1.message.create.return_value = send_resp
@@ -241,12 +246,10 @@ async def test_send_generic_file():
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"
+ # Verify upload_file_resource was called
+ ch._file_service.upload_file_resource.assert_called_once()
+ # Verify message.create was called
+ ch._api_client.im.v1.message.create.assert_called_once()
finally:
os.unlink(tmp_path)
@@ -255,12 +258,10 @@ async def test_send_generic_file():
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
+ # Mock upload_image to return None (failure)
+ ch._file_service.upload_image.return_value = None
+ # Mock message creation for fallback
send_resp = MagicMock()
send_resp.success.return_value = True
ch._api_client.im.v1.message.create.return_value = send_resp
@@ -273,10 +274,9 @@ async def test_send_file_upload_failure_sends_text_fallback():
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"
+ # upload_image should have been called
+ ch._file_service.upload_image.assert_called_once()
+ # message.create should NOT be called since upload failed and no fallback
+ ch._api_client.im.v1.message.create.assert_not_called()
finally:
os.unlink(tmp_path)