1. 程式人生 > >調用微信API發送微信消息python腳本

調用微信API發送微信消息python腳本

imp agen acc sgu byte spl zabbix監控 python3 get

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

調用微信API發送微信消息python腳本