跳转至

element

Ariadne 中的消息元素

App 🔗

Bases: Element

表示消息中自带的 App 消息元素

Source code in graia/ariadne/message/element.py
249
250
251
252
253
254
255
256
257
258
259
260
261
class App(Element):
    """表示消息中自带的 App 消息元素"""

    type = "App"

    content: str
    """App 内容"""

    def __init__(self, content: str, **_) -> None:
        super().__init__(content=content)

    def __str__(self) -> str:
        return "[APP消息]"

content class-attribute 🔗

content: str

App 内容

At 🔗

Bases: Element

该消息元素用于承载消息中用于提醒/呼唤特定用户的部分.

Source code in graia/ariadne/message/element.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
class At(Element):
    """该消息元素用于承载消息中用于提醒/呼唤特定用户的部分."""

    type: str = "At"

    target: int
    """At 的目标 QQ 号"""

    representation: Optional[str] = Field(None, alias="display")
    """显示名称"""

    def __init__(self, target: Union[int, Member] = ..., **data) -> None:
        """实例化一个 At 消息元素, 用于承载消息中用于提醒/呼唤特定用户的部分.

        Args:
            target (int): 需要提醒/呼唤的特定用户的 QQ 号(或者说 id.)
        """
        if target is not ...:
            if isinstance(target, int):
                data.update(target=target)
            else:
                data.update(target=target.id)
        super().__init__(**data)

    def __eq__(self, other: "At"):
        return isinstance(other, At) and self.target == other.target

    def __str__(self) -> str:
        return f"@{self.representation}" if self.representation else f"@{self.target}"

representation class-attribute 🔗

representation: Optional[str] = Field(None, alias='display')

显示名称

target class-attribute 🔗

target: int

At 的目标 QQ 号

__init__ 🔗

__init__(target: Union[int, Member] = Ellipsis, **data) -> None

实例化一个 At 消息元素, 用于承载消息中用于提醒/呼唤特定用户的部分.

Parameters:

  • target (int) –

    需要提醒/呼唤的特定用户的 QQ 号(或者说 id.)

Source code in graia/ariadne/message/element.py
136
137
138
139
140
141
142
143
144
145
146
147
def __init__(self, target: Union[int, Member] = ..., **data) -> None:
    """实例化一个 At 消息元素, 用于承载消息中用于提醒/呼唤特定用户的部分.

    Args:
        target (int): 需要提醒/呼唤的特定用户的 QQ 号(或者说 id.)
    """
    if target is not ...:
        if isinstance(target, int):
            data.update(target=target)
        else:
            data.update(target=target.id)
    super().__init__(**data)

AtAll 🔗

Bases: Element

该消息元素用于群组中的管理员提醒群组中的所有成员

Source code in graia/ariadne/message/element.py
156
157
158
159
160
161
162
163
164
165
class AtAll(Element):
    """该消息元素用于群组中的管理员提醒群组中的所有成员"""

    type: str = "AtAll"

    def __init__(self, *_, **__) -> None:
        super().__init__()

    def __str__(self) -> str:
        return "@全体成员"

Dice 🔗

Bases: Element

表示消息中骰子消息元素

Source code in graia/ariadne/message/element.py
338
339
340
341
342
343
344
345
346
347
348
349
350
class Dice(Element):
    """表示消息中骰子消息元素"""

    type = "Dice"

    value: int
    """骰子值"""

    def __init__(self, value: int, *_, **__) -> None:
        super().__init__(value=value)

    def __str__(self) -> str:
        return f"[骰子:{self.value}]"

value class-attribute 🔗

value: int

骰子值

Element 🔗

Bases: AriadneBaseModel, BaseElement

指示一个消息中的元素. type (str): 元素类型

Source code in graia/ariadne/message/element.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
class Element(AriadneBaseModel, BaseElement):
    """
    指示一个消息中的元素.
    type (str): 元素类型
    """

    type: str = "Unknown"
    """元素类型"""

    def __init__(self, **data):
        return super().__init__(**data)

    def __hash__(self):
        return hash((type(self),) + tuple(self.__dict__.values()))

    @property
    def display(self) -> str:
        """该元素的 "显示" 形式字符串, 趋近于你见到的样子.

        Returns:
            str: "显示" 字符串.
        """
        return str(self)

    def as_persistent_string(self) -> str:
        """持久化字符串表示.

        Returns:
            str: 持久化字符串.
        """
        data: str = escape_bracket(
            j_dump(
                self.dict(
                    exclude={"type"},
                ),
                indent=None,
                separators=(",", ":"),
            )
        )
        return f"[mirai:{self.type}:{data}]"

    def __repr_args__(self) -> "ReprArgs":
        return list(self.dict(exclude={"type"}).items())

    def __str__(self) -> str:
        return ""

    def __add__(self, content: Union["MessageChain", List["Element"], "Element", str]) -> "MessageChain":
        from .chain import MessageChain

        if isinstance(content, str):
            content = Plain(content)
        if isinstance(content, Element):
            content = [content]
        if isinstance(content, MessageChain):
            content = content.__root__
        return MessageChain(content + [self], inline=True)

    def __radd__(self, content: Union["MessageChain", List["Element"], "Element", str]) -> "MessageChain":
        from .chain import MessageChain

        if isinstance(content, str):
            content = Plain(content)
        if isinstance(content, Element):
            content = [content]
        if isinstance(content, MessageChain):
            content = content.__root__
        return MessageChain([self] + content, inline=True)

type class-attribute 🔗

type: str = 'Unknown'

元素类型

as_persistent_string 🔗

as_persistent_string() -> str

持久化字符串表示.

Returns:

  • str( str ) –

    持久化字符串.

Source code in graia/ariadne/message/element.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def as_persistent_string(self) -> str:
    """持久化字符串表示.

    Returns:
        str: 持久化字符串.
    """
    data: str = escape_bracket(
        j_dump(
            self.dict(
                exclude={"type"},
            ),
            indent=None,
            separators=(",", ":"),
        )
    )
    return f"[mirai:{self.type}:{data}]"

display property 🔗

display() -> str

该元素的 "显示" 形式字符串, 趋近于你见到的样子.

Returns:

  • str( str ) –

    "显示" 字符串.

Source code in graia/ariadne/message/element.py
44
45
46
47
48
49
50
51
@property
def display(self) -> str:
    """该元素的 "显示" 形式字符串, 趋近于你见到的样子.

    Returns:
        str: "显示" 字符串.
    """
    return str(self)

Face 🔗

Bases: Element

表示消息中所附带的表情, 这些表情大多都是聊天工具内置的.

Source code in graia/ariadne/message/element.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
class Face(Element):
    """表示消息中所附带的表情, 这些表情大多都是聊天工具内置的."""

    type: str = "Face"

    face_id: Optional[int] = Field(None, alias="faceId")
    """QQ 表情编号, 优先于 name"""

    name: Optional[str] = None
    """QQ 表情名称"""

    def __init__(self, id: int = ..., name: str = ..., **data) -> None:
        """
        Args:
            id (int, optional): QQ 表情编号
            name (str, optional): QQ 表情名称
        """
        if id is not ...:
            data.update(faceId=id)
        if name is not ...:
            data.update(name=name)
        super().__init__(**data)

    def __str__(self) -> str:
        return f"[表情: {self.name or self.face_id}]"

    def __eq__(self, other) -> bool:
        return isinstance(other, Face) and (self.face_id == other.face_id or self.name == other.name)

face_id class-attribute 🔗

face_id: Optional[int] = Field(None, alias='faceId')

QQ 表情编号, 优先于 name

name class-attribute 🔗

name: Optional[str] = None

QQ 表情名称

__init__ 🔗

__init__(id: int = Ellipsis, name: str = Ellipsis, **data) -> None

Parameters:

  • id (int) –

    QQ 表情编号

  • name (str) –

    QQ 表情名称

Source code in graia/ariadne/message/element.py
179
180
181
182
183
184
185
186
187
188
189
def __init__(self, id: int = ..., name: str = ..., **data) -> None:
    """
    Args:
        id (int, optional): QQ 表情编号
        name (str, optional): QQ 表情名称
    """
    if id is not ...:
        data.update(faceId=id)
    if name is not ...:
        data.update(name=name)
    super().__init__(**data)

File 🔗

Bases: Element

指示一个文件信息元素

Source code in graia/ariadne/message/element.py
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
@internal_cls()
class File(Element):
    """指示一个文件信息元素"""

    type = "File"

    id: str
    """文件 ID"""

    name: str
    """文件名"""

    size: int
    """文件大小"""

    def __str__(self) -> str:
        return f"[文件:{self.name}]"

    def as_persistent_string(self) -> str:
        return ""

id class-attribute 🔗

id: str

文件 ID

name class-attribute 🔗

name: str

文件名

size class-attribute 🔗

size: int

文件大小

FlashImage 🔗

Bases: Image

指示消息中的闪照元素

Source code in graia/ariadne/message/element.py
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
class FlashImage(Image):
    """指示消息中的闪照元素"""

    type = "FlashImage"

    def __init__(
        self,
        id: Optional[str] = None,
        url: Optional[str] = None,
        *,
        path: Optional[Union[Path, str]] = None,
        base64: Optional[str] = None,
        data_bytes: Union[None, bytes, BytesIO] = None,
        **kwargs,
    ) -> None:
        super().__init__(id=id, url=url, path=path, base64=base64, data_bytes=data_bytes, **kwargs)

    def to_image(self) -> "Image":
        """将 FlashImage 转换为 Image

        Returns:
            Image: 转换后的 Image
        """
        return Image.parse_obj({**self.dict(), "type": "Image"})

    @classmethod
    def from_image(cls, image: "Image") -> "FlashImage":
        """从 Image 构造 FlashImage

        Returns:
            FlashImage: 构造出的 FlashImage
        """
        return cls.parse_obj({**image.dict(), "type": "FlashImage"})

    def __str__(self) -> str:
        return "[闪照]"

from_image classmethod 🔗

from_image(image: Image) -> FlashImage

从 Image 构造 FlashImage

Returns:

  • FlashImage( FlashImage ) –

    构造出的 FlashImage

Source code in graia/ariadne/message/element.py
758
759
760
761
762
763
764
765
@classmethod
def from_image(cls, image: "Image") -> "FlashImage":
    """从 Image 构造 FlashImage

    Returns:
        FlashImage: 构造出的 FlashImage
    """
    return cls.parse_obj({**image.dict(), "type": "FlashImage"})

to_image 🔗

to_image() -> Image

将 FlashImage 转换为 Image

Returns:

  • Image( Image ) –

    转换后的 Image

Source code in graia/ariadne/message/element.py
750
751
752
753
754
755
756
def to_image(self) -> "Image":
    """将 FlashImage 转换为 Image

    Returns:
        Image: 转换后的 Image
    """
    return Image.parse_obj({**self.dict(), "type": "Image"})

Forward 🔗

Bases: Element

指示合并转发信息

nodeList (List[ForwardNode]): 转发的消息节点

Source code in graia/ariadne/message/element.py
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
class Forward(Element):
    """
    指示合并转发信息

    nodeList (List[ForwardNode]): 转发的消息节点
    """

    type = "Forward"

    node_list: List[ForwardNode] = Field(None, alias="nodeList")
    """转发节点列表"""

    def __init__(self, *nodes: Union[Iterable[ForwardNode], ForwardNode, "MessageEvent"], **data) -> None:
        """构建转发消息对象

        Args:
            *nodes (List[ForwardNode]): 转发节点的列表
        """
        from ..event.message import MessageEvent
        from ..model.relationship import Client

        if nodes:
            node_list: List[ForwardNode] = []
            for i in nodes:
                if isinstance(i, ForwardNode):
                    node_list.append(i)
                elif isinstance(i, MessageEvent):
                    if not isinstance(i.sender, Client):
                        node_list.append(ForwardNode(i.sender, time=i.source.time, message=i.message_chain))
                else:
                    node_list.extend(i)
            data.update(nodeList=node_list)
        super().__init__(**data)

    def __str__(self) -> str:
        return f"[合并转发:共{len(self.node_list)}条]"

    def as_persistent_string(self) -> str:

        data: str = escape_bracket(f"[{','.join(node.json() for node in self.node_list)}]")
        return f"[mirai:{self.type}:{data}]"

    @classmethod
    def parse_obj(cls, obj: Any) -> Self:
        if isinstance(obj, list):
            return cls([ForwardNode.parse_obj(o) for o in obj])
        return cls(**obj)

    @overload
    def __getitem__(self, key: int) -> ForwardNode:
        ...

    @overload
    def __getitem__(self, key: slice) -> List[ForwardNode]:
        ...

    def __getitem__(self, key: Union[int, slice]) -> Union[ForwardNode, List[ForwardNode]]:
        return self.node_list[key]

node_list class-attribute 🔗

node_list: List[ForwardNode] = Field(None, alias='nodeList')

转发节点列表

__init__ 🔗

__init__(
    *nodes: Union[Iterable[ForwardNode], ForwardNode, MessageEvent], **data
) -> None

构建转发消息对象

Parameters:

Source code in graia/ariadne/message/element.py
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
def __init__(self, *nodes: Union[Iterable[ForwardNode], ForwardNode, "MessageEvent"], **data) -> None:
    """构建转发消息对象

    Args:
        *nodes (List[ForwardNode]): 转发节点的列表
    """
    from ..event.message import MessageEvent
    from ..model.relationship import Client

    if nodes:
        node_list: List[ForwardNode] = []
        for i in nodes:
            if isinstance(i, ForwardNode):
                node_list.append(i)
            elif isinstance(i, MessageEvent):
                if not isinstance(i.sender, Client):
                    node_list.append(ForwardNode(i.sender, time=i.source.time, message=i.message_chain))
            else:
                node_list.extend(i)
        data.update(nodeList=node_list)
    super().__init__(**data)

ForwardNode 🔗

Bases: AriadneBaseModel

表示合并转发中的一个节点

Source code in graia/ariadne/message/element.py
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
class ForwardNode(AriadneBaseModel):
    """表示合并转发中的一个节点"""

    sender_id: int = Field(None, alias="senderId")
    """发送者 QQ 号 (决定显示头像)"""

    time: datetime
    """发送时间"""

    sender_name: str = Field(None, alias="senderName")
    """发送者显示名字"""

    message_chain: Optional["MessageChain"] = Field(None, alias="messageChain")
    """发送的消息链"""

    message_id: Optional[int] = Field(None, alias="messageId")
    """缓存的消息 ID"""

    def __init__(
        self,
        target: Union[int, Friend, Member, Stranger] = ...,
        time: datetime = ...,
        message: "MessageChain" = ...,
        name: str = ...,
        **data,
    ) -> None:
        """构建合并转发的一个节点

        Args:
            target (Union[int, Friend, Member, Stranger]): 发送者 QQ
            time (datetime): 发送时间
            message (MessageChain): 发送的消息链
            name (str): 显示的发送者名称
        """
        if target is not ...:
            if isinstance(target, int):
                data.update(senderId=target)
            else:
                data.update(senderId=target.id)
                if isinstance(target, Member):
                    data.update(senderName=target.name)
                else:
                    data.update(senderName=target.nickname)
        if time is not ...:
            data.update(time=time)
        if name is not ...:
            data.update(senderName=name)
        if message is not ...:
            data.update(messageChain=message)
        super().__init__(**data)

message_chain class-attribute 🔗

message_chain: Optional[MessageChain] = Field(None, alias='messageChain')

发送的消息链

message_id class-attribute 🔗

message_id: Optional[int] = Field(None, alias='messageId')

缓存的消息 ID

sender_id class-attribute 🔗

sender_id: int = Field(None, alias='senderId')

发送者 QQ 号 (决定显示头像)

sender_name class-attribute 🔗

sender_name: str = Field(None, alias='senderName')

发送者显示名字

time class-attribute 🔗

time: datetime

发送时间

__init__ 🔗

__init__(
    target: Union[int, Friend, Member, Stranger] = Ellipsis,
    time: datetime = Ellipsis,
    message: MessageChain = Ellipsis,
    name: str = Ellipsis,
    **data
) -> None

构建合并转发的一个节点

Parameters:

Source code in graia/ariadne/message/element.py
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
def __init__(
    self,
    target: Union[int, Friend, Member, Stranger] = ...,
    time: datetime = ...,
    message: "MessageChain" = ...,
    name: str = ...,
    **data,
) -> None:
    """构建合并转发的一个节点

    Args:
        target (Union[int, Friend, Member, Stranger]): 发送者 QQ
        time (datetime): 发送时间
        message (MessageChain): 发送的消息链
        name (str): 显示的发送者名称
    """
    if target is not ...:
        if isinstance(target, int):
            data.update(senderId=target)
        else:
            data.update(senderId=target.id)
            if isinstance(target, Member):
                data.update(senderName=target.name)
            else:
                data.update(senderName=target.nickname)
    if time is not ...:
        data.update(time=time)
    if name is not ...:
        data.update(senderName=name)
    if message is not ...:
        data.update(messageChain=message)
    super().__init__(**data)

Image 🔗

Bases: MultimediaElement

指示消息中的图片元素

Source code in graia/ariadne/message/element.py
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
class Image(MultimediaElement):
    """指示消息中的图片元素"""

    type = "Image"

    id: Optional[str] = Field(None, alias="imageId")

    def __init__(
        self,
        id: Optional[str] = None,
        url: Optional[str] = None,
        *,
        path: Optional[Union[Path, str]] = None,
        base64: Optional[str] = None,
        data_bytes: Union[None, bytes, BytesIO] = None,
        **kwargs,
    ) -> None:
        super().__init__(id=id, url=url, path=path, base64=base64, data_bytes=data_bytes, **kwargs)

    def to_flash_image(self) -> "FlashImage":
        """将 Image 转换为 FlashImage

        Returns:
            FlashImage: 转换后的 FlashImage
        """
        return FlashImage.parse_obj({**self.dict(), "type": "FlashImage"})

    @classmethod
    def from_flash_image(cls, flash: "FlashImage") -> "Image":
        """从 FlashImage 构造 Image

        Returns:
            Image: 构造出的 Image
        """
        return cls.parse_obj({**flash.dict(), "type": "Image"})

    def __str__(self) -> str:
        return "[图片]"

from_flash_image classmethod 🔗

from_flash_image(flash: FlashImage) -> Image

从 FlashImage 构造 Image

Returns:

  • Image( Image ) –

    构造出的 Image

Source code in graia/ariadne/message/element.py
720
721
722
723
724
725
726
727
@classmethod
def from_flash_image(cls, flash: "FlashImage") -> "Image":
    """从 FlashImage 构造 Image

    Returns:
        Image: 构造出的 Image
    """
    return cls.parse_obj({**flash.dict(), "type": "Image"})

to_flash_image 🔗

to_flash_image() -> FlashImage

将 Image 转换为 FlashImage

Returns:

  • FlashImage( FlashImage ) –

    转换后的 FlashImage

Source code in graia/ariadne/message/element.py
712
713
714
715
716
717
718
def to_flash_image(self) -> "FlashImage":
    """将 Image 转换为 FlashImage

    Returns:
        FlashImage: 转换后的 FlashImage
    """
    return FlashImage.parse_obj({**self.dict(), "type": "FlashImage"})

ImageType 🔗

Bases: Enum

Image 类型的枚举.

Source code in graia/ariadne/message/element.py
567
568
569
570
571
572
573
574
575
576
577
578
579
580
class ImageType(Enum):
    """Image 类型的枚举."""

    Friend = "Friend"
    """好友消息"""

    Group = "Group"
    """群组消息"""

    Temp = "Temp"
    """临时消息"""

    Unknown = "Unknown"
    """未知消息"""

Friend class-attribute 🔗

Friend = 'Friend'

好友消息

Group class-attribute 🔗

Group = 'Group'

群组消息

Temp class-attribute 🔗

Temp = 'Temp'

临时消息

Unknown class-attribute 🔗

Unknown = 'Unknown'

未知消息

Json 🔗

Bases: Element

表示消息中的 JSON 消息元素

Source code in graia/ariadne/message/element.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
class Json(Element):
    """表示消息中的 JSON 消息元素"""

    type = "Json"

    Json: str = Field(None, alias="json")
    """JSON 文本"""

    def __init__(self, json: Union[dict, list, str], **kwargs) -> None:
        if isinstance(json, (dict, list)):
            json = j_dump(json)
        super().__init__(json=json, **kwargs)

    def __str__(self) -> str:
        return "[JSON消息]"

Json class-attribute 🔗

Json: str = Field(None, alias='json')

JSON 文本

MarketFace 🔗

Bases: Element

表示消息中的商城表情.

Source code in graia/ariadne/message/element.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
@internal_cls()
class MarketFace(Element):
    """表示消息中的商城表情."""

    type: str = "MarketFace"

    face_id: Optional[int] = Field(None, alias="id")
    """QQ 表情编号"""

    name: Optional[str] = None
    """QQ 表情名称"""

    def __str__(self) -> str:
        return f"[商城表情: {self.name or self.face_id}]"

    def __eq__(self, other) -> bool:
        return isinstance(other, MarketFace) and (self.face_id == other.face_id or self.name == other.name)

face_id class-attribute 🔗

face_id: Optional[int] = Field(None, alias='id')

QQ 表情编号

name class-attribute 🔗

name: Optional[str] = None

QQ 表情名称

MiraiCode 🔗

Bases: Element

Mirai 码, 并不建议直接使用. Ariadne 也不会提供互转换接口.

Source code in graia/ariadne/message/element.py
558
559
560
561
562
563
564
class MiraiCode(Element):
    """Mirai 码, 并不建议直接使用. Ariadne 也不会提供互转换接口."""

    type = "MiraiCode"

    code: str
    """Mirai Code"""

code class-attribute 🔗

code: str

Mirai Code

MultimediaElement 🔗

Bases: Element

指示多媒体消息元素.

Source code in graia/ariadne/message/element.py
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
class MultimediaElement(Element):
    """指示多媒体消息元素."""

    id: Optional[str]
    """元素 ID"""

    url: Optional[str] = None
    """元素的下载 url"""

    base64: Optional[str] = None
    """元素的 base64"""

    def __init__(
        self,
        id: Optional[str] = None,
        url: Optional[str] = None,
        *,
        path: Optional[Union[Path, str]] = None,
        base64: Optional[str] = None,
        data_bytes: Union[None, bytes, BytesIO] = None,
        **kwargs,
    ) -> None:
        """
        id (str, optional): 元素 ID
        url (str, optional): 元素的下载 url
        path (Union[Path, str], optional): 文件路径
        data_bytes (Union[None, BytesIO, bytes], optional): 元素的字节数据
        """
        data = {"id": value for key, value in kwargs.items() if key.lower().endswith("id")}

        if sum([bool(url), bool(path), bool(base64)]) > 1:
            raise ValueError("Too many binary initializers!")
        # Web initializer
        data["id"] = data.get("id", id)
        data["url"] = url
        # Binary initializer
        if path:
            if isinstance(path, str):
                path = Path(path)
            if not path.exists():
                raise FileNotFoundError(f"{path} is not exist!")
            data["base64"] = b64encode(path.read_bytes())
        elif base64:
            data["base64"] = base64
        elif data_bytes:
            if isinstance(data_bytes, bytes):
                data["base64"] = b64encode(data_bytes)
            if isinstance(data_bytes, BytesIO):
                data["base64"] = b64encode(data_bytes.read())
        super().__init__(**data, **kwargs)

    async def get_bytes(self) -> bytes:
        """尝试获取消息元素的 bytes, 注意, 你无法获取并不包含 url 且不包含 base64 属性的本元素的 bytes.

        Raises:
            ValueError: 你尝试获取并不包含 url 属性的本元素的 bytes.

        Returns:
            bytes: 元素原始数据
        """
        from ..app import Ariadne

        if self.base64:
            return b64decode(self.base64)
        if not self.url:
            raise ValueError("you should offer a url.")
        session = Ariadne.launch_manager.get_interface(AiohttpClientInterface).service.session
        async with session.get(self.url) as response:
            response.raise_for_status()
            data = await response.read()
            self.base64 = b64encode(data).decode("ascii")
            return data

    def as_persistent_string(self, binary: bool = True) -> str:
        if binary:
            return super().as_persistent_string()
        else:
            data: str = escape_bracket(
                j_dump(
                    self.dict(
                        exclude={"type", "base64"},
                    ),
                    indent=None,
                    separators=(",", ":"),
                )
            )
        return f"[mirai:{self.type}:{data}]"

    @property
    def uuid(self):
        """多媒体元素的 uuid, 即元素在 mirai 内部的标识"""
        return self.id.split(".")[0].strip("/{}").lower() if self.id else ""

    def __eq__(self, other: "MultimediaElement"):
        if self.__class__ is not other.__class__:
            return False
        if self.uuid and self.uuid == other.uuid:
            return True
        if self.url and self.url == other.url:
            return True
        return self.base64 and self.base64 == other.base64

base64 class-attribute 🔗

base64: Optional[str] = None

元素的 base64

id class-attribute 🔗

id: Optional[str]

元素 ID

url class-attribute 🔗

url: Optional[str] = None

元素的下载 url

__init__ 🔗

__init__(
    id: Optional[str] = None,
    url: Optional[str] = None,
    *,
    path: Optional[Union[Path, str]] = None,
    base64: Optional[str] = None,
    data_bytes: Union[None, bytes, BytesIO] = None,
    **kwargs
) -> None

id (str, optional): 元素 ID url (str, optional): 元素的下载 url path (Union[Path, str], optional): 文件路径 data_bytes (Union[None, BytesIO, bytes], optional): 元素的字节数据

Source code in graia/ariadne/message/element.py
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
def __init__(
    self,
    id: Optional[str] = None,
    url: Optional[str] = None,
    *,
    path: Optional[Union[Path, str]] = None,
    base64: Optional[str] = None,
    data_bytes: Union[None, bytes, BytesIO] = None,
    **kwargs,
) -> None:
    """
    id (str, optional): 元素 ID
    url (str, optional): 元素的下载 url
    path (Union[Path, str], optional): 文件路径
    data_bytes (Union[None, BytesIO, bytes], optional): 元素的字节数据
    """
    data = {"id": value for key, value in kwargs.items() if key.lower().endswith("id")}

    if sum([bool(url), bool(path), bool(base64)]) > 1:
        raise ValueError("Too many binary initializers!")
    # Web initializer
    data["id"] = data.get("id", id)
    data["url"] = url
    # Binary initializer
    if path:
        if isinstance(path, str):
            path = Path(path)
        if not path.exists():
            raise FileNotFoundError(f"{path} is not exist!")
        data["base64"] = b64encode(path.read_bytes())
    elif base64:
        data["base64"] = base64
    elif data_bytes:
        if isinstance(data_bytes, bytes):
            data["base64"] = b64encode(data_bytes)
        if isinstance(data_bytes, BytesIO):
            data["base64"] = b64encode(data_bytes.read())
    super().__init__(**data, **kwargs)

get_bytes async 🔗

get_bytes() -> bytes

尝试获取消息元素的 bytes, 注意, 你无法获取并不包含 url 且不包含 base64 属性的本元素的 bytes.

Raises:

  • ValueError

    你尝试获取并不包含 url 属性的本元素的 bytes.

Returns:

  • bytes( bytes ) –

    元素原始数据

Source code in graia/ariadne/message/element.py
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
async def get_bytes(self) -> bytes:
    """尝试获取消息元素的 bytes, 注意, 你无法获取并不包含 url 且不包含 base64 属性的本元素的 bytes.

    Raises:
        ValueError: 你尝试获取并不包含 url 属性的本元素的 bytes.

    Returns:
        bytes: 元素原始数据
    """
    from ..app import Ariadne

    if self.base64:
        return b64decode(self.base64)
    if not self.url:
        raise ValueError("you should offer a url.")
    session = Ariadne.launch_manager.get_interface(AiohttpClientInterface).service.session
    async with session.get(self.url) as response:
        response.raise_for_status()
        data = await response.read()
        self.base64 = b64encode(data).decode("ascii")
        return data

uuid property 🔗

uuid()

多媒体元素的 uuid, 即元素在 mirai 内部的标识

Source code in graia/ariadne/message/element.py
678
679
680
681
@property
def uuid(self):
    """多媒体元素的 uuid, 即元素在 mirai 内部的标识"""
    return self.id.split(".")[0].strip("/{}").lower() if self.id else ""

MusicShare 🔗

Bases: Element

表示消息中音乐分享消息元素

Source code in graia/ariadne/message/element.py
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
class MusicShare(Element):
    """表示消息中音乐分享消息元素"""

    type = "MusicShare"

    kind: MusicShareKind
    """音乐分享的来源"""

    title: Optional[str]
    """音乐标题"""

    summary: Optional[str]
    """音乐摘要"""

    jumpUrl: Optional[str]
    """音乐跳转链接"""

    pictureUrl: Optional[str]
    """音乐图片链接"""

    musicUrl: Optional[str]
    """音乐链接"""

    brief: Optional[str]
    """音乐简介"""

    def __init__(
        self,
        kind: MusicShareKind,
        title: Optional[str] = None,
        summary: Optional[str] = None,
        jumpUrl: Optional[str] = None,
        pictureUrl: Optional[str] = None,
        musicUrl: Optional[str] = None,
        brief: Optional[str] = None,
        *_,
        **__,
    ) -> None:
        super().__init__(
            kind=kind,
            title=title,
            summary=summary,
            jumpUrl=jumpUrl,
            pictureUrl=pictureUrl,
            musicUrl=musicUrl,
            brief=brief,
        )

    def __str__(self) -> str:
        return f"[音乐分享:{self.title}, {self.brief}]"

brief class-attribute 🔗

brief: Optional[str]

音乐简介

jumpUrl class-attribute 🔗

jumpUrl: Optional[str]

音乐跳转链接

kind class-attribute 🔗

kind: MusicShareKind

音乐分享的来源

musicUrl class-attribute 🔗

musicUrl: Optional[str]

音乐链接

pictureUrl class-attribute 🔗

pictureUrl: Optional[str]

音乐图片链接

summary class-attribute 🔗

summary: Optional[str]

音乐摘要

title class-attribute 🔗

title: Optional[str]

音乐标题

MusicShareKind 🔗

Bases: str, Enum

音乐分享的来源。

Source code in graia/ariadne/message/element.py
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
class MusicShareKind(str, Enum):
    """音乐分享的来源。"""

    NeteaseCloudMusic = "NeteaseCloudMusic"
    """网易云音乐"""

    QQMusic = "QQMusic"
    """QQ音乐"""

    MiguMusic = "MiguMusic"
    """咪咕音乐"""

    KugouMusic = "KugouMusic"
    """酷狗音乐"""

    KuwoMusic = "KuwoMusic"
    """酷我音乐"""

KugouMusic class-attribute 🔗

KugouMusic = 'KugouMusic'

酷狗音乐

KuwoMusic class-attribute 🔗

KuwoMusic = 'KuwoMusic'

酷我音乐

MiguMusic class-attribute 🔗

MiguMusic = 'MiguMusic'

咪咕音乐

NeteaseCloudMusic class-attribute 🔗

NeteaseCloudMusic = 'NeteaseCloudMusic'

网易云音乐

QQMusic class-attribute 🔗

QQMusic = 'QQMusic'

QQ音乐

Plain 🔗

Bases: Element, BaseText

代表消息中的文本元素

Source code in graia/ariadne/message/element.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
class Plain(Element, BaseText):
    """代表消息中的文本元素"""

    type: str = "Plain"

    text: str
    """实际的文本"""

    def __init__(self, text: str, **kwargs) -> None:
        """实例化一个 Plain 消息元素, 用于承载消息中的文字.

        Args:
            text (str): 元素所包含的文字
        """
        super().__init__(text=text)  # type: ignore

    def __str__(self) -> str:
        return self.text

    def as_persistent_string(self) -> str:
        return self.text

    def __eq__(self, other: object) -> bool:
        return isinstance(other, (Plain, BaseText)) and self.text == other.text

text class-attribute 🔗

text: str

实际的文本

__init__ 🔗

__init__(text: str, **kwargs) -> None

实例化一个 Plain 消息元素, 用于承载消息中的文字.

Parameters:

  • text (str) –

    元素所包含的文字

Source code in graia/ariadne/message/element.py
107
108
109
110
111
112
113
def __init__(self, text: str, **kwargs) -> None:
    """实例化一个 Plain 消息元素, 用于承载消息中的文字.

    Args:
        text (str): 元素所包含的文字
    """
    super().__init__(text=text)  # type: ignore

Poke 🔗

Bases: Element

表示消息中戳一戳消息元素

Source code in graia/ariadne/message/element.py
323
324
325
326
327
328
329
330
331
332
333
334
335
class Poke(Element):
    """表示消息中戳一戳消息元素"""

    type = "Poke"

    name: PokeMethods
    """戳一戳使用的方法"""

    def __init__(self, name: PokeMethods, *_, **__) -> None:
        super().__init__(name=name)

    def __str__(self) -> str:
        return f"[戳一戳:{self.name}]"

name class-attribute 🔗

name: PokeMethods

戳一戳使用的方法

PokeMethods 🔗

Bases: str, Enum

戳一戳可用方法

Source code in graia/ariadne/message/element.py
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
class PokeMethods(str, Enum):
    """戳一戳可用方法"""

    ChuoYiChuo = "ChuoYiChuo"
    """戳一戳"""

    BiXin = "BiXin"
    """比心"""

    DianZan = "DianZan"
    """点赞"""

    XinSui = "XinSui"
    """心碎"""

    LiuLiuLiu = "LiuLiuLiu"
    """666"""

    FangDaZhao = "FangDaZhao"
    """放大招"""

    BaoBeiQiu = "BaoBeiQiu"
    """宝贝球"""

    Rose = "Rose"
    """玫瑰花"""

    ZhaoHuanShu = "ZhaoHuanShu"
    """召唤术"""

    RangNiPi = "RangNiPi"
    """让你皮"""

    JeiYin = "JeiYin"
    """结印"""

    ShouLei = "ShouLei"
    """手雷"""

    GouYin = "GouYin"
    """勾引"""

    ZhuaYiXia = "ZhuaYiXia"
    """抓一下"""

    SuiPing = "SuiPing"
    """碎屏"""

    QiaoMen = "QiaoMen"
    """敲门"""

    Unknown = "Unknown"
    """未知戳一戳"""

    @staticmethod
    def _missing_(_) -> "PokeMethods":
        return PokeMethods.Unknown

BaoBeiQiu class-attribute 🔗

BaoBeiQiu = 'BaoBeiQiu'

宝贝球

BiXin class-attribute 🔗

BiXin = 'BiXin'

比心

ChuoYiChuo class-attribute 🔗

ChuoYiChuo = 'ChuoYiChuo'

戳一戳

DianZan class-attribute 🔗

DianZan = 'DianZan'

点赞

FangDaZhao class-attribute 🔗

FangDaZhao = 'FangDaZhao'

放大招

GouYin class-attribute 🔗

GouYin = 'GouYin'

勾引

JeiYin class-attribute 🔗

JeiYin = 'JeiYin'

结印

LiuLiuLiu class-attribute 🔗

LiuLiuLiu = 'LiuLiuLiu'

666

QiaoMen class-attribute 🔗

QiaoMen = 'QiaoMen'

敲门

RangNiPi class-attribute 🔗

RangNiPi = 'RangNiPi'

让你皮

Rose class-attribute 🔗

Rose = 'Rose'

玫瑰花

ShouLei class-attribute 🔗

ShouLei = 'ShouLei'

手雷

SuiPing class-attribute 🔗

SuiPing = 'SuiPing'

碎屏

Unknown class-attribute 🔗

Unknown = 'Unknown'

未知戳一戳

XinSui class-attribute 🔗

XinSui = 'XinSui'

心碎

ZhaoHuanShu class-attribute 🔗

ZhaoHuanShu = 'ZhaoHuanShu'

召唤术

ZhuaYiXia class-attribute 🔗

ZhuaYiXia = 'ZhuaYiXia'

抓一下

Voice 🔗

Bases: MultimediaElement

指示消息中的语音元素

Source code in graia/ariadne/message/element.py
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
class Voice(MultimediaElement):
    """指示消息中的语音元素"""

    type = "Voice"

    id: Optional[str] = Field(None, alias="voiceId")

    def __init__(
        self,
        id: Optional[str] = None,
        url: Optional[str] = None,
        *,
        path: Optional[Union[Path, str]] = None,
        base64: Optional[str] = None,
        data_bytes: Union[None, bytes, BytesIO] = None,
        **kwargs,
    ) -> None:
        super().__init__(id=id, url=url, path=path, base64=base64, data_bytes=data_bytes, **kwargs)

    length: Optional[int]
    """语音长度"""

    def __str__(self) -> str:
        return "[语音]"

length class-attribute 🔗

length: Optional[int]

语音长度

Xml 🔗

Bases: Element

表示消息中的 XML 消息元素

Source code in graia/ariadne/message/element.py
217
218
219
220
221
222
223
224
225
226
227
228
229
class Xml(Element):
    """表示消息中的 XML 消息元素"""

    type = "Xml"

    xml: str
    """XML文本"""

    def __init__(self, xml: str, **_) -> None:
        super().__init__(xml=xml)

    def __str__(self) -> str:
        return "[XML消息]"

xml class-attribute 🔗

xml: str

XML文本