Skip to content

通过实现OneBotListener来监听事件

kotlin
class TestClient : OneBotListener {

    override suspend fun onGroupMessage(message: GroupMessage, json: String) {
        println(message)
    }

    override suspend fun onWebsocketErrorEvent(event: IWebsocketErrorEvent) {
        event.exception.printStackTrace()
    }
}

suspend fun main() {
    val client = TestClient()
    val wsAddress = System.getenv("WS_ADDRESS")
    val wsAccessToken = System.getenv("WS_ACCESS_TOKEN")
    val instance1 = OneBotFactory.createClient(wsAddress, wsAccessToken, client)
}

通过EventBus来监听事件

kotlin
suspend fun main() {
    val instance1 = OneBotFactory.createClient(...)
    instance1.onEvent<GroupMessageEvent> {
        println(it)
    }
}

通过listeners dsl属性监听事件

kotlin
suspend fun main() {
    val instance1 = OneBotFactory.createClient(...)
    // 这里传入的泛型参数和上面EventBus内的一样
    instance1.subscribe<GroupMessageEvent> {
        println(it)
    }
}

通过flow来监听

kotlin
suspend fun main() {
    val instance1 = OneBotFactory.createClient(...)
    instance1.flowEvent<GroupMessageEvent> {
        collect {
            println(it.message.text)
        }
    }
}

使用flowEvent会额外启动一个线程用于collect Channel内的消息, 在有大量监听事件的情况下建议实现OneBotListener来监事件的方法

注: 这4种方式都是等价的按需选择即可

监听指定群聊

kotlin
suspend fun main() {
    val instance1 = OneBotFactory.createClient(...)
    // 114514 和 1919810 都是群号
    instance1.addListeningGroup(114514L, 1919810L)
}

以Apache-2.0开源协议开源