今日分享一个 mirai 的 java 版本框架:happysnaker/hbot: HBot 是一款整合 mirai 与 springboot 的轻量级群聊机器人框架,内置 ChatGpt,现代化 Java 风格,基于 Jdk17,最小依赖,可以快速搭建一个群聊机器人,也可引入插件功能或作为插件发布。 (github.com)。
想要实现一个关键字机器人非常简单,分三步走!
引入依赖
首先需要创建 SpringBoot 项目,SpringBoot 版本最好是 3.x,Jdk 最好是 17。
<dependency>
<groupId>io.github.happysnaker</groupId>
<artifactId>hbot-core</artifactId>
<version>0.0.3</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-core-jvm</artifactId>
<version>1.6.4</version>
</dependency>
编写处理器
使用注解的方式可以快捷的编写关键字以及相关回复,一个关键字由模式、条件、输出组成,可以参考如下代码:
@handler
@InterestFilters(value = {
// 图片地址可能过期,请自行替换为有效的 api
@InterestFilter(mode = Interest.MODE.REGEX, condition = ".*图片.*", output = "[hrobot::$quote](quote)[hrobot::$img](https://shenzilong.cn/util/redirect_to_bing_daily_picture_address)"),
@InterestFilter(mode = Interest.MODE.REGEX, condition = "早.+", output = "[hrobot::$at](sender)早早早,早上好!"),
@InterestFilter(mode = Interest.MODE.REGEX, condition = "晚安.*", output = "晚安,好梦!"),
@InterestFilter(mode = Interest.MODE.REGEX, condition = "你好.*", output = "你好,我好,大家好!"),
@InterestFilter(mode = Interest.MODE.REGEX, condition = "呜.+", output = "哭什么哭,给你淦疼了?")
})
public class InterestHandler extends AdaptInterestMessageEventHandler {
}
HBot 提供正则、匹配、前缀匹配、发送人匹配、群匹配等多种匹配模式,condition 则是具体要匹配的内容,output 则是匹配到的动作,这仅仅只是一个最简单的机器人,更多信息可去官网查看。
当然,我们也可以实现自定义的逻辑:
@handler
public class MyHandler extends GroupMessageEventHandler {
@Override
public List<MessageChain> handleMessageEvent(GroupMessageEvent event, Context ctx) {
// 复读
return buildMessageChainAsSingletonList(getPlantContent(event));
}
@Override
public boolean shouldHandle(GroupMessageEvent event, Context ctx) {
// 接收所有条件
return true;
}
上面这个代码实现了一个复读机器人,我们只需要使用 @handler 注解注册即可。
登录机器人
加上 @EnableHBot 注解,随后扫码登录机器人即可:
@SpringBootApplication
@EnableHBot
public class DemoApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(DemoApplication.class, args);
HBot.loginBotByQRCode(qq, BotConfiguration.MiraiProtocol.ANDROID_WATCH);
}
}
运行项目,扫码登录,大功告成!可以在群聊中和机器人聊天啦!