GitBucket の WebHook Event を hubot で Slack に流す。

GitBucketのWebHook Eventをhubotで受けてSlackに流すスクリプトを作ってみました。

Slack画面

Issue/PR作成、コメント投稿、Issue/PR Closeの時にメッセージが流れます。

gitbucket2slack.coffee

https://gist.github.com/YuG1224/966f2a8b21534568cd5f

# Description:
#   GitBucket to Slack
#
# Dependencies:
#   "hubot-slack": "^3.3.0"
#   "hubot-slack-attachement": "^1.0.1"
#
# Commands:
#   None

module.exports = (robot) ->
  @robot = robot
  @robot.router.post "/hubot/gitbucket2slack/:room", (req, res) =>
    room = req.params.room
    body = req.body

    if body.payload

      payload = JSON.parse body.payload
      repoUrl = payload.repository.html_url
      repoName = payload.repository.full_name
      action = payload.action
      comment = payload.comment
      issue = payload.issue
      pr = payload.pull_request
      commits = payload.commits
      userName = ""
      title = ""
      url = ""
      body = ""

      if action is "created"
        # Comment
        if comment
          action = "updated"
          userName = comment.user.login
          title = "##{issue.number}: #{issue.title}"
          url = comment.html_url
          body = comment.body
          slack = true

      if action in ["opened", "closed", "reopened"]
        # Issue
        if issue
          userName = issue.user.login
          title = "##{issue.number}: #{issue.title}"
          url = issue.html_url
          body = if action is "opened" then issue.body else action
          slack = true

        # Pull Request
        if pr
          userName = pr.user.login
          title = "##{pr.number}: #{pr.title}"
          url = pr.html_url
          body = pr.body
          slack = true

      if slack
        data =
          content:
            fallback: "[#{repoName}] #{userName} #{action} #{title}"
            pretext: "[<#{repoUrl}|#{repoName}>] #{userName} #{action} <#{url}|#{title}>"
            color: "#e3e4e6"
          username: "bot"
          channel: room
          icon_url: "https://raw.githubusercontent.com/takezoe/gitbucket/master/src/main/webapp/assets/common/images/gitbucket.png"
        if action in ["updated", "opened"]
          data.content.text = body
        else
          data.content.text = action

        if action in ["opened", "reopened"]
          data.content.color = "#468847"
        if action in ["closed"]
          data.content.color = "#B94A48"

        @robot.emit "slack.attachment", data

    res.end "OK"

hubot-slack-attachement に依存しているので、npm install --save hubot-slack-attachement は必須。

最初はPushも流すようにしていたのですが、ログが酷いことになったので辞めました。

WebHook URLs

WebHook設定

各リポジトリの設定でhubotへのWebHook http://localhost/gitbucket2slack/:channel を設定しておきます。

/:channel を変えることで任意のchannnelに飛ばすことが出来ます。