python2发微信脚本
阅读原文时间:2023年07月10日阅读:1

#!/usr/bin/env python

-*- coding: utf-8 -*-

import urllib,urllib2,json
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )

class WeChat(object):
__token_id = ''
# init attribute
def __init__(self,url):
self.__url = url.rstrip('/')
self.__corpid = '你的公众号corpid'
self.__secret = '你的密码'

    # Get TokenID  
    def authID(self):  
            params = {'corpid':self.\_\_corpid, 'corpsecret':self.\_\_secret}  
            data = urllib.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 = urllib2.Request(url + data)  
            except KeyError:  
                    raise KeyError  
            result = urllib2.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 = urllib2.Request(url,data)  
            try:  
                    result = urllib2.urlopen(request)  
            except urllib2.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':touser,  
                    'toparty':"2",  
                    'msgtype':"text",  
                    'agentid':"1",  
                    '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])