cwadayi commited on
Commit
0035941
·
verified ·
1 Parent(s): 012dcb2

Create pws_service.py

Browse files
Files changed (1) hide show
  1. pws_service.py +46 -0
pws_service.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pws_service.py
2
+ import requests
3
+ import json
4
+ from config import PWS_API_URL
5
+
6
+ def fetch_latest_pws_info() -> str:
7
+ """
8
+ 從 MCP PWS 伺服器擷取最新的 PWS (Public Weather Service) 發布情形。
9
+ 此端點為 SSE (Server-Sent Events),因此我們需要讀取事件串流。
10
+ """
11
+ try:
12
+ # 使用 stream=True 來處理伺服器發送的事件串流
13
+ r = requests.get(PWS_API_URL, timeout=15, stream=True)
14
+ r.raise_for_status() # 如果 HTTP 狀態碼不是 200,則引發錯誤
15
+
16
+ # 迭代處理從伺服器接收到的每一行資料
17
+ for line in r.iter_lines():
18
+ if line:
19
+ decoded_line = line.decode('utf-8')
20
+ # SSE 事件的資料通常以 "data: " 開頭
21
+ if decoded_line.startswith('data:'):
22
+ # 移除 "data: " 前綴並去除多餘空格,取得 JSON 字串
23
+ json_data_str = decoded_line[5:].strip()
24
+
25
+ try:
26
+ # 解析 JSON 字串
27
+ data = json.loads(json_data_str)
28
+ # 從解析後的資料中提取報告內容 (假設 key 是 'pws_report')
29
+ pws_report = data.get("pws_report")
30
+
31
+ if not pws_report:
32
+ return "❌ PWS 查詢失敗:無法從 API 回應中找到 'pws_report' 欄位。"
33
+
34
+ # 格式化最終要回傳的訊息
35
+ lines = ["🛰️ 最新 PWS 發布情形:", "----------------------------------", pws_report]
36
+ return "\n".join(lines)
37
+
38
+ except json.JSONDecodeError:
39
+ return "❌ PWS 查詢失敗:伺服器回應的格式不正確 (非有效JSON)。"
40
+
41
+ return "❌ PWS 查詢失敗:無法從伺服器串流中解析到有效的 PWS 資料。"
42
+
43
+ except requests.exceptions.RequestException as e:
44
+ return f"❌ PWS 查詢失敗:無法連接到伺服器。\n錯誤訊息:{e}"
45
+ except Exception as e:
46
+ return f"❌ PWS 查詢失敗:發生未預期的錯誤。\n錯誤訊息:{e}"