【Jenkins pipeline企业微信消息推送】message_send.py

企业微信消息推送本质是向连接发送HTTP请求并发送消息

curl "https://qyapi.weixin.qq.com/cgi-bin/webhook/XXXXX" -H "Content-Type: application/json" -d '{"msgtype": "markdown","markdown": {"content":"<font color="info">$JOB_NAME</font>构建<font color="info">$result</font>
>构建用时:<font color="comment">3s</font>
>[查看控制台]$BUILD_URL"}}'
# coding=gbk
#coding:utf-8
import requests
import json
import urllib.request
import urllib.error
import time,os
# 引用Jenkins全局变量
CONF_DONE=os.environ["CONF_DONE"] #获取是构建是否成功
ProjectName=os.environ["JOB_NAME"]#获取构建项目名称
BUILD_URL=os.environ["BUILD_URL"]#获取构建项目URL
BUILD_NUMBER=os.environ["BUILD_NUMBER"]#获取构建编号,用于allure报告链接拼接
duration=os.environ["Elapsed"]#获取构建耗时
#时间换算
def main():
    millis = int(duration)
    seconds=(millis/1000)%60
    seconds = int(seconds)
    minutes=(millis/(1000*60))%60
    minutes = int(minutes)
    hours=(millis/(1000*60*60))%24
    print ("%d:%d:%d" % (hours, minutes, seconds))
    return str("%d时%d分%d秒" % (hours, minutes, seconds))
headers = {"Content-Type": "text/plain"}
send_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/XXXXXXXXXXXXX"# 企业微信机器人的webhook
report=f"http://XXXXX:8080/job/{ProjectName}/{BUILD_NUMBER}/allure/"   #allure报告地址
result=""
colour=""
if CONF_DONE=="0":
    result="成功"
    colour="info"
elif CONF_DONE=="1":
    result = "失败"
    colour = "warning"
elif CONF_DONE=="2":
    result = "中断"
    colour = "comment"
send_data = {
    "msgtype": "markdown",  # 消息类型,此时固定为markdown
    "markdown": {
        "content": f"**<font color="{colour}">【{ProjectName}】</font>构建"+f"<font color="{colour}">{result}</font>**!!!
" +  # 标题 (支持1至6级标题,注意#与文字中间要有空格)
                   f"> 项目名称:<font color="{colour}">{ProjectName}</font> 
" +  # 引用:> 需要引用的文字
                   f"> 构件编号:<font color="{colour}">#{BUILD_NUMBER}</font> 
" +  # 引用:> 需要引用的文字
                   f"> 构建用时:<font color="{colour}">{main()}</font> 
" +  # 引用:> 需要引用的文字
                   f"[报告链接]({report})
"+
                   f"[控制台]({BUILD_URL})"
                     # 加粗:**需要加粗的字**
    }
}
res = requests.post(url=send_url, headers=headers, json=send_data)
print(res.text)
原文地址:https://www.cnblogs.com/ricebug2/p/14324291.html