You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.3 KiB

"""消息数据模型"""
from __future__ import annotations
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Any
class MessageType(Enum):
TEXT = "text"
IMAGE = "image"
FILE = "file"
VOICE = "voice"
VIDEO = "video"
LINK = "link"
SYSTEM = "system"
UNKNOWN = "unknown"
@dataclass
class Message:
"""单条聊天消息"""
msg_id: str
conversation: str # 会话名称(联系人/群名)
sender: str # 发送者
content: str # 消息内容(文本 / 文件路径 / 图片路径等)
msg_type: MessageType = MessageType.TEXT
timestamp: float = field(default_factory=time.time)
is_self: bool = False # 是否自己发送
raw_data: dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> dict[str, Any]:
return {
"msg_id": self.msg_id,
"conversation": self.conversation,
"sender": self.sender,
"content": self.content,
"msg_type": self.msg_type.value,
"timestamp": self.timestamp,
"is_self": self.is_self,
}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> Message:
data = data.copy()
data["msg_type"] = MessageType(data["msg_type"])
return cls(**data)