LoginSignup
32
45

More than 5 years have passed since last update.

Node.jsからSlack WEB API を叩いてメッセージを送信する

Last updated at Posted at 2016-07-10

難易度が高いわけでもないがそこまで情報が無かったので備忘録的なアレです。

やることは至ってシンプル

1.SlackAPIのTokenを発行する
2.Node.jsから叩く叩く!

所要時間は15分

1.SlackAPIのTokenを発行する

SlackAPIページはリンクが多すぎる。。
Tokenを発行したいだけなのにぱっと見ではよく分からない。ちくしょう。

あった、ここだったか。

SlackAPIトップの左メニュー > AUTHENTICATION > Tokens for Testing

最初からtokenでページ内検索すればよかったよね、と思ったあなたはとても賢い方なのだと思います。

チームの一覧で
Create tokenボタン > パスワード入力 > Confirmボタン

とすると下記のようなtokenが画面上に表示されます。

xoxp-00000000000-00000000000-00000000000-0000000000

このtoken使ってrequestモジュールでpostする処理を書いてみる。

slack.ts
request.post('https://slack.com/api/chat.postMessage',
    {
        form: {
            token: '発行したトークン',
            channel: 'チャンネル',
            username: '送信者の名前',
            text: 'メッセージ'
        }
    }
    , (error, response, body) => {
        console.log(error)
    }
)

コンパイルして実行

tsc slack.ts 
node slack.js

メッセージ来た
Kobito.AMKRSA.png

こんな風にclassやモジュールにしておくと何かと便利でした。

import request = require('request')

export interface SlackPostForm {
    token?: string
    channel?: string
    username?: string
    text?: string
}

export default class Slack {
    constructor() {
    }

    post(form: SlackPostForm, callBack: (error: any, response: http.IncomingMessage, body: any) => void) {
        let options: request.CoreOptions = {
            form: {
                token: form.token || 'デフォルトトークン',
                channel: form.channel || 'デフォルトチャンネル',
                username: form.username || 'デフォルト送信者',
                text: form.text || ''
            }
        }
        request.post('https://slack.com/api/chat.postMessage', options, (error, response, body) => {
            callBack(error, response, body)
        })
    }
}
32
45
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
32
45