cwadayi commited on
Commit
83f5761
·
verified ·
1 Parent(s): 5e234b7

Create weather_service.py

Browse files
Files changed (1) hide show
  1. weather_service.py +39 -0
weather_service.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # weather_service.py
2
+ import requests
3
+
4
+ # 中央氣象署 (CWA) 開放資料平台的授權碼是公開的,可以直接使用
5
+ CWA_AUTH_KEY = "CWA-15722330-8255-4252-9523-28E03C5C764C"
6
+ CWA_WEATHER_API = "https://opendata.cwa.gov.tw/api/v1/rest/datastore/O-A0003-001"
7
+
8
+ def fetch_weather_by_location(location_name: str) -> str:
9
+ """根據地點名稱查詢即時天氣資訊。"""
10
+ params = {
11
+ "Authorization": CWA_AUTH_KEY,
12
+ "format": "JSON",
13
+ "locationName": location_name,
14
+ "elementName": "TEMP,HUMD,Weather",
15
+ }
16
+ try:
17
+ r = requests.get(CWA_WEATHER_API, params=params, timeout=10)
18
+ r.raise_for_status()
19
+ data = r.json()
20
+
21
+ if not data.get("records") or not data["records"].get("location"):
22
+ return f"找不到「{location_name}」的即時天氣資訊,請試試看其他縣市或地區。"
23
+
24
+ loc_data = data["records"]["location"][0]
25
+ elements = {elem["elementName"]: elem["elementValue"] for elem in loc_data["weatherElement"]}
26
+
27
+ temp = elements.get("TEMP", "未知")
28
+ humidity = float(elements.get("HUMD", -1)) * 100
29
+ weather_desc = elements.get("Weather", "未知")
30
+
31
+ return (
32
+ f"📍 {loc_data['locationName']} 即時天氣:\n"
33
+ f"天氣狀況:{weather_desc}\n"
34
+ f"溫度:{temp}°C\n"
35
+ f"相對濕度:{humidity:.0f}%"
36
+ )
37
+
38
+ except Exception as e:
39
+ return f"❌ 天氣查詢失敗:{e}"