Skip to content

Instantly share code, notes, and snippets.

@nomnel
Last active December 19, 2015 15:44
Show Gist options
  • Save nomnel/8022a75e50fffcb9196d to your computer and use it in GitHub Desktop.
Save nomnel/8022a75e50fffcb9196d to your computer and use it in GitHub Desktop.
# Description:
# Hubot GitHub Notification for each channel
#
# Commands:
# hubot github_notification on <branch> - コミットを通知するブランチを追加
# hubot github_notification off <branch> - 指定のブランチのコミットを通知しないように
# hubot github_notification ls - 現在のchannelで設定されているブランチの一覧
#
# Author:
# @nomnel
_ = require 'lodash'
module.exports = (robot) ->
KEY = 'github_notification_setting'
commandResponse = (room, data, changed) ->
ok = if changed then 'りょうかい!' else ''
branches = Object.keys(data).filter (branch) -> _.includes(data[branch], room)
if branches.length > 0
"#{ok}今登録されているブランチは#{branches.join('と')}だよ!"
else
"#{ok}今はどのブランチも登録されてないよ!"
fetch = ->
robot.brain.get(KEY) || {}
save = (data) ->
robot.brain.set(KEY, data)
robot.respond /github_notification\s+on\s+(.+)/, (msg) ->
branch = msg.match[1].trim()
room = msg['envelope']['room']
data = fetch()
if data[branch]
data[branch] = _.uniq(data[branch].concat(room)).sort()
else
data[branch] = [room]
save(data)
msg.send commandResponse(room, data, true)
robot.respond /github_notification\s+off\s+(.+)/, (msg) ->
branch = msg.match[1].trim()
room = msg['envelope']['room']
data = fetch()
if data[branch]
data[branch] = data[branch].filter (r) -> r != room
save(data)
msg.send commandResponse(room, data, true)
robot.respond /github_notification\s+ls/, (msg) ->
msg.send commandResponse(msg['envelope']['room'], fetch(), false)
# URLはGitHubのWebhookに登録したもの
# Secretの設定には未対応
robot.router.post '/github/webhook', (req, res) ->
branch = req.body.ref.match(/refs\/heads\/(.+)/)[1]
data = fetch()
rooms = data[branch] || []
if rooms.length > 0
xs = req.body.commits.map (commit) ->
"#{commit.author.username}: #{commit.message}"
body = "新しいコミットだって!\n#{xs.join("\n")}"
for room in rooms
try robot.send { room: room }, body
catch e then 1
res.status(200).send('ok')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment