Search code examples
slacknpm-request

Using slack webhook with node


I am trying to use slack webhook. I can read a lot of variation about how I should proceed, but until now, none of them worked properly.

I am using the request node module to make the api call, but I can change if needed.

First try following this

import request from 'request';
const url = 'https://hooks.slack.com/services/xxx';
const text = '(test)!';
request.post(
  {
    headers : { 'Content-type' : 'application/json' },
    url,
    payload : JSON.stringify({ text }),
  },
  (error, res, body) => console.log(error, body, res.statusCode)
);

I get : null 400 'invalid_payload'

Next try following this

request.post(
  {
    headers : { 'Content-type' : 'application/json' },
    url,
    form : JSON.stringify({ text }),
  },
  (error, res, body) => console.log(error, body, res.statusCode)
);

This time, it works, but Slack displays: %28test%29%21 instead of (test)!

Did I miss something?


Solution

  • Based on your second example and the working Postman request this is how I got it to work, forgive my change to require as I am running older node version right now. I am not exactly sure what your data would look like that you want to post to Slack, that may change how you want to assemble this.

    const request = require('request');
    
    const url = 'https://hooks.slack.com/services/xxxxx';
    const text = '(test)!';
    request.post(
      {
        headers : { 'Content-type' : 'application/json' },
        url,
        form : {payload: JSON.stringify({ text } )}
      },
      (error, res, body) => console.log(error, body, res.statusCode)
    );
    

    If you want to use request you may want to check how slack-node is posting the data, here the relevant snipped from slack-node

    Slack.prototype.webhook = function(options, callback) {
        var emoji, payload;
        emoji = this.detectEmoji(options.icon_emoji);
        payload = {
          response_type: options.response_type || 'ephemeral',
          channel: options.channel,
          text: options.text,
          username: options.username,
          attachments: options.attachments,
          link_names: options.link_names || 0
        };
        payload[emoji.key] = emoji.val;
        return request({
          method: "POST",
          url: this.webhookUrl,
          body: JSON.stringify(payload),
          timeout: this.timeout,
          maxAttempts: this.maxAttempts,
          retryDelay: 0
        }, function(err, body, response) {
          if (err != null) {
            return callback(err);
          }
          return callback(null, {
            status: err || response !== "ok" ? "fail" : "ok",
            statusCode: body.statusCode,
            headers: body.headers,
            response: response
          });
        });
      };