python3 实现公众号自动发消息
前言
最近给女朋友的问候公众号制作爆火,网上的教程有很多但都很零散,可能按着操作结果不知道消息发送去那了,因此本文章就详细地从头教到尾
微信公众号测试号申请
申请测试公众号
微信公众平台
点击登录,微信扫描二维码登录进去
测试号信息
后续脚本中需要测试号信息
测试号二维码
想要把信息发给谁,就让谁进行扫描二维码,扫描后刷新页面,右边用户列表就会出现微信号
后续脚本需要微信号
模板消息接口
新增流程
模板消息的配置(以第二个为例)
- 点击 新增测试模板
-
填写标题
陌生人,早上好! -
填写模板内容
{{date.DATA}}
{{leady.DATA}}
{{love_day.DATA}}
{{ZH.DATA}}
{{EN.DATA}}
模板详解:
- {{date.DATA}} 当天年月日
- {{leady.DATA}} 当天农历年月日
- {{love_day.DATA}} 恋爱开始的时间
- {{ZH.DATA}} 生日
- {{EN.DATA}} 每日一句
4.效果
python 脚本配置
access_token.py
测试号信息(两处需要修改)
- APPID 填写自己的appID
- APPSEARCH 填写自己的appsecret
[root@wh wq]# cat access_token.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@Time :2022/10/5 20:00
@Auth :王谦
@File :access_token.py
@Description:获取access_token
"""
import requests
class AccessToken(object):
# 微信公众测试号账号(填写自己的)
APPID = "填写自己申请的测试公众号ID"
# 微信公众测试号密钥(填写自己的)
APPSEARCH = "填写自己申请的测试公众号appsecret"
def __init__(self, app_id=APPID, app_secret=APPSEARCH) -> None:
self.app_id = app_id
self.app_secret = app_secret
def get_access_token(self) -> str:
"""
获取access_token凭证
:return: access_token
"""
url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={self.app_id}&secret={self.app_secret}"
resp = requests.get(url)
result = resp.json()
if 'access_token' in result:
return result["access_token"]
else:
print(result)
send_message.py
用户列表以及模板消息接口(两处需要修改),这里也是上色的(设置的随机,每天都不一样)
- TROUSER 发单人的启用单人的,多人的使用多人的,填写用户列表的微信号
- TEMPLATE_ID 模板消息接口–>模板ID(用于接口调用)
[root@wh wq]# cat send_message.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@Time :2022/10/5 20:00
@Auth :王谦
@File :send_message.py
@Description:发送微信公众号消息
"""
import json
import requests
import random
from access_token import AccessToken
class SendMessage(object):
# 消息接收者
# 模板 TROUSER = 'oDxxxxxxxxxxxxxxxxxxII',
# 单人
# TROUSER = '填写测试号二维码里边的微信号',
# 多人
TROUSER = '','',''
# 消息模板id
TEMPLATE_ID = 'sPEYDFXQmaFb_ta-tCkCgTWj2eQfY6xHdrSGtYFEUx4'
def __init__(self, tosser=TROUSER, template_id=TEMPLATE_ID) -> None:
"""
构造函数
:param touser: 消息接收者
:param template_id: 消息模板id
"""
self.access_token = AccessToken().get_access_token()
self.trouser = tosser
self.template_id = template_id
def random_color(self):
colors1 = '0123456789ABCDEF'
num = "#"
for i in range(6):
num += random.choice(colors1)
return num
def get_send_data(self, json_data,Recipient) -> object:
"""
获取发送消息data
:param json_data: json数据对应模板
:return: 发送的消息体
"""
content = {}
for k,v in json_data.items():
concrete_content = { k : {"value": v,"color": self.random_color()} }
content.update(concrete_content)
return {
"touser": Recipient,
"template_id": self.template_id,
"topcolor": "#FF0000",
# json数据对应模板
"data": content
}
def send_message(self, json_data) -> None:
"""
发送消息
:param json_data: json数据
:return:
"""
# 模板消息请求地址
url = f"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={self.access_token}"
for Recipient in self.trouser:
data = json.dumps(self.get_send_data(json_data,Recipient))
requests.post(url, data=data)
[root@wh wq]#
information_message.py
对应模板信息
这个是跟模板进行对应的
如果要新增,新增def,以及最后的ALL里边进行添加
[root@wh wq]# cat information_message.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@Time :2022/10/5 20:00
@Auth :王谦
@File :main.py
@Description:微信公众号内容
"""
import requests
import datetime
import time
from zhdate import ZhDate
from dateutil.relativedelta import relativedelta
class Information:
# 当前年月日
def Datum():
today = datetime.date.today()
return today
# 当前星期几
def Boche():
local_time = time.localtime(time.time()) # 获取当前时间的时间元组
# time.struct_time(tm_year=2022, tm_mon=4, tm_mday=9, tm_hour=13, tm_min=48, tm_sec=23, tm_wday=5, tm_yday=99, tm_isdst=0)
week_index = local_time.tm_wday # 获取时间元组内的tm_wday值
# # 配置名称列表
week_list = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
return week_list[week_index]
# 当前农历日期
def Moneylender():
from datetime import datetime
local_time = time.localtime(time.time()) # 获取当前时间的时间元组
dt_date4 = datetime(local_time.tm_year,
local_time.tm_mon, local_time.tm_mday)
date4 = ZhDate.from_datetime(dt_date4)
return date4.chinese()
# 恋爱至现在时长
def LOVE(love_year):
love_year = love_year # 开始恋爱日期
love_day1 = tuple(time.strptime(
love_year, "%Y-%m-%d")) # 将格式化时间 转化为 结构化时间
love_hour = time.strftime("%Y-%m-%d") # 获取当前的格式化时间
d1 = datetime.date(love_day1[0], love_day1[1], love_day1[2])
d2 = datetime.date(int(love_hour.split(
"-")[0]), int(love_hour.split("-")[1]), int(love_hour.split("-")[2]))
d3 = (d2 - d1).days
return f'今天是我们相恋的第{d3}天'
# 距离生日日期
def Geburtstag(month,day,name):
from datetime import datetime
# 公立当前年月日时间获取
today = datetime.now()
oneDay = ZhDate(int(str(ZhDate.today())[2:6]), month, day).to_datetime()
difference = oneDay.toordinal()-today.toordinal()
if(difference < 0):
e = today.strftime('%Y')
oneDay = ZhDate(int(e), month, day).to_datetime()
difference = oneDay.toordinal()-today.toordinal()
return f'距离{name}明年生日还有{difference}天'
elif(difference == 0):
return f'{name}生日快乐'
else:
return f'距离{name}今年生日还有{difference}天'
# 每日一句
def Everyday():
url = 'http://open.iciba.com/dsapi/'
url1 = requests.get(url)
Eng = eval(url1.text)['content']
Ch = eval(url1.text)['note']
combination = Eng + '\n' + Ch
return combination
def whole():
ALL = {
'date': str(Information.Datum()) + ' ' + Information.Boche(),
'leady':Information.Moneylender(),
'love_day':str(Information.LOVE(love_year='2021-08-19')),
'ZH':Information.Geburtstag(name='公举',month=8, day=15) + '\n' + Information.Geburtstag(name='王子',month=12, day=15),
'EN': str(Information.Everyday())
}
return ALL
main.py
最后执行的文件
[root@wh wq]# cat main.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@Time :2022/10/5 20:00
@Auth :王谦
@File :main.py
@Description:微信公众号发送消息主文件
"""
import json
from send_message import SendMessage
from information_message import Information
class Main(object):
def main(self):
# 实例SendMessage
sm = SendMessage()
# 获取接口返回数据
json_data = Information.whole()
# 发送消息
sm.send_message(json_data=json_data)
if __name__ == '__main__':
main = Main()
main.main()
验证
[root@wh test]# ls
access_token.py information_message.py main.py send_message.py
[root@wh test]# python3 main.py
[root@wh test]#
微信订阅号上边收到了信息
定时发送
linux定时任务
[root@wh test]# crontab -l
# 微信公众号定时(每天8点)
0 8 * * * /bin/python3 /data/script/test/main.py
结尾
没有服务器,也想要的,可以私信,目前是免费制定。(最终解释权归博主所有)