forked from slack-samples/bolt-python-news-api-for-slack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharticles.py
97 lines (80 loc) · 2.3 KB
/
articles.py
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import logging
from typing import List
from dataclasses import dataclass
from datetime import datetime
import pytz
import requests
logger = logging.getLogger(__name__)
@dataclass
class Source:
id: str
name: str
@dataclass
class Article:
source: Source
author: str
title: str
description: str
url: str
urlToImage: str
publishedAt: datetime
content: str
def __post_init__(self):
self.publishedAt = datetime.fromisoformat(self.publishedAt[:-1]).replace(
tzinfo=pytz.timezone("UTC")
)
def fetch_articles(
api_key: str, query: str, num_articles: int = 3
) -> List[Article]:
params = {
"apiKey": api_key,
"q": query,
"language": "en",
"pageSize": num_articles,
"sortBy": "publishedAt",
}
url = (
"https://newsapi.org/v2/everything"
if query
else "https://newsapi.org/v2/top-headlines"
)
if query:
# For more complex queries, see the Advanced Search options here: https://newsapi.org/docs/endpoints/everything
params["q"] = query.replace(",", " OR ").replace("、", " OR ")
else:
del params["q"]
response = requests.get(url=url, params=params)
response_body = response.json()
return [Article(**article) for article in response_body.get("articles")]
def format_article(article: Article) -> List[dict]:
blocks = [
{
"type": "header",
"text": {"type": "plain_text", "text": article.title},
},
{
"type": "context",
"elements": [
{
"type": "mrkdwn",
"text": f"⏱ {article.publishedAt.strftime('%Y-%m-%d %H:%M:%S')}",
}
],
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"{article.description[:200]}... <{article.url}|Continue reading...>",
},
"accessory": {
"type": "image",
"image_url": article.urlToImage,
"alt_text": "News article image",
},
},
]
# Remove the image block if there are no images from the News API
if not article.urlToImage:
del blocks[2]["accessory"]
return blocks