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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了调用微信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(‘
‘)
                token = token.strip(‘
‘)
                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脚本的主要内容,如果未能解决你的问题,请参考以下文章

shell或python调用企业微信发送消息(实现报警功能)

python怎样给微信发送

python实现通过企业微信发送消息

脱离微信客户端发送微信消息

python调用企业微信接口发送群聊消息代码参考

itchat发送微信文本消息文件等python