検索結果に出てくる記事が古かったりして時間をロスしてしまうのでメモ。
結論
公式のパッケージを使おう。
www.npmjs.com
npmでインストールできる
$ npm install @slack/webhook
公式のサンプルコードを見ればわかるけどURLを渡してsendするだけで使えてしまう。
const { IncomingWebhook } = require('@slack/webhook');
const url = process.env.SLACK_WEBHOOK_URL;
const webhook = new IncomingWebhook(url);
// Send the notification
(async () => {
await webhook.send({
text: 'I\'ve got news for you...',
});
})();requestsとかaxiosとかの通信ライブラリをインストールしたり、細かい設定を意識せずに使える。
注意するのはsend()がPromiseを返すのでFirebase Functionsなどでやる時は呼び出し側でawaitとかしないとダメなことぐらいだけど、Functions使いなら当たり前か。
TypeScript + Firebase Functionsで使った例
下記レポジトリで使ってる。
GitHub - uyamazak/co2signals: Co2 Sensor System. Raspberry Pi + MH-Z19B + Firebase
とりあえず動いた段階だけど下記のような感じ。anyはなくしたい
import * as functions from 'firebase-functions';
import { IncomingWebhook } from '@slack/webhook';
const slackWebHookURL: string = functions.config()?.slack?.webhook_url ?? '';
export async function sendSlackWebhook (co2: number) : Promise<any> {
if (!slackWebHookURL) {
return Promise.resolve();
}
const webhook = new IncomingWebhook(slackWebHookURL);
try {
const message = `現在のCo2濃度: ${co2} ppm`;
return webhook.send({
text: message
});
} catch (error) {
console.error(`Error occuered in sendSlack: ${error}`, error);
return Promise.reject();
}
}- 作者:Boris Cherny
- 発売日: 2020/03/16
- メディア: 単行本(ソフトカバー)