创建飞书自定义机器人发送 Gerrit 消息提醒

配置 Gerrit Hooks

Gerrit Supported Hooks

patchset-created

每当有新的代码提交时调用(这包括新的更改)。

change-merged

每当合并代码时调用。

reviewer-added

每当增加 reviewer 时调用。

创建飞书自定义机器人

群组内添加自定义机器人

创建飞书群组 >> 群组设置 >> 群机器人 >> 添加机器人 >> 选择添加【自定义机器人】
在这里插入图片描述

自定义机器人配置

在这里插入图片描述
复制 webhook 地址,之后有用。
安全设置设置自定义关键词,只有包含该自定义关键词的消息,才会被接收。

编写 Gerrit Hook

以 patchset-created 举例,传参格式如下:
patchset-created
–change Ia21d96fc3491f79b9beeb9e0dd0aeb9fad9f3fed
–is-draft false
–kind REWORK
–change-url http://gerrit.com/gerrit/5431
–change-owner Anonymous Coward (xxxx@qq.com)
–project rk3568_android11
–branch master
–uploader Anonymous Coward (xxxx@qq.com)
–commit c70a40eeef997ae6dc16abb72bccadc991de6d0e
–patchset 1
————————————————
每当有新的代码提交时调用(这包括新的更改)。代码如下:

#!/usr/bin/python3
#coding:utf-8

import sys
import os
import requests
import json
import time

port = '29418'
user = 'xxx'
ip = 'xxx.xxx.xxx.xxx'
url = 'https://open.feishu.cn/open-apis/bot/v2/hook/xxxxxxxxxx'    #飞书 webhook 地址

commit_sha1 = sys.argv[2]
print(commit_sha1)
query_cmd = 'ssh -p %s %s@%s gerrit query %s --format=JSON --patch-sets --current-patch-set' %(port, user, ip, commit_sha1)
print(query_cmd)
p = os.popen(query_cmd)
query_ret_json = p.read().splitlines()
e = p.close()
if e is not None or len(query_ret_json) != 2:
    sys.exit("fatal: Can't find %s" %commit_sha1)

query_ret = json.loads(query_ret_json[0])
print(len(query_ret['patchSets']))
if len(query_ret['patchSets']) != 1:
    sys.exit()

commit_user = query_ret['owner']['username']
commit_email = query_ret['owner']['email']
commit_project = query_ret['project']
commit_branch = query_ret['branch']
commit_url = query_ret['url']
commit_message = query_ret['commitMessage'].splitlines()[0]
commit_time = query_ret['createdOn']

patchset_msg = '**Subject :** ' + commit_message + '\n' +\
               '**Owner  :** ' + commit_user + '\n' +\
               '**Project :** ' + commit_project + '\n' +\
               '**Branch :** ' + commit_branch
print(patchset_msg)

method = 'post'
headers = {
    'Content-Type': 'application/json'
}
json = {
    "msg_type": "interactive",
    "card": {
        "config": {
            "wide_screen_mode": True
        },
        "elements": [
            {
                "tag": "div",
                "text": {
                    "content": patchset_msg,
                    "tag": "lark_md"
                }
            },
            {
                "tag": "hr"
            },
            {
                "actions": [
                    {
                        "tag": "button",
                        "text": {
                            "content": "Gerrit Review",
                            "tag": "plain_text"
                        },
                        "type": "primary",
                        "url": commit_url
                    }
                ],
                "tag": "action"
            }
        ],
        "header": {
            "template": "blue",
            "title": {
                "content": "Gerrit  " + patchset-created,
                "tag": "plain_text"
            }
        }
    }
}

requests.request(method=method, url=url, headers=headers, json=json)

结果展示

在这里插入图片描述

### 将 Gerrit飞书 Dashboard 集成的方法 要将 Gerrit飞书 Dashboard 进行集成或关联,可以通过以下方式实现: #### 1. **通过 Webhook 实现事件通知** Gerrit 支持通过插件发送 Webhook 请求到外部系统。可以利用这一功能,在每次代码提交、审核状态更新或其他特定事件发生时触发请求,并将其传递给飞书 API。 - 安装 `webhooks` 插件[^1]。 - 配置 Webhook URL 指向飞书机器人接口地址。 ```bash ssh -p 29418 user@gerrit-server gerrit plugin install webhooks ``` - 编辑 Webhook 配置文件 `/path/to/gerrit/site/etc/webhooks.config` 并指定目标 URL: ``` [remote "feishu"] url = https://open.feishu.cn/open-apis/bot/v2/hook/<your-bot-id> events = patchset-created, change-merged, comment-added ``` 此方法允许实时同步数据至飞书 Dashboards[^3]。 --- #### 2. **开发自定义脚本推送消息** 如果需要更复杂的逻辑处理,则可通过编写 Python 脚本来定期抓取 Gerrit 数据并通过飞书 API 发送通知。 以下是示例代码片段用于获取最新变更记录并向飞书发送 POST 请求: ```python import requests from datetime import datetime, timedelta def fetch_gerrit_changes(): """Fetch recent changes from Gerrit.""" since_time = (datetime.now() - timedelta(days=1)).isoformat() response = requests.get( 'http://<gerrit-host>/a/changes/', params={'q': f'status:open after:{since_time}'}, auth=('username', 'password') ) return response.json() def send_to_feishu(data): """Send data to Feishu via webhook.""" feishu_webhook_url = 'https://open.feishu.cn/open-apis/bot/v2/hook/<bot_id>' payload = { "msg_type": "text", "content": {"text": str(data)} } headers = {'Content-Type': 'application/json'} res = requests.post(feishu_webhook_url, json=payload, headers=headers) return res.status_code == 200 if __name__ == "__main__": changes = fetch_gerrit_changes() success = all(send_to_feishu(change) for change in changes) print(f"All messages sent successfully? {success}") ``` 该脚本可以根据需求调整频率并加入定时任务调度器如 Crontab 来执行[^4]。 --- #### 3. **借助第三方工具 Jeepyb 自动化管理** Jeepyb 是一种简化 Gerrit 管理流程的强大工具集,支持 YAML 文件形式描述项目结构及其依赖关系。虽然 Jeepyb 主要是针对 OpenStack 社区设计,但它也可以扩展来满足其他场景下的定制需求。 例如创建一个新的配置项专门用来存储飞书相关参数: ```yaml project: my-gerrit-project description: My custom managed repository. acl-config: /home/gerrit/acls/my-acl.conf upstream: git://example.com/repo.git notifications: enabled: true targets: - type: feishu-webhook url: https://open.feishu.cn/open-apis/bot/v2/hook/<another-bot-id> ``` 这样每当有新的活动产生时都会按照预设规则自动触发展示在飞书界面上[^2]。 --- ### 总结 以上三种方案分别适用于不同层次的技术背景以及实际应用场景。无论是简单的 Webhook 设置还是复杂的数据解析与传输过程都可以找到合适的解决方案完成两者之间的无缝衔接工作。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值