ForcePilot/backend/package/yuxi/channels/adapters/feishu/formatter.py
Kris 69b7139863 refactor(feishu): 清理冗余代码并补全飞书工具集实现
1.  移除多个文件中的空行、冗余导入
2.  修复文件末尾缺少换行符的问题
3.  新增并补全飞书多类工具API实现:
    - 多维表格:更新、删除记录,列出视图
    - 文档:更新、追加、删除块
    - 云文档:上传、下载文件
    - 群组:创建、添加成员、更新信息、创建公告
    - 目录:重构用户部门缓存逻辑
4.  优化消息发送、回复、转发等API的错误处理和逻辑
5.  新增消息列表查询、已读状态查询等功能
2026-05-13 16:07:59 +08:00

98 lines
2.9 KiB
Python

from __future__ import annotations
from typing import Any
from .cards import (
TEXT_CHUNK_LIMIT,
build_feishu_card,
build_feishu_post_content,
build_feishu_text_content,
is_post_format_requested,
)
def format_outbound_message(content: str, *, metadata: dict | None = None, **_kwargs: Any) -> dict[str, Any]:
if is_post_format_requested(metadata):
return _format_post(content)
return _format_text(content)
def format_outbound_card(
content: str,
*,
title: str = "AI 助手",
buttons: list[dict[str, str]] | None = None,
streaming: bool = False,
url_unfurl: list[str] | None = None,
images: list[str] | None = None,
files: list[dict[str, str]] | None = None,
note: str | None = None,
template: str | None = None,
tone: str | None = None,
context_text: str | None = None,
dividers: int = 0,
selectors: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
return build_feishu_card(
content,
title=title,
buttons=buttons,
streaming=streaming,
url_unfurl=url_unfurl,
images=images,
files=files,
note=note,
template=template,
tone=tone,
context_text=context_text,
dividers=dividers,
selectors=selectors,
)
def format_outbound_diagnostic_card(title: str, details: dict[str, Any]) -> dict[str, Any]:
lines = [f"**{title}**", ""]
for key, value in details.items():
lines.append(f"- **{key}**: {str(value)[:200]}")
content = "\n".join(lines)
return build_feishu_card(content, title="系统诊断", template="orange")
def _format_text(content: str) -> dict[str, Any]:
truncated = _truncate_text(content, limit=TEXT_CHUNK_LIMIT)
return build_feishu_text_content(truncated)
def _format_post(content: str) -> dict[str, Any]:
truncated = _truncate_text(content, limit=TEXT_CHUNK_LIMIT)
return build_feishu_post_content(truncated)
def _truncate_text(content: str, limit: int = TEXT_CHUNK_LIMIT) -> str:
if len(content) <= limit:
return content
suffix = "\n\n...(内容过长已截断,请查看完整的消息记录)"
return content[: limit - len(suffix)] + suffix
def make_error_card(title: str, detail: str) -> dict[str, Any]:
return build_feishu_card(
f"**{detail}**",
title=title,
template="red",
tone="danger",
)
def format_outbound(content: str, **_kwargs: Any) -> dict[str, Any]:
result = format_outbound_message(content, metadata=_kwargs.get("metadata"))
result["content"] = content
for key in ("chat_type", "buttons", "thread_id"):
if key in _kwargs:
result[key] = _kwargs[key]
metadata = _kwargs.get("metadata", {})
for key in ("buttons", "thread_id"):
if isinstance(metadata, dict) and key in metadata:
result[key] = metadata[key]
return result