Spaces:
Sleeping
Sleeping
| # news_service.py | |
| import requests | |
| import json | |
| from datetime import datetime | |
| # 從 config.py 匯入 API URL | |
| from config 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}" |