此脚本用到了2个公共API,1. 微信测试公众号官方接口 2. 爱词霸每日推送接口
微信开发已经活跃了很长时间了,在微信开发中有一个神奇的接口它叫模板消息接口,它可以根据用户的openid从服务端给用户推送自定义的模板消息,正因如此,我们可以利用这个特征在服务器端随时向用户推送消息(前提是该用户关注了该公众号)。
总结
1.模板消息的格式可以自定义
2.模板消息的内容可以自定义
3.模板消息发送的时间可以自定义
爱词霸(每日一句)官方文档:http://open.iciba.com/?c=wiki
调用地址:http://open.iciba.com/dsapi/
扫描登录微信公众平台测试号
申请测试号的地址 https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
具体如何使用,请自行查找文档。
几次脚本分2个py文件和一个考研帮文章资讯标题缓存json文件。
send_to_jiao.py
import json
import requests
import re
import time
import datetime
def time_long(time1, time2, type="day"):
"""
计算时间差
:param time1: 较小的时间(datetime类型)
:param time2: 较大的时间(datetime类型)
:param type: 返回结果的时间类型(暂时就是返回相差天数)
:return: 相差的天数
"""
day1 = time.strptime(str(time1), '%Y-%m-%d %H:%M:%S')
day2 = time.strptime(str(time2), '%Y-%m-%d %H:%M:%S')
if type == 'day':
day_num = (int(time.mktime(day2)) - int(time.mktime(day1))) / (
24 * 60 * 60)
return abs(int(day_num))
class SoulSootherToJiao(object):
# 初始化
def __init__(self, config):
self.appid = config['appid']
self.appsecret = config['appsecret']
self.template_id = config['template_id']
self.access_token = ''
# 获取access_token
def get_access_token(self, appid, appsecret):
url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (
str(appid), str(appsecret))
r = requests.get(url)
data = json.loads(r.text)
access_token = data['access_token']
self.access_token = access_token
return self.access_token
# 获取用户列表
def get_user_list(self):
if self.access_token == '':
self.get_access_token(self.appid, self.appsecret)
access_token = self.access_token
url = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s&next_openid=' % str(access_token)
r = requests.get(url)
return json.loads(r.text)
@staticmethod
def get_detail_url():
response = requests.get(url='http://www.kaoyan.com/beikao/jingyan/')
if response.status_code == 200:
response = response.content.decode("utf-8")
else:
response = ''
try:
res_all = re.findall(
'(.*?)(.*?) ',
response)
except Exception as e:
res_all = []
with open('article_name_cache.json', 'r', encoding='utf-8') as f:
article_cache_dict = json.load(f)
send_url = 'https://blog.csdn.net/Tong_T'
for item in res_all:
if item[2] not in article_cache_dict['nameLists']:
send_url = item[1]
article_cache_dict['nameLists'].append(item[2])
break
with open('article_name_cache.json', 'w', encoding='utf-8') as f:
json.dump(article_cache_dict, f, ensure_ascii=False)
return send_url
# 发送消息
def send_msg(self, openid, template_id, soul_soother_everyday):
today = datetime.datetime.now()
msg = {
'touser': openid,
'template_id': template_id,
'url': self.get_detail_url(),
'data': {
'content': {
'value': soul_soother_everyday['note'],
},
'note': {
'value': soul_soother_everyday['translation'].replace('小编的话:', '同哥跟你说:'),
'color': '#0000CD'
},
'signature': {
'value': '考研倒计时提醒:剩下 {0} 天,佛爷亲笔'.format(time_long(time1=datetime.datetime(today.year, today.month, today.day), time2=datetime.datetime(2019, 12, 21))),
}
}
}
json_data = json.dumps(msg)
if self.access_token == '':
self.get_access_token(self.appid, self.appsecret)
access_token = self.access_token
url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s' % str(access_token)
r = requests.post(url, json_data)
return json.loads(r.text)
def get_soul_soother_everyday(self):
url = 'http://open.iciba.com/dsapi/'
r = requests.get(url)
return json.loads(r.text)
# 为设置的用户列表发送消息
def send_everyday_words(self, openids):
everyday_words = self.get_soul_soother_everyday()
for openid in openids:
result = self.send_msg(openid, self.template_id, everyday_words)
if result['errcode'] == 0:
print(' [INFO] send to %s is success' % openid)
else:
print(' [ERROR] send to %s is error' % openid)
# 执行
def run(self, openids=[]):
# 根据openids对用户进行群发
self.send_everyday_words(openids)
主入口文件main.py
import time
from to_jiao_article import SoulSootherToJiao
from apscheduler.schedulers.blocking import BlockingScheduler
def cron_send_job():
# 微信配置
wechat_config = {
'appid': 'XXXXXXXX', # (No.1)此处填写你的appid
'appsecret': 'XXXXXXXX', # (No.2)此处填写你的appsecret
'template_id': 'XXXXXXXX' # (No.3)此处填写你的模板消息ID
}
# 用户列表
openids = [
'XXXXXXXX' # (No.4)此处填写你的微信号(微信公众平台上你的微信号)
]
# 执行
ss_to_jiao = SoulSootherToJiao(config=wechat_config)
# run()方法可以传入openids列表
ss_to_jiao.run(openids=openids)
print('job:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), 'Done.')
return True
if __name__ == '__main__':
scheduler = BlockingScheduler()
# 采用非阻塞的方式
# 采用date的方式,在特定时间里执行一次
scheduler.add_job(cron_send_job, 'cron', day_of_week='0-6', hour=16, minute=59)
# 这是一个独立的线程
scheduler.start()
效果如下: