#!/usr/bin/python
# -*- coding: UTF-8 -*-
#####################################
## created by basededato ##
## 2018-01-02 ##
## 微信
#####################################
import urllib.request
import json
class WxSend(object):
def __init__(self, Token_Url, Msg_Url, Send_Values, Content):
self.Token_Url = Token_Url
self.Msg_Url = Msg_Url
self.Send_Values = Send_Values
self.Content = Content
def getToken(self):
page = urllib.request.urlopen(self.Token_Url)
# 获取网页返回信息
page_data = page.read().decode('utf-8')
# 将json数据格式处理为str
data_json = json.loads(page_data)
# 获取键对应的值
token = data_json['access_token']
# 将token写入文件
fw = open('wx_token', 'w')
fw.write(token)
fw.close
return token
def sendMsg(self):
# dict追加text键值
self.Send_Values['text'] = {'content':self.Content}
# dict转为json格式
json_data = json.dumps(self.Send_Values)
# 发信息请求url
send_url = self.Msg_Url + open('wx_token').read()
request_post = urllib.request.urlopen(send_url, json_data.encode(encoding='UTF-8'))
page_data = json.loads(request_post.read().decode('utf-8'))['errcode']
# 验证返回数据,如果token过期,重新获取
if page_data != 0:
send_url = self.Msg_Url + self.getToken()
request_post = urllib.request.urlopen(send_url, json_data.encode(encoding='UTF-8'))