ForcePilot/backend/package/yuxi/channel/channels/feishu/translator.py
Kris 9a8a27bf36 feat(channel): 新增渠道网关模块完整实现
本次提交新增了完整的多渠道消息网关系统,包括:
1. 支持飞书、钉钉、Web、Hook 四种渠道的适配器与配置
2. 领域模型层:消息、会话、绑定、出箱等核心实体
3. 应用服务层:管道、中间件、DTO 与业务逻辑
4. 基础设施层:持久化、过滤器、队列等端口实现
5. 接口层:REST API、SSE、WebSocket 通信端点
6. 前端页面与路由配置,添加渠道管理菜单
7. 新增相关依赖包与 docker-compose 部署配置
2026-05-30 21:53:09 +08:00

92 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,
},
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