侧边栏壁纸
博主头像
人称西安金城武博主等级

一个假理科生&伪程序员

  • 累计撰写 95 篇文章
  • 累计创建 109 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

微信每日定时发送问候dailyGreeting

人称西安金城武
2022-11-03 / 0 评论 / 2 点赞 / 64 阅读 / 2,358 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-11-08,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

说明

每天给女友发送早安晚安比较繁琐,而且也容易忘记,利用微信公众号可以定时发送模板消息,设定内容,十分方便,特此记录。

步骤

1.首先,个人用户需要使用微信公众测试号才可以发送模板消息,认证过的企业号则不用,微信测试号,注册之后替换代码内的微信公众号的appId和appSecret

2.同时,天气部分使用高德API,也可以自行替换其他API,高德天气API

3.测试号需要新增模板消息,本文使用的模板消息如下:

{{name.DATA}} 今天是{{date.DATA}},星期{{week.DATA}},每天都是超级爱你的一天~

{{name.DATA}} 现在在{{province.DATA}}{{city.DATA}} 今天天气{{weather.DATA}},温度{{temperature.DATA}}摄氏度,空气湿度{{humidity.DATA}}%,{{winddirection.DATA}}风{{windpower.DATA}}级,今天也一定要好好爱护自己哦~ 

今天是我们在一起的第{{togetherDays.DATA}}天,这些日子里都有超级爱你哦~ 

距离{{name.DATA}}的生日还有{{birthDays.DATA}}天,😊

{{sentence.DATA}}

效果如下:

早安

❤️{{name.DATA}}❤️ 

我们已经贴贴{{togetherDays.DATA}}天啦!

{{name.DATA}} 你今天已经很努力了,快睡吧~ 

{{sentenceEn.DATA}} 
{{sentenceZh.DATA}}

效果如下:

晚安

{{name.DATA}} 今天你的幸运颜色是{{luckyColor.DATA}},幸运数字是{{luckyNumber.DATA}},速配星座是{{luckyConstellation.DATA}} 

短评:{{shortComment.DATA}} 

综合运势:{{fortuneText.DATA}} 
爱情运势:{{fortuneLove.DATA}} 
事业运势:{{fortuneWork.DATA}}

效果如下:

今日运势

今日运势如果写了上面的幸运色数字之类的,下面的运势就只能选择性的写三个,再多就显示不下了,但源码已经配置了全部的内容,使用时修改对应字段即可

模板消息配置好之后请替换代码里面的模板消息ID,只能写一个

4.想给谁发送,就需要对方关注测试号,关注之后在用户列表里可以看到微信号,将微信号复制到代码里的用户数组内,可以配置多个

5.先使用pip install requests安装模块,然后使用python morning.py查看运行结果

定时发送

Linux可以使用crontab定时任务进行定时发送

宝塔面板请添加定时任务,shell脚本,内容为

cd /www/wwwroot/python/
python3 morning.py

Linux上默认是没有Python3的,安装方法参考:CentOS安装Python3

GitHub也可以使用Actions进行自动化配置,配置大致如上,图形界面需要手动添加appid等上述内容

问题

目前发现,在模板消息的开头,不要添加表情,否则会产生颜色错位的BUG,如下图:

颜色错位

源码

地址:dailyGreeting

import requests
import json
from datetime import datetime
import random

def httpGet(url, params):
    r = requests.get(url, params)
    return json.loads(r.content)

def httpPost(url, params):
    r = requests.post(url, params)
    return json.loads(r.content)

# 获取微信token
def getAccessToken(appId, appSecret):
    params = {
        'grant_type': 'client_credential',
        'appid': appId,
        'secret': appSecret
    }
    url = 'https://api.weixin.qq.com/cgi-bin/token'
    return httpGet(url, params)

# 获取天气
def getWeather(abCode, key):
    url = 'https://restapi.amap.com/v3/weather/weatherInfo'
    params = {
        'key': key,
        'city': abCode,
        'extensions': 'base',
        'output': 'JSON',
    }
    return httpGet(url, params)

# 获取一句情话
def getMorningGreeting():
    url = 'https://api.vvhan.com/api/love'
    love = httpGet(url, {'type': 'json'})
    return love['ishan']

# 获取生日倒计时
def getBirthDays(birthDay):
    birthDay = datetime.strptime(birthDay, '%Y-%m-%d')
    interval = birthDay - datetime.now()
    return interval.days

# 获取在一起天数
def getTogetherDays(togetherDay):
    togetherDay = datetime.strptime(togetherDay, '%Y-%m-%d')
    interval = datetime.now() - togetherDay
    return interval.days

# 发送模版消息
def sendTemplateMessage(content, accessToken):
    url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' + accessToken
    return httpPost(url, content)

# 获取星期
def getWeek():
    w = datetime.now().strftime('%w')
    data = {
        0: '天',
        1: '一',
        2: '二',
        3: '三',
        4: '四',
        5: '五',
        6: '六'
    }
    return data[int(w)]

# 获取爱称
def getNickName():
    nameHub = ['安琪','安琪宝贝','Angel','安安','琪琪','琪琪子','亲爱的安琪','心爱的安琪']
    currentName = random.choice(nameHub)
    return currentName

if __name__ == '__main__':
    # 微信公众号的appId和appSecret
    appId = 'xxx'
    appSecret = 'xxx'
    # 要发送人的openId列表
    openIdList = ['xxx','xxx','xxx','xxx']
    # 模版Id
    templateId = 'xxx'
    # 高德天气API key
    gaoDeKey = 'xxx'
    # 所在地点abCode(高德后台可以获取 https://a.amap.com/lbs/static/amap_3dmap_lite/AMap_adcode_citycode.zip)
    abCode = '610113'
    # 最近一次生日的日期
    birthDay = '2022-11-01'
    # 在一起的时间
    togetherDay = '2022-11-01'

    accessTokenInfo = getAccessToken(appId, appSecret)
    accessToken = accessTokenInfo['access_token']
    weatherInfo = getWeather(abCode, gaoDeKey)
    weather = weatherInfo['lives'][0]
    sentence = getMorningGreeting()
    birthDays = getBirthDays(birthDay)
    togetherDays = getTogetherDays(togetherDay)
    week = getWeek()
    name = getNickName()

    for i in range(len(openIdList)):
        data = {
            'touser': openIdList[i],
            'template_id': templateId,
            'topcolor' : '#FF0000',
            'data': {
                'date': {
                    'value': datetime.now().strftime('%Y-%m-%d'),
                },
                'province': {
                    'value': weather['province']
                },
                'city': {
                    'value': weather['city']
                },
                'temperature': {
                    'value': weather['temperature'],
                    'color': '#4d79ff'
                },
                'humidity': {
                    'value': weather['humidity'],
                    'color': '#4d79ff'
                },
                'winddirection': {
                    'value': weather['winddirection'],
                },
                'windpower': {
                    'value': weather['windpower']
                },
                'togetherDays': {
                    'value': togetherDays,
                    'color': '#ff4dff'
                },
                'birthDays': {
                    'value': birthDays,
                    'color': '#ff4dff'
                },
                'week': {
                    'value': week,
                },
                'sentence': {
                    'value': sentence,
                    'color': '#ed556a'
                },
                'name':{
                    'value': name,
                    'color': '#ee3f4d'
                }
            }
        }
        params = json.dumps(data)

        print(sendTemplateMessage(params, accessToken))

import requests
import json
from datetime import datetime
import random

def httpGet(url, params):
    r = requests.get(url, params)
    return json.loads(r.content)

def httpPost(url, params):
    r = requests.post(url, params)
    return json.loads(r.content)

# 获取微信token
def getAccessToken(appId, appSecret):
    params = {
        'grant_type': 'client_credential',
        'appid': appId,
        'secret': appSecret
    }
    url = 'https://api.weixin.qq.com/cgi-bin/token'
    return httpGet(url, params)

# 获取每日励志英语(英文)
def getDailyEnglish():
    url = 'https://api.vvhan.com/api/en'
    talk = httpGet(url, {'type': 'json'})
    return talk['data']['en']

# 获取每日励志英语(中文)
def getDailyChinese():
    url = 'https://api.vvhan.com/api/en'
    talk = httpGet(url, {'type': 'json'})
    return talk['data']['zh']

# 获取在一起天数
def getTogetherDays(togetherDay):
    togetherDay = datetime.strptime(togetherDay, '%Y-%m-%d')
    interval = datetime.now() - togetherDay
    return interval.days

# 发送模版消息
def sendTemplateMessage(content, accessToken):
    url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' + accessToken
    return httpPost(url, content)

# 获取爱称
def getNickName():
    nameHub = ['安琪','安琪宝贝','Angel','安安','琪琪','琪琪子','亲爱的安琪','心爱的安琪']
    currentName = random.choice(nameHub)
    return currentName

if __name__ == '__main__':
    # 微信公众号的appId和appSecret
    appId = 'xxx'
    appSecret = 'xxx'
    # 要发送人的openId列表
    openIdList = ['xxx','xxx','xxx','xxx']
    # 模版Id
    templateId = 'xxx'
    # 在一起的时间
    togetherDay = '2022-11-01'

    accessTokenInfo = getAccessToken(appId, appSecret)
    accessToken = accessTokenInfo['access_token']
    sentenceZh = getDailyChinese()
    sentenceEn = getDailyEnglish()
    togetherDays = getTogetherDays(togetherDay)
    name = getNickName()

    for i in range(len(openIdList)):
        data = {
            'touser': openIdList[i],
            'template_id': templateId,
            'topcolor' : '#FF0000',
            'data': {
                'togetherDays': {
                    'value': togetherDays,
                    'color': '#ff4dff'
                },
                'sentenceEn': {
                    'value': sentenceEn,
                    'color': '#2e317c'
                },
                'sentenceZh': {
                    'value': sentenceZh,
                    'color': '#346c9c'
                },
                'name':{
                    'value': name,
                    'color': '#ee3f4d'
                }
            }
        }
        params = json.dumps(data)

        print(sendTemplateMessage(params, accessToken))

import requests
import json
import random

def httpGet(url, params):
    r = requests.get(url, params)
    return json.loads(r.content)

def httpPost(url, params):
    r = requests.post(url, params)
    return json.loads(r.content)

# 获取微信token
def getAccessToken(appId, appSecret):
    params = {
        'grant_type': 'client_credential',
        'appid': appId,
        'secret': appSecret
    }
    url = 'https://api.weixin.qq.com/cgi-bin/token'
    return httpGet(url, params)

# 获取运势信息
def getFortuneData():
    url = 'https://api.vvhan.com/api/horoscope'
    data = httpGet(url, {'type': 'sagittarius','time':'today'})
    return data

# 发送模版消息
def sendTemplateMessage(content, accessToken):
    url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' + accessToken
    return httpPost(url, content)

# 获取爱称
def getNickName():
    nameHub = ['安琪','安琪宝贝','Angel','安安','琪琪','琪琪子','亲爱的安琪','心爱的安琪']
    currentName = random.choice(nameHub)
    return currentName

if __name__ == '__main__':
    # 微信公众号的appId和appSecret
    appId = 'xxx'
    appSecret = 'xxx'
    # 要发送人的openId列表
    openIdList = ['xxx','xxx']
    # 模版Id
    templateId = 'xxx'

    accessTokenInfo = getAccessToken(appId, appSecret)
    accessToken = accessTokenInfo['access_token']
    name = getNickName()
    fortuneData = getFortuneData()
    fortuneTitle = fortuneData['data']['title']
    luckyColor = fortuneData['data']['luckycolor']
    luckyNumber = fortuneData['data']['luckynumber']
    luckyConstellation = fortuneData['data']['luckyconstellation']
    shortComment = fortuneData['data']['shortcomment']
    fortuneText = fortuneData['data']['fortunetext']['all']
    fortuneLove = fortuneData['data']['fortunetext']['love']
    fortuneWork = fortuneData['data']['fortunetext']['work']
    fortuneMoney = fortuneData['data']['fortunetext']['money']
    fortuneHealth = fortuneData['data']['fortunetext']['health']


    for i in range(len(openIdList)):
        data = {
            'touser': openIdList[i],
            'template_id': templateId,
            'topcolor' : '#FF0000',
            'data': {
                'name':{
                    'value': name,
                    'color': '#ee3f4d'
                },
                'fortuneTitle':{
                    'value': fortuneTitle,
                    'color': '#282c34'
                },
                'luckyColor':{
                    'value': luckyColor,
                    'color': '#065279'
                },
                'luckyNumber':{
                    'value': luckyNumber,
                    'color': '#4b5cc4'
                },
                'luckyConstellation':{
                    'value': luckyConstellation,
                    'color': '#e06c75'
                },
                'shortComment':{
                    'value': shortComment,
                    'color':'#4c8dae'
                },
                'fortuneText':{
                    'value': fortuneText,
                    'color': '#db5a6b'
                },
                'fortuneLove':{
                    'value': fortuneLove,
                    'color': '#801dae'
                },
                'fortuneWork':{
                    'value': fortuneWork,
                    'color': '#21a675'
                },
                'fortuneMoney':{
                    'value': fortuneMoney,
                    'color': '#f2be45'
                },
                'fortuneHealth':{
                    'value': fortuneHealth,
                    'color': '#b36d61'
                }
            }
        }
        params = json.dumps(data)

        print(sendTemplateMessage(params, accessToken))

2

评论区