Skip to content

SaltifyDev/milky-kt-sdk

Repository files navigation

Milky SDK for Kotlin

Maven Central kotlinx-serialization ktor

特性

  • 基于 Ktor Client 和 Kotlinx Serialization 实现
  • 兼容 JVM / Native / JS / WASM 平台
  • 支持 Milky 协议的所有功能
    • 例外:不支持通过 WebHook 事件推送监听事件

Tip

使用时,你需要在项目中添加一个 Ktor Client 引擎依赖,例如 ktor-client-cioktor-client-okhttp 等。

用例

ClientTest.kt

初始化

val client = MilkyClient(
    addressBase = "http://localhost:3000",
    eventConnectionType = EventConnectionType.WebSocket,
    // accessToken = "..."
)

调用 API

// API 无参数
val loginInfo = client.getLoginInfo()

// API 有参数
val userProfile = client.getUserProfile(/* userId = */ loginInfo.uin)

发送消息

client.sendGroupMessage(123456789L) {
    text("Hello from Milky🥛!")
    image("https://example.com/example.jpg")
    image("https://example.com/example2.jpg", subType = "sticker")
}

监听事件

// 连接事件服务
client.connectEvent()

// 监听消息事件,并创建 Job 以便后续取消监听
val job = launch {
    client.subscribe {
        if (it is Event.MessageReceive) {
            when (it.data) {
                is IncomingMessage.Group -> {
                    println("Group message from ${it.data.peerId} by ${it.data.senderId}:")
                    println(milkyJsonModule.encodeToString(it.data.segments))
                }

                else -> {}
            }
        }
    }
}

// 退出时取消监听
job.cancel()
client.disconnectEvent()

About

Milky 协议的 Kotlin SDK

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages