微信企业号API SDK Python3版

#!/usr/bin/python3
# -*- coding: utf-8 -*-
#微信企业号API Python3版

import time,datetime
import hashlib,hmac
import urllib.request,urllib.parse
import json,sys


class WXQY:

    # corpid = "wx82e2c31215d9a123"
    apiurl = "https://qyapi.weixin.qq.com/cgi-bin/"

    def __init__(self, corpid, secret, agentid):
        self.corpid = corpid
        self.secret = secret
        self.agentid = agentid
        url = self.apiurl + 'gettoken?corpid=%s&corpsecret=%s'%(self.corpid, self.secret)
        # print(url)
        ret = self.http_request(url)
        if ret['errcode'] != 0:
            print(ret["errmsg"])
            exit()
        else:
            self.access_token = ret["access_token"]

    # 发送消息
    def send_message(self, type, data, touser = '@all', safe = '0'):
        if not data:    #数据为空
            return
            
        msg = {
    
    
            'touser' : touser,
            'agentid' : self.agentid,
            'msgtype' : type,
            'safe' : safe
        }
        
        if type == "text":
            msg[type] = {
    
    'content' : data}
        elif type == "textcard":
            msg[type] = data
        elif type == "news":
            msg[type] = {
    
    'articles' : data}
        else:
            msg["msgtype"] = "text"
            msg["text"] = {
    
    'content' : "不支持的消息类型 " + type}

        url = self.apiurl + 'message/send?access_token=%s'%(self.access_token)
        return self.http_request(url, msg)

    # HTTP请求
    def http_request(self, url, params = None):
        # print(url)
        # print(params)
        req = urllib.request.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36')
        if params: # POST
            data = bytes(json.dumps(params), 'utf-8')
            r = urllib.request.urlopen(req, data)
        else:      # GET
            r = urllib.request.urlopen(req)
        # print(r.read())
        result = json.loads(r.read().decode('utf-8'))
        # print(result)
        return result


if __name__ == '__main__':
    weixin = WXQY("wx82e2c31215d9", "", "11")
    # weixin.send_message("你好", "中国");
    weixin.send_message("text", "中国");
    
    card = {
    
    "title":"领奖通知", "description":"<div class=\"gray\">2016年9月26日</div> <div class=\"normal\">恭喜你抽中iPhone 7一台,领奖码:xxxx</div><div class=\"highlight\">请于2016年10月10日前联系行政同事领取</div>", "url" :"https://www.json.cn/", "btntxt" :"更多"}
    weixin.send_message("textcard", card);
    
    
    data = [] #列表
    data.append({
    
    "title":datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), "description":"", "picurl":"", "url" :""})
    data.append({
    
    "title":"多图文2标题", "description":"多图文2描述", "picurl":"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "url" :""})
    data.append({
    
    "title":"多图文3标题", "description":"多图文3描述", "picurl":"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "url" :""})
    # print(data)
    result = weixin.send_message("news", data);
    
    print(result)
    pass

猜你喜欢

转载自blog.csdn.net/bitquant/article/details/105796036