cwadayi commited on
Commit
93b40f2
·
verified ·
1 Parent(s): d761501

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -10
app.py CHANGED
@@ -23,10 +23,9 @@ configuration = Configuration(access_token=CHANNEL_ACCESS_TOKEN)
23
  handler = WebhookHandler(CHANNEL_SECRET)
24
 
25
 
26
- # --- ✨✨✨ 新增的歡迎頁面路由 ✨✨✨ ---
27
  @app.route("/", methods=['GET'])
28
  def home():
29
- # 當有人用瀏覽器訪問根網址時,回傳這段 HTML 訊息
30
  return """
31
  <html>
32
  <head>
@@ -49,11 +48,11 @@ def home():
49
  </html>
50
  """
51
 
52
- # --- 地震查詢核心邏輯 (與之前相同) ---
53
  USGS_API_BASE_URL = "https://earthquake.usgs.gov/fdsnws/event/1/query"
54
 
55
  def fetch_earthquake_data_for_line():
56
- """查詢過去 24 小時內規模 5.0 以上的地震,並回傳格式化的文字。"""
57
  now = datetime.now()
58
  yesterday = now - timedelta(days=1)
59
 
@@ -92,7 +91,63 @@ def fetch_earthquake_data_for_line():
92
  except Exception as e:
93
  return f"❌ 處理資料時發生未知錯誤: {e}"
94
 
95
- # --- Flask Webhook 路由 (與之前相同) ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  @app.route("/callback", methods=['POST'])
97
  def callback():
98
  signature = request.headers['X-Line-Signature']
@@ -106,18 +161,21 @@ def callback():
106
  abort(400)
107
  return 'OK'
108
 
109
- # --- LINE 訊息處理 (與之前相同) ---
 
110
  @handler.add(MessageEvent, message=TextMessageContent)
111
  def handle_message(event):
112
- user_message = event.message.text
113
  reply_text = ""
114
 
115
- if "地震" in user_message or "quake" in user_message.lower():
 
 
116
  reply_text = fetch_earthquake_data_for_line()
117
  elif "你好" in user_message or "hi" in user_message.lower():
118
- reply_text = "👋 你好!我是地震查詢機器人,試著傳送「地震」來查詢最新資訊吧!"
119
  else:
120
- return
121
 
122
  with ApiClient(configuration) as api_client:
123
  line_bot_api = MessagingApi(api_client)
 
23
  handler = WebhookHandler(CHANNEL_SECRET)
24
 
25
 
26
+ # --- 歡迎頁面路由 ---
27
  @app.route("/", methods=['GET'])
28
  def home():
 
29
  return """
30
  <html>
31
  <head>
 
48
  </html>
49
  """
50
 
51
+ # --- 地震查詢核心邏輯 ---
52
  USGS_API_BASE_URL = "https://earthquake.usgs.gov/fdsnws/event/1/query"
53
 
54
  def fetch_earthquake_data_for_line():
55
+ """查詢過去 24 小時內全球規模 5.0 以上的地震。"""
56
  now = datetime.now()
57
  yesterday = now - timedelta(days=1)
58
 
 
91
  except Exception as e:
92
  return f"❌ 處理資料時發生未知錯誤: {e}"
93
 
94
+
95
+ # --- 「臺灣地震」查詢函式 (已更新座標) ---
96
+ def fetch_taiwan_earthquake_data():
97
+ """查詢今年以來,台灣地區規模 5.0 以上的地震。"""
98
+ now = datetime.now()
99
+ start_of_year = now.replace(month=1, day=1).strftime('%Y-%m-%d')
100
+ today_str = now.strftime('%Y-%m-%d')
101
+
102
+ params = {
103
+ "format": "geojson",
104
+ "starttime": start_of_year,
105
+ "endtime": today_str,
106
+ "minmagnitude": 5.0,
107
+ # --- ✨✨✨ 座標已根據您的要求更新 ✨✨✨ ---
108
+ "minlatitude": 21,
109
+ "maxlatitude": 26,
110
+ "minlongitude": 119,
111
+ "maxlongitude": 123,
112
+ # --- ------------------------------------ ---
113
+ "limit": 100,
114
+ "orderby": "time"
115
+ }
116
+
117
+ try:
118
+ response = requests.get(USGS_API_BASE_URL, params=params, timeout=20)
119
+ response.raise_for_status()
120
+ data = response.json()
121
+
122
+ features = data.get('features', [])
123
+ count = len(features)
124
+
125
+ if not features:
126
+ return f"✅ 今年 ({now.year}年) 以來,在您指定的範圍內尚無規模 5.0 以上的顯著地震紀錄。"
127
+
128
+ reply_text = f"🇹🇼 今年 ({now.year}年) 台灣區域顯著地震 (M≥5.0),共 {count} 筆:\n{'-'*20}\n"
129
+
130
+ for feature in features:
131
+ prop = feature['properties']
132
+ mag = prop['mag']
133
+ place = prop['place']
134
+ event_time_utc = datetime.fromtimestamp(prop['time'] / 1000)
135
+ time_str = event_time_utc.strftime('%Y-%m-%d %H:%M')
136
+
137
+ reply_text += f"震級: {mag:.1f} | 時間: {time_str} (UTC)\n地點: {place}\n\n"
138
+
139
+ if len(reply_text) > 4800:
140
+ reply_text = reply_text[:4800] + "\n... (資料過多,僅顯示部分)"
141
+
142
+ return reply_text.strip()
143
+
144
+ except requests.exceptions.RequestException as e:
145
+ return f"❌ 查詢失敗,無法連接到 USGS 伺服器: {e}"
146
+ except Exception as e:
147
+ return f"❌ 處理資料時發生未知錯誤: {e}"
148
+
149
+
150
+ # --- Flask Webhook 路由 ---
151
  @app.route("/callback", methods=['POST'])
152
  def callback():
153
  signature = request.headers['X-Line-Signature']
 
161
  abort(400)
162
  return 'OK'
163
 
164
+
165
+ # --- LINE 訊息處理 ---
166
  @handler.add(MessageEvent, message=TextMessageContent)
167
  def handle_message(event):
168
+ user_message = event.message.text.strip()
169
  reply_text = ""
170
 
171
+ if "臺灣地震" in user_message or "台灣地震" in user_message:
172
+ reply_text = fetch_taiwan_earthquake_data()
173
+ elif "地震" in user_message or "quake" in user_message.lower():
174
  reply_text = fetch_earthquake_data_for_line()
175
  elif "你好" in user_message or "hi" in user_message.lower():
176
+ reply_text = "👋 你好!我是地震查詢機器人。\n試著傳送以下指令:\n\n- 地震 (查詢全球近24小時強震)\n- 臺灣地震 (查詢今年台灣強震)"
177
  else:
178
+ return
179
 
180
  with ApiClient(configuration) as api_client:
181
  line_bot_api = MessagingApi(api_client)