サンプルとして、1日の終わりに当日のgithubのcontribution数をslackに飛ばすbotをつくりました。
https://github.com/nnishimura/day-summary
かいつまんで説明したいと思います
準備
Slack上で、bot用のIncoming Webhookを作ります。
https://api.slack.com/incoming-webhooks
投稿したいチャンネルを選んで進むと、Webhook URL
が取得できます。
これをコピーして、そのまま登録を完了します。
Commanderを入れる
githubのユーザー名やbotの投稿時間のスケジュールをプログラムに渡せるように、
commanderをnpm installします。
これはnode側からコマンドラインの操作をしやすくするパッケージで、
後で--schedule
等のオプションをつけてスクリプトを実行することで、
自由にbotの投稿時間を設定することができます。
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.github
でakira
が取れるようになります。
node-scheduleを入れる
botの投稿時間を決めるため、node-scheduleをnpm installします。
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のスクリプトを実行し続けることができます。
まとめ
- コマンドラインツール化:commander
- スケジュール:node-schedule
- 永続化:forever