pipeline+shell发消息到企业微信
需要安装的插件
build-user-vars-plugin
Build Timestamp
其中,pipeline内容如下
pipeline {
agent any
stages {
stage('build') {
steps {
sh 'pwd'
}
}
stage('test') {
steps {
wrap([$class: 'BuildUser']) {
script {
JOB_NAME = "${env.JOB_NAME}"
}
}
}
}
}
post {
success {
script {
sh 'export status=success;./1.sh'
}
}
failure {
script {
sh 'export status=failure;./1.sh'
}
}
}
}
shell内容如下(本shell可发送三种类型消息,这里只采用了文本消息)
#!/bin/bash
# 发送消息到企业微信应用里面
# 企业id
id=""
# 应用id
agentid=""
# 应用secret
secret="Q2SCTjwl9wB4"
# 部门id
toparty=x
# 用户id [也就是用户账号,多个用户用|符号分开]
touser="xxxx"
# API接口
url="https://qyapi.weixin.qq.com/cgi-bin"
# 获取token [这里token没做缓存,如果频繁调用gettoken接口,会受到频率拦截,官方默认token值有效时间2小时]
token=`curl -s "$url/gettoken?corpid=$id&corpsecret=$secret"|jq -r .access_token`
# 发送消息参数
part="message/send?access_token=$token"
# 上传临时素材参数
upload="media/upload?access_token=$token&type=$1"
# 执行提示
function tips(){
code=`jq -r .errcode`
if [ "$code" == "0" ]
then
echo -e "\033[32mSend successfully\033[0m"
else
echo -e "\033[31mSend fail,errcode:$code\033[0m"
fi
}
# 判断输入文件路径
function file_dir(){
while true
do
read -p "请输入[ $1 ]的路径:" f
[[ -f $f ]] && break || echo -e "\033[31m请输入正确的 $1 路径!\033[0m"
done
upload_file_dir="$f"
}
# 上传临时素材
function upload_file() {
# 发送的文件路径
file_dir $1
# post 参数
upload_post="-H 'Content-Type:multipart/form-data' -F 'filename=@$upload_file_dir;type=application/octet-stream' $url/$upload$1"
# 获取临时素材id
get_upload_part=`curl -s -X POST $upload_post`
upload_status=`echo "$get_upload_part"|jq -r .errcode`
if [[ $upload_status == 0 ]];then media_id=`echo "$get_upload_part"|jq -r .media_id`;else echo -e "\033[31mFailed to upload file [$f]\033[0m";exit;fi
}
# 发送文本消息 [这里按部门发送toparty]
function send_t(){
name=$(whoami)
time=$(date +'%F %T')
txtcontent="${name}你好,你在${time}构建的项目${JOB_NAME}以构建完成,构建状态为${status}"
textmsg='{"touser":"'$touser'","toparty":"'$toparty'","msgtype":"'text'","agentid":"'$agentid'","'text'":{"content":"'$txtcontent'"},"safe":0}'
curl -s -X POST -d "$textmsg" "$url/$part"|tips
}
# 发送文件图片消息 [这里按部门发送toparty]
function send(){
msg='{"touser":"'$touser'","toparty":"'$toparty'","msgtype":"'$1'","agentid":"'$agentid'","'$1'":{"media_id":"'$media_id'"},"safe":0}'
curl -s -X POST -d "$msg" "$url/$part"|tips
}
# 执行脚本
echo "
1、文本消息
2、文件消息
3、图片消息
"
#read -p "选择发送消息类型: " x
x=1
case $x in
1)
send_t
;;
2)
upload_file file && send file
;;
3)
upload_file image && send image
;;
*)
echo "输入错误,执行结束"
;;
esac