TelegramAktienBot/telegram_bot/news/news_fetcher.py

54 lines
1.3 KiB
Python
Raw Normal View History

2022-03-15 08:05:28 +00:00
"""
script for news fetching (by keywords)
"""
__author__ = "Florian Kellermann, Linus Eickhoff"
__date__ = "15.03.2022"
__version__ = "0.0.1"
2022-03-15 09:39:29 +00:00
__license__ = "None"
import sys
2022-03-15 13:01:33 +00:00
import os
import json
2022-03-15 13:01:33 +00:00
from newsapi import NewsApiClient
from dotenv import load_dotenv
load_dotenv()
2022-03-15 10:27:54 +00:00
# Init
2022-03-15 13:01:33 +00:00
newsapi = NewsApiClient(api_key=os.getenv('NEWS_API_KEY'))
2022-03-15 10:27:54 +00:00
def get_top_news_by_keyword(keyword):
2022-03-15 13:43:05 +00:00
"""get top news to keyword
Args:
keyword (String): keyword for search
Returns:
JSON/dict: dict containing articles
"""
2022-03-16 11:58:58 +00:00
top_headlines = newsapi.get_top_headlines(q=keyword, sources='bbc-news,the-verge,cnn,buzzfeed,fox', language='en')
return top_headlines
def format_article(article):
2022-03-15 13:43:05 +00:00
"""format article for messaging (using markdown syntax)
Args:
article (dict): article to format for messaging
Returns:
String: formatted article
"""
sourcename = article["source"]["name"]
headline = article["title"]
url = article["url"]
2022-03-15 13:24:11 +00:00
formatted_article = f"_{sourcename}_\n*{headline}*\n\n{url}"
return formatted_article
2022-03-15 09:39:29 +00:00
if __name__ == '__main__':
2022-03-15 13:24:11 +00:00
2022-03-15 13:01:33 +00:00
print("fetching top news by keyword business...")
articles = get_top_news_by_keyword("business")
2022-03-15 13:01:33 +00:00
formatted_article = format_article(articles["articles"][0])
print(formatted_article)