微信自动回复天气预报
注册免费天气 API
和风天气 API
注册成功后,控制台 => 新建应用 => 添加 KEY
查询天气
免费个人版只支持3天预报
import requests
import json
url = 'https://free-api.heweather.net/s6/weather/forecast?location=杭州&key=你的key'
res = requests.get(url)
data = json.loads(res.text)
data_str = json.dumps(data, ensure_ascii=False, indent=4, separators=(',', ':'))
print(data_str)
'''
{
"HeWeather6":[
{
"basic":{
"cid":"CN101210101",
"location":"杭州",
"parent_city":"杭州",
"admin_area":"浙江",
"cnty":"中国",
"lat":"30.28745842",
"lon":"120.15357971",
"tz":"+8.00"
},
"update":{
"loc":"2019-12-07 10:56",
"utc":"2019-12-07 02:56"
},
"status":"ok",
"daily_forecast":[
{
"cond_code_d":"100",
"cond_code_n":"100",
"cond_txt_d":"晴",
"cond_txt_n":"晴",
"date":"2019-12-07",
"hum":"60",
"mr":"14:03",
"ms":"01:45",
"pcpn":"0.0",
"pop":"0",
"pres":"1028",
"sr":"06:43",
"ss":"16:58",
"tmp_max":"10",
"tmp_min":"1",
"uv_index":"5",
"vis":"25",
"wind_deg":"-1",
"wind_dir":"无持续风向",
"wind_sc":"1-2",
"wind_spd":"3"
},
......
]
}
]
}
'''
手动解析一下
weather_data = data["HeWeather6"][0]
location = weather_data["basic"]["location"]
admin_area = weather_data["basic"]["admin_area"]
cnty = weather_data["basic"]["cnty"]
time = weather_data["update"]["loc"]
forecast = weather_data["daily_forecast"]
day_text = ["今天","明天","后天"]
message = "地区:{}-{}-{}\n".format(cnty,admin_area,location)
message += "时间:{}\n".format(time)
message += '\n'.join(["{}({}),日间天气{},夜间天气{},相对湿度{}%,最高气温{}度,最低气温{}度,风向{},风力{}级,能见度{}公里。"\
.format(day_text[i],
forecast[i]["date"],
forecast[i]["cond_txt_d"],
forecast[i]["cond_txt_n"],
forecast[i]["hum"],
forecast[i]["tmp_max"],
forecast[i]["tmp_min"],
forecast[i]["wind_dir"],forecast[0]["wind_sc"],forecast[0]["vis"])for i in range(2)])
print(message)
'''
地区:中国-浙江-杭州
时间:2019-12-07 11:55
今天(2019-12-07),日间天气晴,夜间天气晴,相对湿度60%,最高气温10度,最低气温1度,风向无持续风向,风力1-2级,能见度25公里。
明天(2019-12-08),日间天气晴,夜间天气晴,相对湿度62%,最高气温10度,最低气温1度,风向无持续风向,风力1-2级,能见度25公里。
'''
定义获取数据的函数
把上面的代码整合成下面两个函数
- weather_forecast 返回今明两天天气预报
- weather_now 返回实时天气
1. 预报天气
import requests
import json
key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
def weather_forecast(loc):
url = 'https://free-api.heweather.net/s6/weather/forecast?location={}&key={}'.format(loc,key)
res = requests.get(url)
data = json.loads(res.text)
data_str = json.dumps(data, ensure_ascii=False, indent=4, separators=(',', ':'))
weather_data = data["HeWeather6"][0]
location = weather_data["basic"]["location"]
admin_area = weather_data["basic"]["admin_area"]
cnty = weather_data["basic"]["cnty"]
time = weather_data["update"]["loc"]
forecast = weather_data["daily_forecast"]
day_text = ["今天","明天","后天"]
message = "地区:{}-{}-{}\n".format(cnty,admin_area,location)
message += "时间:{}\n".format(time)
message += '\n'.join(["{}({}),日间天气{},夜间天气{},相对湿度{}%,最高气温{}度,最低气温{}度,风向{},风力{}级,能见度{}公里。"\
.format(day_text[i],
forecast[i]["date"],
forecast[i]["cond_txt_d"],
forecast[i]["cond_txt_n"],
forecast[i]["hum"],
forecast[i]["tmp_max"],
forecast[i]["tmp_min"],
forecast[i]["wind_dir"],forecast[0]["wind_sc"],forecast[0]["vis"])for i in range(2)])
return message
2. 实时天气
def weather_now(loc):
url = 'https://free-api.heweather.net/s6/weather/now?location={}&key={}'.format(loc, key)
res = requests.get(url)
data = json.loads(res.text)
data_str = json.dumps(data, ensure_ascii=False, indent=4, separators=(',', ':'))
print(data_str)
weather_data = data["HeWeather6"][0]
location = weather_data["basic"]["location"]
admin_area = weather_data["basic"]["admin_area"]
cnty = weather_data["basic"]["cnty"]
time = weather_data["update"]["loc"]
now = weather_data["now"]
message = "[自动回复-实时天气]\n"
message += "地区:{}-{}-{}\n".format(cnty, admin_area, location)
message += "时间:{}\n".format(time)
message += "天气{},温度{}度,体感温度{}度,相对湿度{}%,风向{},风力{}级,能见度{}公里。" \
.format(now["cond_txt"],
now["tmp"],
now["fl"],
now["hum"],
now["wind_dir"],
now["wind_sc"],
now["vis"])
return message
微信自动发送消息
使用 itchat 给好友发送消息
这里搜索指定 昵称(RemarkName)的好友,当确定搜索结果为1人,且昵称完全匹配的时候再发送!
RemarkName = 'csm' # 搜索昵称
result = itchat.search_friends(nickname)
if len(result)==1 and nickname == result[0]["RemarkName"]: #
target = name[0]["UserName"]
message_concent = weather_forecast(loc='杭州')
itchat.send(message_concent,target)
这可以用于定时给某人发送消息
自动回复消息
当然还可以做成一个被动查询天气的工具,只要聊天中出现地名,就返回查询结果
# 全局变量,控制开关
global on
on = True
CSV_FILE_PATH = './china-city-list.csv'
df = pd.read_csv(CSV_FILE_PATH, skiprows=1)
city_set = set(df["City_CN"])
# 事件驱动函数
@itchat.msg_register(itchat.content.TEXT, isFriendChat=True)
def text_reply(msg):
global on
# json_str = json.dumps(msg, ensure_ascii=False, indent=4, separators=(',', ':'))
# print(json_str)
# 发给文件助手时,相当于发给自己
if msg.toUserName == "filehelper":
msg.fromUserName = msg.toUserName
# 打开、关闭自动回复
if msg.toUserName == msg.fromUserName:
if msg.text == "on":
on = True
elif msg.text == "off":
on = False
print("Auto-Reply: ", on)
if on:
time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(msg.createTime))
msg_str = "Time: {}\nFrom: {} \nTo : {}\nCont: {}".format(time_str, msg.fromUserName, msg.toUserName, msg.content)
print(msg_str)
loc_list = []
for w in jieba.cut(msg.content, cut_all=False):
if w in city_set:
loc_list.append(w)
for loc in loc_list:
m = weather_now(loc)
itchat.send_msg(m, msg.fromUserName)
# 二维码登陆
itchat.auto_login(hotReload=True)
itchat.run()
其中的城市列表下载
参考文献
- 天气API接口说明
- https://itchat.readthedocs.io/zh/latest
- https://www.cnblogs.com/jmmchina/p/6692149.html
源码
https://blog.csdn.net/itnerd/article/details/103433296