LoginSignup
10
9

More than 5 years have passed since last update.

コミット数ランキングを発表するボットを作った

Posted at

経緯

今社内でSlackを使っていて、無料プランだと10000件のメッセージまでしか残せなくて、先日ついに上限に達してしまいました。そこで上の人に有料プランをお願いして課金してもらったので、有効利用しなくちゃ申し訳ないということでボットを作り始めました。

ほとんどのエンジニアの人はレガシーなPHPとjQueryしかいじったことがないので、このボット開発を通して社内のエンジニアの人に少しでも新しいものに触れて欲しいというのも狙いです。

第一弾としてモチベーションに繋がりそうな、リポジトリ名を入力すると1週間のコミット数をランキング表示するボットを作りました。

コード

commend.coffee
token = 'your token'
apiUrl = "https://api.github.com/repos/Organization名"

module.exports = (robot) ->
  robot.respond(/commend (.*)/i, (msg) ->
    repository = msg.match[1]

    oneWeekAgo = new Date()
    oneWeekAgo.setDate(oneWeekAgo.getDate() - 7)
    year = oneWeekAgo.getFullYear()
    month = ("0" + (oneWeekAgo.getMonth() + 1)).substr(-2)
    day = ("0" + oneWeekAgo.getDate()).substr(-2)

    since = "#{year}-#{month}-#{day}T00:00:00Z"

    request = robot.http("#{apiUrl}/#{repository}/commits")
      .query(since: since)
      .query(access_token: token)
      .get()

    committers = {}
    request((err, res, body) ->
      if err
        msg.send("何かエラーになっちゃいました...")
        return

      commits = JSON.parse body

      if commits.message == "Not Found"
        msg.send("#{repository}が見つかりませんでした...")
        return

      for commit, index in commits
        committer = commit.committer.login
        if committers[committer] == undefined
          committers[committer] = 0
        ++committers[committer]

      respond = "発表します!\n\n#{since}から今までで\n\n"
      commended = []
      for i in [0..Object.keys(committers).length - 1]
        max = 0
        nextCommitter = ''
        for committer, count of committers
          if (commended.indexOf(committer) == -1)
            if count >= max
              nextCommitter = committer
              max = count
        commended.push(nextCommitter)
        respond += "#{i + 1}位: #{nextCommitter} #{max} commits\n"

      msg.send(respond)
    )
  )

普段JavaScriptを全然描かないのでもっと効率的にソートする方法があると思うのですが、ここではバブルソートを書いてしまいました笑。githubotというのがあるらしいのですが、見た感じそこまで便利になった感じがしなかったので普通にAPIを呼び出しています。

実行した感じ

slack-bot.png

これでなんかモチベーションが上がる気がしますね!笑

10
9
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
10
9