QQBot 消息收发框架
将以下提示词粘贴到你的 AI 对话框中:
请根据 https://skillhub.cn/install/skillhub.md,把 @user_e7c8a23d/qqbot-messaging 安装到你的 AI 助手中。
技能介绍
解决什么问题
做 QQ 机器人时,常见卡点不是“会不会调 API”,而是频道 @、C2C 私聊、群 @ 三类消息的 Intent、事件名、回复接口和用户标识不一致:漏开 public_guild_messages=True 会收不到频道消息,C2C 与群消息又共用 public_messages=True,但回复时分别需要 post_c2c_message 和 post_group_message。如果还要做定时推送,asyncio 循环、事件循环初始化和 msg_id 过期也会让消息链路变得不可靠。
技能如何工作
该技能围绕 qq-botpy 提供一套消息收发模板,核心是把三类场景拆成可直接对照的实现:
- 频道 @ 消息:监听
on_at_message_create(message: Message),通过message.reply(content="...")回复,主动发送时使用self.api.post_message(channel_id=..., content=..., msg_id=message.id),用户标识取message.author.id。 - C2C 私聊:监听
on_c2c_message_create(message: C2CMessage),回复走message._api.post_c2c_message(openid=..., msg_type=0, msg_id=message.id, content=...),用户标识取message.author.user_openid。 - 群 @ 消息:监听
on_group_at_message_create(message: GroupMessage),回复走message._api.post_group_message(group_openid=..., msg_type=0, msg_id=message.id, content=...),用户标识取message.author.member_openid。
它还给出定时推送的 asyncio.create_task() 后台协程模式:循环内用 await asyncio.sleep(seconds) 等待,并用 try/except asyncio.CancelledError 优雅退出。对于带指令前缀的消息,需要先用 parse_cmd() 之类的逻辑剔除前缀,再解析参数。
适用边界与注意点
- Intent 是硬依赖:频道需要
public_guild_messages=True,C2C 与群消息需要public_messages=True。 - 被动回复依赖
msg_id:被动消息有效期短,定时推送若依赖旧msg_id可能失败,通常需要主动消息权限或在收到新消息后刷新msg_id。 - Python 3.10+ 事件循环:若出现
RuntimeError: There is no current event loop,启动前需要显式调用asyncio.new_event_loop()和asyncio.set_event_loop()。
使用场景
- 在 QQ 频道里实现 @ 指令,解析消息前缀并用 reply 或 post_message 返回结果。
- 在 C2C 私聊中监听用户消息,按 open_id 调用 post_c2c_message 回复或推送。
- 在 QQ 群中处理 @ 消息,区分 member_openid 与 group_openid 后发送群回复。
- 用 asyncio 后台任务实现定时推送,并用 CancelledError 处理停止。
适合人员
- 维护 QQ 频道的 Python 后端工程师,需要把 @ 消息路由到指令处理函数。
- 做客服或通知机器人的开发者,需要在 C2C 私聊中稳定回复用户。
- 管理 QQ 群通知的工程师,需要识别群 @ 消息并按群和成员标识发送结果。
- 使用 asyncio 做后台推送的服务开发者,需要管理定时任务和优雅退出。