Skip to content

事件列表

SDK 通过 WebSocket 接收 QQ 机器人平台推送的实时事件。继承 Client 并实现 on_* 方法来监听事件。

事件注册机制

当 WebSocket 收到事件时,ConnectionStateparse_* 方法将原始数据解析为模型对象,然后通过 Client.ws_dispatch 调用对应的 on_* 方法。

源码位置:

解析流程

WebSocket 收到事件 payload
  → ConnectionState.parsers 匹配 parse_{event_name}
  → 创建领域模型对象 (Guild/Message/Member 等)
  → Client.ws_dispatch("event_name", model_object)
  → 查找 Client 的 on_event_name 方法
  → _schedule_event 将协程包装为 asyncio.Task 执行

parsers 自动发现

ConnectionState.__init__ 中使用 inspect.getmembers(self) 自动发现所有以 parse_ 开头的方法,并建立 {event_name: parse_method} 映射:

python
self.parsers: Dict[str, Callable[[Any], None]]
self.parsers = {}
for attr, func in inspect.getmembers(self):
    if attr.startswith("parse_"):
        self.parsers[attr[6:].lower()] = func

源码位置:botpy/connection.py 第 84-88 行

ws_dispatch 分发

python
def ws_dispatch(self, event: str, *args: Any, **kwargs: Any) -> None:
    method = "on_" + event
    if hasattr(self, method):
        coro = getattr(self, method)
        self._schedule_event(coro, method, *args, **kwargs)

源码位置:botpy/client.py 第 250-262 行

事件注册示例

python
class MyClient(botpy.Client):
    # 方法名 = "on_" + 事件名(小写)
    async def on_at_message_create(self, message: Message):
        # 处理 @消息 事件
        pass

事件分类

分类对应 Intents说明
频道/子频道事件guilds频道创建、更新、删除,子频道变化
消息事件public_guild_messages / guild_messages / direct_message / message_audit@消息、消息创建/删除、私信、审核
成员事件guild_members成员加入、更新、退出
表态事件guild_message_reactions消息表情表态
音频事件audio_action音频播放、上/下麦
论坛事件forums / open_forum_event论坛帖子/评论
互动事件interaction按钮回调等
群管理事件public_messages群添加/移除机器人、C2C 好友事件
音视频成员事件audio_or_live_channel_member用户进出音视频/直播子频道

事件与模型对照表

事件方法parse_* 方法领域模型模型位置
on_guild_createparse_guild_createGuildbotpy/guild.py
on_channel_createparse_channel_createChannelbotpy/channel.py
on_at_message_createparse_at_message_createMessagebotpy/message.py
on_guild_member_addparse_guild_member_addMemberbotpy/user.py
on_message_reaction_addparse_message_reaction_addReactionbotpy/reaction.py
on_audio_startparse_audio_startAudiobotpy/audio.py
on_forum_thread_createparse_forum_thread_createThreadbotpy/forum.py
on_interaction_createparse_interaction_createInteractionbotpy/interaction.py
on_group_at_message_createparse_group_at_message_createGroupMessagebotpy/message.py
on_c2c_message_createparse_c2c_message_createC2CMessagebotpy/message.py
on_group_add_robotparse_group_add_robotGroupManageEventbotpy/manage.py
on_friend_addparse_friend_addC2CManageEventbotpy/manage.py
on_audio_or_live_channel_member_enterparse_audio_or_live_channel_member_enterPublicAudiobotpy/audio.py
on_open_forum_thread_createparse_open_forum_thread_createOpenThreadbotpy/forum.py