60 lines
1.9 KiB
Python
60 lines
1.9 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import logging
|
||
|
|
from datetime import datetime, UTC
|
||
|
|
|
||
|
|
from yuxi.channel.extensions.lazada.types import InboundLazadaMessage
|
||
|
|
from yuxi.channel.message.models import MessageType, PeerInfo, UnifiedMessage
|
||
|
|
from yuxi.channel.routing.models import PeerKind
|
||
|
|
|
||
|
|
logger = logging.getLogger(__name__)
|
||
|
|
|
||
|
|
|
||
|
|
class LazadaMonitor:
|
||
|
|
def convert_to_unified(self, msg: InboundLazadaMessage) -> UnifiedMessage:
|
||
|
|
msg_type = self._resolve_message_type(msg.template_id)
|
||
|
|
content = self._extract_content(msg)
|
||
|
|
|
||
|
|
return UnifiedMessage(
|
||
|
|
msg_id=msg.message_id,
|
||
|
|
channel_type="lazada",
|
||
|
|
account_id="default",
|
||
|
|
content=content,
|
||
|
|
message_type=msg_type,
|
||
|
|
sender=PeerInfo(
|
||
|
|
id=msg.from_account_id,
|
||
|
|
kind=PeerKind.DIRECT,
|
||
|
|
display_name=msg.from_account_id,
|
||
|
|
),
|
||
|
|
timestamp=self._parse_timestamp(msg.send_time),
|
||
|
|
raw_payload=msg.raw_event,
|
||
|
|
body_for_agent=content,
|
||
|
|
metadata={
|
||
|
|
"session_id": msg.session_id,
|
||
|
|
"to_account_id": msg.to_account_id,
|
||
|
|
"template_id": msg.template_id,
|
||
|
|
"site_id": msg.site_id,
|
||
|
|
"auto_reply": msg.auto_reply,
|
||
|
|
"status": msg.status,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
|
||
|
|
def _resolve_message_type(self, template_id: int) -> MessageType:
|
||
|
|
mapping = {
|
||
|
|
1: MessageType.TEXT,
|
||
|
|
3: MessageType.IMAGE,
|
||
|
|
6: MessageType.TEXT,
|
||
|
|
}
|
||
|
|
return mapping.get(template_id, MessageType.TEXT)
|
||
|
|
|
||
|
|
def _extract_content(self, msg: InboundLazadaMessage) -> str:
|
||
|
|
return msg.content
|
||
|
|
|
||
|
|
def _parse_timestamp(self, send_time: int) -> datetime | None:
|
||
|
|
try:
|
||
|
|
if send_time > 0:
|
||
|
|
return datetime.fromtimestamp(send_time / 1000, tz=UTC)
|
||
|
|
except (ValueError, OSError):
|
||
|
|
pass
|
||
|
|
return datetime.now(tz=UTC)
|