处理好友请求和加群请求
约 520 字大约 2 分钟
2025-04-22
主动模式
from ncatbot.core import BotClient, Request
import time
def handle_request(msg: Request):
# 同步版本
comment = msg.comment # 获取验证信息
if "特定关键词" in comment:
msg.reply_sync(True, comment="请求已通过")
else:
msg.reply_sync(False, comment="请求被拒绝")
async def handle_request_async(msg: Request):
# 异步版本
comment = msg.comment # 获取验证信息
if "特定关键词" in comment:
await msg.reply(True, comment="请求已通过")
else:
await msg.reply(False, comment="请求被拒绝")
bot = BotClient()
bot.add_request_handler(handle_request)
bot.run_blocking(bt_uin="123456", root="1234567")
time.sleep(1000) # 睡眠, 此时 NcatBot 仍然在运行,收到好友请求后将调用 handle_request 函数
bot.exit() # 退出 NcatBot
add_request_handler
用于注册 Request 事件处理器,好友请求和加群请求属于 Request 类事件。- 上面代码包含同步和异步两个版本,功能完全一致,且都支持使用
add_request_handler
添加。 - 也可以使用修饰器来注册回调函数,参考回调函数。
插件模式
请先了解插件项目的文件结构,参考了解插件
from ncatbot.plugin import BasePlugin, CompatibleEnrollment
from ncatbot.core import Request
bot = CompatibleEnrollment()
class RequestHandlerPlugin(BasePlugin):
name = "RequestHandler"
version = "1.0"
@bot.request_event()
async def handle_request(self, msg: Request):
comment = msg.comment
if "特定关键词" in comment:
await msg.reply(True, comment="请求已通过")
else:
await msg.reply(False, comment="请求被拒绝")
async def handle_request_with_event(self, event: Event):
request = event.data
comment = request.comment
if "特定关键词" in comment:
await request.reply(True, comment="请求已通过")
else:
await request.reply(False, comment="请求被拒绝")
async def on_load(self):
print(f"{self.name} 插件已加载")
# self.register_handler("ncatbot.request_event", self.handle_request_with_event)
async def on_unload(self):
print(f"{self.name} 插件已卸载")
版权所有
版权归属:huan-yp