素材:
注册 微信公众平台的订阅号开通开发者中心功能,注册公众平台测试账号。获取到appID和appsecret
摘要:
使用Python 2.7基于 微信‘公众平台测试账号’的appID和appsecret实现自动刷新 access_token,和(根据接收列表)发送消息的功能
代码:
"""
Created on Mon Apr 03 21:24:18 2017
@author: Selay
"""
import requests
import json
import threading
allusers = {
'大大':
'eXIuShYFO7tghjb_4YWA'}
def usersto(users = None):
if users ==
None:
return allusers[
'大大']
elif users ==
"All":
return ','.join(set(allusers.values()))
else:
if isinstance(users,list):
usersinfo = []
for user
in users:
usersinfo.append(allusers[user])
return ','.join(set(usersinfo))
else:
print "'users' must be a list!"
return
def json_post_data_generator(content='Hi!你好!',users = None):
msg_content = {}
msg_content[
'content'] = content
post_data = {}
post_data[
'text'] = msg_content
post_data[
'touser'] =
"%s" % usersto(users)
post_data[
'toparty'] =
''
post_data[
'msgtype'] =
'text'
post_data[
'agentid'] =
'9'
post_data[
'safe'] =
'0'
return json.dumps(post_data,
False,
False)
def appInfos():
APPID =
"****************"
APPSECRET =
"******************"
return (APPID,APPSECRET)
def get_token_info():
APPInfo = appInfos()
r = requests.get(
"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" % APPInfo)
js = r.json()
if "errcode" not in js:
access_token = js[
"access_token"]
expires_in = js[
"expires_in"]
else:
print "Can not get the access_token"
print js
quit()
return access_token,expires_in
post_url_freshing = [
'']
def post_url():
access_token,expires_in = get_token_info()
print "token expires_in:%s" % expires_in
timer = threading.Timer((expires_in-
200),post_url)
timer.start()
post_url_freshing[
0] =
'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s'
转载请注明原文地址: https://ju.6miu.com/read-13430.html