ForcePilot/backend/package/yuxi/channel/channels/feishu/translator.py
Kris c61d5f0163 feat: 完成通道服务多轮功能迭代
本次提交完成了一系列核心功能迭代与优化:
1.  新增并完善了多个领域模型与端口定义,补充了`__all__`导出规范
2.  优化了会话、绑定、出箱等模块的数据模型,修复了时间字段类型不一致问题
3.  新增了代理ID解析、缓存发布等接口,扩展了系统能力
4.  重构了去重中间件逻辑,优化了空内容校验规则
5.  新增了认证中间件的匿名访问支持,完善了鉴权流程
6.  优化了SSE连接管理,增加了单会话连接上限限制
7.  重构了消息日志与仓储相关代码,将数据类迁移至对应模型目录
8.  新增了重复绑定校验、绑定更新接口,完善了绑定服务逻辑
9.  优化了健康检查逻辑,新增了环境变量控制启动时间线展示
10. 重构了出箱重试工作线程,使用缓存端口替代直接redis操作,新增了消息处理标记逻辑
11. 完善了飞书、Web、钩子等通道的翻译器逻辑,补充了账户ID传递
12. 新增了多种自定义异常类型,优化了异常映射与错误处理流程
13. 完善了配置热重载逻辑,同步认证凭证与校验器配置
14. 重构了Redis缓存实现,增加了异常捕获与包装
2026-05-31 21:42:03 +08:00

93 lines
2.9 KiB
Python

from __future__ import annotations
import json
from yuxi.channel.domain.model.message.attachment import Attachment
from yuxi.channel.domain.model.message.peer import Peer
from yuxi.channel.domain.model.message.unified_message import UnifiedMessage
from yuxi.channel.domain.model.shared.channel_type import ChannelType
class FeishuTranslator:
@staticmethod
def translate_event(raw: dict) -> UnifiedMessage:
event = raw.get("event", {})
message = event.get("message", {})
sender = event.get("sender", {})
sender_id = sender.get("sender_id", {}).get("user_id", "")
chat_type = message.get("chat_type", "p2p")
is_group = chat_type == "group"
group_id = message.get("chat_id", "") if is_group else ""
attachments = _extract_attachments(raw)
text_content = _extract_text(message)
return UnifiedMessage(
message_id=message.get("message_id", ""),
channel_type=ChannelType.FEISHU,
sender=Peer(id=sender_id, name=sender_id, kind="user"),
content=text_content,
metadata={
"is_group": is_group,
"group_id": group_id,
"chat_type": chat_type,
"account_id": sender_id,
},
attachments=attachments,
raw_payload=raw,
)
def _extract_text(message: dict) -> str:
content_raw = message.get("content", "")
if not content_raw:
return ""
try:
content = json.loads(content_raw) if isinstance(content_raw, str) else content_raw
except (json.JSONDecodeError, TypeError):
return content_raw
if isinstance(content, dict):
return content.get("text", content_raw)
return content_raw
def _extract_attachments(body: dict) -> list[Attachment]:
attachments = []
msg = body.get("event", {}).get("message", {})
msg_type = msg.get("message_type", "")
content_raw = msg.get("content", "{}")
try:
content = json.loads(content_raw) if isinstance(content_raw, str) else content_raw
except (json.JSONDecodeError, TypeError):
return attachments
if msg_type == "image":
image_key = content.get("image_key", "")
if image_key:
attachments.append(
Attachment(
url=image_key,
media_type="image",
filename="",
size_bytes=0,
mime_type="image/png",
)
)
elif msg_type == "file":
file_key = content.get("file_key", "")
file_name = content.get("file_name", "")
if file_key:
attachments.append(
Attachment(
url=file_key,
media_type="file",
filename=file_name,
size_bytes=0,
mime_type="application/octet-stream",
)
)
return attachments