|
|
""" |
|
|
消息结构定义 |
|
|
""" |
|
|
|
|
|
from dataclasses import dataclass |
|
|
from typing import Dict, Any |
|
|
from datetime import datetime |
|
|
|
|
|
|
|
|
@dataclass |
|
|
class Message: |
|
|
"""消息结构""" |
|
|
sender_id: str |
|
|
receiver_id: str |
|
|
timestamp: datetime |
|
|
content: str |
|
|
|
|
|
def to_dict(self) -> Dict[str, Any]: |
|
|
"""转换为字典格式""" |
|
|
return { |
|
|
'sender_id': self.sender_id, |
|
|
'receiver_id': self.receiver_id, |
|
|
'timestamp': self.timestamp.isoformat(), |
|
|
'content': self.content |
|
|
} |
|
|
|
|
|
@classmethod |
|
|
def from_dict(cls, data: Dict[str, Any]) -> 'Message': |
|
|
"""从字典创建消息对象""" |
|
|
return cls( |
|
|
sender_id=data['sender_id'], |
|
|
receiver_id=data['receiver_id'], |
|
|
timestamp=datetime.fromisoformat(data['timestamp']), |
|
|
content=data['content'] |
|
|
) |