✨ Sync message to SN
This commit is contained in:
@@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user