97 lines
2.4 KiB
Python
97 lines
2.4 KiB
Python
"""
|
||
消息段模型模块
|
||
|
||
定义了 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}]"
|
||
|
||
# --- 快捷构造方法 ---
|
||
|
||
@staticmethod
|
||
def text(text: str) -> "MessageSegment":
|
||
"""
|
||
构造文本消息段
|
||
|
||
:param text: 文本内容
|
||
:return: MessageSegment 对象
|
||
"""
|
||
return MessageSegment(type="text", data={"text": text})
|
||
|
||
@staticmethod
|
||
def at(user_id: int | str) -> "MessageSegment":
|
||
"""
|
||
构造 @某人 消息段
|
||
|
||
:param user_id: 目标 QQ 号,"all" 表示 @全体成员
|
||
:return: MessageSegment 对象
|
||
"""
|
||
return MessageSegment(type="at", data={"qq": str(user_id)})
|
||
|
||
@staticmethod
|
||
def image(file: str) -> "MessageSegment":
|
||
"""
|
||
构造图片消息段
|
||
|
||
:param file: 图片文件名、URL 或 Base64
|
||
:return: MessageSegment 对象
|
||
"""
|
||
return MessageSegment(type="image", data={"file": file})
|
||
|
||
@staticmethod
|
||
def face(id: int) -> "MessageSegment":
|
||
"""
|
||
构造表情消息段
|
||
|
||
:param id: 表情 ID
|
||
:return: MessageSegment 对象
|
||
"""
|
||
return MessageSegment(type="face", data={"id": str(id)})
|