-1

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,
        }
      ]
  };
};
cbutler
  • 1,111
  • 5
  • 16
  • 32
  • What is the problem you get when you use `JSON.stringify(data)`? – Ouroborus Jan 27 '22 at 18:59
  • it displays as `[object Object]` – cbutler Jan 27 '22 at 19:02
  • Before the `return`, add `console.log(typeof data);`. Run the command and check the console logs. If it says "string", it means this function is receiving `data` as a string and something else is mangling the data before this function is called. – Ouroborus Jan 27 '22 at 19:08
  • (`[object Object]` usually comes from something like `someObject.toString()`. So I suspect that the data has had `.toString()` used on it and the results of that are being passed to this function. If that's the case, `typeof data`, in the test I suggested, would return `string`.) – Ouroborus Jan 27 '22 at 19:14
  • Please include an example of `data` and the API. as it applies to `data` – zer00ne Jan 27 '22 at 19:24

1 Answers1

1

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

Ouroborus
  • 16,237
  • 4
  • 39
  • 62
Balint
  • 295
  • 2
  • 11
  • Not so wild it turns out. However I think the missing link for me was actually formatting with JSON.stringify. this is my working solution "text": `\`\`\`${JSON.stringify(data, null, 2)}\`\`\``, – cbutler Jan 27 '22 at 20:00