LoginSignup
28
25

More than 5 years have passed since last update.

hubotでcron風に特定の時間に処理を実行させる方法

Last updated at Posted at 2016-03-25

はじめに

今回の例では、特定のチャットの部屋(slackだとchannel)へメッセージを送信しリマインダとしての役割を実装する。

※注意 ここでは、hubotとslackの連携方法やサーバで実行する方法等は記載していない。

動作確認環境

普通にhubotが動いていて、各アダプタでチャットツールと接続していればhipchatでも動くと思われる

  • node.js version v5.9.1
  • hubot version v2.12.0
  • hubotのホスティング先はheroku
  • slack アダプタを利用し、hubotとslackが連携している

実装コード及び解説

package.jsonにcronを追加する

package.json
{
  "name": "xxxxx",
  "version": "0.0.0",
  "private": true,
  "author": "xxxxx",
  "description": "A simple helpful robot for your Company",
  "dependencies": {
    "hubot": "^2.12.0",
    "hubot-diagnostics": "0.0.1",
    "hubot-google-images": "^0.1.4",
    "hubot-google-translate": "^0.1.0",
    "hubot-help": "^0.1.1",
    "hubot-heroku-keepalive": "0.0.4",
    "hubot-maps": "0.0.2",
    "hubot-pugme": "^0.1.0",
    "hubot-redis-brain": "0.0.2",
    "hubot-rules": "^0.1.0",
    "hubot-scripts": "^2.5.16",
    "hubot-shipit": "^0.2.0",
    "hubot-slack": "^3.3.0",
    "hubot-youtube": "^0.1.2",
    "cron": "^1.1.0" //追加
  },
  "engines": {
    "node": "x.x.x"
  }
}

scripts/cron.coffeeと言うファイルを作り、以下のようなコードを書く

# 定期処理をするオブジェクトを宣言
cronJob = require('cron').CronJob


module.exports = (robot) ->

  # 特定のチャンネルへ送信するメソッド(定期実行時に呼ばれる) 
  send = (channel, msg) ->
    robot.send {room: channel}, msg

  # Crontabの設定方法と基本一緒 *(sec) *(min) *(hour) *(day) *(month) *(day of the week)
  # #your_channelと言う部屋に、平日の18:30時に実行
  new cronJob('0 30 18 * * 1-5', () ->
    # ↑のほうで宣言しているsendメソッドを実行する
    send '#your_channel', "@here そろそろ帰る準備をしよう"
  ).start()

  # #your_channelと言う部屋に、平日の13:00時に実行
  new cronJob('0 00 13 * * 1-5', () ->
    send '#your_channel', "@here ランチの時間だよ!!"
  ).start()

これで、平日18:30と13:00にslackのyour_roomと言うchannelへ、その部屋を見ている人へメンション付きのメッセージが飛ぶようになる

28
25
2

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
28
25