-
Notifications
You must be signed in to change notification settings - Fork 986
/
Copy pathbook.py
44 lines (37 loc) · 1.74 KB
/
book.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import requests
import requests_cache
import config
import os
from html2text import html2text
from xml.etree import ElementTree
from templates.button import *
from error_msg import QUERY_ERROR, EXAMPLE_BOOKS
GOODREADS_ACCESS_TOKEN = os.environ.get('GOODREADS_ACCESS_TOKEN', config.GOODREADS_ACCESS_TOKEN)
def process(input, entities):
output = {}
try:
book_title = entities['book'][0]['value']
with requests_cache.enabled('book_cache', backend='sqlite', expire_after=86400):
response = requests.get('https://www.goodreads.com/book/title.xml?key=' + GOODREADS_ACCESS_TOKEN + '&title=' + book_title)
data = ElementTree.fromstring(response.content)
book_node = data.find('book')
author = book_node.find('authors').find('author').find('name').text
title = book_node.find('title').text
description = html2text(book_node.find('description').text)
average_rating = book_node.find('average_rating').text
link = book_node.find('link').text
goodreads_attribution = '- Powered by Goodreads'
template = TextTemplate()
template.set_text('Title: ' + title + '\nAuthor: ' + author + '\nDescription: ' + description)
template.set_post_text('\nAverage Rating: ' + average_rating + ' / 5' + '\n' + goodreads_attribution)
text = template.get_text()
template = ButtonTemplate(text)
template.add_web_url('Goodreads Link', link)
output['input'] = input
output['output'] = template.get_message()
output['success'] = True
except:
error_message = QUERY_ERROR.format('books') + EXAMPLE_BOOKS
output['error_msg'] = TextTemplate(error_message).get_message()
output['success'] = False
return output