Files
NeoBot/models/message.py
2026-01-01 18:43:14 +08:00

55 lines
1.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
消息段模型模块
定义了 MessageSegment 类,用于封装 OneBot 11 的消息段。
"""
from dataclasses import dataclass
from typing import Any, Dict
@dataclass
class MessageSegment:
"""
消息段,对应 OneBot 11 标准中的消息段对象
"""
type: str
"""消息段类型,如 text, image, at 等"""
data: Dict[str, Any]
"""消息段数据"""
@property
def text(self) -> str:
"""
获取文本内容(仅当 type 为 text 时有效)
:return: 文本内容
"""
return self.data.get("text", "") if self.type == "text" else ""
@property
def image_url(self) -> str:
"""
获取图片 URL仅当 type 为 image 时有效)
:return: 图片 URL
"""
return self.data.get("url", "") if self.type == "image" else ""
def is_at(self, user_id: int = None) -> bool:
"""
判断是否为 @某人
:param user_id: 指定的 QQ 号,如果为 None 则只判断是否为 at 类型
:return: 是否匹配
"""
if self.type != "at":
return False
if user_id is None:
return True
return str(self.data.get("qq")) == str(user_id)
def __repr__(self):
return f"[MS:{self.type}:{self.data}]"