seaswalker / posts

0 stars 0 forks source link

Bash钉钉工作日排班提醒 #51

Open seaswalker opened 3 years ago

seaswalker commented 3 years ago

bash脚本定时发送钉钉消息:

!/bin/bash

remindMessage='晨会提醒'
atPeopleMessage='请今日负责组织晨会的同学做好记录'

# 判断今天是否是工作日
today=`date +%Y-%m-%d`
response=`curl -s http://timor.tech/api/holiday/info/${today}`
echo "工作日API查询结果: ${response}"

code=`echo ${response} | jq .code`
if [[ "${code}" -ne 0  ]]
then
    echo '查询节假日出错'
    exit 0
fi

type=`echo ${response} | jq .type.type`
if [[ "${type}" -ne 0  ]]
then
    echo "${today} 不是工作日, 类型: ${type}"
    exit 0
fi

mobiles=''
exec < /home/dev/script/mobiles_morning

i=0
while read line
do
    mobiles="${mobiles}${line},"
    array[$i]=${line}
    let i=i+1
done

mobiles=${mobiles%?}

response=`curl -s --request POST --url 'https://oapi.dingtalk.com/robot/send?access_token=xxx' --header 'Content-Type: application/json' --data "{'msgtype': 'text','at': {'isAtAll': false, 'atMobiles': [${mobiles}]},'text': {'content': \"${remindMessage}\"}}"`
echo "请求钉钉结果: $response"

last_mobile=`cat /home/dev/script/mobiles_morning_last`
next=$((${last_mobile}+1))

if [[ "${next}" -gt "${#array[*]}" ]]
then
    next=1
fi

`echo ${next} > /home/dev/script/mobiles_morning_last`

let next=next-1
response=`curl -s --request POST --url 'https://oapi.dingtalk.com/robot/send?access_token=xxx' --header 'Content-Type: application/json' --data "{'msgtype': 'text','at': {'isAtAll': false, 'atMobiles': [${array[$next]}]},'text': {'content': \"${atPeopleMessage}\"}}"`
echo "请求钉钉结果: $response"

这里钉钉群使用的是IP白名单,需要自己先设置下。获取公网IP方法:

curl ip.sb

mobiles是手机号文件,每个一行,注意这里读取文件不能使用这种写法:

cat mobiles.txt | while read line 
do
    #...
done

因为管道后对外部变量进行赋值是不行的。最后crontab -e:

30 10 * * 1,2,3,4,5 /bin/bash /home/dev/scripts/remind.sh

编辑完成后定时任务即可执行。crontab的表达式可能和普通的不同,参考这个网站: 在线crontab表达式执行时间计算