使用 Java 快速制作 QQ 機器人

今日分享一個 mirai 的 java 版本框架:happysnaker/hbot: HBot 是一款整合 mirai 與 springboot 的輕量級群聊機器人框架,內(nèi)置 ChatGpt,現(xiàn)代化 Java 風格,基于 Jdk17,最小依賴,可以快速搭建一個群聊機器人,也可引入插件功能或作為插件發(fā)布。 (github.com)。

想要實現(xiàn)一個關(guān)鍵字機器人非常簡單,分三步走!

引入依賴

首先需要創(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)回復,一個關(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 則是匹配到的動作,這僅僅只是一個最簡單的機器人,更多信息可去官網(wǎng)查看。

當然,我們也可以實現(xiàn)自定義的邏輯:

@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;
    }

上面這個代碼實現(xiàn)了一個復讀機器人,我們只需要使用 @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);
    }
}

運行項目,掃碼登錄,大功告成!可以在群聊中和機器人聊天啦!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容