dongfg' blog

无数渺小的思考填满了人的一生

0%

个人消息推送方案

简单说明

消息推送需求,服务器监控、系统发布、爬虫执行等等这些情况都可能用到消息推送,消息推送要尽量保证实时及成功,之前用过这些方案:

  • 邮件,使用微信绑定QQ或者企业邮箱接收消息
  • 自己写APP集成极光等推送平台
  • Server酱

自己可以APP可以灵活控制消息格式,但是APP包活是主要问题;Server酱通过微信发送可以保证到达及实时性,简单消息个人一直使用Server酱发送,缺点是消息格式单一

企业微信方案

这个方案无需安装企业微信APP,使用普通微信就可以接收消息,而且消息格式支持文本、图片、音频、视频、Markdown等。

注册企业微信

注册地址: https://work.weixin.qq.com/wework_admin/register_wx,注册后无需企业认证即可使用推送(当然只能推送给自己)

关注微工作台

路径:我的企业 -> 微工作台 -> 邀请关注

创建应用

发送消息需要使用发送应用消息接口,先创建应用:应用与小程序 -> 创建应用,需要应用的 AgentId 用于后续消息推送,网页控制台可以手动发送消息进行测试。

发送消息

消息发送接口:发送应用消息,发送消息前需要获取 ACCESS_TOKEN

shell 发送简单消息

agentid 替换成之前创建应用的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/bin/bash

main() {
check $@
TOKEN=`curl -s "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$CORP_ID&corpsecret=$CORP_SECRET" | jq -r ".access_token"`
curl -X POST -d '{
"touser": "@all",
"msgtype": "text",
"agentid": 1000002,
"text": {
"content": "'$@'"
},
"safe": 0
}' "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$TOKEN"
}

check() {
if [[ -z "${CORP_ID}" ]]; then
echo "Error: missing environment variable CORP_ID"
exit 1
fi
if [[ -z "${CORP_SECRET}" ]]; then
echo "Error: missing environment variable CORP_SECRET"
exit 1
fi
command -v jq >/dev/null 2>&1 || {
echo "Error: jq is not installed"
exit 1
}
if [ "$#" -eq 0 ]; then
echo "Illegal number of parameters.\nUsage: ./notify.sh <message>"
exit 1
fi
}

main $@

发送复杂消息

接口支持发送文本、图片、语音、视频、文件、文本卡片等,我用 go 写的工具简单封装了这个接口,可以方便的使用,具体查看 Github。

Github: dongfg/notify