使用Python脚本定时发送天气通知

使用Python脚本定时发送天气通知

阅读量:
评论数:

使用Python脚本定时发送天气通知

之前用shell脚本检测第二天下不下雨,太简陋了😋这次白嫖下和风天气的api,用python写一个脚本

其实现在手机自带的天气app功能更多更完善更及时更美观,写脚本就是图一乐罢了,就是玩🥰

介绍

和风天气官网:和风天气开发服务 ~ 强大、丰富的天气数据服务 (qweather.com)

免费订阅每天有1000次请求

常见城市列表:LocationList/China-City-List-latest.csv at master · qwd/LocationList (github.com)

获取3天内的天气,判断第二天是否有雨,是否温度过高,是否温度急速变化。

定时任务发送邮件。

预览

邮件-1.webp邮件-2.webp

代码

只需安装requests,白嫖QQ、网易、阿里等邮箱免费的SMTP

vim weather.pyi 编辑

修改好后粘贴进去

import requests
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

# 邮箱配置
def mail(subject,message):
    sender = 'test@test'  # 发件人邮箱
    receiver  = 'test@test'  # 收件人邮箱
    mail_host = "smtp.qq.com"  # 设置SMTP服务器
    mail_pass = "qq是授权码"  # 密码
    msg = MIMEText(message, 'plain', 'utf-8')
    msg['From'] = formataddr(("天气通知", sender))  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
    msg['To'] = formataddr(("weather", receiver))  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
    msg['Subject'] = subject  # 邮件的主题,也可以说是标题
    server = smtplib.SMTP_SSL(mail_host, 465)  # 发件人邮箱中的SMTP服务器
    server.login(sender, mail_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
    server.sendmail(sender, [receiver, ], msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
    server.quit()  # 关闭连接


location = '101220107'  # 见开头 常见城市列表
key = 'xxxxxxxxxxxxxxx'  # 

# 免费订阅url用https://devapi.qweather.com/
base_url = 'https://devapi.qweather.com/v7/weather/3d?location=%s&key=%s'

url = base_url % (location, key)

response = requests.get(url)
result = response.json()


# 白天天气
textDay_0 = result['daily'][0]['textDay']
textDay_1 = result['daily'][1]['textDay']

# 夜晚天气
textNight_0 = result['daily'][0]['textNight']
textNight_1 = result['daily'][1]['textNight']

# 降雨量
precip = result['daily'][1]['precip']

# 今明两日温度
tempMax_0 = int(result['daily'][0]['tempMax'])
tempMax_1 = int(result['daily'][1]['tempMax'])
tempMin_0 = int(result['daily'][0]['tempMin'])
tempMin_1 = int(result['daily'][1]['tempMin'])
#计算绝对值
diff = abs(tempMax_1 - tempMax_0)



# 邮件内容
message = f'今日天气:白天 {textDay_0},夜晚 {textNight_0}\n今日气温:最高{tempMax_0}℃,最低{tempMin_0}℃\n明日天气:白天 {textDay_1},夜晚:{textNight_1}\n明日气温:最高{tempMax_1}℃,最低{tempMin_1}℃\n明日降雨量:{precip}mm'

# 邮件标题,暂时只想到这3种通知
subject_rain = '明日可能下雨,出门记得带伞'
subject_hot = '高温预警!'
subject_diff = '明日温度变化较大,注意增减衣物'



# 判断
if '雨' in textDay_1 or '雨' in textNight_1:
    mail(subject_rain,message)
if tempMax_1 > 40:
    mail(subject_hot,message)
if diff > 8:
    mail(subject_diff,message)

esc :wq 回车保存退出(还是micro方便😊)

crontab -e 最后添加一行自动任务,修改为自己的脚本路径

例如0 7 * * * python3 /root/playground/weather/weather.py 每天早上7点运行

Built with Halo
主题 Stack Jimmy 设计 • 由Jiewen移植
📑共水了 93篇文章.
载入天数... 载入时分秒...
RSS Icon RSS订阅