cwadayi commited on
Commit
57beba3
·
verified ·
1 Parent(s): 78b49af

Create news_service.py

Browse files
Files changed (1) hide show
  1. news_service.py +75 -0
news_service.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # news_service.py
2
+ import requests
3
+ import json
4
+ from datetime import datetime
5
+
6
+ # 從 config.py 匯入 API URL
7
+ from config import PTS_NEWS_API
8
+
9
+ def fetch_today_news() -> str:
10
+ """
11
+ 從公視新聞網 API 擷取今日新聞並格式化為易於閱讀的文字訊息。
12
+ """
13
+ try:
14
+ # 發送 API 請求
15
+ response = requests.get(PTS_NEWS_API, timeout=20)
16
+ response.raise_for_status() # 確保請求成功
17
+
18
+ # 解析 JSON 回應
19
+ data = response.json()
20
+
21
+ source = data.get("source", "未知來源")
22
+ last_updated_raw = data.get("last_updated")
23
+
24
+ # 格式化資料更新時間
25
+ if last_updated_raw:
26
+ try:
27
+ # 處理可能包含時區資訊的 ISO 格式時間
28
+ last_updated_dt = datetime.fromisoformat(last_updated_raw.replace("Z", "+00:00"))
29
+ last_updated_str = last_updated_dt.strftime('%Y-%m-%d %H:%M')
30
+ except (ValueError, TypeError):
31
+ last_updated_str = str(last_updated_raw)
32
+ else:
33
+ last_updated_str = "未知"
34
+
35
+ # 建立訊息標頭
36
+ lines = [
37
+ f"📰 今日新聞摘要 ({source})",
38
+ f" (資料更新: {last_updated_str})",
39
+ "─" * 25
40
+ ]
41
+
42
+ articles = data.get("articles", [])
43
+ if not articles:
44
+ lines.append("\nℹ️ 目前沒有可顯示的新聞。")
45
+ return "\n".join(lines)
46
+
47
+ # 逐條解析並格式化新聞
48
+ for i, article in enumerate(articles[:10]): # 最多顯示 10 則新聞
49
+ title = article.get("title", "無標題").strip()
50
+ link = article.get("link", "#")
51
+ summary = article.get("summary", "無摘要。").strip()
52
+
53
+ # 組合單條新聞訊息
54
+ article_lines = [
55
+ f"📌 {title}",
56
+ f"📝 摘要: {summary}",
57
+ f"🔗 閱讀全文: {link}"
58
+ ]
59
+
60
+ lines.append("\n".join(article_lines))
61
+
62
+ # 在新聞之間加入分隔線
63
+ if i < len(articles) - 1:
64
+ lines.append("-" * 15)
65
+
66
+ return "\n\n".join(lines)
67
+
68
+ except requests.exceptions.Timeout:
69
+ return "❌ 新聞查詢失敗:連線超時。"
70
+ except requests.exceptions.RequestException as e:
71
+ return f"❌ 新聞查詢失敗:網路連線錯誤。\n錯誤訊息:{e}"
72
+ except json.JSONDecodeError:
73
+ return "❌ 新聞查詢失敗:無法解析伺服器回傳的資料格式。"
74
+ except Exception as e:
75
+ return f"❌ 新聞查詢失敗:發生未預期的錯誤。\n錯誤訊息:{e}"