This article mainly introduces python3.8 wechat server monitoring alarm message code implementation, in this article through the example code introduction is very detailed, for everyone’s learning or work has a certain reference learning value, need friends can refer to



Python version

>>> import sys
>>> sys.version
'3.8.0 (Tags/V3.8.0: FA919FD, Oct 14 2019, 19:37:50) [MSC V. 1916 64-bit (AMD64)]'Copy the code

code

import urllib.request,urllib.error,json
import sys
 
class WeChat(object):
    __token_id = ' '
    # init attribute
    def __init__(self,url):
        self.__url = url.rstrip('/')
        self.__corpid = '[Logo of the Enterprise]'
        self.__secret = '[Admin group credential key]'
 
    # Get TokenID
    def authID(self):
        params = {'corpid':self.__corpid, 'corpsecret':self.__secret}
        data = urllib.parse.urlencode(params)
 
        content = self.getToken(data)
 
        try:
            self.__token_id = content['access_token']
            # print content['access_token']
        except KeyError:
            raise KeyError
 
    # Establish a connection
    def getToken(self,data,url_prefix='/'):
        url = self.__url + url_prefix + 'gettoken? '
        try:
            response = urllib.request.Request(url + data)
        except KeyError:
            raise KeyError
        result = urllib.request.urlopen(response)
        content = json.loads(result.read())
        return content
 
    # Get sendmessage url
    def postData(self,data,url_prefix='/'):
        url = self.__url + url_prefix + 'message/send? access_token=%s' % self.__token_id
        request = urllib.request.Request(url,data.encode())
        print(url)
        print(data)
        try:
            result = urllib.request.urlopen(request)
        except urllib.error.HTTPError as e:
            if hasattr(e,'reason') :print('reason',e.reason)
            elif hasattr(e,'code') :print('code',e.code)
            return 0
        else:
            content = json.loads(result.read())
            result.close()
        return content
 
    # send message
    def sendMessage(self,touser,message):
 
        self.authID()
 
        data = json.dumps({
            'touser':"[User account in enterprise]".'toparty':"[Department ID in enterprise]".'msgtype':"[Message type]".'agentid':"[Application ID in enterprise]".'text': {'content':message
            },
            'safe':"0"
        },ensure_ascii=False)
 
        response = self.postData(data)
        print(response)
 
 
if __name__ == '__main__':
    a = WeChat('https://qyapi.weixin.qq.com/cgi-bin')
    a.sendMessage(sys.argv[1],sys.argv[3])Copy the code

The effect .