|
| 1 | +import requests |
| 2 | +import config |
| 3 | +import os |
| 4 | +from templates.generic import * |
| 5 | +from templates.text import TextTemplate |
| 6 | + |
| 7 | +NEWS_API_KEY = os.environ.get('NEWS_API_KEY', config.NEWS_API_KEY) |
| 8 | + |
| 9 | +def process(input, entities=None): |
| 10 | + output = {} |
| 11 | + source = 'google-news' |
| 12 | + try: |
| 13 | + r = requests.get('https://newsapi.org/v1/articles?source=' + source + '&apiKey=' + NEWS_API_KEY) |
| 14 | + data = r.json() |
| 15 | + assert(len(data["articles"]) > 0) |
| 16 | + template = GenericTemplate() |
| 17 | + for article in data['articles']: |
| 18 | + title = article['title'] |
| 19 | + description = article['description'] |
| 20 | + url = article['url'] |
| 21 | + buttons = ButtonTemplate() |
| 22 | + buttons.add_web_url('Powered by NewsAPI', 'https://newsapi.org/') |
| 23 | + template.add_element(title=title, item_url=url, subtitle=description, buttons=buttons.get_buttons()) |
| 24 | + output['input'] = input |
| 25 | + output['output'] = template.get_message() |
| 26 | + output['success'] = True |
| 27 | + except: |
| 28 | + error_message = 'I couldn\'t perform that action.' |
| 29 | + error_message += '\nPlease ask me something else, like:' |
| 30 | + error_message += '\n - latest news' |
| 31 | + error_message += '\n - world news' |
| 32 | + error_message += '\n - news' |
| 33 | + output['error_msg'] = TextTemplate(error_message).get_message() |
| 34 | + output['success'] = False |
| 35 | + return output |
0 commit comments