Skip to content

Instantly share code, notes, and snippets.

@guoxiaoqiao
Last active October 25, 2023 13:45
Show Gist options
  • Save guoxiaoqiao/20ffc6fd95810b3b6712b1cf062472f5 to your computer and use it in GitHub Desktop.
Save guoxiaoqiao/20ffc6fd95810b3b6712b1cf062472f5 to your computer and use it in GitHub Desktop.
GitLab的企业微信机器人通知转发代码。(本人只是搬运工,原创作者:建帅小伙儿,URL:https://developer.aliyun.com/article/1025391
# coding=utf-8
"""
@Project :pachong-master
@File :gitlab_wechat.py
@Author :gaojs
@Date :2022/8/10 21:56
@Blogs : https://www.gaojs.com.cn
"""
from flask import Flask, request, json
import argparse
import requests
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook():
# 请求参数
params = request.json
# 打印接收到的原始数据
print("接收到的数据:", json.dumps(params, indent=4, ensure_ascii=False))
# 检查object_kind,如果不是push则直接退出
if params.get('object_kind') != 'push':
return '不是push事件,忽略处理。'
# 用户名
user_name = params['user_name']
# 项目名称
repository_name = params['repository']['name']
# 分支名,去除refs/heads/
branch_name = params['ref'].split('/')[-1]
# 总commits数
total_commits_count = str(params['total_commits_count'])
# 准备发送的数据
content = f"{user_name} 提交了 {total_commits_count} 个新的提交到 {repository_name} 的 {branch_name} 分支\n"
for commit in params['commits']:
content += f"\n> {commit['id'][0:8]} - {commit['title']}"
body = {
"msgtype": "markdown",
"markdown": {
"content": content
}
}
# 打印准备发送的数据
print("准备发送的数据:", json.dumps(body, indent=4, ensure_ascii=False))
# 发送请求到企业微信
requests.request('POST', wechat_url, headers={'Content-Type': 'application/json'}, json=body)
return 'OK'
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--wechatKey', type=str, help="企业微信URL的key部分。")
parser.add_argument('--port', type=int, default=8007, help="运行服务器的端口号。")
args = parser.parse_args()
# 构建完整的企业微信URL
wechat_url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={args.wechatKey}"
if args.wechatKey:
app.run(host='0.0.0.0', port=args.port)
else:
print("错误:缺少--wechatKey参数,程序退出。")
@guoxiaoqiao
Copy link
Author

guoxiaoqiao commented Oct 14, 2023

使用方法:
1、安装依赖
pip3 install flask requests

2、在GitLab服务器上执行脚本:
python3 gitlab_wechat.py --wechatKey 2ae8c2ac-fb29-4160-a26f-a44494c63099 --port 8007
注意:后面的机器人地址请替换为你自己的

3、配置GitLab允许本地请求
打开 管理中心->设置->网络
找到“出站请求”设置,勾选“允许来自 webhooks 和集成对本地网络的请求”,保存更改

3、配置GitLab Hook
gitlab上配置webhook格式如下:
webhook:http://127.0.0.1:8007/webhook

4、推送代码体验效果吧

更详细信息,请参考原创:https://developer.aliyun.com/article/1025391

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment