基于 qq-botpy 的 QQ 机器人消息收发框架。
pip install qq-botpy
创建 config.yaml:
appid: "YOUR_APPID"
secret: "YOUR_SECRET"
public_guild_messages=Trueon_at_message_create(message: Message)from botpy.message import Messageawait message.reply(content="...")await self.api.post_message(channel_id=..., content=..., msg_id=message.id)message.author.id,频道:message.channel_id<@!botid> 前缀,需先剔除(见 scripts/bot_utils.py 中的 parse_cmd())public_messages=Trueon_c2c_message_create(message: C2CMessage)from botpy.message import C2CMessageawait message._api.post_c2c_message(openid=..., msg_type=0, msg_id=message.id, content=...)message.author.user_openidpublic_messages=Trueon_group_at_message_create(message: GroupMessage)from botpy.message import GroupMessageawait message._api.post_group_message(group_openid=..., msg_type=0, msg_id=message.id, content=...)message.author.member_openid,群:message.group_openid> C2C 和群消息共用 public_messages=True,可同时监听两者。
使用 asyncio.create_task() 启动后台协程实现定时推送:
task = asyncio.create_task(self._push_loop(key, message))
tasks[key] = task
# 取消:tasks.pop(key).cancel()
循环内用 await asyncio.sleep(seconds) 等待,用 try/except asyncio.CancelledError 优雅退出。
# Python 3.10+ 必须显式创建 event loop
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
intents = botpy.Intents(public_guild_messages=True, public_messages=True)
client = MyBot(intents=intents)
client.run(appid=config["appid"], secret=config["secret"])
见 scripts/bot_template.py,包含三种消息处理器 + 定时推送的完整可运行示例。
| 问题 | 原因 | 解决 |
|---|---|---|
| ------ | ------ | ------ |
RuntimeError: There is no current event loop | Python 3.10+ 不再自动创建 loop | 启动前调用 asyncio.new_event_loop() + asyncio.set_event_loop() |
| 收不到消息 | Intent 未开启 | C2C/群需要 public_messages=True,频道需要 public_guild_messages=True |
| 发消息失败 | msg_id 过期(被动消息有效期短) | 定时推送需申请主动消息权限,或每次收到消息后更新 msg_id |
共 1 个版本