python实现定时发送天气预报,超好用
python实现定时发送天气预报,超好用
在服务器上直接全程运行,7点准时发送,13点有天气预警就发送邮件,没有则不发送
先上效果图
首先免费注册一个和风天气开发者的账号:https://dev.qweather.com/docs/api/
先创建自己的应用,获得key
如何获得地理id:
https://geoapi.qweather.com/v2/city/lookup?location=beiji&key=XXXX key为和风授权码 location为要查询的地址
直接复制,直接使用,源码如下
入口 定时发送天气.py
#coding:utf-8
#导入相应的包
import smtplib
import time
from email.mime.text import MIMEText
from gettianqi import zhutian
# MIMEText三个主要参数
# 1. 邮件内容
# 2. MIME子类型,在此案例我们用plain表示text类型
# 3. 邮件编码格式,一定要用"utf-8"编码,因为内容可能包含非英文字符,不用的可能收到的邮件是乱码
# 发送email地址,填入你授权码的那个邮箱地址,此处地址是我常用QQ的地址
from email.utils import formataddr
from chuanyi import remind,yujing
def login(srv,from_addr,from_pwd):
try:
# 不能直接使用smtplib.SMTP来实例化,第三方邮箱会认为它是不安全的而报错
# 使用加密过的SMTP_SSL来实例化,它负责让服务器做出具体操作,它有两个参数
# 第一个是服务器地址,但它是bytes格式,所以需要编码
# 第二个参数是服务器的接受访问端口,SMTP_SSL协议默认端口是465
# 使用授权码登录你的QQ邮箱
srv.login(from_addr, from_pwd)
srv = smtplib.SMTP_SSL(smtp_srv.encode(), 465)
# 使用授权码登录你的QQ邮箱
srv.login(from_addr, from_pwd)
time.sleep(5)
print('登录成功')
except Exception as e:
print('发送失败'+str(e))
'''退出邮箱'''
srv.quit()
def send(to_addr,address,id,title,state):
mail_text_cont = zhutian(address, id)
mail_text_tixing = remind(id)
if state=='one':
mail_text_yujing = '</br>一切安好,快乐加倍!精神!(((o(*゚▽゚*)o)))♡'
else:
mail_text_yujing = yujing(id)[0]
mail_text=mail_text_cont+mail_text_tixing+mail_text_yujing
print(mail_text)
msg = MIMEText(mail_text, "html", "utf-8")
msg['Subject'] = title
msg['From'] = formataddr(['天气预报', from_addr])
msg['To'] = to_addr
# 第一个是发送地址
# 第二个是接受地址,是list格式,意在同时发送给多个邮箱
# 第三个是发送内容,作为字符串发送
print(to_addr)
srv.sendmail(from_addr, [to_addr], msg.as_string())#开始发送
if __name__ == '__main__':
from_addr = "你的邮箱XXXX@qq.com"
from_pwd = "你邮箱的授权码,不会的自动百度就好啦"
smtp_srv = "smtp.qq.com"
srv = smtplib.SMTP_SSL( smtp_srv.encode(), 465 )
'''list列表为接收人的名称,邮箱,位置,位置id'''
list={
'me':['xxxxxx@qq.com','历下',101120107],
'me2': ['xxxxxxxx@qq.com', '东平', 101120805],
}
a = time.strftime('%H', time.localtime(time.time()))
fanhui = '</br>一切安好,快乐加倍!精神!(((o(*゚▽゚*)o)))♡'
if a=='07':
# if '07' == '07':
title='天气预报机器人'
login(srv, from_addr, from_pwd)
for i in dict(list):
richang=time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime() )
print( '日常预报--已发送%s%s' % (list.get(i)[1],richang) )
# print(list.get(i)[0])
# print(list.get(i)[1])
send(list.get(i)[0],list.get(i)[1],list.get(i)[2],title,'one')
print('------------------------------%s日常'%richang)
srv.quit()
else:
login(srv, from_addr, from_pwd)
for i in dict(list):
text=yujing(list.get(i)[2])
title = text[1]
jinggao = time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime() )
if text!=fanhui:
print( '灾害预警发送--%s%s' % (list.get( i )[1], jinggao) )
send(list.get(i)[0], list.get(i)[1], list.get(i)[2],title,'two')
else:
print('%s-----没有到7点且没有警报!'%list.get(i)[1])
print( '------------------------------%s警报方法' % jinggao )
gettianqi.py 获取天气信息
#coding:utf-8
import requests
import json
def getID(address,key):
# address = '北京'
url = f'https://geoapi.qweather.com/v2/city/lookup?location={address}&key={key}'
datas = requests.get(url).json()
# print(data)
# print(type(datas))
for data in datas['location']:
if data['name'] == address:
ID = data['id']
return ID
'''后三天的天气'''
def zhutian(address,id):
url=f'https://devapi.qweather.com/v7/weather/3d?key=此处为你的key&location={id}'
tianqis = requests.get(url).json()
# print(tianqis)
dailys=tianqis.get('daily')
yubaotime=dailys[0]['fxDate']
maxwendu=dailys[0]['tempMax']
minwendu=dailys[0]['tempMin']
baitian=dailys[0]['textDay']
yejian=dailys[0]['textNight']
baitianfengxiang=dailys[0]['windDirDay']
baifengdengji=dailys[0]['windScaleDay']
jiangshui=dailys[0]['precip']
nengjiandu=dailys[0]['vis']
two=dailys[1]['textDay']
# print(yubaotime,maxwendu,minwendu,baitian,yejian,baitianfengxiang,baifengdengji,jiangshui,nengjiandu)
a = (
'<h1>今天:{0} {5}</h1>明天: {10}</br>时间:{1}</br>最高温度:{2}°    最低温度:{3}°</br>白天天气:{4}    夜间天气:{5}</br> 白天风向:{6}'
'    等级:{7}级</br> 降水:{8}毫米</br>能见度:{9}公里</br>'
.format(address, yubaotime, maxwendu, minwendu, baitian, yejian, baitianfengxiang,
baifengdengji,jiangshui,nengjiandu,two))
return (a)
if __name__ == '__main__':
pass
# # address = input('请输入要查询的天气:')
# address='济南'
# # ID = getID(address,key)
# # getData(address, ID)
# zhutian(address,101101015)
chuanyi.py 获取穿衣意见
#coding:utf-8
import requests
import json
def remind(id):
url=f'https://devapi.qweather.com/v7/indices/1d?type=1&location={id}&key=你的key'
cont=requests.get(url)
cont=json.loads(cont.text)
a=cont.get('daily')
tishi=(a[0].get('text'))
# print(tishi)
return tishi
def yujing(id):
# id=101101015
header={
'user - agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'
}
url=f'https://devapi.qweather.com/v7/warning/now?location={id}&key=你的key'
cont = requests.get( url,headers=header )
cont = json.loads( cont.text )
try:
if len(cont.get('warning'))!=0:
text=cont.get( 'warning' )[0]
a=' <font color="red"><h1>预警</h1></br>'+text.get('text')+'</font>'
title=text.get('title')
return [a,title]
except:
print('警告获取报错!!!')
else:
# print( '无预警!' )
a='</br>一切安好,快乐加倍!精神!(((o(*゚▽゚*)o)))♡'
# print(a)
return a
# yujing()
版权声明:本文为qq_41644139原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。