From 8c9ab4439487e1a9e5ff1da59c7d47e13f3b5cf9 Mon Sep 17 00:00:00 2001 From: kevincaires Date: Tue, 30 Aug 2022 01:44:39 -0300 Subject: [PATCH] ADD command to get news from google API. --- utils/commands.py | 20 ++++++++++++++++++++ utils/news_paper.py | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 utils/news_paper.py diff --git a/utils/commands.py b/utils/commands.py index ca07fd0..60a5c3e 100644 --- a/utils/commands.py +++ b/utils/commands.py @@ -2,6 +2,7 @@ Bot commands. """ import logging +from datetime import datetime from random import choice from discord import Embed, Intents @@ -11,6 +12,7 @@ from settings.config import IMAGE_TYPES, OW_API_CONFIG, PERMISSIONS from utils.database import (count_quotes, get_by_id, get_quote_contains, get_quotes, remove_quote, set_quote) from utils.machine_monitor import Monitor +from utils.news_paper import News from utils.tools import kbytes_to_gbytes from utils.weather import displayweather, getweatherdata @@ -308,3 +310,21 @@ async def machine_info(bot: object, *args: str) -> str: await bot.send(f'**`{io}`**', embed=embed) return + + +@client.command(aliases=['nw']) +async def news(bot: object) -> None: + f""" + Return some news from Google. + """ + _news = News(quantity=2) + news = _news.news() + embed = Embed(type='rich') + + for new in news: + dt = datetime.fromisoformat(new['publishedAt']) + embed.add_field(name='Published at', value=dt.date().isoformat(), inline=False) + embed.add_field(name='link', value=new['url'], inline=False) + embed.add_field(name=new['title'], value=new['description'], inline=False) + embed.add_field(name='Img', value=new['urlToImage']) + await bot.send(f'**`{new["source"]["name"]}`**', embed=embed) diff --git a/utils/news_paper.py b/utils/news_paper.py new file mode 100644 index 0000000..db6258b --- /dev/null +++ b/utils/news_paper.py @@ -0,0 +1,39 @@ +import logging +import requests +from settings.config import GOOGLE_NEWS + +logger = logging.getLogger(__name__) + + +class News: + """ + Get the information in IBGE API. + """ + _url = f'{GOOGLE_NEWS["url"]}top-headlines?'\ + f'sources={GOOGLE_NEWS["source"]}'\ + f'&apiKey={GOOGLE_NEWS["token"]}' + + def __init__(self, quantity: int=5) -> None: + """ + Constructor. + """ + self.quantity = quantity + + def _get_and_resolve_news(self) -> list: + """ + Get the information based in self.quantity attribute. + """ + _response = requests.get(url=self._url) + content, status = _response.json(), _response.status_code + + if not status == 200: + logger.error(content) + raise Exception(content) + + return content['articles'][:self.quantity] + + def news(self) -> list: + """ + Get news in target based. + """ + return self._get_and_resolve_news()