參考範例知識庫:
https://opendata.cwb.gov.tw/devManual/insrtuction?fbclid=IwAR1zwO-DgQW9Ot0E9pyUaKkwCxRix1E4EJpueBN_9chxPpYXbSI4DTrLvyE
3.資料擷取-使用說明及目前開放資料擷取之氣象資料 線上API使用說明
https://ithelp.ithome.com.tw/articles/10223413
https://www.runoob.com/python/att-dictionary-get.html
https://ithelp.ithome.com.tw/articles/10235251
3.程式分成 兩個def 模組,一個是get_weather 進行Request 取值,一個是 LineNotifyMessage 通知LineBOT
程式碼:
import requests
import json
import time
def get_weather():
# cityname=input("輸入天氣查詢城市")
# F-C0032-001 是要查詢的資料種類,分類請查裝央氣象局對照表
cityname="桃園市"
# url 是來自中央氣象局給的 wbe query 網址, authorization 後面xxxxx...填入氣象局給你的授權碼..後面參數格式請查中央氣象局資料網站有說明.
url="https://opendata.cwb.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=XXX-XXX&limit=1&elementName=Wx&format=JSON&locationName="
city_url=url + cityname
res=requests.get(city_url).text
# print(res)
res=json.loads(res)
a=res["records"]["location"][0]["locationName"]
b=res["records"]["location"][0]["weatherElement"][0]['time'][0]
c=res["records"]["location"][0]["weatherElement"][0]['time'][1]
d=res["records"]["location"][0]["weatherElement"][0]['time'][2]
k=res["records"]["datasetDescription"]
l=b["parameter"]["parameterName"]
# print("res 是何種資料結構 : ",type(res))
# print("a=",a)
# print("b=",b)
# print("c=",c)
# print("d=",d)
# print("K=",k)
# print("b類別=:",type(b))
# print("天氣 :" ,l)
bmsg=b.get("startTime") + "至\n" + b.get("endTime") + ":\n" + l
cmsg=c.get("startTime") + "至\n" + c.get("endTime") + ":\n" + c["parameter"]["parameterName"]
dmsg=d.get("startTime") + "至\n" + d.get("endTime") + ":\n" + d["parameter"]["parameterName"]
Tmsg="\n"+a+"\n"+ k + "\n"+ bmsg+ "\n"+ "\n" +cmsg +"\n"+'\n'+dmsg
# print("Tmsg=",Tmsg)
return Tmsg #回傳值給msg
#------------------------------------------line 通知 的模組
def lineNotifyMessage(token, msg):
headers = {
"Authorization": "Bearer " + token,
"Content-Type" : "application/x-www-form-urlencoded"
}
payload = {'message': msg}
r = requests.post("https://notify-api.line.me/api/notify", headers = headers, params = payload)
return r.status_code
msg = get_weather()
token = '填入line給你的token 一長串字碼'
print("傳給line的msg=\n",msg)
#get_weather()
lineNotifyMessage(token,msg)
沒有留言:
張貼留言