1、获取 飞书 Bot webhook 和 secret。
2、python脚本,参考@Song_Estelle 的文章,这里重写了部分代码,以签名校验方式发送通知(记得安装相关依赖)。
#! /usr/bin/python3
#-*- encoding: utf-8 -*-
import sys
import requests
import time
import hmac
import base64
import hashlib
from datetime import datetime
class JenkinsInfo(object):
def __init__(self, feis_webhook, feis_secret, job_url, job_name, build_number):
self.feis_webhook = feis_webhook
self.feis_secret = feis_secret
self.currenttime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.timestamp = int(time.time()) # datetime.timestamp(datetime.now())
self.JOB_URL = job_url
self.JOB_NAME = job_name
self.BUILD_NUMBER = build_number
def gen_sign(self):
# 拼接timestamp 和 secret
string_to_sign = '{}\n{}'.format(self.timestamp, self.feis_secret)
hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()
# 对结果进行base64处理
sign = base64.b64encode(hmac_code).decode('utf-8')
return sign
def feis_post(self):
method = 'post'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3775.400 QQBrowser/10.6.4209.400',
'Content-Type': 'application/json'
}
json = {
"timestamp": self.timestamp,
"sign": self.gen_sign(),
"msg_type": "interactive",
"card": {
"config": {
"wide_screen_mode": True,
"enable_forward": True
},
"elements": [{
"tag": "div",
"text": {
"content": "项目名称:" + JOB_NAME + "\n构建编号:第" + BUILD_NUMBER + "次构建\n运行时间:" + self.currenttime,
"tag": "lark_md"
}
}, {
"actions": [{
"tag": "button",
"text": {
"content": "查看报告",
"tag": "lark_md"
},
"url": JOB_URL,
"type": "default",
"value": {}
}],
"tag": "action"
}],
"header": {
"title": {
"content": JOB_NAME + " 构建报告",
"tag": "plain_text"
}
}
}
}
res = requests.request(method=method, url=self.feis_webhook, headers=headers, json=json)
print(res, "=======>>", res.json())
if __name__ == "__main__":
feis_webhook = r"https://open.feishu.cn/open-apis/bot/v2/hook/"
feis_secret = "YPkEsfe"
JOB_URL = sys.argv[1]
JOB_NAME = sys.argv[2]
BUILD_NUMBER = sys.argv[3]
# JOB_URL = JOB_NAME = BUILD_NUMBER = "123"
t = JenkinsInfo(feis_webhook, feis_secret, JOB_URL, JOB_NAME, BUILD_NUMBER)
t.feis_post()
3、Jenkins项目中添加配置
在配置中的构建中 加上一行命令即可
python3 /usr/local/jenkinsInfo/feishutongzhi.py $JOB_URL $JOB_NAME $BUILD_NUMBER
4、验证
引用:
Jenkins+飞书机器人发送通知_Song_Estelle的博客-CSDN博客_飞书机器人向用户个人发消息
https://blog.csdn.net/weixin_43484014/article/details/121950558自定义机器人指南 - 客户端文档 - 开发文档 - 飞书开放平台
https://open.feishu.cn/document/ukTMukTMukTM/ucTM5YjL3ETO24yNxkjNjenkins持续集成飞书发送报告通知 - 测试小小小白 - 博客园
https://www.cnblogs.com/spl-/p/14866221.htmlgitlab、jenkins + webhook 做代码合并管理者的消息通知 - BraveDu
http://www.bravedu.com/archives/204/