Sync message to SN

This commit is contained in:
2025-10-05 03:06:23 +08:00
parent e77841fc09
commit 6303d44ab4
6 changed files with 96 additions and 48 deletions

View File

@@ -0,0 +1,40 @@
package dev.solsynth.snConnect.services
import kotlinx.serialization.SerialName
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.UUID
@Serializable
data class SnMessageRequest(
val content: String,
val nonce: String
)
class SnMessageService(private val sn: SnService) {
private val 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")
}
}
}
}