LoginSignup
2
7

More than 5 years have passed since last update.

githubのpullrequestの情報をAPI経由で取得する

Posted at

参考リンク:https://qiita.com/kz800/items/f822fe7a3b285b14085c

情報を取得して、定期的にslackへ通知するような仕組みを作成したいと思います。レビューやマージの依頼を受けたけど、放置してしまうこともありチーム全体で定期的にPRを認知する仕組みです。似たようなことができる仕組みはありますが、ある程度自分で制御できるという意味で自作したい。

仕組み

・定期的にgithubのapiからpullrequestの一覧を取得する
・pullrequestがあればslackに通知する

slackへの通知

APIを利用するためトークンを取得する

アプリを登録する →https://api.slack.com/
create_app.png

作成したアプリのインストール
install.png

アクセストークンの取得
token_2.png
※トークン文字列が表示されているため、上部のみキャプチャしてます

(任意)permissionを追加する
per.png

メッセージを投稿する

API一覧は以下に記載があります
https://api.slack.com/methods
今回はまずslackに通知してみるので、以下を利用します
https://api.slack.com/methods/chat.postMessage

シェル(curl)経由で通知する

$ curl -X POST -d 'token=アクセストークン' -d 'channel=#general' -d 'text=post it!' https://slack.com/api/chat.postMessage

通知受け取り
slackpost.png

githubから情報取得

APIを利用するためトークン取得

「setting」->「Developer settings」->「Personal access tokens」からトークン生成

シェル(curl)経由で取得する
以下のリポジトリにPRが1件あるため取得できるか確認
https://github.com/kaikusakari/kaikusakari.github.io

$ curl https://api.github.com/repos/kaikusakari/kaikusakari.github.io/pulls?access_token=アクセストークン
[
  {
    "url": "https://api.github.com/repos/kaikusakari/kaikusakari.github.io/pulls/1",
    "id": 161073288,
     ・・・中略・・・
    "author_association": "OWNER"
  }
]

gitから情報を取得して、slackにPOSTする

pythonで実装します。動作は以下の通り。
1.gitのAPIからPR一覧を取得
2.レスポンスで受け取ったJSON文字列を取捨選択
3.slackに通知
pythonのインストールや、importモジュールのインストールは省略・・・。

receve.py
# -*- coding: UTF-8 -*-
import requests
import json

def main():
    results = ''
    repogitories = requests.get('https://api.github.com/user/repos?access_token=gitのアクセストークン')
    for repogitory in repogitories.json():
        pullrequests = requests.get('https://api.github.com/repos/' + repogitory["full_name"] + '/pulls?access_token=gitのアクセストークン')
        for pullrequest in pullrequests.json():
            results += pullrequest["url"] + ", updated_at:" + pullrequest["updated_at"] + '\n'
    post_data = {}
    if len(results) == 0:
        post_data = {'token':'slackのアクセストークン','channel':'#general', 'username':'github_pullrequest', 'text':'open状態のPRはありません'}
    else:
        post_data = {'token':'slackのアクセストークン','channel':'#general', 'username':'github_pullrequest', 'text':results}
    requests.post('https://slack.com/api/chat.postMessage',data=post_data)

if __name__== '__main__':
    main()

結果
slack_result.png

何度か失敗した通知が出てますが笑、リンクと時間を表示しています。
時間を相対時間にして、より視覚的にわかりやすくするなど修正していきたいです。
※PRをマージすると、APIで取得できなくなります

注意
GitHub APIのリクエスト回数は1時間5000回が上限のようです。情報取得は1日1回も実施すれば良いと思いますが、アクセス可能な全リポジトリを巡回しているので上限は注意してください。(参考:https://developer.github.com/v3/#rate-limiting)

2
7
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
2
7