slackslack-apislack-block-kit

Getting bad request while converting a JSON to Block kit in slack


I am trying to post my lighthouse report to slack using the block kit I am getting 400 status code, could you please help e to understand what I am missing here? (Couldn't find similar post)

The Report that is in JSON format is

{
  'Performance Score': [
    { Performance: ' 59 %', Color: 'ORANGE' },
    { Accessibility: '  85 %', Color: 'ORANGE' },
    { BestPractices: '  96 %', Color: 'GREEN' },
    { SEO: '  100 %', Color: 'GREEN' }
  ],
  'Performace KPI': [
    {
      'First Contentful Paint (FCP)': '1.7 s',
      'Speed Index': '4.7 s',
      'Largest Contentful Paint (LCP)': '8.7 s',
      'Total Blocking Time (TBT)': '70 ms',
      'Cumulative Layout Shift (CLS)': '0.012'
    }
  ]
}

I am trying to post the above to slack using the web hook url along with block kit,

I tried with

const reportblocks = [
            {
              "type": "section",
              "text": {
                "type": "mrkdwn",
                "text": "*Performance Score*"
              },
              "fields": [
                {
                  "type": "mrkdwn",
                  "text": `• Performance: ${payload['Performance Score'][0]['Performance']} (${payload['Performance Score'][0]['Color']})`
                },
                {
                  "type": "mrkdwn",
                  "text": `• Accessibility: ${payload['Performance Score'][1]['Accessibility']} (${payload['Performance Score'][1]['Color']})`
                },
                {
                  "type": "mrkdwn",
                  "text": `• Best Practices: ${payload['Performance Score'][2]['BestPractices']} (${payload['Performance Score'][2]['Color']})`
                },
                {
                  "type": "mrkdwn",
                  "text": `• SEO: ${payload['Performance Score'][3]['SEO']} (${payload['Performance Score'][3]['Color']})`
                }
              ]
            },
            {
              "type": "section",
              "text": {
                "type": "mrkdwn",
                "text": "*Performance KPI*"
              },
              "fields": [
                {
                  "type": "mrkdwn",
                  "text": `• First Contentful Paint (FCP): ${payload['Performace KPI'][0]['First Contentful Paint (FCP)']}`
                },
                {
                  "type": "mrkdwn",
                  "text": `• Speed Index: ${payload['Performace KPI'][0]['Speed Index']}`
                },
                {
                  "type": "mrkdwn",
                  "text": `• Largest Contentful Paint (LCP): ${payload['Performace KPI'][0]['Largest Contentful Paint (LCP)']}`
                },
                {
                  "type": "mrkdwn",
                  "text": `• Total Blocking Time (TBT): ${payload['Performace KPI'][0]['Total Blocking Time (TBT)']}`
                },
                {
                  "type": "mrkdwn",
                  "text": `• Cumulative Layout Shift (CLS): ${payload['Performace KPI'][0]['Cumulative Layout Shift (CLS)']}`
                }
              ]
            }
          ];

I am getting

Slack notification sent successfully. Response: {"status":"fail","statusCode":400,"headers":{"date":"Mon, 08 Apr 2024 16:46:09 GMT","server":"Apache","vary":"Accept-Encoding","strict-transport-security":"max-age=31536000; includeSubDomains; preload","referrer-policy":"no-referrer","x-slack-unique-id":"ZhQfUQd89LozgBIYrwHtqgAAACM","x-slack-backend":"r","access-control-allow-origin":"*","x-frame-options":"SAMEORIGIN","content-type":"text/html","content-length":"7","via":"1.1 slack-prod.tinyspeck.com, envoy-www-iad-lopevkmr, envoy-edge-canary-bom-bccpskqz","x-envoy-attempt-count":"1","x-envoy-upstream-service-time":"217","x-backend":"main_normal main_canary_with_overflow main_control_with_overflow","x-server":"slack-www-hhvm-main-iad-szna","x-slack-shared-secret-outcome":"no-match","x-edge-backend":"envoy-www","x-slack-edge-shared-secret-outcome":"no-match"},"response":"no_text"}

So I changed it to

const reportblocks = {
    type: "section",
    text: {
      type: "mrkdwn",
      text: `
      *Performance Score:*
      • Performance: ${payload["Performance Score"][0]["Performance"]} (${payload["Performance Score"][0]["Color"]})
      • Accessibility: ${payload["Performance Score"][1]["Accessibility"]} (${payload["Performance Score"][1]["Color"]})
      • Best Practices: ${payload["Performance Score"][2]["BestPractices"]} (${payload["Performance Score"][2]["Color"]})
      • SEO: ${payload["Performance Score"][3]["SEO"]} (${payload["Performance Score"][3]["Color"]})
      
      *Performance KPI:*
      • First Contentful Paint (FCP): ${payload["Performace KPI"][0]["First Contentful Paint (FCP)"]}
      • Speed Index: ${payload["Performace KPI"][0]["Speed Index"]}
      • Largest Contentful Paint (LCP): ${payload["Performace KPI"][0]["Largest Contentful Paint (LCP)"]}
      • Total Blocking Time (TBT): ${payload["Performace KPI"][0]["Total Blocking Time (TBT)"]}
      • Cumulative Layout Shift (CLS): ${payload["Performace KPI"][0]["Cumulative Layout Shift (CLS)"]}
      `,
    },
  };

I am getting

Slack notification sent successfully. Response: {"status":"fail","statusCode":400,"headers":{"date":"Mon, 08 Apr 2024 16:43:12 GMT","server":"Apache","vary":"Accept-Encoding","strict-transport-security":"max-age=31536000; includeSubDomains; preload","referrer-policy":"no-referrer","x-slack-unique-id":"ZhQeoEg0VRsef1dgHS9gqAAAABw","x-slack-backend":"r","access-control-allow-origin":"*","x-frame-options":"SAMEORIGIN","content-type":"text/html","content-length":"7","via":"1.1 slack-prod.tinyspeck.com, envoy-www-iad-qmigteht, envoy-edge-bom-bevupifn","x-envoy-attempt-count":"1","x-envoy-upstream-service-time":"203","x-backend":"main_normal main_canary_with_overflow main_control_with_overflow","x-server":"slack-www-hhvm-main-iad-sbvy","x-slack-shared-secret-outcome":"no-match","x-edge-backend":"envoy-www","x-slack-edge-shared-secret-outcome":"no-match"},"response":"no_text"}

I am using a nodejs script for posting it and when I run it normally without formatting it is posting but want it in JSON format

const Slack = require("slack-node");
const logger = require("../../reporting/logger");
const apiEndPoints = require("../../config/apiEndPoints");

const webhookurl = `${apiEndPoints.SLACK_SDET_URL}`;

async function sendSlackNotification(payload) {
    try {
      logger.info(`Sending Slack notification to: ${webhookurl}`);
  
      const slack = new Slack();
      slack.setWebhook(webhookurl);
  
      const reportblocks = [
        {
          type: 'section',
          text: { type: 'mrkdwn', text: '*Performance Score:*' },
          fields: payload['Performance Score'].map(score => ({
            type: 'mrkdwn',
            text: `${Object.keys(score)[0]}: ${Object.values(score)[0]}`,
          })),
        }
      ];
  
      const message = {
        blocks: reportblocks ,
      };
  
      slack.webhook(message, function (err, response) {
        if (err) {
          logger.error(`Error occurred while sending Slack notification: ${err}`);
        } else {
          logger.info(`Slack notification sent successfully: ${JSON.stringify(response)}`);
        }
      });
    } catch (error) {
      logger.error("Error occurred:", error);
    }
  }

sendSlackNotification();

module.exports = {
  sendSlackNotification,
};

Working Fine

enter image description here


Solution

  • I have fixed the issue, thought I can be sharing this to community

    Now the issue is with the npm library used only accept text as payload.

    const Slack = require("slack-node");

    So choose a new npm library which is

    const { IncomingWebhook } = require("@slack/webhook");

    And changed the code,

    const { IncomingWebhook } = require("@slack/webhook");
    const logger = require("../../reporting/logger");
    const apiEndPoints = require("../../config/apiEndPoints");
    
    //const webhookUrl = apiEndPoints.SLACK_SOLUTION_URL;
    const webhookUrl = apiEndPoints.SLACK_SDET_URL;
    
    async function sendSlackNotification(payload) {
      try {
        // Initialize the webhook with the provided URL
        const webhook = new IncomingWebhook(webhookUrl);
    
        // Construct the message payload
        const block = {
          blocks: [
            {
              type: "section",
              text: {
                type: "mrkdwn",
                text: "*Google Lighthouse Score [Home Page | Desktop Platform]*",
              },
            },
            {
              type: "section",
              fields: [
                {
                  type: "mrkdwn",
                  text: `• Performance: *${
                    payload["Performance Score"][0]["Performance"]
                  }* | ${setButtonBasedOnColor(
                    `${payload["Performance Score"][0]["Color"]}`
                  )}`,
                }
              ],
            }
          ],
        };
    
        // Send the payload to Slack
           await webhook.send(block);
      } catch (error) {
        logger.error(`Error sending Slack notification: ${error}`);
      }
    }
    
    module.exports = {
      sendSlackNotification,
    };