树莓派通过API向企业微信推送图文

参考文献:
【实现】树莓派开机自动向微信发消息报告ip地址(无第三方代理)

  • 在 企业微信 官网 注册,不一定要是已注册的企业,个人筹备中的公司也能注册,只是会对外名字后显示 未验证 字样,个人使用的话不必在意。

  • 注册好之后进入企业微信网页版,在“应用管理>应用>自建”一栏中点击“创建应用”,根据提示创建一个应用 H-GetMsg即可。

    记住几个关键信息
    以下两个在刚才创建的应用列表里找到:
    1. 应用ID(AgentId)
    2. 秘钥(corpSecret)
    在“我的企业>企业信息”最下方找到“企业ID”
    3.企业ID(corpID)

  • 在树莓派上,创建sh文件:
    ----发送文字
    /home/pi/myboot/sendmsg2wx.sh

    #!/bin/bash
    #usage: sh sendmsg2wx.sh "msgstr"
    AgentId=
    corpSecret=
    corpId=
    temp=`curl https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$corpId\&corpsecret=$corpSecret`
    if [ -n `echo $temp|awk -F ':"' '{print $3}'` ];then
        access_token=`echo $temp|awk -F ':"' '{print $3}'|awk -F '","' '{print $1}'`
    fi
    msgstr=$1
    PostURL="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$access_token"
    curl -H "Content-type: application/json" -X POST -d '{"touser":"@all","msgtype":"text","agentid":"'"$AgentId"'","text":{
          
          "content":"'"$msgstr"'"},"safe":0}' $PostURL
    

    使用方式: sh sendmsg2wx.sh "msgstr"
    主要逻辑:

    1. 调用 获取凭证API,使用 corpId 和 corpSecret 获取应用调用api的凭证 access_token。
    2. 调用 发送应用消息API,将msgstr放在请求结构体中 发送到 终端,msgstr包含空格等字符的话需要用双引号括起来。
      (更多API可参见 企业微信API官网文档)
    • 在企业微信 手机端 就能接收到H-GetMsg的消息了。

☆更新:----发送图片/文件
/home/pi/myboot/sendpic2wx.sh

	#!/bin/bash
	#usage: sh sendpic2wx.sh  picfile
	AgentId=
	corpSecret=
	corpId=
	temp=`curl https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$corpId\&corpsecret=$corpSecret`
	if [ -n `echo $temp|awk -F ':"' '{print $3}'` ];then
	    access_token=`echo $temp|awk -F ':"' '{print $3}'|awk -F '","' '{print $1}'`
	fi
	
	filename=$1
	
	PostUploadURL="https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=$access_token&type=file"
	resupload=`curl --request POST $PostUploadURL \
	--header 'Content-Type: multipart/form-data' \
	--form 'name="mypictmp"' \
	--form 'filename=@'$1`
	if [ -n `echo $resupload|awk -F ':"' '{print $4}'` ];then
	        media_id=`echo $resupload|awk -F ':"' '{print $4}'|awk -F '","' '{print $1}'`
	fi
	
	PostURL="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$access_token"
	curl -H "Content-type: application/json" -X POST -d '{"touser":"@all","msgtype":"image","agentid":"'"$AgentId"'","image":{
    
    "media_id":"'"$media_id"'"},"safe":0}' $PostURL

猜你喜欢

转载自blog.csdn.net/ttyt1217/article/details/119879757