Skip to content

Instantly share code, notes, and snippets.

@lucaspg96
Created January 24, 2019 17:57
Show Gist options
  • Save lucaspg96/31088332960e7d0822354b1f6be39b5c to your computer and use it in GitHub Desktop.
Save lucaspg96/31088332960e7d0822354b1f6be39b5c to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
from uuid import uuid4
from telegram.utils.helpers import escape_markdown
from telegram import InlineQueryResultArticle, ParseMode, \
InputTextMessageContent
from telegram.ext import Updater, InlineQueryHandler, CommandHandler
import logging
from bs4 import BeautifulSoup
from requests import get
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
def get_comics_rates(name):
url = "https://comicbookroundup.com/search_results.php?f_search={}".format("+".join(name.split()))
response = get(url)
page = BeautifulSoup(response.content, "html.parser")
results = []
for r in page.find_all("tr",{"class": "search_results"}):
try:
review = r.find_all("td",{"class": "rating"})[0].text.replace("\n","")
name = r.find_all("td",{"class": "current"})[0].text
publisher = r.find_all("td",{"class": "publisher"})[0].text
issues = r.find_all("td",{"class": "issues"})[0].text
link = "http://comicbookroundup.com"+r.find_all("a")[0].get("href")
results.append((review,name,publisher,issues, link))
except Exception as e:
pass
return results
def start(bot, update):
"""Send a message when the command /start is issued."""
update.message.reply_text("""
Hi, I'm a bot to search for Comic Books ant its reviews! My reviews come from https://comicbookroundup.com .
If you want to search for some comic book, just type the name and select one of the suggestions!
<b>Remember</b>: I'm a <b>Inline Query Bot</b>, so any search must start with you calling me in a message, like:
{} batman
<b>HINT</b>: if you want the results sort from the best reviews, just finish the message with 'r', like:
{} batman r
""".format(bot.name,bot.name), parse_mode=ParseMode.HTML)
def inlinequery(bot, update):
"""Handle the inline query."""
rate = False
query = update.inline_query.query
if query.endswith(" r"):
query = query[:-2]
rate = True
options = get_comics_rates(query)[:20]
if rate :
options.sort(key=lambda x: float(x[0]), reverse=True)
results = []
for op in options:
txt = "{} - {}".format(op[0], op[1])
content = '<b>{}</b> - <a href="{}">{}</a>'.format(op[0],op[4],op[1])
obj = InlineQueryResultArticle(
id=uuid4(),
title=txt,
input_message_content=InputTextMessageContent(content,parse_mode=ParseMode.HTML))
results.append(obj)
update.inline_query.answer(results)
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
def main():
updater = Updater("TOKEN")
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", start))
dp.add_handler(InlineQueryHandler(inlinequery))
dp.add_error_handler(error)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment