|
import json
|
|
import logging
|
|
import time
|
|
import urllib.request
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class NewsFetcher:
|
|
TTL_SECONDS = 1800
|
|
|
|
def __init__(self, news_api: str):
|
|
self.news_api = news_api
|
|
self.articles: list[dict] = []
|
|
self.fetched_at: float = 0.0
|
|
|
|
def fetch(self) -> list[dict]:
|
|
fresh = (
|
|
self.articles and (time.monotonic() - self.fetched_at) < self.TTL_SECONDS
|
|
)
|
|
if fresh:
|
|
return self.articles
|
|
try:
|
|
req = urllib.request.Request(
|
|
self.news_api, headers={"User-Agent": "dpbot/1.0"}
|
|
)
|
|
with urllib.request.urlopen(req, timeout=10) as resp:
|
|
articles = json.loads(resp.read()).get("articles", [])
|
|
if articles:
|
|
self.articles = articles
|
|
self.fetched_at = time.monotonic()
|
|
logger.info("Fetched %d news articles", len(self.articles))
|
|
except Exception as e:
|
|
logger.warning("News fetch failed: %s", e)
|
|
return self.articles
|