今日分享一個(gè) mirai 的 java 版本框架:happysnaker/hbot: HBot 是一款整合 mirai 與 springboot 的輕量級(jí)群聊機(jī)器人框架,內(nèi)置 ChatGpt,現(xiàn)代化 Java 風(fēng)格,基于 Jdk17,最小依賴,可以快速搭建一個(gè)群聊機(jī)器人,也可引入插件功能或作為插件發(fā)布。 (github.com)。
想要實(shí)現(xiàn)一個(gè)關(guān)鍵字機(jī)器人非常簡(jiǎn)單,分三步走!
引入依賴
首先需要?jiǎng)?chuàng)建 SpringBoot 項(xiàng)目,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>
編寫處理器
使用注解的方式可以快捷的編寫關(guān)鍵字以及相關(guān)回復(fù),一個(gè)關(guān)鍵字由模式、條件、輸出組成,可以參考如下代碼:
@handler
@InterestFilters(value = {
// 圖片地址可能過期,請(qǐng)自行替換為有效的 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 = "晚安,好夢(mèng)!"),
@InterestFilter(mode = Interest.MODE.REGEX, condition = "你好.*", output = "你好,我好,大家好!"),
@InterestFilter(mode = Interest.MODE.REGEX, condition = "嗚.+", output = "哭什么哭,給你淦疼了?")
})
public class InterestHandler extends AdaptInterestMessageEventHandler {
}
HBot 提供正則、匹配、前綴匹配、發(fā)送人匹配、群匹配等多種匹配模式,condition 則是具體要匹配的內(nèi)容,output 則是匹配到的動(dòng)作,這僅僅只是一個(gè)最簡(jiǎn)單的機(jī)器人,更多信息可去官網(wǎng)查看。
當(dāng)然,我們也可以實(shí)現(xiàn)自定義的邏輯:
@handler
public class MyHandler extends GroupMessageEventHandler {
@Override
public List<MessageChain> handleMessageEvent(GroupMessageEvent event, Context ctx) {
// 復(fù)讀
return buildMessageChainAsSingletonList(getPlantContent(event));
}
@Override
public boolean shouldHandle(GroupMessageEvent event, Context ctx) {
// 接收所有條件
return true;
}
上面這個(gè)代碼實(shí)現(xiàn)了一個(gè)復(fù)讀機(jī)器人,我們只需要使用 @handler 注解注冊(cè)即可。
登錄機(jī)器人
加上 @EnableHBot 注解,隨后掃碼登錄機(jī)器人即可:
@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);
}
}
運(yùn)行項(xiàng)目,掃碼登錄,大功告成!可以在群聊中和機(jī)器人聊天啦!