Skip to content

Commit c637142

Browse files
author
Foxlet
committed
books.py - Find Books on Google Books
1 parent e2a0868 commit c637142

1 file changed

Lines changed: 63 additions & 0 deletions

File tree

plugins/books.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import requests
2+
import json
3+
4+
from cloudbot import hook
5+
from cloudbot.util import formatting
6+
7+
base_url = 'https://www.googleapis.com/books/v1/'
8+
book_search_api = base_url + 'volumes?'
9+
10+
11+
# shrt by petermanser - https://github.com/petermanser/shrt/blob/master/shrt.py
12+
def shrt(url):
13+
r = requests.post('https://www.googleapis.com/urlshortener/v1/url',
14+
data=json.dumps({"longUrl": url}),
15+
headers={'content-type': 'application/json'})
16+
17+
content = json.loads(r.content.decode("UTF-8"))
18+
if r.status_code == 200:
19+
return content['id']
20+
else:
21+
return "%s: %s" % (content['code'], content['message'])
22+
23+
24+
@hook.onload()
25+
def load_key(bot):
26+
global dev_key
27+
dev_key = bot.config.get("api_keys", {}).get("google_dev_key")
28+
29+
30+
@hook.command("books", "gbooks")
31+
def books(text):
32+
"""books <query> -- Searches Google Books for <query>."""
33+
json = requests.get(book_search_api, params={"q": text, "key": dev_key}).json()
34+
35+
if 'error' in json:
36+
return 'Error performing search.'
37+
38+
if json['totalItems'] == 0:
39+
return 'No results found.'
40+
41+
book = json['items'][0]['volumeInfo']
42+
title = book['title']
43+
author = book['authors'][0]
44+
45+
try:
46+
description = formatting.truncate_str(book['description'], 130)
47+
except KeyError:
48+
description = "No description available."
49+
50+
try:
51+
year = book['publishedDate'][:4]
52+
except KeyError:
53+
year = "No Year"
54+
55+
try:
56+
page_count = book['pageCount']
57+
pages = ' - \x02{:,}\x02 page{}'.format(page_count, "s"[page_count == 1:])
58+
except KeyError:
59+
pages = ''
60+
61+
link = shrt(book['infoLink'])
62+
63+
return "\x02{}\x02 by \x02{}\x02 ({}){} - {} - {}".format(title, author, year, pages, description, link)

0 commit comments

Comments
 (0)