当前位置: 首页>前端>正文

用Python为爱加码:每日微信播报的浪漫攻略

鍏ㄦ枃鍏?162瀛楋紝闃呰澶х害闇€瑕?0鍒嗛挓

鏈€杩戝湪缇ら噷鐪嬪埌涓€涓ソ鐜╃殑娑堟伅鎺ㄩ€佸満鏅紝濡備笅鍥炬墍绀猴紝鍘熺悊鏄湪寰俊鎴栬€呬紒涓氬井淇¢€氳繃璋冪敤瀹樻柟鐨勬帴鍙e疄鐜版瘡鏃ュ畾鏃舵帹閫佹秷鎭€備粖澶╁氨甯﹀ぇ瀹舵潵鐮旂┒涓嬪畠鏄€庝箞瀹炵幇鐨勩€?/em>

用Python为爱加码:每日微信播报的浪漫攻略,第1张
鏁堟灉鍥?/div>

鏁翠釜浠g爜浼氬垎鍑犱釜閮ㄥ垎鏉ヨ瑙?/p>

  • 鏃ュ織锛氫负浜嗗疄鏃剁洃娴嬬▼搴忕殑杩愯鐘舵€侊紝鍙婂悗鏈熼棶棰樻帓鏌?/p>

  • 澶╂皵API璇﹁В锛氫細璁茶堪濡備綍璋冪敤鍏嶈垂鐨勫ぉ姘擜PI鎺ュ彛

  • Python鏃ユ湡澶勭悊锛歅ython涓棩鏈熻浆鎹㈠強鏃ユ湡澶╂暟鐨勮绠?/p>

  • 瀹屾暣鐨勬秷鎭帹閫?/p>

1.鏃ュ織

Python鏃ュ織璁板綍鐨勪唬鐮侊紝鍙湪浠讳綍鍦烘櫙涓嬪鐢紝瀹冭兘澶熷疄鏃剁洃娴嬬▼搴忕殑杩愯鐘舵€侊紝杞绘澗瑙e喅娴嬭瘯鍜岄棶棰樻帓鏌ョ殑闅鹃銆?/p>

娉ㄦ剰锛?code>log_home闇€瑕佹敼涓鸿嚜宸辨湰鍦拌矾寰?/p>

_tb_nm = '寰俊姣忔棩鎺ㄩ€?
_tb_nm_cn = "寰俊姣忔棩鎺ㄩ€?
_service_code = _tb_nm
# 鏃ュ織鐩綍
log_home = '/home/xusl/log/wx'

# 鏃ュ織level
log_level = logging.INFO

# 鏃ュ織鎵撳嵃鍒版帶鍒跺彴
log_to_console = True

log_config = {
    'version': 1,
    'formatters': {
        'generic': {
            'format': '%(asctime)s %(levelname)-5.5s [%(name)s:%(lineno)s][%(threadName)s] %(message)s',
        },
        'simple': {
            'format': '%(asctime)s %(levelname)-5.5s %(message)s',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'generic',
        },
        'file': {
            'class': 'logging.FileHandler',
            'filename': os.path.join(log_home, 'excel_to_data.log'),
            'encoding': 'utf-8',
            'formatter': 'generic',

        },
    },
    'root': {
        'level': log_level,
        'handlers': ['console', 'file', ] if log_to_console else ['file', ],
    }
}
logging.config.dictConfig(log_config)
logger = logging.getLogger(__name__)

2.澶╂皵API璇﹁В

鍦ㄨ繖閲屾彁渚涗竴涓綉绔?澶╂皵API璇存槑锛屾劅璋綔鑰呮彁渚涗簡8涓ぉ姘旀帴鍙o紝鍝嶅簲鏁堢巼楂橈紝鍙互杈惧埌涓嶉檺鍒舵鏁般€傚叧閿槸鍏嶈垂鐨勶紝JSON涓ょ鏂瑰紡杩斿洖銆?/p>

鎺ュ彛杩斿洖鐨勫ぉ姘旀寚鏁版暟鎹緢鍏ㄩ潰锛屽锛氭俯搴︺€佹渶楂樻俯搴︺€佹渶浣庢俯搴︺€侀銆佸ぉ姘斻€佺┖姘旇川閲忔寚鏁般€?/p>

鍙傛暟鍙湁涓€涓紝灏辨槸cityId銆?/p>

姣斿涓婃捣甯傜殑cityId鏄?01020100锛岃幏鍙栧ぉ姘旂殑API鎺ュ彛灏辨槸http://t.weather.sojson.com/api/weather/city/101020100

璁块棶杩欎釜鍦板潃锛岃繑鍥炵殑鏁版嵁濡備笅锛?/p>

用Python为爱加码:每日微信播报的浪漫攻略,第2张

鍥犱负杩斿洖鐨勭粨鏋滄湁杩?5澶╃殑澶╂皵锛屾墍浠ヨ瀵圭粨鏋滃仛涓€涓亶鍘嗭紝鍙栧嚭浠婂ぉ瀵瑰簲鐨勫ぉ姘斾俊鎭€傚悓鏃跺ぉ姘旀洿鏂版椂闂翠负姣忓ぉ鐨勶細3鐐?8鐐?13鐐?19鐐癸紝鎵€浠ュ缓璁笉瑕佸噷鏅ㄥ幓鑾峰彇锛屽姞涓奀DN鏈?涓皬鏃剁殑缂撳瓨锛屽缓璁?鐐?9鐐?14鐐?20鐐瑰悗鑾峰彇銆?/p>

娉ㄦ剰锛氬洜涓烘垜浠殑绋嬪簭鏄瘡鏃ユ帹閫佷竴娆★紝鎵€浠ユ病鏈夊澶╂皵缁撴灉杩涜缂撳瓨澶勭悊锛屼絾濡傛灉浣犵殑绋嬪簭闇€瑕侀绻佽皟鐢ㄥぉ姘旀帴鍙o紝涓轰簡鍑忓皯瀵规柟鐨凜DN鍔犻€熻垂鐢紝涓€瀹氳鍦ㄤ唬鐮侀噷鍔犲叆缂撳瓨锛孉PI鎺ュ彛鏄瘡8灏忔椂鏇存柊涓€娆★紝鏈哄埗鏄疌DN缂撳瓨8灏忔椂鏇存柊涓€娆°€?/p>

鍩庡競鏁版嵁璇峰湪鐧惧害缃戠洏涓嬭浇锛?/strong>

閾炬帴: https://pan.baidu.com/s/1JFAwnH2MRLc5OD3hsJZwGQ 鎻愬彇鐮? u8sk

3.Python鏃ユ湡澶勭悊

鑰冭檻鍒扮▼搴忎腑鏈夋棩鏈熻浆瀛楃涓诧紝瀛楃涓茶浆鏃ユ湡锛屾棩鏈熺浉鍑忥紝鎵€浠ュ啓浜嗗嚑涓柟娉曚緵澶у鍙傝€冿紝鍚屾椂鍏奸【浜嗗浗鍘嗗拰鍐滃巻鐢熸棩淇℃伅鐨勮幏鍙栵紝鍏蜂綋濡備笅

import datetime

from time import localtime


def get_now_datetime():
    """
    鑾峰彇褰撳墠鏃ユ湡
    :return: datetime now
    """
    return datetime.datetime.now()


def get_datetime_str(d_date=None, pattern='%Y-%m-%d'):
    """
    鑾峰彇鎸囧畾鏃ユ湡 瀛楃鏍煎紡
    :param d_date:
    :param pattern:
    :return:
    """
    if not d_date:
        d_date = get_now_datetime()
    return datetime.datetime.strftime(d_date, pattern)


def parse_str2date(s_date, pattern='%Y-%m-%d'):
    """
    灏嗗瓧绗︿覆杞崲涓烘棩鏈熸牸寮?
    :param s_date:
    :param pattern:
    :return:
    """
    return datetime.datetime.strptime(s_date, pattern)


def get_birthday(config, year, today_dt):
    """
    鑾峰彇璺濈涓嬫鐢熸棩鐨勬椂闂?
    :return:
    """
    logger.info('鑾峰彇璺濈涓嬫鐢熸棩鐨勬椂闂?..................')
    birthday = config["birth_day"]  # 鑾峰彇鐢熸棩鏃ユ湡
    birthday_year = birthday.split("-")[0]  # 2023 or r2023
    # 灏唖tr鏃ユ湡杞崲涓烘棩鏈熷瀷
    # d_birthday = datetime.datetime.strptime(birthday, "%Y-%m-%d")

    # 鍒ゆ柇鏄惁涓哄啘鍘嗙敓鏃?
    if birthday_year[0] == "r":
        # 鑾峰彇鍐滃巻鐢熸棩鐨勪粖骞村搴旂殑鏈堝拰鏃?
        try:
            r_mouth = int(birthday.split("-")[1])
            r_day = int(birthday.split("-")[2])
            nl_birthday = ZhDate(year, r_mouth, r_day).to_datetime().date()
        except TypeError:
            logger.error("璇锋鏌ョ敓鏃ョ殑鏃ュ瓙鏄惁鍦ㄤ粖骞村瓨鍦?)
            # 璋冪敤绯荤粺鍛戒护琛屾墽琛?pause 鍛戒护锛岀洰鐨勬槸鍦ㄦ帶鍒跺彴绐楀彛鏄剧ず "璇锋寜浠绘剰閿户缁? . ." 鐨勬彁绀轰俊鎭紝骞剁瓑寰呯敤鎴锋寜涓嬩换鎰忛敭鍚庣户缁墽琛岀▼搴?
            # os.system("pause")
            sys.exit(1)     # 寮傚父閫€鍑?

        birthday_month = nl_birthday.month
        birthday_day = nl_birthday.day
        # 浠婂勾鐢熸棩
        year_date = datetime.date(int(year), birthday_month, birthday_day)
    else:
        # 鑾峰彇鍥藉巻鐢熸棩鐨勪粖骞村搴旀湀鍜屾棩
        birthday_month = int(birthday.split("-")[1])
        birthday_day = int(birthday.split("-")[2])
        # 鑾峰彇鍥藉巻鐢熸棩鐨勪粖骞村搴旀湀鍜屾棩
        year_date = datetime.date(int(year), birthday_month, birthday_day)

    # 璁$畻鐢熸棩骞翠唤锛屽鏋滆繕娌¤繃锛屾寜褰撳勾鍑忥紝濡傛灉杩囦簡闇€瑕?1
    year_date = get_datetime_str(year_date)
    if today_dt > year_date:
        if birthday_year[0] == "r":
            r_mouth = int(birthday.split("-")[1])
            r_day = int(birthday.split("-")[2])
            # 鑾峰彇鍐滃巻鏄庡勾鐢熸棩鐨勬湀鍜屾棩
            r_last_birthday = ZhDate((int(year) + 1), r_mouth, r_day).to_datetime().date()
            birth_date = datetime.date((int(year) + 1), r_last_birthday.month, r_last_birthday.day)
            print(type(birth_date))
        else:
            # 鑾峰彇鍥藉巻鏄庡勾鐢熸棩鐨勬湀鍜屾棩
            birth_date = datetime.date((int(year) + 1), birthday_month, birthday_day)

            str_birth_date = get_datetime_str(birth_date)
        birth_day = (datetime.datetime.strptime(str_birth_date, "%Y-%m-%d").date() - datetime.datetime.strptime(today_dt, "%Y-%m-%d").date()).days

    elif today_dt == year_date:
        birth_day = 0
    else:
        birth_day = (datetime.datetime.strptime(year_date, "%Y-%m-%d").date() - datetime.datetime.strptime(today_dt, "%Y-%m-%d").date()).days

    if birth_day == 0:
        birthday_data = "鐢熸棩蹇箰锛岀绂忎綘鏃犱簨缁婂績寮︼紝鎵€蹇电殕濡傛効銆?
    else:
        birthday_data = "骞冲畨鍠滀箰锛屽緱鍋挎墍鎰裤€?

    return birth_day, birthday_data

*娉細鐢熸棩褰撳ぉ鐨勬枃妗堝彲鏍规嵁鑷繁鐨勯鏍间慨鏀桂煒?/p>

4.瀹屾暣鐨勬秷鎭帹閫佽剼鏈?/h2>

鏁翠釜娑堟伅鎺ㄩ€佽剼鏈垎涓や釜鏂囦欢锛屽垎鍒槸閰嶇疆淇℃伅鍜宲ython鑴氭湰锛屽紑濮嬩箣鍓嶆垜浠鍑嗗涓€涓嬮厤缃俊鎭€?/p>

  • 鐢宠鐩稿叧鐨勪俊鎭?code>app_id銆?code>app_secret銆?code>template_id銆?code>user 鍘诲井淇$敵璇凤紝寰俊鍏紬骞冲彴鎺ュ彛娴嬭瘯璐﹀彿鐢宠锛歨ttps://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login锛?br>

    用Python为爱加码:每日微信播报的浪漫攻略,第3张
  • 濡備笅鍥炬墍绀猴紝鐧诲綍鍚庝細鏈夊搴旂殑app_id銆?code>app_secret

    用Python为爱加码:每日微信播报的浪漫攻略,第4张
  • 鐒跺悗鎵爜鍏虫敞锛屽氨鑳界湅鍒板搴旂殑寰俊鍙蜂俊鎭紝杩欓噷鐨勫井淇″彿鏄斁鍦ㄩ厤缃枃浠剁殑user鐨?br>

    用Python为爱加码:每日微信播报的浪漫攻略,第5张
  • 鎺ョ潃鏄渶閲嶈鐨勪竴姝ワ紝鍐欏叆涓嬫柟鐨勬ā鏉夸俊鎭紝妯℃澘ID鍗充负鎴戜滑template_id

    用Python为爱加码:每日微信播报的浪漫攻略,第6张
鉁岀編濂界殑涓€澶╁紑濮嬪暒(麓鈯櫹夆姍`) 
鈽曚粖澶╂槸锛歿{date.DATA}} 
鈴╀笅闈㈠紑濮嬩负浣犳挱鎶{city_nm.DATA}}鐨勫ぉ姘?

鉀呬粖澶╃殑澶╂皵锛歿{weather.DATA}}
鈽€鏈€楂橈細{{max_temperature.DATA}}
鉂勬渶浣庯細{{min_temperature.DATA}}

鉂も潳鉂も潳鉂わ細{{glowing_terms.DATA}}

鈴宠窛绂诲疂璐濈殑鐢熸棩锛歿{birth_day.DATA}} 澶?
猸愨瓙猸愶細{{birthday_data.DATA}}
  • 鏈€鍚庝慨鏀规垜浠厤缃俊鎭?code>config.txt鍜?code>wx_message.py銆?/li>

config.txt

{
# 寰俊鍏紬鍙烽厤缃?
"app_id": "xxx",
"app_secret": "xxx",
"template_id": "xxx",
"user": ["xxx"], # 鎺ユ敹娑堟伅鐨勫井淇″彿锛屽涓井淇$敤鑻辨枃閫楀彿闂撮殧锛屼緥濡俒"wx1", "wx2"]

# 淇℃伅閰嶇疆
"city_id": "101020100",
"city_nm": "涓婃捣甯?,
"birth_day":"2023-08-22",   # 鐢熸棩鑻ヤ负鍐滃巻鍦ㄦ渶鍓嶉潰鍔犱笂r鍗冲彲
}

wx_message.py

# Created on 2024/1/19
# @title: '寰俊鍏紬鍙峰彂閫佹秷鎭?
# @author: Xusl

import logging.config
import random
import datetime
import sys, json
import os
import requests

from time import localtime
from requests import get, post
from zhdate import ZhDate


_tb_nm = '寰俊姣忔棩鎺ㄩ€?
_tb_nm_cn = "寰俊姣忔棩鎺ㄩ€?
_service_code = _tb_nm
# 鏃ュ織鐩綍
log_home = '/home/xusl/log/wx'

# 鏃ュ織level
log_level = logging.INFO

# 鏃ュ織鎵撳嵃鍒版帶鍒跺彴
log_to_console = True


log_config = {
    'version': 1,
    'formatters': {
        'generic': {
            'format': '%(asctime)s %(levelname)-5.5s [%(name)s:%(lineno)s][%(threadName)s] %(message)s',
        },
        'simple': {
            'format': '%(asctime)s %(levelname)-5.5s %(message)s',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'generic',
        },
        'file': {
            'class': 'logging.FileHandler',
            'filename': os.path.join(log_home, _tb_nm + '.log'),
            'encoding': 'utf-8',
            'formatter': 'generic',

        },
    },
    'root': {
        'level': log_level,
        'handlers': ['console', 'file', ] if log_to_console else ['file', ],
    }
}
logging.config.dictConfig(log_config)
logger = logging.getLogger(_tb_nm)

# 姣忔棩涓€瑷€
lines = [
    "浼氬ソ锛岃繜鏃┿€?,
    "鐢熷懡鍑犺锛岄伒浠庤嚜宸憋紝鍒刀璺紝鎰熷彈璺€?,
    "鍘荤埍鍏蜂綋鐨勭敓娲汇€?,
    "鎷愪釜寮紝涓庣敓娲诲拰瑙o紝寰楀け閮介殢鎰忋€?,
    "涓嶈棰勭煡鏄庡ぉ鐨勭儲鎭笺€?,
    "鍚庢潵閲嶉椈寰€浜嬪鑰虫梺杩囬锛屼笉鎱屼笉蹇欍€?,
    "鍕囨暍鐨勪汉鍏堜韩鍙椾笘鐣屻€?,
    "鐜懓涓嶇敤闀块珮锛屾櫄闇炶嚜浼氫刊鑵帮紝鐖辨剰闅忛濂旇窇锛屾俯鏌旀极杩囧北鑵般€?,
    "鏄ラ寰楁剰椹箘鐤撅紝涓€鏃ョ湅灏介暱瀹夎姳銆?,
    "浣犺嫢鍐冲畾鐏跨儌锛屽北鏃犻伄锛屾捣鏃犳嫤銆?,
    "涓€斾笅杞︾殑浜哄緢澶氾紝浣犱笉蹇呰€胯€夸簬鎬€銆?,
    "鍐呭績涓扮泩鑰咃紝鐙涔熷浼椼€?,
    "浣犺寰楄姳锛岃姳灏变笉鎬曟灟钀庛€?,
    "鏄ユ棩涓嶈繜锛岀浉閫㈢粓鏈夋椂銆?,
    "鏃ュ崌鏈堣惤鎬绘湁榛庢槑銆?,
    "鏈変汉绛夌儫闆紝鏈変汉鎬洦鎬ャ€?,
    "绛夐鏉ワ紝涓嶅杩介鍘汇€?,
    "鐪熻瘹姘歌繙鍙吹銆?,
    "鍠滀箰鏈夊垎浜紝鍏卞害鏃ユ湀闀裤€?,
    "鍦ㄨ繃绋嬩腑杩介€愭剰涔夈€?
]


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(config):
    logger.info('鑾峰彇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:
        logging.error("鑾峰彇access_token澶辫触锛岃妫€鏌pp_id鍜宎pp_secret鏄惁姝g‘")
        sys.exit(1)
    return access_token


def get_now_datetime():
    """
    鑾峰彇褰撳墠鏃ユ湡
    :return: datetime now
    """
    return datetime.datetime.now()


def get_datetime_str(d_date=None, pattern='%Y-%m-%d'):
    """
    鑾峰彇鎸囧畾鏃ユ湡 瀛楃鏍煎紡
    :param d_date:
    :param pattern:
    :return:
    """
    if not d_date:
        d_date = get_now_datetime()
    return datetime.datetime.strftime(d_date, pattern)


def parse_str2date(s_date, pattern='%Y-%m-%d'):
    """
    灏嗗瓧绗︿覆杞崲涓烘棩鏈熸牸寮?
    :param s_date:
    :param pattern:
    :return:
    """
    return datetime.datetime.strptime(s_date, pattern)


def get_weather_info(config, today_dt):
    """
    鑾峰彇鍩庡競褰撴棩澶╂皵
    :return:
    """
    logger.info('鑾峰彇澶╂皵...................')
    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'
    }
    city_id = config["city_id"]
    region_url = "http://t.weather.sojson.com/api/weather/city/{}".format(city_id)
    response = get(region_url, headers=headers).json()

    if response["status"] == 200:
        forecast = response["data"]["forecast"]
        for item in forecast:
            if item["ymd"] == today_dt:
                return True, item
    else:
        logging.error("澶╂皵淇℃伅鑾峰彇澶辫触锛岃妫€鏌ュぉ姘擜PI鏄惁姝e父")
        return False, response["status"]


def get_birthday(config, year, today_dt):
    """
    鑾峰彇璺濈涓嬫鐢熸棩鐨勬椂闂?
    :return:
    """
    logger.info('鑾峰彇璺濈涓嬫鐢熸棩鐨勬椂闂?..................')
    birthday = config["birth_day"]  # 鑾峰彇鐢熸棩鏃ユ湡
    birthday_year = birthday.split("-")[0]  # 2023 or r2023
    # 灏唖tr鏃ユ湡杞崲涓烘棩鏈熷瀷
    # d_birthday = datetime.datetime.strptime(birthday, "%Y-%m-%d")

    # 鍒ゆ柇鏄惁涓哄啘鍘嗙敓鏃?
    if birthday_year[0] == "r":
        # 鑾峰彇鍐滃巻鐢熸棩鐨勪粖骞村搴旂殑鏈堝拰鏃?
        try:
            r_mouth = int(birthday.split("-")[1])
            r_day = int(birthday.split("-")[2])
            nl_birthday = ZhDate(year, r_mouth, r_day).to_datetime().date()
        except TypeError:
            logger.error("璇锋鏌ョ敓鏃ョ殑鏃ュ瓙鏄惁鍦ㄤ粖骞村瓨鍦?)
            # 璋冪敤绯荤粺鍛戒护琛屾墽琛?pause 鍛戒护锛岀洰鐨勬槸鍦ㄦ帶鍒跺彴绐楀彛鏄剧ず "璇锋寜浠绘剰閿户缁? . ." 鐨勬彁绀轰俊鎭紝骞剁瓑寰呯敤鎴锋寜涓嬩换鎰忛敭鍚庣户缁墽琛岀▼搴?
            # os.system("pause")
            sys.exit(1)     # 寮傚父閫€鍑?

        birthday_month = nl_birthday.month
        birthday_day = nl_birthday.day
        # 浠婂勾鐢熸棩
        year_date = datetime.date(int(year), birthday_month, birthday_day)
    else:
        # 鑾峰彇鍥藉巻鐢熸棩鐨勪粖骞村搴旀湀鍜屾棩
        birthday_month = int(birthday.split("-")[1])
        birthday_day = int(birthday.split("-")[2])
        # 鑾峰彇鍥藉巻鐢熸棩鐨勪粖骞村搴旀湀鍜屾棩
        year_date = datetime.date(int(year), birthday_month, birthday_day)

    # 璁$畻鐢熸棩骞翠唤锛屽鏋滆繕娌¤繃锛屾寜褰撳勾鍑忥紝濡傛灉杩囦簡闇€瑕?1
    year_date = get_datetime_str(year_date)
    if today_dt > year_date:
        if birthday_year[0] == "r":
            r_mouth = int(birthday.split("-")[1])
            r_day = int(birthday.split("-")[2])
            # 鑾峰彇鍐滃巻鏄庡勾鐢熸棩鐨勬湀鍜屾棩
            r_last_birthday = ZhDate((int(year) + 1), r_mouth, r_day).to_datetime().date()
            birth_date = datetime.date((int(year) + 1), r_last_birthday.month, r_last_birthday.day)
            print(type(birth_date))
        else:
            # 鑾峰彇鍥藉巻鏄庡勾鐢熸棩鐨勬湀鍜屾棩
            birth_date = datetime.date((int(year) + 1), birthday_month, birthday_day)

            str_birth_date = get_datetime_str(birth_date)
        birth_day = (datetime.datetime.strptime(str_birth_date, "%Y-%m-%d").date() - datetime.datetime.strptime(today_dt, "%Y-%m-%d").date()).days

    elif today_dt == year_date:
        birth_day = 0
    else:
        birth_day = (datetime.datetime.strptime(year_date, "%Y-%m-%d").date() - datetime.datetime.strptime(today_dt, "%Y-%m-%d").date()).days

    if birth_day == 0:
        birthday_data = "鐢熸棩蹇箰锛岀绂忎綘鏃犱簨缁婂績寮︼紝鎵€蹇电殕濡傛効銆?
    else:
        birthday_data = "骞冲畨鍠滀箰锛屽緱鍋挎墍鎰裤€?

    return birth_day, birthday_data


def get_image_url():
    url = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1"
    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',
        'Content-type': 'application/x-www-form-urlencoded'

    }
    r = requests.get(url, headers=headers, verify=False)
    r.encoding = 'UTF-8-sig'
    image_url = "https://cn.bing.com" + json.loads(r.text)["images"][0]["url"]

    return image_url


def send_message(to_user, access_token, template_id, result, city_nm, birth_day, birthday_data):
    """
    鍙戦€佸井淇¢€氱煡
    :param to_user:
    :param access_token:
    :param template_id:
    :param result:
    :param city_nm:
    :param birth_day:
    :param birthday_data:
    :return:
    """
    logger.info('鍙戦€佸井淇¢€氱煡...................')
    weather = result["type"]  # 澶╂皵
    max_temperature = result["high"]  # 楂樻俯
    min_temperature = result["low"]  # 浣庢俯
    glowing_terms = random.choice(lines)  # 姣忔棩涓€瑷€

    url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={}".format(access_token)
    week_list = ["鏄熸湡鏃?, "鏄熸湡涓€", "鏄熸湡浜?, "鏄熸湡涓?, "鏄熸湡鍥?, "鏄熸湡浜?, "鏄熸湡鍏?]
    year = localtime().tm_year  # 骞?2024
    month = localtime().tm_mon  # 鏈?1
    day = localtime().tm_mday  # 鏃?19

    today = datetime.date(year=year, month=month, day=day)
    logging.info('today锛?s ' % today)
    week = week_list[today.isoweekday() % 7]
    logging.info('week锛?s ' % week)

    logging.info('鍩庡競锛歿}锛屽ぉ姘旓細{}锛岄珮娓╋細{}锛屼綆娓╋細{}'.format(city_nm, weather, max_temperature, min_temperature))
    data = {
        "touser": to_user,
        "template_id": template_id,
        "url": "http://weixin.qq.com/download",
        "topcolor": "#FF0000",
        "data": {
            "date": {
                "value": "{} {}".format(today, week),
                "color": get_color()
            },
            "city_nm": {
                "value": city_nm,
                "color": get_color()
            },
            "weather": {
                "value": weather,
                "color": get_color()
            },
            "max_temperature": {
                "value": max_temperature,
                "color": get_color()
            },
            "min_temperature": {
                "value": min_temperature,
                "color": get_color()
            },
            "glowing_terms": {
                "value": glowing_terms,
                "color": get_color()
            },
            "birth_day": {
                "value": birth_day,
                "color": get_color()
            },
            "birthday_data": {
                "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:
        logger.error("鎺ㄩ€佹秷鎭け璐ワ紝璇锋鏌ユā鏉縤d鏄惁姝g‘")
    elif response["errcode"] == 40036:
        logger.error("鎺ㄩ€佹秷鎭け璐ワ紝璇锋鏌ユā鏉縤d鏄惁涓虹┖")
    elif response["errcode"] == 40003:
        logger.error("鎺ㄩ€佹秷鎭け璐ワ紝璇锋鏌ュ井淇″彿鏄惁姝g‘")
    elif response["errcode"] == 0:
        logger.info("鎺ㄩ€佹秷鎭垚鍔?)
    else:
        logger.info(response)


if __name__ == '__main__':
    today_dt = get_datetime_str()       # 鑾峰彇褰撴棩鏃ユ湡
    t_year = today_dt.split("-")[0]       # 褰撳勾

    try:
        with open("config.txt", encoding="utf-8") as f:
            config = eval(f.read())
            access_token = get_access_token(config)
            birth_day, birthday_data = get_birthday(config, t_year, today_dt)    # 鐢熸棩绁濈璇?
            city_nm = config["city_nm"]                 # 鍩庡競鍚?
            # 鑾峰彇鍩庡競褰撴棩澶╂皵
            flag, result = get_weather_info(config, today_dt)
            template_id = config["template_id"]         # 妯℃澘ID
            # 鎺ユ敹鐨勭敤鎴?
            to_user = config["user"]                    # 鐢ㄦ埛閲岃濂?

            if flag is True:
                logging.info(f'澶╂皵鑾峰彇鎴愬姛 {result}: {str(result)}')
                for user in to_user:
                    send_message(user, access_token, template_id, result, city_nm, birth_day, birthday_data)
            else:
                logging.error(f'寮傚父 {result}: {str(result)}')
    except FileNotFoundError:
        logging.error("鎺ㄩ€佹秷鎭け璐ワ紝璇锋鏌onfig.txt鏂囦欢鏄惁涓庣▼搴忎綅浜庡悓涓€璺緞")

5.缁撳熬

鏁翠釜绋嬪簭灏藉彲鑳藉湪浠g爜閲屼綋鐜颁簡澶囨敞淇℃伅锛屼粛鐒舵湁鍑犵偣缇庝腑涓嶈冻

  • 姣忔棩涓€瑷€閮ㄥ垎澶皯锛岃В鍐虫柟妗堝彲浠ヤ紭鍖栨垚鑾峰彇鐩稿叧缃戠珯鐨勬暟鎹繚璇佹瘡澶╀笉鏄噸澶嶇殑锛屾垨鑰呭彲浠ョ洿鎺ユ墿澶ц瘝搴搇ines銆?/p>

  • 鎶ご閮ㄥ垎涓嶈兘鑷畾涔変慨鏀癸紝鏈€鏃╃殑鎯虫硶鏄敼鎴愯嚜宸辩殑鍏紬鍙凤紝姣忔棩瀹氭椂鎺ㄩ€侊紝鐮旂┒鍙戠幇鍏紬鍙蜂笉鑳借嚜瀹氫箟妯℃澘锛屽彧鑳戒粠瀹樻柟鐨勬ā鏉块噷鎸戦€夛紝灞€闄愭€у氨澶ぇ浜嗐€?/p>

    用Python为爱加码:每日微信播报的浪漫攻略,第7张

    瑙e喅鏂规硶鍙互鎶婁唬鐮佺Щ妞嶈嚦浼佷笟寰俊锛岃繖鏍锋姮澶存敮鎸佽嚜瀹氫箟锛屾崲姹や笉鎹㈣嵂锛屽敮涓€闇€瑕佹洿鏀圭殑灏辨槸鐢宠娉ㄥ唽浼佷笟寰俊锛屽悓鏃舵洿鎹负浼佷笟寰俊鐩稿叧閰嶇疆淇℃伅锛屽鏋滄椂闂村厑璁革紝鎴戝敖閲忓啀鍑轰竴鐗堜紒涓氬井淇$殑鏁欑▼銆?喔?鈥⑻€_鈥⑻?喔?/p>

  • 鏈€鍚庣殑瀹氭椂浠诲姟灏变笉鍐嶈繃澶氳瑙d簡锛岀洿鎺ヤ娇鐢ㄦ湇鍔″櫒鐨?code>crontab鍗冲彲

鏈€鍚庣殑鏈€鍚庯紝甯屾湜鍗曡韩鐨勬湅鍙嬫湁鍙屽悜鏆楁亱锛屾棭鏃ヨ拷鍒板績閫夛紝鏃╂棩蹇冨姩銆傚笇鏈涗笉鍗曡韩鐨勬湅鍙嬪郊姝ょ弽鎯滐紝鍜屽璞¢暱涔呫€傚笇鏈涙墍鏈変汉閮借兘鎷ユ湁鐖憋紝鎵€鏈変汉閮借兘琚埍鎷ユ湁銆?/strong>


https://www.xamrdz.com/web/2h71997313.html

相关文章: