概述
使用请求和风天气获取当天的天气信息, 然后使用微信公众号推送模板消息
注册开发公众号
地址:
https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index
按照步骤注册,然后保存好appID 和 appsecret, 后面会使用到
然后自己打开手机微信, 扫描二维码关注公众号,关注完毕后记下微信号,后面发消息会使用。
之后点击新增测试模板
然后输入如下字符
日期:{{fxDate.DATA}}
白天天气:{{textDay.DATA}}
夜间天气:{{textNight.DATA}}
最高气温:{{tempMax.DATA}}
最低气温:{{tempMin.DATA}}
会得到一个消息模板ID,记下模板ID
注册和风天气
地址: https://dev.qweather.com/
然后进入控制台(右上角)
点击创建项目得到一个项目的Key, 存储下来后面调用接口使用
Python脚本
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# 导入requests包
import requests
import time
import json
## 要发送的微信号,上面关注公众号得到的, 改成自己的
touser=""
## 消息模板ID, 改成自己的
template_id="uc6Vw1wy2HS1IANwpqhvRHleRTpHG1Bp5lkOCD1xkX4"
## 微信开发者的 appID, 改成自己的
wx_appid = "##########"
## 微信开发者的 appsecret, 改成自己的
wx_secret = "###################"
## 获取token的URL,不用改
wx_token_url = "https://api.weixin.qq.com/cgi-bin/token"
## 获取天气URL, 不用改
we_url = "https://devapi.qweather.com/v7/weather/3d"
## 和风天气项目的key, 改成自己的
we_key ="###############"
## 和风天气的地市代码,从这里查 https://github.com/qwd/LocationList/blob/master/POI-Air-Monitoring-Station-List-latest.csv,
## 或者调用API查询, 文档参考:https://dev.qweather.com/docs/api/geoapi/
we_location = "101120801"
## 微信消息URL, 不用改
msg_url ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="
def send_msg():
# 字典格式,推荐使用,它会自动帮你按照k-v拼接url
my_params = {"grant_type":"client_credential","appid":wx_appid, "secret": wx_secret}
## 请求获取token
res = requests.get(url=wx_token_url, params=my_params)
print("微信token:",res.text) # 返回请求结果
if res.json()['access_token'] == "":
return "微信Token失败"
we_param = {"location":we_location,"key": we_key}
## 请求获取天气
we_res = requests.get(url=we_url, params=we_param)
print("天气返回:",we_res.text)
if we_res.json()['code'] != '200':
return "获取天气失败"
we_data = we_res.json()['daily'][0]
print("天气返回:",we_data)
## 发送模板消息
cur_time = time.time()
msg_id = str(int(cur_time))
## 组装微信模版消息的数据
send_json = {
"touser":touser,
"template_id":template_id,
"url":"https://www.qweather.com/",
"client_msg_id": msg_id,
"data":{
"fxDate": {
"value":we_data['fxDate'],
"color":"#173177"
},
"textDay":{
"value":we_data['textDay'],
"color":"#173177"
},
"textNight": {
"value":we_data['textNight'],
"color":"#173177"
},
"tempMax": {
"value":we_data['tempMax'],
"color":"#173177"
},
"tempMin":{
"value":we_data['tempMin'],
"color":"#173177"
}
}
}
## 发送微信模版消息
msg_res = requests.post(url=msg_url+res.json()['access_token'],data=json.JSONEncoder().encode(send_json))
print("消息返回:",msg_res.text)
if msg_res.json()['errcode'] == 0:
return "发送成功"
return "发送失败"
print(send_msg())
执行脚本即可发送信息。注意安装依赖