""" 消息段模型模块 定义了 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}]"