Search code examples
javascriptslack-commands

Send response as code snippet for slack slash command


I am creating a slack slash command and I want to return a javascript object (a JSON response from another api call) as code.

---EDIT---

I can send a markdown response using the code below. The issue now is that I cannot show JSON / JavaScript object as formatted code. the data argument is an API response of JSON and I wanted to show that as code.

I have tried sending it as plain data as JSON.stringify(data), but nothing seems to work.

---Second EDIT---

Have it working now with the following implementation. The accepted answer below prompted me to try the following (in case anyone comes looking for this)

createResponse = function (data) {
  const date = new Date().getTime() / 1000;

  return {
      "response_type": "ephemeral", // only show message to user who issued command
      "attachments": [
        {
          "mrkdwn_in": ["text"],
          "fallback": data,
          "color": "#002868",
          "pretext": 'Here you go...',
          "text": `\`\`\`${JSON.stringify(data, null, 2)}\`\`\``,
          "footer": "Here you go...",
          "ts": date,
        }
      ]
  };
};

Solution

  • It is a a bit of a wild shot have try to add ``` for format your return string

    const returnValue =  {
          "response_type": "ephemeral", // only show message to user who issued command
          "attachments": [
            {
              "mrkdwn_in": ["text"],
              "fallback": data,
              "color": "#002868",
              "pretext": 'Here you go...',
              "text":"```" + JSON.stringify(someObject)  
              "footer": "Here you go...",
              "ts": date,
            }
          ]
      };
      

    https://slack.com/intl/it-it/help/articles/202288908-Formattare-i-messaggi