Search code examples
javascriptslack-apislack-block-kit

How to separate Slack blocks into a separate file


I'm working on a slack bot in JS, and using Slack's "block kit" to format the messages. However, quite often I get a function that looks like this:

app.command('/workspace-request', async ({ command, ack, respond }) => {
  await ack();

  //posts message to user
  await app.client.chat.postEphemeral({
    channel: command.channel_id,
    user: command.user_id,
    text: "Your request has been sent"
  })

  const blocks = [
    {
      "type": "section",
      "text": {
        "type": "mrkdwn",
        "text": "New Workspace Request:"
      }
    },
    {
      "type": "section",
      "text": {
        "type": "mrkdwn",
        "text": `*User:* @${command.user_name}`
      }
    },
    {
      "type": "section",
      "text": {
        "type": "mrkdwn",
        "text": `*Description:* ${command.text}`
      }
    },
    {
      "type": "actions",
      "elements": [
        {
          "type": "button",
          "text": {
            "type": "plain_text",
            "text": "Add to tasks"
          },
          "style": "primary",
          "value": "RequestApprove"
        },
        {
          "type": "button",
          "text": {
            "type": "plain_text",
            "text": "Deny"
          },
          "style": "danger",
          "value": "RequestDeny"
        }
      ]
    }
  ]


  //posts message to workspace core
  await app.client.chat.postMessage({
    channel: "workspace-core",
    link_names: true,
    blocks: blocks


  })

  console.log(command)
});
Most of the code is just formatting the block kit text, and it makes it difficult to navigate. Is there a common way to organize this code so the blocks aren't taking up so much space? I tried making it into a separate file, but I ran into issues when trying to reference it in the main file, and I wasn't convinced that's the best way to do it. Any suggested would be much appreciated!


Solution

  • Usual method is that you can keep the block kit as separate json file. And read block from that file.

    Please find sample code below:

    fs.readFile(filename, 'utf8', async (err, data) => {
          if (err) throw err;
          try {        
            const block   = JSON.parse(data); 
    
          **// use block accordingly**
            
          } catch (e) {
            
          }
        });