钉钉机器人自动关联 GitHub 发送 approval prs

2020-06-17 10:18:36 +08:00
 NebulaGraph

摘要:用技术来解决 PM 枯燥的 approval pr 工作,本文将阐述如何自动化获取 GitHub Organization 下各个 repo 待 merge 的 pull requests 并通知相关人员,告别每日的手动操作。

在日常工作中,你是否遇到以下场景:

用技术来解决 PM 枯燥的 approval pr 工作,本文将阐述如何自动化获取 GitHub Organization 下各个 repo 待 merge 的 pull requests 并通知相关人员,告别每日的手动操作。此文主要提供了解决自动发送 approval prs 的思路,并以钉钉群和 Slack 为例,给出了其 Python 的实现方式,如果你使用其他通讯工具,实现原理是相通的。

配置消息接收

配置钉钉群机器人

  1. 打开机器人管理页面。以 PC 端为例,打开 PC 端钉钉,点击“群设置” => “智能群助手” => “添加机器人”。

  1. 点击“添加机器人”,选择“自定义”

本例的“安全设置”使用自定义关键词的方式,之后给机器人所发送的消息中必须包含此处设置的关键词。

  1. 点击“完成”,获取 Webhook

详细的钉钉 bot 配置文档可参见官方文档:https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq/26eaddd5

配置 Slack bot

详细的 Slack bot 配置步骤参见官方英文文档:https://slack.com/intl/en-cn/help/articles/115005265703-Create-a-bot-for-your-workspace#add-a-bot-user

配置 Github 获取 Personal Access Tokens

生成 Token,赋予相应权限。在此例中,读取了 Organization 下所有 Public 和 Private Repos,需要勾选 repo 。

详细 GitHub Token 配置步骤参见官方文档:https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line

代码说明

获取 Github 待 merge pr

PyGithub 提供了访问 Github V3 API 的功能,可以让你用代码去实现 GitHub 上的操作,可通过 pip install pygithub 进行安装。

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
        """
        #实例化对 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:
        		#生成查询的 filter,指定 org/repo 下已经 approved 的 pr
            filter = self.FILTER_TEMPLATE.format(org=self._org,
                                                 repo=self._repo)
        #查询
        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

函数说明:

用户也可指定 Github issues 的筛选条件,使用示例:

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

更多筛选条件,请参见官方文档:https://help.github.com/en/github/searching-for-information-on-github/searching-issues-and-pull-requests

发送消息

发送钉钉消息

DingtalkChatbot 对钉钉消息类型进行了封装。本文使用此工具发送待 merge 的 pr 到钉钉群,可通过 pip install DingtalkChatbot 安装 DingtalkChatbot 。

from dingtalkchatbot.chatbot import DingtalkChatbot

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

xiaoding = DingtalkChatbot(webhook)
xiaoding.sendMsg({自定义关键词} + "上文中的 pr list", atPerson)

将消息发送到钉钉群,此处需要用到上文中的钉钉群机器人的 Webhook 和自定义的关键词。

发送 slack 消息

Python slackclient 是 Slack 开发的官方 API 库,能够从 Slack 频道中获取信息,也能将信息发送到 Slack 频道中,支持 Python 3.6 及以上版本。可通过 pip3 install slackclient 进行安装。

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']}")

用上文配置的 token 替换此处的 {your_token},替换 {channel_name},将 pr_list 发送给目标 channel 。

至此,大功告成!来看看效果

本文中如有任何错误或疏漏,欢迎去 GitHub:https://github.com/vesoft-inc/nebula issue 区向我们提 issue 或者前往官方论坛:https://discuss.nebula-graph.com.cn/建议反馈 分类下提建议 👏;加入 Nebula Graph 交流群,请联系 Nebula Graph 官方小助手微信号:NebulaGraphbot

作者有话说:Hi,我是 Jude,图数据 Nebula Graph 的 PM,欢迎大家提需求,虽然不一定都会实现,但是我们会认真评估^ ^

1694 次点击
所在节点    推广
6 条回复
hantsy
2020-06-17 10:33:58 +08:00
唉,Slack 中用来接收各种通知,已经用了好多年了。

搞半天还是利用 SlackBot,我还以为钉自己跟上脚步了。昨天看看钉钉的男装视频,鸡皮疙瘩都起来了。
hantsy
2020-06-17 10:37:05 +08:00
你这个体验与 Slack 差得有点远,Slack 中很多深度集成的工具,可以直接在 Slack 中进行操作,不需要再跳到原有的系统界面上去操作。
NebulaGraph
2020-06-17 10:59:26 +08:00
@hantsy 我们主要是为了使用同一个套逻辑去适配 Slack 和钉钉,btw,钉钉的“女”装视频看个截图就好 😂
hantsy
2020-06-17 11:42:25 +08:00
很多国外已经很多产品在做 GitOps,ChatOps 等理念,与 软件工程,软件交付过程 紧密相结合的,更好实现交付自动化。

Spring 的他始人(已经脱离 Spring 很久了) Johnson 的新公司也是做一款软件交付的产品。

https://atomist.com/

以前看过一篇文章,可以在 Slack 监控服务器中 APP 运行状态等,也可以通过 Slack 命令类似 /start 这样的消息,去重启,部署,Scale 应用。
NebulaGraph
2020-06-17 11:59:27 +08:00
@hantsy Slack 果然强大,我们内部还是用的钉钉,Slack 主要是给国际友人来反馈信息用的
xiaochun41
2020-06-17 15:16:04 +08:00
ChatOps 的理念还是很好的,自己帮团队也做过一些尝试,提效还是很明显的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/682245

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX