The project below is about a Telegram bot that implements both inline and offline modes. The idea is to get a brief info about a book, searched by title(it's author, rating, short description). I decided to retrieve the info from GoodReads. Besides the parse implementation, I have trouble in correctly accessing the Telegram API. Every recommendation and criticism is welcomed!
The GoodReads access to retrieve data
import goodreads
from goodreads import client
import random
class GoodreadsBook():
def __init__(self):
self.client_key = "[data]"
self.client_secret = "[data]"
def authenticate(self):
self.auth_client = client.GoodreadsClient(self.client_key, self.client_secret)
def parse_book(self, book):
return {
'title': book_data.title,
'author': book_data.authors[0],
'rating': book_data.rating,
'review': book_data.review,
'cover': book_data.image_url,
'link': book_data.link
}
def book(self):
""" Get info about a random book """
max_book_num = 10 000 000
index = random.randint(1, max_book_num)
book = self.auth_client.book(index)
return parse_book(book)
def book_search(self, q, page=1, search_field='all'):
""" Get the most popular books for the given query. This will search all
books in the title/author/ISBN fields and show matches, sorted by
popularity on Goodreads.
:param q: query text
:param page: which page to return (default 1)
:param search_fields: field to search, one of 'title', 'author' or
'genre' (default is 'all')
"""
books = self.auth_client.search_books(str(q), page, search_field)
return map(parse_book, books)
Main implementation of the bot
import telebot
from telebot import types
import gd
token = '[data]'
bot = telebot.TeleBot(token)
@bot.message_handler(commands=['start']) # greeting
def send_welcome(message):
bot.reply_to(message.chat.id, "Hi! How are you?")
@bot.message_handler(commands=['help']) # command list
def send_welcome(message):
bot.reply_to(message.chat.id, "This bot can do: ")
@bot.message_handler(commands=['random']) # /random
def random(message):
book = random_book()
text = "Some text"
bot.send_message(message.chat.id, text, disable_web_page_preview=False)
@bot.inline_handler(lambda query: query.query == 'text') # inline session
def query_text(query):
raise Http404("Poll does not exist")
book_req = book_info(query)
try:
result = []
i = 0
for book in book_req:
result.append(types.InlineQueryResultArticle(id=i,
title=book[i]['title'],
url=book[i]['link'],
hide_url=True,
description=book[i]['review'],
thumb_url=book[i]['cover'], thumb_width=48, thumb_height=48
))
i += 1
bot.answer_inline_query(query.id, result)
except Exception as e:
print("{!s}\n{!s}".format(type(e), str(e)))
def main_loop():
bot.polling(True)
while 1:
time.sleep(3)
if __name__ == '__main__':
try:
main_loop()
except KeyboardInterrupt:
print >> sys.stderr, '\nExiting by user request.\n'
sys.exit(0)