Skip to content

Instantly share code, notes, and snippets.

@CubeVic
Last active May 13, 2022 08:09
Show Gist options
  • Save CubeVic/96d29109c8aee6c38834f5570d103ef0 to your computer and use it in GitHub Desktop.
Save CubeVic/96d29109c8aee6c38834f5570d103ef0 to your computer and use it in GitHub Desktop.
[Medium Article: News aggregator with Python and NewsAPI.] This code represent the TelegramBot. This bot is use to interact with the news aggregator. This Gist is calling the module "news" and the class "Aggregator", they can be found here https://gist.github.com/CubeVic/fd472c5acc15e2c084b6ae480f98dfb4
from news import Aggregator
import os
import datetime
import telebot
from telebot import types
import logging
def configure_loger():
"""Configure Logger"""
global logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
stream_formatter = logging.Formatter(
fmt='%(asctime)s - %(message)s',
datefmt='%d-%b-%y %H:%M:%S')
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(stream_formatter)
logger.addHandler(stream_handler)
bot = telebot.TeleBot(token=os.environ['BOTAPIKEY'])
# TODO: Allow Client to change time frame.
today = datetime.date.today()
older = today - datetime.timedelta(days=4)
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
"""bot start function"""
bot.reply_to(message, "Type 'News' follow by a key work, you will get back a list of the latest 3 news")
# validate the keyword, call get_news just if the message has news follow by the keywords
def verify_key(message):
"""Verify the message start with News follow by a keyword"""
logger.debug(msg=f'string receive: {message.text}')
text = message.text.split()
tag, key_word = text[0].lower(), " ".join(text[1:])
if tag in 'news' and len(key_word) > 1:
return True
def bot_create_msg(message, news):
"""separate the news articles on individual message bubbles"""
for new in news:
logger.debug(msg=f'Sending message with {new}')
bot.send_message(message.chat.id, new, disable_web_page_preview=True)
@bot.message_handler(func=verify_key)
def bot_get_news(message):
"""Get the news """
# get the topics
text = message.text.split()
_, key_words = text[0], text[1:]
# call the object aggregator that contain the topics and the news
news = Aggregator(
topics_of_interest=key_words,
newsapi_key=os.environ['NEWS_API'],
from_time=older,
to_time=today
)
# get the articles
msg = news.get_news()
logger.debug(msg=f"getting the news: \n{msg}")
for topics, news in msg.items():
bot.send_message(message.chat.id, topics.replace(',', '').upper())
bot_create_msg(message=message, news=news)
def main():
configure_loger()
# keep the bot running
bot.infinity_polling()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment