cwadayi commited on
Commit
139ddee
·
verified ·
1 Parent(s): 97ce441

Update command_handler.py

Browse files
Files changed (1) hide show
  1. command_handler.py +199 -142
command_handler.py CHANGED
@@ -1,153 +1,210 @@
1
- # command_handler.py
 
 
 
 
2
  import pandas as pd
3
- from linebot.v3.messaging import TextMessage, ImageMessage
4
-
5
- # 匯入服務函式
6
- from cwa_service import fetch_cwa_alarm_list, fetch_significant_earthquakes
7
- from usgs_service import fetch_global_last24h_text, fetch_taiwan_df_this_year
8
- from plotting_service import create_and_save_map
9
- from ai_service import generate_ai_text
10
- from config import CURRENT_YEAR, HF_SPACE_URL
11
-
12
- def get_help_message() -> TextMessage:
13
- """回傳包含所有可用指令的說明訊息。"""
14
- text = (
15
- "📖 指令列表\n\n"
16
- "【地震資訊】\n"
17
- "• /latest - 查詢最新一筆顯著地震(含圖)\n"
18
- "• /global - 查詢全球近24小時顯著地震\n"
19
- "• /taiwan - 顯示今年台灣顯著地震列表\n"
20
- "• /map - 取得台灣顯著地震地圖連結\n"
21
- "• /alert - 獲取 CWA 最新地震預警\n"
22
- "• /significant - CWA 最新顯著有感地震\n\n"
23
- "【AI 與工具】\n"
24
- "• /ai <問題> - 與 AI 助理對話\n\n"
25
- "【基本指令】\n"
26
- "• /info - 關於此機器人\n"
27
- "• /help - 顯示此說明"
28
- )
29
- return TextMessage(text=text)
30
-
31
- def get_info_message() -> TextMessage:
32
- """回傳機器人資訊。"""
33
- text = (
34
- "🤖 關於我\n\n"
35
- "我是一個多功能助理機器人,提供地震查詢與 AI 對話功能。\n\n"
36
- "• 版本: 2.5\n"
37
- "• 資料來源: CWA, USGS, Hugging Face\n"
38
- "• 開發者: dayichen"
39
- )
40
- return TextMessage(text=text)
41
-
42
- def get_taiwan_earthquake_list() -> TextMessage:
43
- """回傳近期的台灣地震文字列表。"""
44
- result = fetch_taiwan_df_this_year()
45
- if isinstance(result, pd.DataFrame):
46
- count = len(result)
47
- lines = [f"🇹🇼 今年 ({CURRENT_YEAR} 年) 台灣區域顯著地震 (M≥5.0),共 {count} 筆:", "-" * 20]
48
- for _, row in result.head(15).iterrows():
49
- t = row["time_utc"].strftime("%Y-%m-%d %H:%M")
50
- lines.append(
51
- # [修改] 將 "震級" 改為 "規模"
52
- f"規模: {row['magnitude']:.1f} | 日期時間: {t} (UTC)\n"
53
- f"地點: {row['place']}\n"
54
- f"報告連結: {row.get('url', '無')}"
55
- )
56
- if count > 15:
57
- lines.append(f"... (還有 {count - 15} 筆,請用 /map 查看全部)")
58
- reply_text = "\n\n".join(lines)
59
- else:
60
- reply_text = result
61
- return TextMessage(text=reply_text)
62
-
63
- def get_taiwan_earthquake_map(base_url: str) -> list:
64
- """產生地震地圖,並回傳包含連結的文字訊息。"""
65
- result = fetch_taiwan_df_this_year()
66
- if isinstance(result, pd.DataFrame):
67
- filename = create_and_save_map(result)
68
- image_url = f"{(HF_SPACE_URL or base_url)}/static/{filename}"
69
- reply_text = (
70
- "🗺️ 已為您繪製地震分佈圖。\n\n"
71
- "請點擊以下連結查看圖片:\n"
72
- f"{image_url}"
73
- )
74
- return [TextMessage(text=reply_text)]
75
- else:
76
- return [TextMessage(text=result)]
77
 
78
- def process_message(user_message_raw: str, request_base_url: str) -> list:
79
- """處理使用者的文字訊息並回傳一個包含回覆訊息的列表。"""
80
- user_message = (user_message_raw or "").strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
- # 將舊指令對應到新指令,提供向下相容
83
- if user_message.lower() in ["地震", "quake"]:
84
- user_message = "/global"
85
- elif user_message.lower() in ["台灣地震", "臺灣地震"]:
86
- user_message = "/taiwan"
87
- elif user_message.lower() in ["台灣地震畫圖", "臺灣地震畫圖"]:
88
- user_message = "/map"
89
- elif user_message.lower() == "地震預警":
90
- user_message = "/alert"
91
-
92
- if user_message.startswith('/'):
93
- parts = user_message.split(' ', 1)
94
- command = parts[0].lower()
95
- arg = parts[1] if len(parts) > 1 else ""
96
-
97
- if command == '/help':
98
- return [get_help_message()]
99
- elif command == '/info':
100
- return [get_info_message()]
101
- elif command == '/latest':
102
- return get_latest_earthquake_reply()
103
- elif command == '/global':
104
- return [TextMessage(text=fetch_global_last24h_text())]
105
- elif command == '/taiwan':
106
- return [get_taiwan_earthquake_list()]
107
- elif command == '/map':
108
- return get_taiwan_earthquake_map(request_base_url)
109
- elif command == '/alert':
110
- return [TextMessage(text=fetch_cwa_alarm_list(limit=5))]
111
- elif command == '/significant':
112
- return [TextMessage(text=fetch_significant_earthquakes(limit=5))]
113
- elif command == '/ai':
114
- if not arg:
115
- return [TextMessage(text="請輸入問題,例如:/ai 台灣最高的山是哪座?")]
116
- return [TextMessage(text=generate_ai_text(arg))]
117
-
118
- # 若非指令,則預設交給 AI 處理 (作為備援)
119
- return [TextMessage(text=generate_ai_text(user_message))]
120
-
121
- # --- [新功能] 處理 /latest 指令的回覆 ---
122
- def get_latest_earthquake_reply() -> list:
123
- """獲取最新地震資訊並組合成 LINE 訊息"""
124
  try:
125
- latest_eq = fetch_latest_significant_earthquake()
126
- if not latest_eq:
127
- return [TextMessage(text="✅ 近期無顯著有感地震報告。")]
 
 
128
 
129
- # 組合文字訊息
130
- mag_str = f"{latest_eq['Magnitude']:.1f}" if latest_eq.get('Magnitude') is not None else "—"
131
- depth_str = f"{latest_eq['Depth']:.0f}" if latest_eq.get('Depth') is not None else "—"
132
-
133
- text_message_content = (
134
- f"🚨 CWA 最新顯著有感地震\n"
135
- f"----------------------------------\n"
136
- f"時間: {latest_eq.get('TimeStr', '—')}\n"
137
- f"地點: {latest_eq.get('Location', '—')}\n"
138
- f"規模: M{mag_str} | 深度: {depth_str} km\n"
139
- f"報告: {latest_eq.get('URL', '無')}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  )
141
- reply_messages = [TextMessage(text=text_message_content)]
142
 
143
- # 如果有圖片網址,則新增圖片訊息
144
- if latest_eq.get("ImageURL"):
145
- image_url = latest_eq["ImageURL"]
146
- reply_messages.append(
147
- ImageMessage(original_content_url=image_url, preview_image_url=image_url)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
 
150
- return reply_messages
 
 
 
151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  except Exception as e:
153
- return [TextMessage(text=f"❌ 查詢最新地震失敗:{e}")]
 
1
+ # cwa_service.py
2
+ # -*- coding: utf-8 -*-
3
+ from __future__ import annotations
4
+ import requests
5
+ import re
6
  import pandas as pd
7
+ from datetime import datetime, timedelta, timezone
8
+ from config import CWA_API_KEY, CWA_ALARM_API, CWA_SIGNIFICANT_API, CWA_LOCAL_EQ_API
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ TAIPEI_TZ = timezone(timedelta(hours=8))
11
+
12
+ # --- Helper Functions ---
13
+ def _to_float(x):
14
+ if x is None: return None
15
+ s = str(x).strip()
16
+ m = re.search(r"[-+]?\d+(?:\.\d+)?", s)
17
+ return float(m.group()) if m else None
18
+
19
+ def _parse_cwa_time(s: str) -> tuple[str, str]:
20
+ if not s: return ("未知", "未知")
21
+ try:
22
+ dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
23
+ tw = dt.astimezone(TAIPEI_TZ).strftime("%Y-%m-%d %H:%M")
24
+ utc = dt.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M")
25
+ return (tw, utc)
26
+ except Exception:
27
+ return (s, "未知")
28
+
29
+ def _normalize_cwa_area_name(area_name: str) -> str:
30
+ """自動校正縣市名稱,以符合 CWA API 查詢需求"""
31
+ area_name = area_name.replace("台", "臺")
32
+ if area_name.endswith("市") or area_name.endswith("縣"):
33
+ return area_name
34
 
35
+ major_cities = "臺北,新北,基隆,桃園,新竹,臺中,嘉義,臺南,高雄".split(',')
36
+ if any(city in area_name for city in major_cities):
37
+ return f"{area_name}市"
38
+ else:
39
+ return f"{area_name}縣"
40
+
41
+ # --- 地震預警 (CWA_ALARM_API) ---
42
+ def fetch_cwa_alarm_list(limit: int = 5) -> str:
43
+ """抓 CWA 地震預警並格式化輸出。"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  try:
45
+ r = requests.get(CWA_ALARM_API, timeout=10)
46
+ r.raise_for_status()
47
+ payload = r.json()
48
+ except Exception as e:
49
+ return f"❌ 地震預警查詢失敗:{e}"
50
 
51
+ items = payload.get("data", [])
52
+ if not items:
53
+ return " 目前沒有地震預警。"
54
+
55
+ def _key(it):
56
+ try:
57
+ return datetime.fromisoformat(it.get("originTime", "").replace("Z", "+00:00"))
58
+ except:
59
+ return datetime.min.replace(tzinfo=timezone.utc)
60
+
61
+ items = sorted(items, key=_key, reverse=True)
62
+ lines = ["🚨 地震預警(最新):", "-" * 20]
63
+ for it in items[:limit]:
64
+ mag = _to_float(it.get("magnitudeValue"))
65
+ depth = _to_float(it.get("depth"))
66
+ tw_str, _ = _parse_cwa_time(it.get("originTime", ""))
67
+ identifier = str(it.get('identifier', '—')).replace('{', '{{').replace('}', '}}')
68
+ msg_type = str(it.get('msgType', '—')).replace('{', '{{').replace('}', '}}')
69
+ msg_no = str(it.get('msgNo', '—')).replace('{', '{{').replace('}', '}}')
70
+ areas = str(it.get('alertAreas') or '—').replace('{', '{{').replace('}', '}}')
71
+ mag_str = f"{mag:.1f}" if mag is not None else "—"
72
+ depth_str = f"{depth:.0f}" if depth is not None else "—"
73
+ lines.append(
74
+ f"事件: {identifier} | 類型: {msg_type}#{msg_no}\n"
75
+ f"規模/深度: M{mag_str} / {depth_str} km\n"
76
+ f"時間: {tw_str}(台灣)\n"
77
+ f"預警地區: {areas}"
78
  )
79
+ return "\n\n".join(lines).strip()
80
 
81
+ # --- 顯著有感地震 (E-A0015-001) ---
82
+ def _parse_significant_earthquakes(obj: dict) -> pd.DataFrame:
83
+ """最穩健的解析邏輯,供 /significant 和 /latest 共用"""
84
+ records = obj.get("records") or obj.get("Records") or {}
85
+ quakes = records.get("earthquake") or records.get("Earthquake") or []
86
+ rows = []
87
+ for q in quakes:
88
+ ei = q.get("EarthquakeInfo") or q.get("earthquakeInfo") or {}
89
+ epic = ei.get("Epicenter") or ei.get("epicenter") or {}
90
+ mag_info = ei.get("Magnitude") or ei.get("magnitude") or ei.get("EarthquakeMagnitude") or {}
91
+
92
+ depth_raw = ei.get("FocalDepth") or ei.get("depth") or ei.get("Depth")
93
+ mag_raw = mag_info.get("MagnitudeValue") or mag_info.get("magnitudeValue") or mag_info.get("Value") or mag_info.get("value")
94
+
95
+ rows.append({
96
+ "ID": q.get("EarthquakeNo"), "Time": ei.get("OriginTime"),
97
+ "Lat": _to_float(epic.get("EpicenterLatitude") or epic.get("epicenterLatitude")),
98
+ "Lon": _to_float(epic.get("EpicenterLongitude") or epic.get("epicenterLongitude")),
99
+ "Depth": _to_float(depth_raw), "Magnitude": _to_float(mag_raw),
100
+ "Location": epic.get("Location") or epic.get("location"),
101
+ "URL": q.get("Web") or q.get("ReportURL"),
102
+ })
103
+ df = pd.DataFrame(rows)
104
+ if not df.empty and "Time" in df.columns:
105
+ time_series = pd.to_datetime(df["Time"], errors="coerce")
106
+ if pd.api.types.is_datetime64_any_dtype(time_series):
107
+ df["Time"] = time_series.dt.tz_localize("UTC").dt.tz_convert(TAIPEI_TZ)
108
+ return df
109
+
110
+ def fetch_significant_earthquakes(days: int = 7, limit: int = 5) -> str:
111
+ if not CWA_API_KEY: return "❌ 顯著地震查詢失敗:管理者尚未設定 CWA_API_KEY。"
112
+ now = datetime.now(timezone.utc)
113
+ time_from = (now - timedelta(days=days)).strftime("%Y-%m-%d")
114
+ params = {"Authorization": CWA_API_KEY, "format": "JSON", "timeFrom": time_from}
115
+ try:
116
+ r = requests.get(CWA_SIGNIFICANT_API, params=params, timeout=15)
117
+ r.raise_for_status()
118
+ data = r.json()
119
+ df = _parse_significant_earthquakes(data)
120
+ if df.empty: return f"✅ 過去 {days} 天內沒有顯著有感地震報告。"
121
+ df = df.sort_values(by="Time", ascending=False).head(limit)
122
+
123
+ lines = [f"🚨 CWA 最新顯著有感地震 (近{days}天內):", "-" * 20]
124
+ for _, row in df.iterrows():
125
+ mag_str = f"{row['Magnitude']:.1f}" if pd.notna(row['Magnitude']) else "—"
126
+ depth_str = f"{row['Depth']:.0f}" if pd.notna(row['Depth']) else "—"
127
+ lines.append(
128
+ f"時間: {row['Time'].strftime('%Y-%m-%d %H:%M') if pd.notna(row['Time']) else '—'}\n"
129
+ f"地點: {row['Location'] or '—'}\n"
130
+ f"規模: M{mag_str} | 深度: {depth_str} km\n"
131
+ f"報告: {row['URL'] or '無'}"
132
  )
133
+ return "\n\n".join(lines)
134
+ except Exception as e:
135
+ return f"❌ 顯著地震查詢失敗:{e}"
136
+
137
+ # --- 最新一筆顯著地震 ---
138
+ def fetch_latest_significant_earthquake() -> dict | None:
139
+ """從 CWA 獲取最新一筆顯著地震,並重用現有的解析邏輯"""
140
+ if not CWA_API_KEY:
141
+ raise ValueError("錯誤:尚未設定 CWA_API_KEY Secret。")
142
+
143
+ now = datetime.now(timezone.utc)
144
+ time_from = (now - timedelta(days=2)).strftime("%Y-%m-%dT%H:%M:%S")
145
+ params = {"Authorization": CWA_API_KEY, "format": "JSON", "limit": 1}
146
+
147
+ r = requests.get(CWA_SIGNIFICANT_API, params=params, timeout=15)
148
+ r.raise_for_status()
149
+ data = r.json()
150
+
151
+ df = _parse_significant_earthquakes(data)
152
+ if df.empty:
153
+ return None
154
+
155
+ latest_eq_data = df.sort_values(by="Time", ascending=False).iloc[0].to_dict()
156
+
157
+ quakes = data.get("records", {}).get("Earthquake", [])
158
+ if quakes:
159
+ latest_eq_data["ImageURL"] = quakes[0].get("ReportImageURI")
160
+
161
+ if pd.notna(latest_eq_data.get("Time")):
162
+ latest_eq_data["TimeStr"] = latest_eq_data["Time"].strftime('%Y-%m-%d %H:%M')
163
+
164
+ return latest_eq_data
165
+
166
+ # --- 小區域有感地震 (E-A0016-001) ---
167
+ def fetch_local_earthquakes(area_name: str = "", limit: int = 5) -> str:
168
+ """從 CWA 獲取小區域有感地震報告。如果 area_name 為空,則查詢全台灣。"""
169
+ if not CWA_API_KEY: return "❌ 查詢失敗:管理者尚未設定 CWA_API_KEY。"
170
+
171
+ params = {"Authorization": CWA_API_KEY, "format": "JSON", "limit": limit}
172
+ title = "🇹🇼 台灣近期小區域有感地震:"
173
+
174
+ if area_name:
175
+ normalized_area = _normalize_cwa_area_name(area_name)
176
+ params["AreaName"] = normalized_area
177
+ title = f"🚨 「{normalized_area}」近期小區域有感地震:"
178
+
179
+ try:
180
+ r = requests.get(CWA_LOCAL_EQ_API, params=params, timeout=15)
181
+ r.raise_for_status()
182
+ data = r.json()
183
 
184
+ earthquakes = data.get("records", {}).get("Earthquake", [])
185
+ if not earthquakes:
186
+ msg = f"✅ 在「{area_name}」" if area_name else "✅ 台灣"
187
+ return f"{msg}近期沒有小區域有感地震報告。"
188
 
189
+ lines = [title, "-" * 20]
190
+ for eq in earthquakes:
191
+ info = eq.get("earthquakeInfo", {})
192
+ epi = info.get("epicenter", {})
193
+ mag = info.get("magnitude", {})
194
+ depth = info.get("depth", {})
195
+
196
+ intensity_areas = eq.get("intensity", {}).get("shakingArea", [])
197
+ area_strs = [f"{area.get('areaDesc')} {area.get('areaIntensity')}級" for area in intensity_areas if area.get("areaIntensity") and float(area.get("areaIntensity", 0)) > 0]
198
+ intensity_str = "、".join(area_strs) if area_strs else "無具體震度回報"
199
+
200
+ lines.append(
201
+ f"報告: {eq.get('reportContent', '—')}\n"
202
+ f"時間: {info.get('originTime', '—')}\n"
203
+ f"地點: {epi.get('location', '—')}\n"
204
+ f"規模: M{mag.get('magnitudeValue', '—')} | 深度: {depth.get('value', '—')} km\n"
205
+ f"主要影響區域: {intensity_str}"
206
+ )
207
+ return "\n\n".join(lines)
208
+
209
  except Exception as e:
210
+ return f"❌ 小區域地震查詢失敗:{e}"