-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot.py
191 lines (167 loc) · 6.45 KB
/
bot.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import logging
import os
import random
from telegram import (
CallbackQuery,
ForceReply,
InlineKeyboardButton,
InlineKeyboardMarkup,
InlineQueryResultArticle,
InlineQueryResultPhoto,
InputTextMessageContent,
ParseMode,
Update,
)
from telegram.ext import (
CallbackContext,
CallbackQueryHandler,
CommandHandler,
Filters,
InlineQueryHandler,
MessageHandler,
Updater,
)
from scraper import scrape_zlib
TOKEN = os.environ.get("TELEGRAM_TOKEN")
updater = Updater(token=TOKEN, use_context=True)
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.DEBUG
)
logger = logging.getLogger(__name__)
PORT = os.environ.get("PORT")
WELCOME_TEXT = "Hey *{}*!🙃\n\nEasily source for books 📚 at your comfort 🛀. \n\n🏃♂️🏃♂️🏃♂ Byeee! Start searching"
BOOK_RESPONSE = "`Title: {}`\n\n`Author(s): {}`\n\n`Size: {}`"
def start(update: Update, context: CallbackContext):
update.message.reply_text(
text=WELCOME_TEXT.format(update.effective_user.first_name),
parse_mode=ParseMode.MARKDOWN,
)
def search(update: Update, context: CallbackContext):
update.message.reply_text(
reply_markup=ForceReply(selective=True),
text="What book do you want to search for 🤔?",
)
# Send search confirmation
def echo(update: Update, context: CallbackContext):
update.message.reply_text(
text="Search for *{}* 🧐?".format(update.message.text),
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton("Yes", callback_data="1, {}".format(update.message.text)),
InlineKeyboardButton("No", callback_data="0"),
],
]
),
parse_mode=ParseMode.MARKDOWN,
)
# Handle search confirmation
def button(update: Update, context: CallbackContext):
query: CallbackQuery = update.callback_query
query.answer()
if query.data != "0":
try:
results = scrape_zlib(query.data.split(", ")[-1].strip())
except:
query.edit_message_text(text="Ooops! An error occurred ☹.️")
else:
if len(results) == 0:
query.edit_message_text(
text="No result(s) found for *{}* 😔".format(
query.data.split(", ")[-1].strip()
),
parse_mode=ParseMode.MARKDOWN,
)
else:
query.edit_message_text(
text="🤗 `Result(s)` `for` *{}*".format(query.data.split(", ")[-1].strip()),
parse_mode=ParseMode.MARKDOWN,
)
# add pagination later
for item in results[:15]:
context.bot.send_photo(
chat_id=update.effective_chat.id,
photo=item["image"],
caption=BOOK_RESPONSE.format(item["title"], item["authors"], item["size"]),
reply_markup=InlineKeyboardMarkup(
[[InlineKeyboardButton("More Info", url=item["url"])]]
),
parse_mode=ParseMode.MARKDOWN,
)
else:
query.edit_message_text(text="Okay 😑.")
# inline search
def inline_search(update: Update, context: CallbackContext):
query_response = []
query = update.inline_query.query
try:
results = scrape_zlib(query)
except:
update.inline_query.answer(
[
InlineQueryResultArticle(
id=str(random.randint(1, 100)),
title="error",
description="Ooops! An error occurred ☹.️",
input_message_content=InputTextMessageContent("Ooops! An error occurred ☹.️"),
)
]
)
else:
if len(results) == 0:
update.inline_query.answer(
[
InlineQueryResultArticle(
id=str(random.randint(1, 100)),
title="error",
description="No result(s) found for *{}* 😔".format(query),
input_message_content=InputTextMessageContent(
"No result(s) found for *{}* 😔".format(query),
parse_mode=ParseMode.MARKDOWN,
),
)
]
)
else:
for index, item in enumerate(results):
query_response.append(
InlineQueryResultPhoto(
str(index),
photo_url=item["image"],
thumb_url=item["image"],
caption=BOOK_RESPONSE.format(item["title"], item["authors"], item["size"]),
parse_mode=ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup(
[[InlineKeyboardButton("More Info", url=item["url"])]]
),
)
)
update.inline_query.answer(query_response)
# handle unknown commands
def unknown(update: Update, context: CallbackContext):
update.message.reply_text(text="Please type a language I understand 😪.")
def contact(update: Update, context: CallbackContext):
context.bot.send_message(
update.effective_chat.id,
"Reach me on:",
reply_markup=InlineKeyboardMarkup(
[
[InlineKeyboardButton("Twitter", url="https://twitter.com/_peratzatha")],
]
),
)
# error handler
def error(update, context):
logger.warning('Update "%s" caused error "%s"', update, context.error)
updater.dispatcher.add_handler(CommandHandler("start", start))
updater.dispatcher.add_handler(CommandHandler("search", search))
updater.dispatcher.add_handler(CommandHandler("contact", contact))
updater.dispatcher.add_handler(CallbackQueryHandler(button))
updater.dispatcher.add_handler(InlineQueryHandler(inline_search))
updater.dispatcher.add_handler(MessageHandler(Filters.text & (~Filters.command), echo))
updater.dispatcher.add_handler(MessageHandler(Filters.command, unknown))
updater.dispatcher.add_error_handler(error)
if __name__ == "__main__":
updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN)
updater.bot.setWebhook(f"https://bookilo.herokuapp.com/{TOKEN}")
updater.idle()