File size: 2,690 Bytes
3aab70e
 
 
 
cc337b3
 
3aab70e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# news_service.py
import requests
import json
from datetime import datetime
# ✨ CORRECTED IMPORT
from config.settings import PTS_NEWS_API

def fetch_today_news() -> str:
    """
    從公視新聞網 API 擷取今日新聞並格式化為易於閱讀的文字訊息。
    """
    try:
        # 發送 API 請求
        response = requests.get(PTS_NEWS_API, timeout=20)
        response.raise_for_status()  # 確保請求成功

        # 解析 JSON 回應
        data = response.json()
        
        source = data.get("source", "未知來源")
        last_updated_raw = data.get("last_updated")

        # 格式化資料更新時間
        if last_updated_raw:
            try:
                # 處理可能包含時區資訊的 ISO 格式時間
                last_updated_dt = datetime.fromisoformat(last_updated_raw.replace("Z", "+00:00"))
                last_updated_str = last_updated_dt.strftime('%Y-%m-%d %H:%M')
            except (ValueError, TypeError):
                last_updated_str = str(last_updated_raw)
        else:
            last_updated_str = "未知"
            
        # 建立訊息標頭
        lines = [
            f"📰 今日新聞摘要 ({source})",
            f"   (資料更新: {last_updated_str})",
            "─" * 25
        ]

        articles = data.get("articles", [])
        if not articles:
            lines.append("\nℹ️ 目前沒有可顯示的新聞。")
            return "\n".join(lines)
            
        # 逐條解析並格式化新聞
        for i, article in enumerate(articles[:10]): # 最多顯示 10 則新聞
            title = article.get("title", "無標題").strip()
            link = article.get("link", "#")
            summary = article.get("summary", "無摘要。").strip()

            # 組合單條新聞訊息
            article_lines = [
                f"📌 {title}",
                f"📝 摘要: {summary}",
                f"🔗 閱讀全文: {link}"
            ]
            
            lines.append("\n".join(article_lines))
            
            # 在新聞之間加入分隔線
            if i < len(articles) - 1:
                lines.append("-" * 15)

        return "\n\n".join(lines)

    except requests.exceptions.Timeout:
        return "❌ 新聞查詢失敗:連線超時。"
    except requests.exceptions.RequestException as e:
        return f"❌ 新聞查詢失敗:網路連線錯誤。\n錯誤訊息:{e}"
    except json.JSONDecodeError:
        return "❌ 新聞查詢失敗:無法解析伺服器回傳的資料格式。"
    except Exception as e:
        return f"❌ 新聞查詢失敗:發生未預期的錯誤。\n錯誤訊息:{e}"