pcdr
pcdr

Reputation: 193

chat.postMessage response of invalid_json

I'm trying to use the Slack api method chat.postMessage. Here's the documentation for sending JSON in their blocks format:

enter image description here

This is the code that I'm using with google app script to send a message:

try {
    var params = {
      method: "post",
      headers: {
        Authorization: "Bearer " + token,
        "Content-Type": "application/json; charset=utf-8"
      },
      payload: {
        text: "posted",
        channel: channel_id,
        blocks: encodeURIComponent(JSON.stringify(result.payload.blocks))
      }
    };
    var url = "https://slack.com/api/chat.postMessage";
    var response = UrlFetchApp.fetch(url, params);
    var json = response.getContentText();
    var data = JSON.parse(json);
    log("Response Data: " + JSON.stringify(data));
...

The response I'm getting is {"ok":false,"error":"invalid_json"}.

I've taken the JSON and tested it using Slack's Block Kit Builder where the JSON appears to be well-formated.

In the code above, I've tried it with and without the encodeURIComponent and get the same error. I figured I needed to encode it because of the documentation in the picture above.

I've searched around for a solution, but haven't found a similar question. What should I be looking for here? At a loss. Thanks!

Upvotes: 1

Views: 2965

Answers (1)

Tanaike
Tanaike

Reputation: 201428

How about this modification?

Modification points:

  • In this case, please use JSON.stringify() to the while payload, and encodeURIComponent() is not required.

Modified script:

When your script is modified, please modify as follows.

From:
var params = {
  method: "post",
  headers: {
    Authorization: "Bearer " + token,
    "Content-Type": "application/json; charset=utf-8"
  },
  payload: {
    text: "posted",
    channel: channel_id,
    blocks: encodeURIComponent(JSON.stringify(result.payload.blocks))
  }
};
To:
var params = {
  method: "post",
  headers: {Authorization: "Bearer " + token},
  contentType: "application/json",
  payload: JSON.stringify({
    text: "posted",
    channel: channel_id,
    blocks: result.payload.blocks
  })
};

Note:

  • If an error related to the scopes, please add the scopes for using "chat.postMessage".
  • I'm not sure about result.payload.blocks. So if the structure of result.payload.blocks is not correct, an error occurs. Please be careful this.

References:

If I misunderstood your question and this was not the direct solution of your issue, I apologize.

Upvotes: 1

Related Questions