LoginSignup
15
10

More than 5 years have passed since last update.

node.jsでIncoming-webhookでslackメッセージ送る

Posted at

node.jsからslackのメッセージを送りたい場合のメモ。

WebHookの設定

ここからチャネルなどを選びcURLとかでテストしておく。

別にテストは必須ではない。

実装

AWSのLambdaで利用するつもりなので追加モジュールは利用しない。こちらを参考にさせていただきました。
とりあえず下記の感じで動きます。

index.js
const https = require('https');

//メッセージ設定
var data = JSON.stringify({"username":"node_bot","text": "こんばんわ","icon_emoji":":ghost:"});

//オプション情報設定
var  options = {
    hostname: 'hooks.slack.com',
    port: 443,
    path: '/services/AAAAAAAA/BBBBBBBB/CCCCCCCCCCCCCCC',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(data)
    }
};

//リクエスト
var req = https.request(options, (res) =>{
    if(res.statusCode===200){
        console.log("OK:"+res.statusCode);
    }else{
        console.log("Status Error:"+res.statusCode);
    }
});

//そもそもなエラー時
req.on('error',(e)=>{
    console.error(e);
});

//データ送信
req.write(data);
//終わり
req.end();

簡単ではありますが、以上です。

15
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
10