大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全系列IDE稳定放心使用
前阵子部署zabbix监控系统,做了个微信报警,下面分享下微信调API发消息的脚本。要用微信发消息,自己首先要有微信企业号,如果没有申请也容易
准备工作:
1.申请微信企业号
2.在企业号后台创建应用
3.关注微信企业号
脚本用Python3写的,内容如下:
#!/usr/local/python3.5/bin/python3.5
import json
import sys
import os
import time
import urllib.request
tkapi = ‘https://qyapi.weixin.qq.com/cgi-bin/gettoken‘
msgapi = ‘https://qyapi.weixin.qq.com/cgi-bin/message/send‘
corpid = ‘微信企业号corpid‘
corpsecret = ‘微信企业号corpsecret‘
agentid = ‘微信企业号创建的应用ID‘
tokentmp = ‘token.txt‘
url = “%s?corpid=%s&corpsecret=%s” % (tkapi,corpid,corpsecret)
senduser = sys.argv[1]
msg = sys.argv[2]
nowtime = int(time.time())
def gettoken():
try:
res = urllib.request.urlopen(url)
if res.status == 200:
result = res.read()
result = str(result, encoding = “utf-8”)
jresult = json.loads(result)
errcode = jresult[‘errcode‘]
if errcode == 0:
token = jresult[‘access_token‘]
token = token.strip(‘\r‘)
token = token.strip(‘\n‘)
f = open(tokentmp,‘w‘)
log = “%s:%s” % (nowtime,token)
f.write(log)
f.close()
return(‘0‘,token)
else:
return(‘1‘,‘get token fail‘)
else:
return(‘1‘,‘get token return http code error‘)
except Exception as e:
#print(Exception,”:”,e)
return(‘1‘,‘get token http request fail‘)
def sendmsg(token,senduser,msg):
SendMsgUrl = “%s?access_token=%s” % (msgapi,token)
data = {‘touser‘:senduser,‘msgtype‘:‘text‘,‘agentid‘:agentid,‘text‘:{‘content‘:msg}}
data = json.dumps(data)
data = data.replace(‘-n‘,‘\\n‘)
data = bytes(data,‘utf8‘)
try:
request = urllib.request.Request(SendMsgUrl)
res1 = urllib.request.urlopen(request,data)
if res1.status == 200:
result1 = res1.read()
result1 = str(result1, encoding = “utf-8”)
jresult1 = json.loads(result1)
errcode1 = jresult1[‘errcode‘]
if errcode1 == 0:
return(‘0‘,errcode1)
else:
return(‘1‘,‘send msg fail‘)
else:
return(‘1‘,‘send msg return http code error‘)
except:
return(‘1‘,‘send msg http request fail‘)
if os.path.exists(tokentmp):
tk = open(tokentmp,‘r‘).readline()
tk = str(tk)
tkstrs = tk.split(‘:‘)
lasttime = int(tkstrs[0])
if nowtime – lasttime < 3600:
token = tkstrs[1]
stat = ‘0‘
else:
(stat,token) = gettoken()
else:
(stat,token) = gettoken()
if stat == ‘0‘:
(stat1,msgresult) = sendmsg(token,senduser,msg)
if stat1 == ‘0‘:
print(‘send message success‘)
else:
print(‘get token success,send message fail errinfo:‘+msgresult)
else:
print(‘get token fail errinfo:‘+token)
脚本使用方法:
python3.5 wenxin.py 消息接收人 消息内容
python3.5 wenxin.py opsfans ‘微信测试消息‘
消息内容换行符为‘-n‘python水平有限,大牛勿喷
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/186648.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...