今日分享一個 mirai 的 java 版本框架:happysnaker/hbot: HBot 是一款整合 mirai 與 springboot 的輕量級群聊機(jī)器人框架闷煤,內(nèi)置 ChatGpt秕豫,現(xiàn)代化 Java 風(fēng)格促煮,基于 Jdk17掷漱,最小依賴壁肋,可以快速搭建一個群聊機(jī)器人,也可引入插件功能或作為插件發(fā)布粗合。 (github.com)。
想要實現(xiàn)一個關(guān)鍵字機(jī)器人非常簡單衡瓶,分三步走!
引入依賴
首先需要創(chuàng)建 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>
編寫處理器
使用注解的方式可以快捷的編寫關(guān)鍵字以及相關(guān)回復(fù)坦袍,一個關(guān)鍵字由模式十厢、條件、輸出組成捂齐,可以參考如下代碼:
@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 提供正則佃迄、匹配、前綴匹配贵少、發(fā)送人匹配呵俏、群匹配等多種匹配模式,condition 則是具體要匹配的內(nèi)容滔灶,output 則是匹配到的動作普碎,這僅僅只是一個最簡單的機(jī)器人,更多信息可去官網(wǎng)查看录平。
當(dāng)然随常,我們也可以實現(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;
}
上面這個代碼實現(xiàn)了一個復(fù)讀機(jī)器人,我們只需要使用 @handler 注解注冊即可萄涯。
登錄機(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)行項目唆鸡,掃碼登錄涝影,大功告成!可以在群聊中和機(jī)器人聊天啦争占!