kakakakakku blog

Weekly Tech Blog: Keep on Learning!

Hubot で GitHub Trending Repositories を取得する

Hubot で Trending repositories on GitHub today · GitHub から人気のリポジトリを取得するスクリプトを書いてみた.Hubot も Coffee も初心者だからコードは雑だけど,まぁ検証用だしってことで!ちなみに Trending は GitHub API からは取得できず,今回はスクレイピングで取得するようにしてみた.ご利用は計画的に.

cheerio

cheerio-httpcli を使ってスクレイピングする例もあったけど,今回は requestcheerio を試してみた.cheerio は取得したページ情報を jQuery 的にセレクタで処理できて凄く簡単だった.

github.com

サンプルコード

以下のようなメッセージに反応するようにしている.

  • hubot github trending
  • hubot github trending go
  • hubot github trending ruby

5件を取得するロジックがクソすぎて笑えてくるw

# Description:
#   Get GitHub trending repositories
#
# Commands:
#   hubot github trending - Get top 5 GitHub trending repositories
#   hubot github trending :lang - Get top 5 GitHub trending repositories with lang
cheerio = require 'cheerio'
request = require 'request'

module.exports = (robot) ->

  robot.respond /github trending$/i, (msg) ->
    baseUrl = 'https://github.com'
    request baseUrl + '/trending', (_, res) ->
      $ = cheerio.load res.body

      i = 0
      $('.repo-list-name a').each ->
        a = $(this)
        url = baseUrl + a.attr('href')
        msg.send url
        i++
        if i >= 5
          return false

  robot.respond /github trending (.+)$/i, (msg) ->
    lang = msg.match[1]
    baseUrl = 'https://github.com'
    request baseUrl + '/trending/' + lang, (_, res) ->
      $ = cheerio.load res.body

      i = 0
      $('.repo-list-name a').each ->
        a = $(this)
        url = baseUrl + a.attr('href')
        msg.send url
        i++
        if i >= 5
          return false

botty

コミットしておいた!

github.com

hubot github trending go

実際に Slack から呼び出してみた.トレンドになってるリポジトリのコードを読むのを習慣にしたいな!

f:id:kakku22:20160203232916p:plain

関連記事

kakakakakku.hatenablog.com