使用Node.js使用Slack webhook

3

我正在尝试使用Slack Webhook。我可以阅读很多关于如何进行的变化,但到目前为止,它们都没有正常工作。

我正在使用request节点模块进行API调用,但如果需要,我可以更改。

首先尝试遵循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)
);

我得到的是:null 400 'invalid_payload'

接下来尝试按照this的步骤进行。

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

这次它有效了,但是Slack显示:%28test%29%21而不是(test)! 我有遗漏什么吗?

我找出了一个我以前用来测试的旧的Postman请求,它可以工作,但由于这已经是文本了,问题似乎在于JSON如何转换为文本。你有没有尝试过不使用JSON.stringify的第一个示例呢? - d parolin
3个回答

4

根据您提供的第二个示例和Postman请求,这是我使其工作的方法。请原谅我的更改,因为我现在运行的是较旧的节点版本,需要使用require。我不确定您要发布到Slack的数据的实际情况,这可能会影响您如何组装它。

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)
);

如果你想使用request,可能需要查看slack-node如何发布数据,这里是来自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
      });
    });
  };

1
你的解决方案 form: {payload: JSON.stringify({text: xxx})}} 是可行的。 - Sharcoux

1
你可以尝试使用slack-node模块,将post包装到hook中。这是我用来推送AWS实例通知的一个简化修改后的真实世界示例。
[编辑]更改为使用您的文本
现在,使用slack-node,您自己组装{},添加文本和其他参数,并将其传递给.webhook。
const Slack = require('slack-node');

const webhookUri = 'https://hooks.slack.com/services/xxxxx';
const slack = new Slack();
slack.setWebhook(webhookUri);

text = "(test)!"

slack.webhook({
        text: text
        // text: JSON.stringify({ text })
    }, function(err, response) {
       console.log(err, response);
});

0

我最终选择了Slack-webhook,它比slack-node更好。d parolin的解决方案是我问题的最佳答案,但我想提及pthm的工作以供参考。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接