Itiviti / simple-slack-api

(simple) Java Slack client library
470 stars 193 forks source link

Is it possible to (un)marshal SlackPreparedMessage from JSON string? #260

Open boobiq opened 5 years ago

boobiq commented 5 years ago

Hi,

I'm trying to use actions (https://api.slack.com/docs/message-buttons) in messages. I have simple webserver with endpoint for handling callbacks running and getting response after clicking triggering actions from message works well.

In request Slack makes as callback, there is payload JSON containing original message (JSON string). Since I want to update previous message (imagine simple message with 1 button which will be changed to "thank you" message after clicked), I'd like to create SlackPreparedMessage from that JSON, update attachments, texts etc and than get JSON string from it so I can send it back to Slack.

Is this possible somehow? currently I was doing something like this just to test if it works (using org.json.JSONObject) in Kotlin:

// ctx.formParam("payload") is JSON string containin data sent by Slack after clicking on action
val requestData = JSONObject(ctx.formParam("payload"))
val responseUrl = requestData.getString("response_url")
val callbackId = requestData.getString("callback_id")
val originalMessage = requestData.getJSONObject("original_message")

val oldAttachments = originalMessage.getJSONArray("attachments")
oldAttachments.getJSONObject(0)
    .put("callback_id", "new callb")
    .put("text", "some new text")
    .put(
        "actions", JSONArray(
            arrayOf(
                // new actions to replace old buttons
            )
        )
    )

// send message back to responseUrl via Fuel
val (_, response, result) = Fuel.post(responseUrl)
    .body(originalMessage.toString())
    .header("Content-Type" to "application/json")
    .responseString()

I would like to do something like (kind of pseudo-code 😄)

val newAttachment = SlackAttachment().apply {
    // ...setting attachment fields
}
val msg = SlackPreparedMessage.parse(originalMessage)
    .withAttachments(listOf(newAttachments))
    .toJson()

//send POST request with msg

Thanks