This repository was archived by the owner on Aug 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
消息链基础
Tarrailt edited this page Nov 20, 2021
·
3 revisions
QQ 消息并不只是纯文本, 也不只是单一类型的消息. 文本中可以夹杂着图片, At 某人等多种类型的消息.
在 mirai-core 的设计中, mamoe 的开发者们使用的不是一串字符串, 而是一个列表来表示消息,即消息链 (Message Chain)这一方式
消息链可以看作是一系列元素 (Element) 构成的列表. 消息组件表示消息中的一部分, 比如纯文本Plain
, At 某人 At
等等.
关于可用的元素, 参看mirai-api-http的 API 文档.
Cesloi关于消息链的部分在arclet/cesloi/message/里:
from arclet.cesloi.message.messageChain import MessageChain
msg = MessageChain.create("Hello,World!")
>>>msg.to_text()
'Hello,World!'
构造新的消息链时, 建议采用 MessageChain.create(),如
message_chain = MessageChain.create(
At(12345),
Plain("Hello World!")
)
MessageChain.create() 方法支持直接使用字符串,如
message_chain = MessageChain.create(
At(12345),
"Hello World!"
)
也可以直接实例化,如
message_chain = MessageChain([
At(12345),
Plain("Hello World!")
])
如果只发送文本消息, 可以使用MessageChain.from_text(),如
message_chain = MessageChain.from_text("Hello World!")
使用 MessageChain.to_text() 可以将消息连内容以纯文本形式表示.表示的格式类似于手机 QQ 在通知栏消息中的格式, 例如图片会被转化为 [图片], 等等.
>>> msg = MessageChain.create("你好,",At(123456),",我是BOT",Image(path='test.png'))
>>> msg.to_text()
'你好,@123456,我是BOT[图片]'
使用 MessageChain.to_serialization() 可以将消息链尽量以序列化形式保存.
>>> msg = MessageChain.create("你好,",At(123456),",我是BOT",Image(url="https://www.baidu.com"))
>>> msg.to_serialization()
'__root__: 你好,[mirai:At:{"target": 123456}],我是BOT[mirai:Image:{"url": "https://www.baidu.com"}]'
可以使用 for 循环遍历消息链中的元素.
for element in message_chain:
print(element.to_text())
使用 MessageChain.findall() 可以获取消息链中指定元素类型的所有消息元素
>>>msg.findall(Plain)
[Plain("你好,"), Plain(",我是BOT")]
使用 MessageChain.find() 可以获取消息链中指定元素类型的第一个消息元素,否则返回False,类似于列表的寻找操作
>>>msg.findall(Plain)
Plain("你好,")
>>>msg.findall(Face)
False