使用 Java 快速制作 QQ 机器人

今日分享一个 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);
    }
}

运行项目,扫码登录,大功告成!可以在群聊中和机器人聊天啦!

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容