40 lines
1.2 KiB
Kotlin
40 lines
1.2 KiB
Kotlin
package dev.solsynth.snConnect.services
|
|
|
|
import kotlinx.serialization.Serializable
|
|
import kotlinx.serialization.json.Json
|
|
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
|
import okhttp3.Request
|
|
import okhttp3.RequestBody.Companion.toRequestBody
|
|
import java.io.IOException
|
|
import java.util.*
|
|
|
|
@Serializable
|
|
data class SnMessageRequest(
|
|
val content: String,
|
|
val nonce: String
|
|
)
|
|
|
|
class SnMessageService(private val sn: SnService) {
|
|
private val json: Json = Json {
|
|
ignoreUnknownKeys = true
|
|
}
|
|
|
|
fun sendMessage(chatRoomId: String, content: String) {
|
|
val body = SnMessageRequest(content, UUID.randomUUID().toString())
|
|
val request = Request.Builder()
|
|
.url(sn.getUrl("sphere", "/chat/$chatRoomId/messages"))
|
|
.post(json.encodeToString(body).toRequestBody("application/json".toMediaTypeOrNull()))
|
|
.apply {
|
|
sn.botApiKey?.let { header("Authorization", "Bearer $it") }
|
|
}
|
|
.build()
|
|
|
|
sn.client.newCall(request).execute().use { response ->
|
|
if (!response.isSuccessful) {
|
|
val responseBody = response.body?.string() ?: "No body"
|
|
throw IOException("Unexpected code $response: $responseBody")
|
|
}
|
|
}
|
|
}
|
|
}
|