微信推送问候(Python)

微信推送问候

因为可能存在GitHub账号封的风险,所以在登录GitHub账号的时候一定要进入无痕模式!!!!!!
给在库(即扫码关注的人)推送个人需要的信息

使用GitHub网页,减少不必要的软件下载使用

微信测试账号的申请
微信模版推送的配置
GitHub的使用
金山词霸每日金句
英文金句

最后文件夹里面的内容有

在这里插入图片描述
.github里面还有一个workflows文件夹,文件夹里是weixin.yml文件
config.txt是GitHub最后跑代码所要用到的文件
main是pycharm的代码文件
requirements.txt是请求和农历处理。
模板内容为所需要发送的文字

步骤以及源码

  • 打开微信
    用微信扫码登录此网站: 进入平台快速连接。获取微信公众号的测试号在这里插入图片描述
    所需推送用户扫码关注公众号(可以先自行测试)
    用户扫码获取ID
    编辑所需要发送内容
    内容编辑
    模板内容我们可以用到记事本来编写(可以根据自己需要增加或减少)
    在这里插入图片描述

连接推送天气所需要的网站

———第三方网站和风天气
天气网站操作相关步骤

  • 1注册
  • 登录后点击左边控制台的“应用管理”
  • 2点击马上创建
  • 3选择免费版
  • 4应用名称(根据个人喜好随便输入)
  • 5选择Web API
  • 随便输入KEY名称(也是根据个人喜好而定)
  • 复制KEY到记事本,后续会用到

编辑GitHub最后跑代码所要用到的文件

在这里插入图片描述
所需要用到的时间包
把下面文本复制到记事本,命名为weixin.yml(需要手动改文件后缀)
把他放到所需要的文件夹,它要放在workflows文件夹里,workflows文件夹需要放到.github文件夹中
在这里插入图片描述

weixin.yml文件

name: weixin
on:
  workflow_dispatch:
  schedule: 
    # 代表国际标准时间2130分,北京时间需要+8小时,代表北京时间上午530分点运行
    - cron: '30 21 * * *'
jobs:
#将工作流程中运行的所有作业组合在一起
  build:
  #定义名为 build 的作业。 子键将定义作业的属性 
    runs-on: ubuntu-latest 
    steps:
      - uses: actions/checkout
    
      - name: Set up Python 3.9
        uses: actions/setup-python
        with:
          python-version: 3.9.1
      - name: Set timezone
        run: |
          cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
      - name: install pip packages
        run: |
          python -m pip install --upgrade pip
          pip3 install -r requirements.txt
      - name: weixin
        run: |
          python3 main.py

这个是pycharm2021版本创建一个main函数之后在里面编辑的内容。我们这里只需要用到一个main的py文件即可,然后保存放到文件夹。

import random
from time import localtime
from requests import get, post
from datetime import datetime, date
from zhdate import ZhDate
import sys
import os
 
 
def get_color():
    # 获取随机颜色
    get_colors = lambda n: list(map(lambda i: "#" + "%06x" % random.randint(0, 0xFFFFFF), range(n)))
    color_list = get_colors(100)
    return random.choice(color_list)
 
 
def get_access_token():
    # appId
    app_id = config["app_id"]
    # appSecret
    app_secret = config["app_secret"]
    post_url = ("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}"
                .format(app_id, app_secret))
    try:
        access_token = get(post_url).json()['access_token']
    except KeyError:
        print("获取access_token失败,请检查app_id和app_secret是否正确")
        os.system("pause")
        sys.exit(1)
    # print(access_token)
    return access_token
 
 
def get_weather(region):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
    }
    key = config["weather_key"]
    region_url = "https://geoapi.qweather.com/v2/city/lookup?location={}&key={}".format(region, key)
    response = get(region_url, headers=headers).json()
    if response["code"] == "404":
        print("推送消息失败,请检查地区名是否有误!")
        os.system("pause")
        sys.exit(1)
    elif response["code"] == "401":
        print("推送消息失败,请检查和风天气key是否正确!")
        os.system("pause")
        sys.exit(1)
    else:
        # 获取地区的location--id
        location_id = response["location"][0]["id"]
    weather_url = "https://devapi.qweather.com/v7/weather/now?location={}&key={}".format(location_id, key)
    response = get(weather_url, headers=headers).json()
    # 天气
    weather = response["now"]["text"]
    # 当前温度
    temp = response["now"]["temp"] + u"\N{DEGREE SIGN}" + "C"
    # 风向
    wind_dir = response["now"]["windDir"]
    return weather, temp, wind_dir
 
 
def get_birthday(birthday, year, today):
    birthday_year = birthday.split("-")[0]
    # 判断是否为农历生日
    if birthday_year[0] == "r":
        r_mouth = int(birthday.split("-")[1])
        r_day = int(birthday.split("-")[2])
        # 获取农历生日的今年对应的月和日
        try:
            birthday = ZhDate(year, r_mouth, r_day).to_datetime().date()
        except TypeError:
            print("请检查生日的日子是否在今年存在")
            os.system("pause")
            sys.exit(1)
        birthday_month = birthday.month
        birthday_day = birthday.day
        # 今年生日
        year_date = date(year, birthday_month, birthday_day)
 
    else:
        # 获取国历生日的今年对应月和日
        birthday_month = int(birthday.split("-")[1])
        birthday_day = int(birthday.split("-")[2])
        # 今年生日
        year_date = date(year, birthday_month, birthday_day)
    # 计算生日年份,如果还没过,按当年减,如果过了需要+1
    if today > year_date:
        if birthday_year[0] == "r":
            # 获取农历明年生日的月和日
            r_last_birthday = ZhDate((year + 1), r_mouth, r_day).to_datetime().date()
            birth_date = date((year + 1), r_last_birthday.month, r_last_birthday.day)
        else:
            birth_date = date((year + 1), birthday_month, birthday_day)
        birth_day = str(birth_date.__sub__(today)).split(" ")[0]
    elif today == year_date:
        birth_day = 0
    else:
        birth_date = year_date
        birth_day = str(birth_date.__sub__(today)).split(" ")[0]
    return birth_day
 
 
def get_ciba():
    url = "http://open.iciba.com/dsapi/"
    headers = {
        'Content-Type': 'application/json',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
    }
    r = get(url, headers=headers)
    note_en = r.json()["content"]
    note_ch = r.json()["note"]
    return note_ch, note_en
 
 
def send_message(to_user, access_token, region_name, weather, temp, wind_dir, note_ch, note_en):
    url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={}".format(access_token)
    week_list = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
    year = localtime().tm_year
    month = localtime().tm_mon
    day = localtime().tm_mday
    today = datetime.date(datetime(year=year, month=month, day=day))
    week = week_list[today.isoweekday() % 7]
    # 获取在一起的日子的日期格式
    love_year = int(config["love_date"].split("-")[0])
    love_month = int(config["love_date"].split("-")[1])
    love_day = int(config["love_date"].split("-")[2])
    love_date = date(love_year, love_month, love_day)
    # 获取在一起的日期差
    love_days = str(today.__sub__(love_date)).split(" ")[0]
    # 获取所有生日数据
    birthdays = {}
    for k, v in config.items():
        if k[0:5] == "birth":
            birthdays[k] = v
    data = {
        "touser": to_user,
        "template_id": config["template_id"],
        "url": "http://weixin.qq.com/download",
        "topcolor": "#FF0000",
        "data": {
            "date": {
                "value": "{} {}".format(today, week),
                "color": get_color()
            },
            "region": {
                "value": region_name,
                "color": get_color()
            },
            "weather": {
                "value": weather,
                "color": get_color()
            },
            "temp": {
                "value": temp,
                "color": get_color()
            },
            "wind_dir": {
                "value": wind_dir,
                "color": get_color()
            },
            "love_day": {
                "value": love_days,
                "color": get_color()
            },
            "note_en": {
                "value": note_en,
                "color": get_color()
            },
            "note_ch": {
                "value": note_ch,
                "color": get_color()
            }
        }
    }
    for key, value in birthdays.items():
        # 获取距离下次生日的时间
        birth_day = get_birthday(value["birthday"], year, today)
        if birth_day == 0:
            birthday_data = "今天{}生日哦,祝{}生日快乐!".format(value["name"], value["name"])
        else:
            birthday_data = "距离{}的生日还有{}天".format(value["name"], birth_day)
        # 将生日数据插入data
        data["data"][key] = {"value": birthday_data, "color": get_color()}
    headers = {
        'Content-Type': 'application/json',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
    }
    response = post(url, headers=headers, json=data).json()
    if response["errcode"] == 40037:
        print("推送消息失败,请检查模板id是否正确")
    elif response["errcode"] == 40036:
        print("推送消息失败,请检查模板id是否为空")
    elif response["errcode"] == 40003:
        print("推送消息失败,请检查微信号是否正确")
    elif response["errcode"] == 0:
        print("推送消息成功")
    else:
        print(response)
 
 
if __name__ == "__main__":
    try:
        with open("config.txt", encoding="utf-8") as f:
            config = eval(f.read())
    except FileNotFoundError:
        print("推送消息失败,请检查config.txt文件是否与程序位于同一路径")
        os.system("pause")
        sys.exit(1)
    except SyntaxError:
        print("推送消息失败,请检查配置文件格式是否正确")
        os.system("pause")
        sys.exit(1)
 
    # 获取accessToken
    accessToken = get_access_token()
    # 接收的用户
    users = config["user"]
    # 传入地区获取天气信息
    region = config["region"]
    weather, temp, wind_dir = get_weather(region)
    note_ch = config["note_ch"]
    note_en = config["note_en"]
    if note_ch == "" and note_en == "":
        # 获取词霸每日金句
        note_ch, note_en = get_ciba()
    # 公众号推送消息
    for user in users:
        send_message(user, accessToken, region, weather, temp, wind_dir, note_ch, note_en)
    os.system("pause")

requirements.txt文件内容

requests==2.28.1 zhdate==0.1

GitHub使用

使用前先进入无痕模式,我使用的是edge的浏览器
(点击新建In Private进入无痕模式)
在这里插入图片描述
然后进入GitHub官网 快捷登录
注册好之后点击右上角
在这里插入图片描述

  • 点开之后点击 New repository
  • 然后输入Repository name的内容,内容自拟
  • 滑到最下面保存。
  • 点击creating a new
    在这里插入图片描述
    上传上面刚开始准备的文件夹所有内容。
    在这里插入图片描述
    等待进度条完成后点击绿色的提交按钮。

复制weixin.yml的全部内容

  • 点击Actions播放按钮
  • 点击自己设置工作流程。
    在这里插入图片描述
  • 把Edit new file的文件全选复制成weixin.yml的内容
  • 完成后点击绿色的提交按钮,再点击运行按钮
    在这里插入图片描述
  • 如图操作
    在这里插入图片描述
    运行后点击三个点再点击下面的黑色字体的进程查看状态
    在这里插入图片描述
    等待一会即可获得微信公众号发来的信息,每天都会有的在这里插入图片描述
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值