from flask import Flask, request, make_response, jsonify
from requests import get
from bs4 import BeautifulSoup

noticias =[]
app = Flask(__name__)

def coleta_noticias():
    site = get('https://news.google.com/news/rss/headlines/section/topic/TECHNOLOGY?hl=pt-BR')
    soup = BeautifulSoup(site.text, 'html.parser')
    for item in soup.findAll('item')[:7]:
        noticia = item.title.text
        noticia = noticia.rsplit(' - ', 1)
        noticias.append(noticia[0])
        
def formata_ssml(noticias):
    texto_titulo = '<p>'+ 'Últimas Notícias' + '<break time="200ms"/>' + '</p>'
    texto_mensagem = ''
    for noticia in noticias:
        texto_mensagem = texto_mensagem + '<p>' + noticia + '<break time="200ms"/>' + '</p>'
    ssml = '<speak>'+texto_titulo+texto_mensagem+'</speak>'
    return {'fulfillmentText': ssml}

@app.route('/webhook', methods=['POST'])
def webhook(request):
    coleta_noticias()
    return make_response(jsonify(formata_ssml(noticias)))

if __name__ == '__main__':
    app.run()