LoginSignup
5
3

More than 5 years have passed since last update.

nodejs: スケジュール設定付きSlack botの簡単なサンプル

Last updated at Posted at 2018-04-28

image.png

サンプルとして、1日の終わりに当日のgithubのcontribution数をslackに飛ばすbotをつくりました。
https://github.com/nnishimura/day-summary

かいつまんで説明したいと思います

準備

Slack上で、bot用のIncoming Webhookを作ります。
https://api.slack.com/incoming-webhooks

image.png

投稿したいチャンネルを選んで進むと、Webhook URLが取得できます。
image.png

これをコピーして、そのまま登録を完了します。

Commanderを入れる

githubのユーザー名やbotの投稿時間のスケジュールをプログラムに渡せるように、
commanderをnpm installします。

これはnode側からコマンドラインの操作をしやすくするパッケージで、
後で--schedule等のオプションをつけてスクリプトを実行することで、
自由にbotの投稿時間を設定することができます。

index.js
const program = require('commander')

program
  .version('0.1.0')
  .option('--github <string>', 'Add github username')
  .option(
    '--schedule [string]',
    'cron pattern, defaults to 20:00 every day',
    '00 20 * * *'
  )
  .parse(process.argv)

こうすると、例えばnode index.js --github 'akira'というコマンドを実行した時、program.githubakiraが取れるようになります。

node-scheduleを入れる

botの投稿時間を決めるため、node-scheduleをnpm installします。

index.js
const schedule = require('node-schedule')

const pattern = program.schedule || '00 20 * * *'

const j = schedule.scheduleJob(pattern, () => {
  // slackに投稿する処理
})

前のステップで--scheduleオプションに渡したパターン通り、slack通知の関数をトリガすることができます。
例えば、00 20 * * *だと毎日20時になります。

*    *    *    *    *    *
┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    │
│    │    │    │    │    └ day of week (0 - 7) (0 or 7 is Sun)
│    │    │    │    └───── month (1 - 12)
│    │    │    └────────── day of month (1 - 31)
│    │    └─────────────── hour (0 - 23)
│    └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)

スラック投稿の処理

さきほど取得したWebhook URLにメッセージをPOSTします。
Webhook URLはそのままコード上に入れないで、環境変数として登録してください。

const request = require('request')

const DEFAULT_PARAMS = {
  url: process.env.SLACK_WEB_HOOK_URL, // 環境変数
  form: 'payload={text: "default message",username: "test bot",icon_emoji: ":bar_chart:"}',
  headers,
  json: true
}

request.post(DEFAULT_PARAMS, (error, response, body) => {
  if (!error && response.statusCode == 200) {
    return console.log(body) // logs 'ok'
  }

  console.log('error: ' + response)
})

動かす

node index.js --github 'USER_NAME' --schedule 'SCHEDULE_PATTERN'

とりあえずこれで動きますが、このスクリプトをずっと実行したいので、foreverというパッケージを使います。

Foreverで永続化

  • npm install -g foreverでグローバルインストールした場合は、
forever index.js --github 'USER_NAME' --schedule 'SCHEDULE_PATTERN'
  • ローカルにしかない場合
./node_modules/.bin/forever index.js --github 'USER_NAME' --schedule 'SCHEDULE_PATTERN'

これでslack botのスクリプトを実行し続けることができます。

まとめ

5
3
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
5
3