dingbot
Contents
钉钉机器人发消息
1、签名计算
由于 mac 上的是 BSD 的 date,与 linux 上的 date 不同,在 mac 上使用需要替换为 linux 的 gdate。
#!/usr/bin/env bash
## 需要艾特的人的手机号码,以空格隔开
atMobiles=(13333333333 18888888888)
ACCESS_TOKEN="fdebf803ece5080bdb432446ef6649e8c371bcxxxxxxxxxxx"
SECRET="SEC4622afcfbf51b8e71f0cc22154ba2f6f87xxxxxxxxxxxx"
dingbot() {
message=$1
timestamp=$(date +%s%3N)
stringtosign="${timestamp}\n${SECRET}"
signdata=$(printf "${stringtosign}" | openssl dgst -sha256 -hmac ${SECRET} -binary | base64)
sign=$(echo -n "${signdata}" | xxd -plain | tr -d '\n' | sed 's/\(..\)/%\1/g')
webhook_url="https://oapi.dingtalk.com/robot/send?access_token=${ACCESS_TOKEN}×tamp=${timestamp}&sign=${sign}"
at_who=$(printf '"%s",' "${atMobiles[@]}")
at_who=${at_who%,} # 移除最后一个逗号
# 构造JSON数据
json_data=$(cat <<EOF
{
"at": {
"atMobiles": [${at_who}]
},
"msgtype": "text",
"text": {
"content": "${message}"
}
}
EOF
)
curl -s -X POST -H 'Content-Type: application/json' "${webhook_url}" -d "${json_data}"
}
dingbot "你好,这是一个测试消息。"
function dingbotMD(){
title="$1"
message="$2"
timestamp=$(date +%s%3N)
stringtosign="${timestamp}\n${SECRET}"
signdata=$(printf "${stringtosign}" | openssl dgst -sha256 -hmac ${SECRET} -binary | base64)
sign=$(echo -n "${signdata}" | xxd -plain | tr -d '\n' | sed 's/\(..\)/%\1/g')
webhook_url="https://oapi.dingtalk.com/robot/send?access_token=${ACCESS_TOKEN}×tamp=${timestamp}&sign=${sign}"
at_who=$(printf '"%s",' "${atMobiles[@]}")
at_who=${at_who%,} # 移除最后一个逗号
# 构造JSON数据
json_data=$(cat <<EOF
{
"msgtype": "markdown",
"markdown": {
"title": "${title}",
"text": "${message}"
}
}
EOF
)
curl -s -X POST -H 'Content-Type: application/json' "${webhook_url}" -d "${json_data}"
}
msg="$(date)"
dingbotMD "msg" "### 东八区时间:${msg}"
echo
2、通用版
#!/usr/bin/env bash
# ***********************************************************************
# Description : Dingbot for shell
# Author : serialt
# Email : tserialt@gmail.com
# FilePath : /shell/DingMsg.sh
# Other :
# :
#
# 支持安全类型:【关键字】 和 【加签】
# 依赖命令:curl openssl date echo
#
# 注意:mac上的date命令是bsd的,与linux上的date不同,获取不到毫秒,不能用于签名计算。
# 或者安装coreutils,使用gdate替换date
#
# ***********************************************************************
## 钉钉机器人配置
dingbot_secret='SECa87a39d5b80e32xxxxxxxxxxxxxxxxxxxxxxxx'
dingbot_url='https://oapi.dingtalk.com/robot/send?access_token=cd316d9df306852b6da7d10xxxxxxxxxxxxxxxxxxxxxxx'
## secret_type keywords || sign
ding_secret_type='sign'
## 需要艾特的人的手机号码,以空格隔开
atMobiles=(13333333333 18888888888)
## encode url
function url_encode() {
t="${1}"
if [[ -n "${1}" && -n "${2}" ]];then
if ! echo 'xX' | grep -q "${t}";then
t='x'
fi
echo -n "${2}" | od -t d1 | awk -v a="${t}" '{for (i = 2; i <= NF; i++) {printf(($i>=48 && $i<=57) || ($i>=65 &&$i<=90) || ($i>=97 && $i<=122) ||$i==45 || $i==46 || $i==95 || $i==126 ?"%c" : "%%%02"a, $i)}}'
else
echo -e '$1 and $2 can not empty\n$1 ==> 'x' or 'X', x ==> lower, X ==> toupper.\n$2 ==> Strings need to url encode'
fi
}
## dingbot
function dingbot(){
send_strs="${1}"
new_url="${dingbot_url}"
at_who=''
for i in ${atMobiles[*]}
do
if [ -n "${at_who}" ];then
at_who="${at_who},\"${i}\""
else
at_who="\"${i}\""
fi
done
if [ "${ding_secret_type}" == 'keywords' ];then
curl -s -X POST -H 'Content-Type: application/json' "${new_url}" \
-d "{\"at\":{\"atMobiles\":[${at_who}]},\"msgtype\":\"text\",\"text\":{\"content\":\"${send_strs}\"}}"
elif [ "${ding_secret_type}" == 'sign' ];then
timestamp=$(date "+%s%3N")
dingbot_sign=$(echo -ne "${timestamp}\n${dingbot_secret}" | openssl dgst -sha256 -hmac "${dingbot_secret}" -binary | base64)
dingbot_sign=$(url_encode 'X' "${dingbot_sign}")
post_url="${dingbot_url}×tamp=${timestamp}&sign=${dingbot_sign}"
curl -s -X POST -H 'Content-Type: application/json' "${post_url}" \
-d "{\"at\":{\"atMobiles\":[${at_who}]},\"msgtype\":\"text\",\"text\":{\"content\":\"${send_strs}\"}}"
else
echo "secret_type 未知,请检查配置"
fi
}
msg="$(date)"
dingbot "东八区时间:${msg}"
3、其他 shell 版本
#!/usr/bin/env bash
info='msg to you'
#发送消息
sendMsg(){
token='1e18ffe069052b56f5a0f8fe9b6c058373e7df7ef49dc24baa6xxxxxxxxxxxxxx'
curl -s "https://oapi.dingtalk.com/robot/send?access_token=$token" \
-H 'Content-Type: application/json' \
-d "{'msgtype': 'text','text': {'content': 'msg:\n$*'}}
}
main(){
logRotate
sendMsg $info
}
main
#!/bin/bash
# ******************************************************
# Description : send msg by dingRobot
# 使用脚本前请设置钉钉机器人的安全类型,脚本支持关键字和IP
#
# ******************************************************
logFile='/var/log/dingbot.log'
#发送消息
sendMsg(){
local info=$*
token='1e18ffe069052b56f5a0f8fe9b6c058373e7df7ef49dc24bacccccccccccc'
result=`curl -s "https://oapi.dingtalk.com/robot/send?access_token=$token" \
-H 'Content-Type: application/json' \
-d "{'msgtype': 'text',
'text': {
'content': '$info'
}
}"`
[ `echo $result | grep "errmsg.*ok"` ] && echo 'send succees!'
echo "$(date +'%Y-%m-%d %H:%M.%S') state: $result MessagesType: text [ text: $* ]" >> $logFile
}
SendMsgByMD(){
local info=$1 # $info markdown的标题
local infoMsg=$2 # $infoMsg 内容
token='1e18ffe069052b56f5a0f8fe9b6c058373e7df7ef49dc24baa6cccccccccc'
result=`curl -s "https://oapi.dingtalk.com/robot/send?access_token=$token" \
-H 'Content-Type: application/json' \
-d "{
'msgtype': 'markdown',
'markdown': {
'title':'$info',
'text': '$infoMsg'
},
'at': {
'atMobiles': [
'156xxxx8827',
'189xxxx8325'
],
'isAtAll': true
}
}"`
[ `echo $result | grep "errmsg.*ok"` ] && echo 'send succees!'
echo "$(date +'%Y-%m-%d %H:%M.%S') state: $result MessagesType: markdown [ title: $info text: $infoMsg ]" >> $logFile
}
#main()
(sendMsg 'zabbix' )&
(SendMsgByMD 'zabbix' '# send msg')&
exit 55
4、python 版
https://github.com/zhuifengshen/DingtalkChatbot