Nail robot automatically associated GitHub to send approval PRS

Time:2020-7-31

Abstract: using technology to solve the boring approval PR work of PM, this paper describes how to automatically obtain the pull requests of each repo to merge under GitHub organization and notify relevant personnel, saying goodbye to daily manual operation.

Nail robot automatically associated GitHub to send approval PRS

In your daily work, do you encounter the following scenarios:

  • GitHub has multiple repos. In daily work, a large number of pull requests to be merged need to be manually filtered one by one
  • To find out more than one repoready to reviewYou need to manually filter, paste, copy, and submit dev for review again and again. It’s boring
  • If you want to push the PRS of GitHub to merge automatically, GitHub webhooks does not have the event
  • ……

Using technology to solve the boring approval PR work of PM, this paper will describe how to automatically obtain the pull requests of each repo to merge under GitHub organization and inform relevant personnel to say goodbye to daily manual operation. This paper mainly provides a solution to automatically send approval PRs, and takes nail group and slack as examples, gives the implementation of Python. If you use other communication tools, the implementation principle is interlinked.

Configure message reception

Configuration of nail swarm robot

  1. Open the robot management page. Take the PC terminal as an example, open the pin on the PC side, and click “group settings” = > “intelligent group assistant” = > “add robot”.

Nail robot automatically associated GitHub to send approval PRS

  1. Click “add robot” and select “custom”

Nail robot automatically associated GitHub to send approval PRS

The “security settings” in this example use custom keywords, and the messages sent to the robot must contain the keywords set here.

  1. Click Finish to get the webhook

Please refer to the official document for details of the nailing BOT configuration document https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq/26eaddd5

Configure slack BOT

  • Create an app (link: https://api.slack.com/apps ), set the app name and select the target slack workspace
  • In the left column, select “basic information” = > “add features and functionality” in “bots”

Nail robot automatically associated GitHub to send approval PRS

  • Select “OAuth & permissions” in the left column, and click “add an OAuth scope” in “Scopes” to addchat:write.public 
  • Click “install app to workspace”
  • Get OAuth access token

For detailed configuration steps of slack BOT, please refer to the official English document: https://slack.com/intl/en-cn/help/articles/115005265703-Create-a-bot-for-your-workspace#add -a-bot-user

Configure GitHub to get personal access tokens

Generate token and give corresponding permission. In this example, after reading all public and private repos under the organization, you need to check repo.

Nail robot automatically associated GitHub to send approval PRS

For details of GitHub token configuration steps, please refer to the official document: https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line

Code description

Get GitHub to merge pr

Pygithub provides the function of accessing GitHub V3 API, which allows you to implement the operation on GitHub with code. You can use thepip install pygithubInstall.

FILTER_TEMPLATE = "repo:{org}/{repo} is:pr is:open review:approved"

class GithubPrList:

    @property
    def gh(self):
        return self._gh

    @property
    def org(self):
        return self._org

    FILTER_TEMPLATE = "repo:{org}/{repo} is:pr is:open review:approved"

    def __init__(self,
                 org,
                 repo,
                 login_or_token,
                 password=None,
                 timeout=DEFAULT_CONNECT_TIMEOUT,
                 retry=None,
                 ):
        """
        :param org: string
        :param repo: string
        :param login_or_token: string,token or username
        :param password: string
        :param timeout: integer
        :param retry: int or urllib3.util.retry.Retry object
        """
        #Instantiating access to GitHub API V3
        self._gh = Github(login_or_token=login_or_token,
                          password=password,
                          timeout=timeout,
                          retry=retry)
        self._org = org
        self._repo = repo

        def getIssues(self,
                            filter=None,
                       sort=DEFAULT_PR_SORT,
                       order=DEFAULT_ORDER,
                       ):
        """
        :param filter: string
        :param order: string ('asc', 'desc')
        :param sort: string('comments', 'created', 'updated')
        :rtype :class:`List` of :class:`PrList2.PrElement`
        """
        if not filter:
                #Generate the filter of the query, and specify the PR approved under org / repo
            filter = self.FILTER_TEMPLATE.format(org=self._org,
                                                 repo=self._repo)
        #Inquiry
        issues = self._gh.search_issues(filter, sort, order)
        prList = []

        for issue in issues:
            prList.append(PrElement(issue.number, issue.title, issue.html_url))

        return prList

Function Description:

  • __init__Support the use of username / password or token to instantiate access to the GitHub API v3.
  • In GitHub, pull requests are also issues,getIssues()Function allows the user to use default conditions(repo:{org}/{repo} is:pr is:open review:approved)Find pull requests with approved status under the specified org / repo, that is, the PRS to be merged. Among them:
Qualifier explain
repo:org_/_repo Find the projects under the specified organization repo
is:pr Find pull requests
is:open Find open issues
review:approved If the review status is approved, the value of review status may be selected_ none_ 、_ required_ 、_ approved_ 、_ changes requested_

The user can also specify the filter conditions of GitHub issues

filter = "repo:myOrg/myRepo is:pr is:open review:approved"
GithubPrList(self.org, 
                            self.repo, 
              self.token).getIssues(filter)

For more screening criteria, please refer to the official document: https://help.github.com/en/github/searching-for-information-on-github/searching-issues-and-pull-requests

send message

Send nail message

Dingtalk Chatbot encapsulates the nail message type. In this paper, we use this tool to send the PR to be merged to the nail grouppip install DingtalkChatbotInstall dingtalk Chatbot.

from dingtalkchatbot.chatbot import DingtalkChatbot

webhook = "https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxxx"
atPerson = ["123xxx456","123xxx678"]

xiaoding = DingtalkChatbot(webhook)
xiaoding.sendMsg ({custom keyword} + "PR list above", at person)

To send the message to the nailing group, we need to use the webhook of the nailing group robot mentioned above and the custom keywords.

Send a slack message

Python slackclient is the official API library developed by slack. It can obtain information from and send information to the slack channel. It supports Python 3.6 and above. Can be passed throughpip3 install slackclientInstall.

from slack import WebClient
from slack.errors import SlackApiError

client = WebClient(token={your_token})

try:
    response = client.chat_postMessage(
        channel='#{channel_name}',
        text="Hello world!")
    assert response["message"]["text"] == {pr_list}
except SlackApiError as e:
    # You will get a SlackApiError if "ok" is False
    assert e.response["ok"] is False
    assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
    print(f"Got an error: {e.response['error']}")

Replace {your here with the token configured above_ Token}, replace {channel_ Name}, set pr_ List is sent to the target channel.

So far, it’s done! Let’s see how it works

Nail robot automatically associated GitHub to send approval PRS

If there are any mistakes or omissions in this article, please go to GitHub: https://github.com/vesoft-inc/nebula The issue area asks us about the issue or goes to the official forum: https://discuss.nebula-graph.com.cn/ OfSuggestion feedbackTo join the nebula graph communication group, please contact the official assistant of nebula graph: nebulagraphbot

The author has said: Hi, I’m Jude, PM of nebula graph. Welcome to ask for your requirements. Although not all of them will be realized, we will seriously evaluate it^

Recommended Today

Regular expression sharing for checking primes

This regular expression is shown as follows: Regular expressions for checking prime numbers or not To use this positive regular expression, you need to convert the natural number into multiple 1 strings. For example, 2 should be written as “11”, 3 should be written as “111”, 17 should be written as “11111111111”. This kind of […]