如何使用云功能将 firebase 数据发送到 slack?

How to send firebase data to slack using cloud functions?

我克隆了这个示例 minimal-webhook 并开始工作。我想通过将写入发送到 slack 来扩展此功能。

我正在使用 slack 的传入 webhook。我想问题是我如何在 nodejs 中添加数据有效负载的方式。谁能帮忙?提前致谢。附上我的代码和来自 firebase 的错误日志。

const functions = require('firebase-functions');
const request = require('request-promise');
const WEBHOOK_URL = 'https://hooks.slack.com/services/abc'
var headers = {
    'Content-type': 'application/json'
};
exports.webhook = functions.database.ref('/hooks/{hookId}').onWrite(event => {
  return request({
    uri: WEBHOOK_URL,
    method: 'POST',
    headers: headers,
     body: event.data.toJSON,
    resolveWithFullResponse: true
  }).then(response => {
    if (response.statusCode >= 400) {
      throw new Error(`HTTP Error: ${response.statusCode}`);
    }
    console.log('SUCCESS! Posted', event.data.ref);
  });
});`

使用 body: event.data.val() 而不是 body: event.data.toJSON。您还需要 json: true。为失败添加 catch()

数据应至少包括 属性 text:

{
  "text": "Hello World!"
}

更新代码:

exports.webhook = functions.database.ref('/hooks/{hookId}').onWrite(event => {
  return request({
    uri: WEBHOOK_URL,
    method: 'POST',
    headers: headers,
    body: event.data.val(), // <= CHANGED
    json: true, // <= ADDED
    resolveWithFullResponse: true
  }).then(response => {
    if (response.statusCode >= 400) {
      throw new Error(`HTTP Error: ${response.statusCode}`);
    }
    console.log('SUCCESS! Posted', event.data.ref);
  })
  .catch(err => { // <= ADDED
    console.log('FAILED err=', err);
  });
});

走在正确的轨道上。但是,当您使用网络挂钩时,​​Slack 会期待某些事情。

向webhook发送POST请求时,需要满足以下条件:

  • Content-Type 必须是 application/json
  • 请求正文的格式必须正确JSON。
  • 请求正文必须包含以下字段之一:textfallbackattachments.

现在,当你在 firebase 上存储数据时,你可以将你需要的所有信息存储在数据库中,或者你可以只保留代码中的通用内容,只放置有效负载(你要发送的数据)在数据库中。

下面的代码片段将允许您在数据库的指定位置存储您想要的任何内容。存储在那里的数据将作为 web hook 的文本参数以 JSON 格式传输。

exports.webhook = functions.database.ref('/hooks/{hookId}').onWrite(event => {
  var body = {
    "channel": "#general",
    "username": "your-bot-name-here",
    "icon_emoji": ":computer:",
    "text": event.data.toJSON()
  };

  return request({
    uri: WEBHOOK_URL,
    method: 'POST',
    body: body,
    json: true,
    resolveWithFullResponse: true
  }).then(response => {
    if (response.statusCode >= 400) {
      throw new Error(`HTTP Error: ${response.statusCode}`);
    }
    console.log('SUCCESS! Posted', event.data.ref);
  });
});

注:函数toJSON()由Firebase的DataSnapshotclass添加(event.data是一个实例的)。如果使用不同的对象,使用 JSON.stringify(obj).

可以获得相同的结果

您还应该考虑检查 onWrite() 事件的类型。删除数据后向 Slack 发送请求毫无意义(使用 if (!event.data.exists()) { /* data was deleted */ return; }),您可能还希望只发送一次请求(使用 if (event.data.previous.exists()) { /* data has been updated */ return; })。

如果您想让消息看起来更好看,您可以在 https://api.slack.com/docs/messages/builder

找到有关格式化 text 字段的信息