Skip to content

监听事件

有多种方式可以监听各种事件, 对于Kotlin使用者推荐使用subscribe机制dsl机制

Kotlin

Subscribe

kotlin
val bot = MilkyBotFactory.createBot("http://127.0.0.1:3000", "114514")
bot.subscribe<GroupMessageEvent> {
    println(it.event.reply("114514"))
}

DSL

kotlin
val bot = MilkyBotFactory.createBot("http://127.0.0.1:3000", "114514")
with(bot.listener) {
    onGroupMessage {
        println(it.event.segments.text)
    }
}

Java

对于Java使用者只能继承Listener类重写需要监听的事件方法

java
public class EventListener {
    public static void main(String[] args) {
        BotInstance bot = MilkyBotFactory.createBot("ws://127.0.0.1:3000", "114514");
        MilkyListener listener = new MilkyListener() {
            @Override
            public void onGroupMessage(@NotNull GroupMessageEvent event) {
                event.getEvent().replyAsync("Hello");
            }
        };
        bot.setListener(listener);
    }
}

以Apache-2.0开源协议开源