Messages
Sending messages in Threads.
Info
Message data
, publicMeta
and privateMeta
fields support any kind of data formats encoded to byte arrays. Examples in this section use kotlinx-serialization-json-jvm
dependency for Kotlin and com.google.code.gson:gson
for Java to serialize object to JSON format.
Messages inside Threads
Messages inside Threads are sent in binary format. Before sending a message, you need to decide on the message format and choose the appropriate data serialization method.
For more information about the Threads architecture and best practices for sending messages, visit the Threads Documentation.
Sending Messages
Example of sending a message in Plain Text:
val threadID = "THREAD_ID"
val message = "Message text"
val threadApi = connection.threadApi
val messageID = threadApi.sendMessage(
threadID,
ByteArray(0),
ByteArray(0),
message.encodeToByteArray()
)
Getting Messages
Define message item class with decoded data
and publicMeta
:
data class MessageItem(
val message: Message,
val decodedData: String,
val decodedPublicMeta: MessagePublicMeta
)
Fetching the most recent messages in given Thread:
val threadId = "THREAD_ID"
val startIndex = 0L
val pageSize = 100L
val threadApi = connection.threadApi
val messagesPagingList = threadApi.listMessages(
threadId,
startIndex,
pageSize,
SortOrder.DESC
)
val messages = messagesPagingList.readItems.map {
MessageItem(
it,
it.data.decodeToString(),
Json.decodeFromString(it.publicMeta.decodeToString())
)
}
Managing Messages
Example of updating the message content:
val messageID = "MESSAGE_ID"
val message: Message = connection.threadApi.getMessage(messageID)
val newMessage = "New message"
val threadApi = connection.threadApi
threadApi.updateMessage(
messageID,
message.publicMeta,
message.privateMeta,
newMessage.encodeToByteArray()
)