-
Notifications
You must be signed in to change notification settings - Fork 2
/
kitaab_bot.py
200 lines (164 loc) · 7.62 KB
/
kitaab_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
192
193
194
195
196
197
198
199
200
import time
import telepot
from urllib2 import *
from bs4 import BeautifulSoup
from pprint import pprint
import pymysql
import scrape
import os.path
import json
#Required Edit 1
#add your custom download path below in the quotes('')
DOWNLOAD_PATH = ' '
#Required Edit 2
#add your custom Log path below in the quotes('')
LOG_PATH = ' '
welcome_msg = 'Hey there %s!!\nTo start using kitaab bot (the book bot),\
all you have to do is send the name of the book and it will\
revert you with choices e.g., you send programming python and it will\
respond with 125 : Programming python.\nThe next\
step is to send /book 125 and it will automatically download and send\
you the book.\n.If the bot is not responding, it may be due to internet\
fault in my laptop, be patient and wait for the reply before sending a new message.\
\nFor any help, send /help\nEnjoy ;)'
help_msg = 'Just type the book name as accurate as possible\
to get best results. Maximum size of book telegram supports\
as of now is 50mb so some pdfs can\'t be sent. After typing the book\
name you will get response of the form number : name. Last step is to\
send /book <number> without brackets with number selected from results.'
BOOK_DETAILS_LINK = 'http://it-ebooks.info/book/%s/'
def search_name(book_name):
conn = pymysql.connect(host='127.0.0.1',
unix_socket='/var/run/mysqld/mysqld.sock',
user='root',
passwd='password',
db='mysql')
cur = conn.cursor()
cur.execute("USE books;")
query_name = '"' + '%' + book_name + '%' + '";'
cur.execute('SELECT * FROM names where name like ' + query_name)
result = cur.fetchall()
cur.close()
conn.close()
return result
def send_list(msg, book_list):
content_type, chat_type, chat_id = telepot.glance(msg)
user_name = msg['from']['first_name']
string = ''
for number, name in book_list:
string += number + ' : ' + name + '\n\n'
bot.sendMessage(chat_id, string)
print('list sent to ' + user_name + '\n')
save_user_logs(msg, 'list sent to ' + user_name)
def get_book_name(number):
conn = pymysql.connect(host='127.0.0.1',
unix_socket='/var/run/mysqld/mysqld.sock',
user='root',
passwd='password',
db='mysql')
cur = conn.cursor()
cur.execute("USE books;")
query_name = number + ';'
cur.execute('SELECT name FROM names where number = ' + query_name)
result = cur.fetchall()
cur.close()
conn.close()
return result
def send_book(msg, name):
content_type, chat_type, chat_id = telepot.glance(msg)
user_name = msg['from']['first_name']
bot.sendMessage(chat_id, 'Your book has been downloaded ' + user_name + ', sending it to you now....')
bot.sendChatAction(chat_id, 'upload_document')
book = open(DOWNLOAD_PATH + name + '.pdf', 'rb')
bot.sendMessage(chat_id, 'Started to upload the book, it may take some time')
bot.sendDocument(chat_id, book)
print('book sent to ' + user_name)
def save_user_logs(msg, message):
user_name = msg['from']['first_name']
final_message = json.dumps(message, sort_keys=True, indent=4, separators=(',', ': '))
with open(LOG_PATH + user_name + '.txt', 'a') as text_file:
text_file.write(final_message)
text_file.write('\n')
#Required Edit 3
#Replace the below path with your path of log file
with open(LOG_PATH +'/logs.txt', 'a') as log_file:
log_file.write(final_message)
log_file.write('\n')
def scrape_book_details(number):
html = urlopen(BOOK_DETAILS_LINK % number)
bsObj = BeautifulSoup(html.read(), 'html.parser')
book_name = bsObj.find("h1", {"itemprop" : "name"}).get_text()
book_publisher = bsObj.find("a", {"itemprop" : "publisher"}).get_text()
book_author = bsObj.find("b", {"itemprop" : "author"}).get_text()
book_date = bsObj.find("b", {"itemprop" : "datePublished"}).get_text()
book_pages = bsObj.find("b", {"itemprop" : "numberOfPages"}).get_text()
size_table = bsObj.find("b", {"itemprop" : "bookFormat"}).parent.parent.parent
table_rows = size_table.findAll('tr')
description = "Book name : " + book_name + "\nPublisher : " + book_publisher + \
"\nAuthor : " + book_author + "\nDate : " + book_date + "\nPages : " + book_pages + \
"\n" + table_rows[7].get_text() + "\nBuy original from : " + table_rows[12].a['href']
return description
def handle(msg):
content_type, chat_type, chat_id = telepot.glance(msg)
user_name = msg['from']['first_name']
if content_type == 'text':
message = msg['text']
pprint(msg)
save_user_logs(msg, msg)
if message == '/start':
bot.sendMessage(chat_id, welcome_msg % user_name)
save_user_logs(msg, welcome_msg % user_name)
elif message == '/help':
bot.sendMessage(chat_id, help_msg)
save_user_logs(msg, help_msg)
elif message.split(' ')[0] == '/book':
number = str(message.split(' ')[1])
book_name = get_book_name(number)[0][0]
book_description = scrape_book_details(number)
bot.sendMessage(chat_id, book_description)
save_user_logs(msg, book_description)
print(book_description)
#Required Edit 4
#add your pre existing book's folder path below in the quotes (' ')
if os.path.isfile(DOWNLOAD_PATH + book_name + '.pdf'):
bot.sendMessage(chat_id, "Downloading your book, it may take some time\nWait for the bot to send this book before requesting any other book.")
save_user_logs(msg, 'book already existed')
send_book(msg, book_name)
else:
save_user_logs(msg, 'downloading the book')
bot.sendMessage(chat_id, "Downloading your book, it may take some time.\nWait for the bot to send this book before requesting any other book.")
scrape.download_book('http://it-ebooks.info/book/' + number, book_name)
send_book(msg, book_name)
else:
try:
book_list = search_name(message.lower())
except UnicodeEncodeError as e:
bot.sendMessage(chat_id, "Emojis and special characters are not supported.")
try:
send_list(msg, book_list)
except telepot.TelegramError as e:
if e[0] == 'Bad Request: Message text is empty':
bot.sendMessage(chat_id, "Book not found. Try changing the keyword")
save_user_logs(msg, "Book not found. Try changing the keyword")
else:
counter = 0
message = ""
for li in book_list:
message += li[0] + ' : ' + li[1] + '\n\n'
counter += 1
if counter >= 50:
bot.sendMessage(chat_id, message)
counter = 0
message = ""
bot.sendMessage(chat_id, "Your keyword maybe too general. Try to be more specific next time.")
save_user_logs(msg, "List sent but the keyword was too general")
print("List sent but the keyword was too general")
else:
bot.sendMessage(chat_id, 'Please send a book name only!!')
save_user_logs(msg, 'Error! user sent some file')
TOKEN = 'add your telegram api token'
bot = telepot.Bot(TOKEN)
bot.message_loop(handle)
print('Listening....')
while 1:
time.sleep(5)