Files
server-configs/check_news.py
2026-02-13 22:24:27 +08:00

104 lines
2.9 KiB
Python
Executable File

#!/usr/bin/env python3
"""
全球新闻获取 (NewsAPI)
需要先注册获取 API Key: https://newsapi.org
"""
import requests
import os
from datetime import datetime
# 配置
API_KEY = os.getenv("NEWS_API_KEY", "YOUR_API_KEY_HERE")
BASE_URL = "https://newsapi.org/v2"
def get_top_headlines(category=None, country="us"):
"""获取头条新闻"""
url = f"{BASE_URL}/top-headlines"
params = {
"country": country,
"apiKey": API_KEY
}
if category:
params["category"] = category
try:
response = requests.get(url, params=params, timeout=10)
data = response.json()
if data.get("status") == "ok":
return data.get("articles", [])
else:
print(f"Error: {data.get('message')}")
return []
except Exception as e:
print(f"Request failed: {e}")
return []
def get_everything(query=None, language="en"):
"""搜索新闻"""
url = f"{BASE_URL}/everything"
params = {
"language": language,
"sortBy": "publishedAt",
"apiKey": API_KEY
}
if query:
params["q"] = query
try:
response = requests.get(url, params=params, timeout=10)
data = response.json()
if data.get("status") == "ok":
return data.get("articles", [])
else:
print(f"Error: {data.get('message')}")
return []
except Exception as e:
print(f"Request failed: {e}")
return []
def print_news(articles, title="Top Headlines"):
"""打印新闻"""
print(f"\n{'='*60}")
print(f"📰 {title}")
print(f"{'='*60}")
for i, article in enumerate(articles[:10], 1):
source = article.get("source", {}).get("name", "Unknown")
title = article.get("title", "No title")
url = article.get("url", "")
published = article.get("publishedAt", "")[:10]
print(f"\n{i}. {title}")
print(f" 来源: {source} | 日期: {published}")
print(f" 链接: {url}")
def main():
print(f"\n{'='*60}")
print("📰 全球新闻 (NewsAPI)")
print(f"{'='*60}")
if API_KEY == "YOUR_API_KEY_HERE":
print("\n⚠️ 请设置环境变量 NEWS_API_KEY")
print(" export NEWS_API_KEY='你的API Key'")
print(" 或在 https://newsapi.org 注册获取")
return
# 科技新闻
print("\n🔧 获取科技新闻...")
tech = get_top_headlines(category="technology", country="us")
print_news(tech, "Technology News")
# 商业新闻
print("\n💼 获取商业新闻...")
business = get_top_headlines(category="business", country="us")
print_news(business, "Business News")
# 中国新闻
print("\n🇨🇳 获取中国新闻...")
china = get_everything(query="China", language="zh")
print_news(china, "China News (Chinese)")
if __name__ == "__main__":
main()