调用微信API发送微信消息python脚本

前阵子部署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水平有限,大牛勿喷

猜你喜欢

转载自blog.51cto.com/13719882/2129939