iT邦幫忙

3

LINE BOT聊天機器人-查詢天氣資訊

  • 分享至 

  • xImage
  •  

遮是一篇超級沒有語言技術性質的文章!請三思慎入!!

今天要來做查詢天氣的功能。
一樣有事前作業:
1.要先到氣象局註冊會員
2.到會員資訊中API授權碼的地方取得我們的Token
如此一來,就可以使用中央氣象局的API,然後在程式碼中使用Python內的requests套件做查詢


if (msg.find(keyWord_Weather) >= 0): # 台北市天氣 如果在關鍵字開頭,有找到視為0,即是索引位置

    # 把縣市拿出來放到getWeather()做搜尋
    user_city = message[:3]
    # 找到該城市的天氣資料
    weather = getWeather(user_city)
    # 如果沒有找到資料
    if (weather == 'no data'):

        msg_error = '查詢天氣狀況,使用方式: [縣市名稱][天氣]。例如:台北市天氣'
        line_bot_api.reply_message(
            replyToken, TextMessage(text=msg_error))
        print('getWeather: no data')

    else:
        # 將取得的城市天氣資料處理成我需要的資訊
        msg_weaterInfo = transferWeatherData(weather)
        line_bot_api.reply_message(
            replyToken, TextSendMessage(text=msg_weaterInfo))
        print('transferWeatherData: success')
 

def getWeather(city):
# 取氣象局的授權與資料--天氣

# 開放查詢
res = requests.get(
    'https://opendata.cwb.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=你的TOKEN')

# 處理台跟臺
if(city[0] == '台'):
    city = city.replace("台", "臺")

weather_Josn = json.loads(res.text)  # 讀取json 物件型態
locations = weather_Josn["records"]["location"]
# FIND CITY
try:
    i = 0
    while (i <= (len(locations))):
        if (locations[i]["locationName"] == city):
            item = locations[i]
            break
        i += 1
    return item

except IndexError:
    print('you get IndexError: list index out of range')
    return 'no data'

將取得的城市天氣資料處理成我需要的資訊

def transferWeatherData(item):

cityName = item["locationName"]
weatherElement = item["weatherElement"]  # 取得該縣市的天氣資料

# 天氣現象
if (weatherElement[0]["elementName"] == 'Wx'):
    timeDicts = weatherElement[0]["time"]  # 依時間區段設定早晚跟明天
    Wx_morning = timeDicts[0]["parameter"]["parameterName"]
    Wx_night = timeDicts[1]["parameter"]["parameterName"]
    Wx_tomorrow = timeDicts[2]["parameter"]["parameterName"]

# 降雨機率
if (weatherElement[1]["elementName"] == 'PoP'):
    timeDicts = weatherElement[1]["time"]  # 依時間區段設定早晚跟明天
    PoP_morning = str(timeDicts[0]["parameter"]["parameterName"]) + \
        timeDicts[0]["parameter"]["parameterUnit"]
    PoP_night = str(timeDicts[1]["parameter"]["parameterName"]) + \
        timeDicts[1]["parameter"]["parameterUnit"]
    PoP_tomorrow = str(timeDicts[2]["parameter"]["parameterName"]) + \
        timeDicts[2]["parameter"]["parameterUnit"]

# 低溫
if (weatherElement[2]["elementName"] == 'MinT'):
    timeDicts = weatherElement[2]["time"]  # 依時間區段設定早晚跟明天
    MinT_morning = timeDicts[0]["parameter"]["parameterName"] + \
        timeDicts[0]["parameter"]["parameterUnit"]
    MinT_night = timeDicts[1]["parameter"]["parameterName"] + \
        timeDicts[1]["parameter"]["parameterUnit"]
    MinT_tomorrow = timeDicts[2]["parameter"]["parameterName"] + \
        timeDicts[2]["parameter"]["parameterUnit"]

# 舒適度
if (weatherElement[3]["elementName"] == 'CI'):
    timeDicts = weatherElement[3]["time"]  # 依時間區段設定早晚跟明天
    CI_morning = timeDicts[0]["parameter"]["parameterName"]
    CI_night = timeDicts[1]["parameter"]["parameterName"]
    CI_tomorrow = timeDicts[2]["parameter"]["parameterName"]

# 高溫
if (weatherElement[4]["elementName"] == 'MaxT'):
    timeDicts = weatherElement[4]["time"]  # 依時間區段設定早晚跟明天
    MaxT_morning = timeDicts[0]["parameter"]["parameterName"] + \
        timeDicts[0]["parameter"]["parameterUnit"]
    MaxT_night = timeDicts[1]["parameter"]["parameterName"] + \
        timeDicts[1]["parameter"]["parameterUnit"]
    MaxT_tomorrow = timeDicts[2]["parameter"]["parameterName"] + \
        timeDicts[2]["parameter"]["parameterUnit"]

    today = timeDicts[0]["startTime"].split(
        ",")
    tomorrow = timeDicts[2]["endTime"].split(
        ",")

replyMsg = cityName + "今明兩日天氣預報:" + '\n' + \
    str(today[0][0:10]) + "," + Wx_morning + " " + CI_morning + '\n' + "白天高溫: " + MaxT_morning + '\n' + "今白天低溫: " + MinT_morning + '\n' + "白天下雨機率: " + PoP_morning + '\n' + "晚上高溫: " + MaxT_night + '\n' + "晚上低溫: " + \
    MinT_night + '\n' + "晚上下雨機率: " + PoP_night + '\n' + \
    str(tomorrow[0][0:10]) + "," + Wx_tomorrow + " " + CI_tomorrow + '\n' + "高溫: " + \
    MaxT_tomorrow + '\n' + "低溫: " + MinT_tomorrow + '\n' + "下雨機率: " + PoP_tomorrow

# 低溫提醒
# notice_minT()
minT = min([weatherElement[2]["time"][0]["parameter"]["parameterName"], weatherElement[2]["time"]
            [1]["parameter"]["parameterName"], weatherElement[2]["time"][2]["parameter"]["parameterName"]])
# 高溫提醒
maxT = max([weatherElement[4]["time"][0]["parameter"]["parameterName"], weatherElement[4]["time"]
            [1]["parameter"]["parameterName"], weatherElement[4]["time"][2]["parameter"]["parameterName"]])
pop = max([weatherElement[1]["time"][0]["parameter"]["parameterName"], weatherElement[1]["time"]
           [1]["parameter"]["parameterName"], weatherElement[1]["time"][2]["parameter"]["parameterName"]])

if (int(minT) < 10):
    replyMsg = replyMsg + "請注意低溫"
    return str(replyMsg)

elif(int(maxT) > 36):
    replyMsg = replyMsg + "請注意高溫"
    return str(replyMsg)

elif(int(pop) > 42):  # 降雨提醒 pop=12h/ pop6=6h
    replyMsg = replyMsg + '\n' + "請攜待雨具"
    return str(replyMsg)

else:
    return replyMsg          

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言