Bot(机器人)

Bot 是 Matrix 适配器的核心类,继承自 NoneBot 的 Bot 基类和 API 客户端,封装了所有用户可见的 Matrix 操作。

核心 API

发送消息
房间操作

属性

Bot.user_id
Bot.device_id
Bot.bot_info
Bot.self_info
Bot.next_batch: str | None
Bot.crypto: CryptoEngine | None

方法参考

async Bot.send(event, message, **kwargs)[源代码]

调用机器人基础发送消息接口

返回类型:

EventIdResponse

参数:
  • event (Event)

  • message (str | Message | MessageSegment)

  • kwargs (Any)

参数:

event: 上报事件 message: 要发送的消息 kwargs: 任意额外参数

向事件来源房间发送消息。消息类型遵循 Matrix 规范,支持纯文本、HTML、表情和通知。

若房间启用了 E2EE,消息会自动用 Megolm 加密。

参数:
  • event -- 必须为 MessageEvent 类型,需要包含 room_id。

  • message -- 字符串 / Message / MessageSegment。

  • **kwargs -- 额外参数(如 txn_id)。

返回:

EventIdResponse -- 包含已发送事件的 event_id。

Bot.get_room(room_id)[源代码]
返回类型:

Room | None

参数:

room_id (str)

返回已同步的 Room 对象。房间对象提供 enable_encryption、send、 send_attachment、decrypt_event 和 discard_room_key。

Bot.encryption()[源代码]
返回类型:

CryptoEngine

返回 CryptoEngine。E2EE 初始化失败或显式关闭时会抛出 CryptoError, 不会自动降级为明文。

async Bot.send_to(room_id, message, **kwargs)[源代码]
返回类型:

EventIdResponse

参数:

向指定房间发送消息。与 send 相同,但显式指定 room_id。

async Bot.send_event(*, room_id, event_type, txn_id, content)[源代码]

Send an arbitrary room event via _api_send_event.

Supports custom event types such as m.room.encrypted.

返回类型:

EventIdResponse

参数:

发送任意类型的 Matrix 房间事件。用于发送非 m.room.message 的事件(如 m.room.encrypted)。

async Bot.react(room_id, event_id, key, *, txn_id=None)[源代码]
返回类型:

EventIdResponse

参数:

对指定事件发送表情反应(m.reaction annotation)。

参数:
  • room_id -- 房间 ID。

  • event_id -- 目标事件 ID。

  • key -- 反应 key,如 "👍"。

  • txn_id -- 事务 ID(可选,默认自动生成)。

async Bot.redact(room_id, event_id, *, reason=None, txn_id=None)[源代码]
返回类型:

EventIdResponse

参数:

撤回(redact)指定事件。

参数:
  • room_id -- 房间 ID。

  • event_id -- 要撤回的事件 ID。

  • reason -- 撤回原因(可选)。

  • txn_id -- 事务 ID(可选)。

async Bot.join_room(*, room_id, reason=None)[源代码]

Join a Matrix room by ID. Returns the room_id of the joined room.

返回类型:

JoinRoomResponse

参数:

加入 Matrix 房间。

参数:
  • room_id -- 房间 ID 或别名。

  • reason -- 加入原因(可选)。

返回:

JoinRoomResponse

async Bot.set_typing_state(room_id, *, typing=True, timeout=None)[源代码]
返回类型:

None

参数:

设置机器人的输入状态。

参数:
  • room_id -- 房间 ID。

  • typing -- 是否正在输入。

  • timeout -- 超时时间(毫秒,可选)。

async Bot.mark_read(room_id, event_id, *, receipt_type='m.read', thread_id=None)[源代码]
返回类型:

None

参数:

向房间发送已读回执。

参数:
  • room_id -- 房间 ID。

  • event_id -- 标记为已读的事件 ID。

  • receipt_type -- 回执类型,默认 "m.read"。

  • thread_id -- 线程 ID(可选)。

async Bot.upload_media(content, *, filename=None, content_type=None)[源代码]
返回类型:

UploadResponse

参数:
  • content (bytes)

  • filename (str | None)

  • content_type (str | None)

上传媒体内容到 Matrix homeserver 的 media repository。

参数:
  • content -- 媒体二进制数据。

  • filename -- 文件名(可选)。

  • content_type -- MIME Type(可选)。

返回:

UploadResponse -- 包含 content_uri``(即 ``mxc:// URI)。