使用 Java 快速制作 QQ 機(jī)器人

今日分享一個(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ī)器人聊天啦!

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

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

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