处理好友请求和加群请求
约 575 字大约 2 分钟
2025-04-22
后台模式
from ncatbot.core import BotClient, RequestEvent
from ncatbot.utils import get_log
import time
LOG = get_log("request_example")
bot = BotClient()
@bot.on_request
def handle_request(msg: RequestEvent):
# 同步版本
comment = msg.comment # 获取验证信息
if msg.is_friend_request():
LOG.info(f"收到好友请求,验证信息:{comment}")
if "特定关键词" in comment:
LOG.info("通过好友请求")
msg.reply_sync(True, remark="好友的名字")
else:
LOG.info("拒绝好友请求")
msg.reply_sync(False)
@bot.on_request
async def handle_request_async(msg: Request):
# 异步版本
comment = msg.comment # 获取验证信息
if msg.is_group_request():
LOG.info(f"收到加群请求,验证信息:{comment}")
if "特定关键词" in comment:
await msg.reply(True)
else:
await msg.reply(False, reason="拒绝你的请求")
api = bot.run_backend(bt_uin="987654", root="456789")
time.sleep(86400) # 睡眠, 此时 NcatBot 仍然在运行,收到好友请求后将调用 handle_request 函数
bot.exit() # 退出 NcatBot
- 上面代码包含同步和异步两个版本,功能完全一致,且都支持使用
add_request_handler
添加。
前台模式(插件版)
了解插件。
plugin.py
from ncatbot.plugin_system import NcatBotPlugin, on_request
from ncatbot.utils import OFFICIAL_REQUEST_EVENT
from ncatbot.core import Request
bot = CompatibleEnrollment()
class RequestHandlerPlugin(BasePlugin):
name = "RequestHandler"
version = "1.0.0"
dependencies = {}
async def on_load(self):
print(f"{self.name} 插件已加载")
self.register_handler(OFFICIAL_REQUEST_EVENT, self.handle_request_async)
@on_request
def handle_request(msg: RequestEvent):
# 同步版本
comment = msg.comment # 获取验证信息
if msg.is_friend_request():
LOG.info(f"收到好友请求,验证信息:{comment}")
if "特定关键词" in comment:
LOG.info("通过好友请求")
msg.reply_sync(True, remark="好友的名字")
else:
LOG.info("拒绝好友请求")
msg.reply_sync(False)
async def handle_request_async(msg: NcatBotEvent):
# 获取实际数据
msg: RequestEvent = msg.data # 官方事件的数据格式有一定约定
# 异步版本
comment = msg.comment # 获取验证信息
if msg.is_group_request():
LOG.info(f"收到加群请求,验证信息:{comment}")
if "特定关键词" in comment:
await msg.reply(True)
else:
await msg.reply(False, reason="拒绝你的请求")
- 同步版本使用了
UnifiedRegistry
内置插件提供的on_request
装饰器来注册请求处理器参考。(on_request
装饰器也可以用于普通方法) - 异步版本使用了
register_handler
方法来注册请求处理器,参考。
main.py
from ncatbot.core import BotClient
bot = BotClient()
bot.run_frontend(bt_uin="456789", root="987654")
- 运行
main.py
即可启动 NcatBot,插件中的请求处理器将会生效。
版权所有
版权归属:huan-yp