第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > 使用python实现微信公众号发送天气预报

使用python实现微信公众号发送天气预报

时间:2022-10-27 23:14:29

相关推荐

使用python实现微信公众号发送天气预报

概述

使用请求和风天气获取当天的天气信息, 然后使用微信公众号推送模板消息

注册开发公众号

地址:

https://mp./debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index

按照步骤注册,然后保存好appID 和 appsecret, 后面会使用到

然后自己打开手机微信, 扫描二维码关注公众号,关注完毕后记下微信号,后面发消息会使用。

之后点击新增测试模板

然后输入如下字符

日期:{{fxDate.DATA}} 白天天气:{{textDay.DATA}} 夜间天气:{{textNight.DATA}} 最高气温:{{tempMax.DATA}} 最低气温:{{tempMin.DATA}}

会得到一个消息模板ID,记下模板ID

注册和风天气

地址: /

然后进入控制台(右上角)

点击创建项目得到一个项目的Key, 存储下来后面调用接口使用

Python脚本

#!/usr/bin/python# 导入requests包import requestsimport timeimport json## 要发送的微信号,上面关注公众号得到的, 改成自己的touser=""## 消息模板ID, 改成自己的template_id="uc6Vw1wy2HS1IANwpqhvRHleRTpHG1Bp5lkOCD1xkX4"## 微信开发者的 appID, 改成自己的wx_appid = "##########"## 微信开发者的 appsecret, 改成自己的wx_secret = "###################"## 获取token的URL,不用改wx_token_url = "https://api./cgi-bin/token"## 获取天气URL, 不用改we_url = "/v7/weather/3d"## 和风天气项目的key, 改成自己的we_key ="###############"## 和风天气的地市代码,从这里查 /qwd/LocationList/blob/master/POI-Air-Monitoring-Station-List-latest.csv, ## 或者调用API查询, 文档参考:/docs/api/geoapi/we_location = "101120801"## 微信消息URL, 不用改msg_url ="https://api./cgi-bin/message/template/send?access_token="def send_msg():# 字典格式,推荐使用,它会自动帮你按照k-v拼接urlmy_params = {"grant_type":"client_credential","appid":wx_appid, "secret": wx_secret}## 请求获取tokenres = 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":"/","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())

执行脚本即可发送信息。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。