Spaces:
Sleeping
Sleeping
Update weather_service.py
Browse files- weather_service.py +9 -88
weather_service.py
CHANGED
|
@@ -1,100 +1,21 @@
|
|
| 1 |
# weather_service.py
|
| 2 |
import requests
|
| 3 |
-
from config import
|
| 4 |
from datetime import datetime
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
def _format_time_period(start_str: str, end_str: str) -> str:
|
| 9 |
-
"""將時間格式化為易讀的時段名稱"""
|
| 10 |
-
start_dt = datetime.fromisoformat(start_str)
|
| 11 |
-
start_hour = start_dt.hour
|
| 12 |
-
|
| 13 |
-
if start_hour >= 18 or start_hour < 6:
|
| 14 |
-
return f"{start_dt.strftime('%m/%d')} 晚上至隔日清晨"
|
| 15 |
-
elif start_hour >= 6 and start_hour < 18:
|
| 16 |
-
return f"{start_dt.strftime('%m/%d')} 白天"
|
| 17 |
-
return f"{start_dt.strftime('%m/%d %H:%M')}"
|
| 18 |
-
|
| 19 |
|
| 20 |
def fetch_forecast_by_location(location_name: str) -> str:
|
| 21 |
"""根據地點名稱查詢未來 36 小時天氣預報。"""
|
| 22 |
-
if not
|
| 23 |
-
return "❌ 天氣預報查詢失敗:管理者尚未設定
|
| 24 |
|
|
|
|
|
|
|
| 25 |
params = {
|
| 26 |
-
"Authorization":
|
| 27 |
"format": "JSON",
|
| 28 |
-
|
| 29 |
"elementName": ["Wx", "PoP", "MinT", "MaxT"],
|
| 30 |
}
|
| 31 |
-
|
| 32 |
-
try:
|
| 33 |
-
r = requests.get(CWA_FORECAST_API, params=params, timeout=15)
|
| 34 |
-
r.raise_for_status()
|
| 35 |
-
data = r.json()
|
| 36 |
-
|
| 37 |
-
if not data.get("records") or not data["records"]["location"]:
|
| 38 |
-
return "❌ 無法從 CWA 獲取任何天氣預報資料。"
|
| 39 |
-
|
| 40 |
-
all_locations = data["records"]["location"]
|
| 41 |
-
|
| 42 |
-
# [修改] 在所有回傳的資料中,手動尋找使用者指定的地點
|
| 43 |
-
normalized_input = location_name.replace("台", "臺")
|
| 44 |
-
if not (normalized_input.endswith("市") or normalized_input.endswith("縣")):
|
| 45 |
-
normalized_input += "市" # 預設加上 "市" 來比對
|
| 46 |
-
|
| 47 |
-
target_location = None
|
| 48 |
-
for loc in all_locations:
|
| 49 |
-
if loc["locationName"] == normalized_input:
|
| 50 |
-
target_location = loc
|
| 51 |
-
break
|
| 52 |
-
|
| 53 |
-
# 如果找不到 "市",試試看 "縣"
|
| 54 |
-
if not target_location:
|
| 55 |
-
normalized_input = normalized_input.replace("市", "縣")
|
| 56 |
-
for loc in all_locations:
|
| 57 |
-
if loc["locationName"] == normalized_input:
|
| 58 |
-
target_location = loc
|
| 59 |
-
break
|
| 60 |
-
|
| 61 |
-
if not target_location:
|
| 62 |
-
return f"找不到「{location_name}」的預報資訊。\n請確認是否為台灣的縣市名稱 (例如: 臺北市, 花蓮縣)。"
|
| 63 |
-
|
| 64 |
-
# --- 找到地點後,格式化輸出 (邏輯不變) ---
|
| 65 |
-
loc_data = target_location
|
| 66 |
-
elements = {elem["elementName"]: elem["time"] for elem in loc_data["weatherElement"]}
|
| 67 |
-
|
| 68 |
-
forecasts = []
|
| 69 |
-
for i in range(3):
|
| 70 |
-
try:
|
| 71 |
-
start_time = elements["Wx"][i]["startTime"]
|
| 72 |
-
end_time = elements["Wx"][i]["endTime"]
|
| 73 |
-
wx = elements["Wx"][i]["parameter"]["parameterName"]
|
| 74 |
-
pop = elements["PoP"][i]["parameter"]["parameterName"]
|
| 75 |
-
min_t = elements["MinT"][i]["parameter"]["parameterName"]
|
| 76 |
-
max_t = elements["MaxT"][i]["parameter"]["parameterName"]
|
| 77 |
-
|
| 78 |
-
period_name = _format_time_period(start_time, end_time)
|
| 79 |
-
|
| 80 |
-
forecast_str = (
|
| 81 |
-
f"➢ {period_name}:\n"
|
| 82 |
-
f" 天氣:{wx}\n"
|
| 83 |
-
f" 氣溫:{min_t}°C - {max_t}°C\n"
|
| 84 |
-
f" 降雨機率:{pop}%"
|
| 85 |
-
)
|
| 86 |
-
forecasts.append(forecast_str)
|
| 87 |
-
except (IndexError, KeyError):
|
| 88 |
-
continue
|
| 89 |
-
|
| 90 |
-
if not forecasts:
|
| 91 |
-
return f"無法解析「{location_name}」的預報資料。"
|
| 92 |
-
|
| 93 |
-
return f"📍 {loc_data['locationName']} 未來 36 小時天氣預報:\n\n" + "\n\n".join(forecasts)
|
| 94 |
-
|
| 95 |
-
except requests.exceptions.HTTPError as e:
|
| 96 |
-
if e.response.status_code == 401:
|
| 97 |
-
return "❌ 預報查詢失敗:CWA 授權金鑰 (API Key) 無效。"
|
| 98 |
-
return f"❌ 預報查詢失敗:{e}"
|
| 99 |
-
except Exception as e:
|
| 100 |
-
return f"❌ 預報查詢失敗:{e}"
|
|
|
|
| 1 |
# weather_service.py
|
| 2 |
import requests
|
| 3 |
+
from config import CWA_API_KEY # [修改] 更新變數名稱
|
| 4 |
from datetime import datetime
|
| 5 |
|
| 6 |
+
# ... (檔案其餘部分不變) ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
def fetch_forecast_by_location(location_name: str) -> str:
|
| 9 |
"""根據地點名稱查詢未來 36 小時天氣預報。"""
|
| 10 |
+
if not CWA_API_KEY: # [修改] 更新變數名稱
|
| 11 |
+
return "❌ 天氣預報查詢失敗:管理者尚未設定 CWA_API_KEY。"
|
| 12 |
|
| 13 |
+
normalized_loc = _normalize_location_name(location_name)
|
| 14 |
+
|
| 15 |
params = {
|
| 16 |
+
"Authorization": CWA_API_KEY, # [修改] 更新變數名稱
|
| 17 |
"format": "JSON",
|
| 18 |
+
"locationName": normalized_loc,
|
| 19 |
"elementName": ["Wx", "PoP", "MinT", "MaxT"],
|
| 20 |
}
|
| 21 |
+
# ... (try...except 區塊不變) ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|