-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1287 lines (873 loc) ยท 38.7 KB
/
main.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os, re, datetime, base64
import wget, requests
import psycopg2
import convertapi
from time import sleep
from random import choice
from math import log
import telebot
from telebot import types
from bs4 import BeautifulSoup
# Telegram group id for logging events
# Bot should be admin of the group for this to work
group_id = os.environ.get("GROUP_ID")
# Heroku postgres databse url
database_url = os.environ.get("DATABASE_URL")
# Convertapi secret token
convertapi_secret = os.environ.get("CONVERTAPI_SECRET")
# Webshare rotating username-rotate:password
webshare_user = os.environ.get("WEBSHARE_USER")
# Webshare api secret token
# This is required to get a static ip address
webshare_token = os.environ.get("WEBSHARE_TOKEN")
# Telegram bot token
bot_token = os.environ.get("TELEGRAM_API")
bot = telebot.TeleBot(bot_token, parse_mode="HTML")
header = {
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Language': 'en-IN,en;q=0.9',
'Accept-Encoding': 'gzip, deflate'
}
# Returns user's full name and username
def get_username(message_object):
name = str(message_object.from_user.first_name)
last_name = message_object.from_user.last_name
if last_name:
name += f" {str(last_name)}"
if "<" in name:
name = name.replace("<","<")
username = message_object.from_user.username
if username:
username = "@" + str(username)
else:
username = "None"
return name, username
# Add a user to database
def add(user_id, num_searches, last_message, user_sites, page_num, member_type, date, info):
connection = psycopg2.connect(database_url)
cur = connection.cursor()
cur.execute('''INSERT INTO users (user_id, num_searches, last_message, user_sites, page_num, member_type, date, info) VALUES (%s,%s,%s,%s,%s,%s,%s,%s);''', (user_id, num_searches, last_message, user_sites, page_num, member_type, date, info))
connection.commit()
connection.close()
# Search user data by telegram user_id
def search(user_id):
connection = psycopg2.connect(database_url)
cur = connection.cursor()
cur.execute("SELECT * FROM users WHERE user_id = %s;", (user_id,))
data = cur.fetchall()
connection.close()
num_searches = last_message = user_sites = page_num = member_type = date = info = None
for row in data:
(
num_searches,
last_message,
user_sites,
page_num,
member_type,
date,
info
) = (row[1], row[2], row[3], row[4], row[5], row[6], row[7])
return num_searches, last_message, user_sites, page_num, member_type, date, info
# Update database
def update(user_id, num_searches, last_message, user_sites, page_num, member_type, date, info):
connection = psycopg2.connect(database_url)
cur = connection.cursor()
cur.execute('''UPDATE users SET num_searches = %s, last_message = %s, user_sites = %s, page_num = %s, member_type = %s, date = %s, info = %s WHERE user_id = %s;''', (num_searches, last_message, user_sites, page_num, member_type, date, info, user_id))
connection.commit()
connection.close()
# Returns a list of available books, containing book's
# details as dictionary
def bcc_search(search_query):
# Important
# Host this script on eu-server, else b-ok.global won't work
response = requests.get(
f"https://b-ok.global/s/{search_query}",
headers=header
)
soup = BeautifulSoup(response.content, 'html.parser')
books = soup.find_all('table', class_='resItemTable')
book_data = []
for book in books:
name_header = book.select("h3[itemprop='name']")
link = name_header[0].find('a')
book_name = link.text
book_link = link['href']
prop_year = book.find('div', class_='property_year')
if prop_year:
book_year = prop_year.find('div', class_='property_value').text
else:
book_year = ''
prop_file = book.find('div', class_='property__file')
metadata = prop_file.find('div', class_='property_value')
file_type, file_size = metadata.text.split(',')
file_size = file_size.strip()
author_div = book.find('div', class_='authors')
author_list = author_div.select("a[itemprop='author']")
authors = []
for author in author_list:
authors.append(author.text)
book_data.append({
"book_name": book_name,
"link": book_link,
"authors": authors,
"upload_year": book_year,
"file_format": file_type,
"file_size": file_size
})
return book_data
# Returns a specific book details
# Book link (e.g. /book/5422789/495673) is required as parameter
def bcc_info(book_link):
login = f"http://{webshare_user}@p.webshare.io:80"
webshare = {
"http": login, "https": login
}
# https://3lib.net is global (us, de, spain, brazil) server
# We can use b-ok.global if script is hosted on eu-servers
response = requests.get(
"https://3lib.net" + book_link,
headers=header,
proxies=webshare
)
soup = BeautifulSoup(response.content, 'html.parser')
container = soup.find('div', class_='cardBooks')
title = container.select("h1[itemprop='name']")[0].text.strip()
cover = container.find('div', class_='z-book-cover')
if cover:
cover_img = cover.img['src']
else:
cover_img = ""
author_data = container.select("a[itemprop='author']")
author_list = [link.text for link in author_data]
authors = " โข ".join(author_list)
prop_file = container.find('div', class_='property__file')
metadata = prop_file.find('div', class_='property_value')
file_type, file_size = metadata.text.split(',')
file_size = file_size.strip()
prop_year = container.select("div.property_year > div.property_value")
if prop_year:
year = prop_year[0].text
else:
year = ""
prop_publisher = container.select("div.property_publisher > div.property_value")
if prop_publisher:
publisher = prop_publisher[0].text
else:
publisher = ""
prop_pages = container.select("div.property_pages > div.property_value")
if prop_pages:
pages = prop_pages[0].span.text
else:
pages = ""
prop_isbn = container.find('div', class_='bookProperty property_isbn 13')
if prop_isbn:
isbn = prop_isbn.find('div', class_='property_value').text
else:
isbn = ""
return {
'title': title,
'authors': authors,
'cover_img': cover_img,
'year': year,
'publisher': publisher,
'pages': pages,
'isbn': isbn,
'file_type': file_type,
'size': file_size
}
# Downloads the book from global (https://3lib.net) server
# Fixed ip is required for each request
def bcc_download(user_id, book_link, extention):
# Get list of fresh webshare ips
response = requests.get(
"https://proxy.webshare.io/api/proxy/list",
headers={
"Authorization": "Token " + webshare_token
})
data = response.json()
# Pick a random ip
# This ip will be used for subsequent requests
picker = choice(data['results'])
login = f"http://{picker['username']}:{picker['password']}@{picker['proxy_address']}:{str(picker['ports']['http'])}"
webshare = {
"http": login, "https": login
}
try:
response = requests.get(
"https://3lib.net" + book_link,
proxies=webshare,
allow_redirects=False
)
except:
bot.send_message(user_id, 'โ ๏ธ Something went wrong')
bot.send_message(group_id, f"<b>User ID:</b> {user_id}\n\n<b>โ ๏ธ Event: </b>Dead proxy ~ 210078\n\n<b>Book Link: </b>https://3lib.net{book_link}\n\n<b>Proxy: </b>{login}")
return
soup = BeautifulSoup(response.content, 'html.parser')
link = soup.find('a', class_='btn btn-primary dlButton addDownloadedBook')
if link:
download_link = link['href']
# Download link not found
# Check if file was deleted due to dmca
else:
deleted = soup.find('a', class_='btn btn-primary dlButton disabled')
if deleted:
bot.send_message(user_id, 'โ ๏ธ Link deleted by legal owner')
else:
bot.send_message(user_id, 'โ ๏ธ Something went wrong')
bot.send_message(group_id, f"<b>User ID:</b> {user_id}\n\n<b>โ ๏ธ Event: </b>Download link not fount for book ~ code: 325247\n\n<b>Book Link: </b>https://3lib.net{book_link}\n\n<b>Proxy: </b>{login}")
return
book_name = soup.select("h1[itemprop='name']")[0].text.strip()
book_name_full = book_name
# This is name for saving the downloaded e-book
# Remove invalid characters and add file extention to name
book_name = book_name[:32]
invalid_chars = ['!', '@', '#', '$', '%', '^', '&', '*', '+', '\'', '"', '\\', '/', ',', '~', '|', '`', '<', '>', ';', ':', '?']
book_name = book_name.translate({ ord(char) : ' ' for char in invalid_chars })
book_name = book_name.strip() + "." + extention.lower()
book_name = book_name.replace(" ", " - ")
# Response containes download link in header
try:
book_data = requests.get(
f"https://3lib.net{download_link}",
proxies=webshare,
allow_redirects=False
).headers
except:
bot.send_message(user_id, 'โ ๏ธ Something went wrong')
bot.send_message(group_id, f"<b>User ID:</b> {user_id}\n\n<b>โ ๏ธ Event: </b>Download failed ~ 217014\n\n<b>Book Link: </b>https://3lib.net{book_link}\n\n<b>Proxy: </b>{login}")
return
# Download link
redirect = book_data.get('Location')
if redirect:
# Error due to ip mismatch
if 'wrongHash' in redirect:
bot.send_message(user_id, '๐ค Something went wrong')
bot.send_message(group_id, f"<b>User ID:</b> {user_id}\n\n<b>Book Link: </b>https://3lib.net{book_link}\n\n<b>Bot Reply: </b>IP mismatch: wrong hash\n\n<b>Proxy: </b>{login}")
# Download book and send it to user
else:
try:
filename = wget.download(redirect, 'Downloads/' + book_name)
# Download failed due to network error or dead link
except:
bot.send_message(user_id, "๐ค Couldn't download book")
return
book = open(os.path.join(os.getcwd(), filename), 'rb')
caption = "๐ <b>" + book_name_full + "</b>"
bot.send_document(user_id, book, caption=caption)
book.close()
os.unlink(os.path.join(os.getcwd(), filename))
bot.send_message(group_id, f"<b>User ID:</b> hidden\n\n<b>Book Link: </b>https://3lib.net{book_link}\n\n<b>Event: </b>Book download success\n\n<b>Proxy: </b>{login}")
# Download link not found
else:
bot.send_message(user_id, '๐ค Something went wrong')
bot.send_message(group_id, f"<b>User ID:</b> {user_id}\n\n<b>Book Link: </b>https://3lib.net{book_link}\n\n<b>Event: </b> No redirect location\n\n<b>Proxy: </b>{login}")
# Downloads the book from libgen server
# Download using cloudflare (fast) link if cloudflare param is true
# If convert is true, e-book is converted to pdf after download
def libgen_download(user_id, link, extention, cloudflare=None, book_size=1, convert=False):
login = f"http://{webshare_user}@p.webshare.io:80"
webshare = {
"http": login, "https": login
}
try:
response = requests.get(
f"http://library.lol/main/{link}",
headers=header,
proxies=webshare
)
except:
bot.send_message(user_id, "โ ๏ธ Something went wrong")
bot.send_message(group_id, f"<b>User ID:</b> {user_id}\n\n<b>Book Link: </b>http://library.lol/main/{link}\n\n<b>Event: </b>โ ๏ธ Couldn't connect to library.lol (315529)")
return
soup = BeautifulSoup(response.content, 'html.parser')
book_name = soup.find('h1').text
download_div = soup.find(id='download')
# Libgen direct download link
download_link = download_div.find('h2').a['href']
# Cloudflare download link
fast_download = download_div.ul.li.a['href']
# Use full name for caption
caption = "๐ <b>" + book_name + "</b>"
book_name = book_name[:32]
invalid_chars = ['!', '@', '#', '$', '%', '^', '&', '*', '+', '\'', '"', '\\', '/', ',', '~', '|', '`', '<', '>', ';', ':', '?']
book_name = book_name.translate({ ord(char) : ' ' for char in invalid_chars })
extention = extention.lower()
book_name = book_name.strip() + "." + extention
book_name = book_name.replace(" ", " - ")
# Use fast server if cloudflare param is true
if cloudflare:
download_link = fast_download
# Download book and convert to pdf
if convert:
convertapi.api_secret = convertapi_secret
try:
result = convertapi.convert('pdf',{
'File': download_link
}, from_format = extention, timeout=300)
except convertapi.exceptions.ApiError as e:
if 'Parameter validation error' in e.message:
bot.send_message(user_id, f"โ ๏ธ Cannot convert .{extention} files")
elif 'Invalid user credentials' in e.message:
bot.send_message(user_id, "โ ๏ธ Conversion feature is disabled")
bot.send_message(group_id, f"<b>User ID:</b> {user_id}\n\n<b>Book Link: </b>{download_link}\n\n<b>Event: </b>โ ๏ธ Conversion failed (315149)\n\n<b>Reason: </b>Invalid convert-api credentials")
else:
bot.send_message(user_id, "โ ๏ธ Something went wrong")
bot.send_message(group_id, f"<b>User ID:</b> {user_id}\n\n<b>Book Link: </b>{download_link}\n\n<b>Event: </b>โ ๏ธ Conversion failed (315167)")
return
location = result.file.save('Converted/' + os.path.splitext(book_name)[0]+'.pdf')
book = open(location, 'rb')
bot.send_document(user_id, book, caption=caption + "\n\nConverted to pdf by โ(@Bookemybot)")
book.close()
os.unlink(location)
bot.send_message(group_id, f"<b>User ID:</b> {user_id}\n\n<b>Book Link: </b>{download_link}\n\n<b>Event: </b>Converted .{extention} to .pdf\n\nCredits <b>({result.conversion_cost})</b>")
else:
# Book size is within download limit
# Files greater than 250 MB can't be uploaded to file.io
if book_size < 250:
try:
filename = wget.download(download_link, 'Downloads/' + book_name)
# Download failed due to network error or dead link
except:
bot.send_message(user_id, "๐ค Couldn't download book")
return
book = open(os.path.join(os.getcwd(), filename), 'rb')
# Books less than 50 MB can be directly sent over telegram
if book_size < 50:
if extention == 'pdf':
bot.send_document(user_id, book, caption=caption)
# Book is not .pdf format
# Send markup, ask if user wants to convert to pdf
else:
markup = types.InlineKeyboardMarkup()
foodie = choice(['๐ฟ','๐','๐ง','๐ท','๐','๐','๐','๐จ'])
convert_btn = types.InlineKeyboardButton(foodie + " Convert to pdf (free)", callback_data="convert~" + link + "~" + extention + "~" + str(book_size))
markup.row(convert_btn)
bot.send_document(user_id, book, caption=caption, reply_markup=markup)
# Book size between 50 and 250 MB
# Upload book to file.io cloud and send download link
else:
try:
upload = requests.post(
'https://file.io',
files = { "file": book }
).json()
except:
bot.send_message(user_id, "โ ๏ธ Something went wrong")
bot.send_message(group_id, f"<b>User ID:</b> {user_id}\n\n<b>Book Link: </b>{download_link}\n\n<b>Event: </b>Upload to file.io failed.\n\<b>Error code: </b>617293")
# Book upload failed
# Close and delete the downloaded e-book
book.close()
os.unlink(os.path.join(os.getcwd(), filename))
return
# File upload success
# Send the download link received from file.io
if upload['success']:
bot.send_message(user_id, upload['link'])
else:
bot.send_message(user_id, "โ ๏ธ Something went wrong")
bot.send_message(group_id, f"<b>User ID:</b> {user_id}\n\n<b>Book Link: </b>{download_link}\n\n<b>Event: </b>Upload to file.io failed.\n\<b>Error code: </b>617112")
book.close()
os.unlink(os.path.join(os.getcwd(), filename))
else:
bot.send_message(user_id, "โ ๏ธ Unsupported file size")
bot.send_message(group_id, f"<b>User ID:</b> hidden\n\n<b>Book Link: </b>{download_link}\n\n<b>Event: </b>Book download success")
# Search libgen for e-books
# Returns a list of available books, containing book's
# details as dictionary
def libgen_search(search_query, link=None, filter_with=None, file_type=None):
login = f"http://{webshare_user}@p.webshare.io:80"
webshare = {
"http": login, "https": login
}
# Libgen default search
# It will search in book title and author
url = f"https://libgen.is/search.php?req={search_query}&open=0&res=25&view=detailed&phrase=1&column=def"
# Filter search using isbn
if filter_with == 'isbn':
if file_type.lower() == 'pdf':
url = f"https://libgen.is/search.php?req={search_query}&open=0&res=25&view=detailed&phrase=1&column=identifier&sort=extension&sortmode=DESC"
else:
url = f"https://libgen.is/search.php?req={search_query}&open=0&res=25&view=detailed&phrase=1&column=identifier"
response = requests.get(
url,
headers=header,
proxies=webshare
)
soup = BeautifulSoup(response.content, 'html.parser')
# Brown line above each book's row
target = soup.find_all('tr', {'height': '2', 'valign': 'top'})
book_data = []
for book in target:
# Siblings of book contain book's information
data = book.find_next_siblings()
part = data[0]
book_cover = part.a.img['src']
book_name = part.b.text
# This is hash of book
# Slicing removes everything except hash
book_link = part.a['href'][10:]
author_data = data[1]
a = author_data.find_all('a')
author_list = map(lambda author: author.text, a)
authors = " โข ".join(author_list)
publisher = data[3].find('td', text='Publisher:').find_next_sibling().text
year = data[4].find('td', text='Year:').find_next_sibling().text
pages = data[5].find('td', text='Pages:').find_next_sibling().text
size = data[8].find('td', text='Size:').find_next_sibling().text
# Remove the size in bytes
size = size.split('(')[0].strip()
extension = data[8].find('td', text='Extension:').find_next_sibling().text
extension = extension.upper()
# User picked a particular book
# Return that book's details
if link:
if book_link == link:
return {
'title': book_name,
'link': book_link,
'authors': authors,
'cover_img': book_cover,
'year': year,
'publisher': publisher,
'pages': pages,
'file_type': extension,
'size': size
}
# User sent a book name
# Add every book's data to book-data list
else:
book_data.append({
'title': book_name,
'link': book_link,
'authors': authors,
'cover_img': book_cover,
'year': year,
'publisher': publisher,
'pages': pages,
'file_type': extension,
'size': size
})
# Fast download
if file_type:
if file_type.upper() == extension:
return (book_link, extension)
return book_data
# Returns a list of all udemy courses
def fetch_courses():
# Final list containes slugified course names e.g. flask-framework
courses_list = []
response = requests.get("https://www.discudemy.com/all", headers=header)
soup = BeautifulSoup(response.content, 'html.parser')
courses = soup.find_all('a', class_='card-header')
# New courses
for course in courses:
# Removes 'https://www.discudemy.com/category/' from links
link = re.match('https://www.discudemy.com(/.+)?/(.+)', course['href'])
courses_list.append(link.group(2))
popular = soup.find_all('div', class_='five wide column')
# Popular courses
for div in popular:
links = div.find_all('a')
for link in links:
# Remove 'http://www.discudemy.com/' from link
course = link['href'][25:]
if course not in courses_list:
courses_list.append(course)
return courses_list
# Returns actual course name
# Parameter c-name is slugified course name
def course_name(c_name):
formatted = "โ " + " ".join(map(lambda word: word.capitalize(), c_name.split('-')))
# Prevents accidently removing last "-" from real url
if c_name.endswith("-"):
formatted = formatted.strip() + "-"
return formatted
# Converts course name to slug
# Fetches the course coupon and returns udemy link
def get_coupon(user_choice):
# Slicing removes โ
course_meta = user_choice[3:].replace(" ", "-")
response = requests.get("http://www.discudemy.com/go/" + course_meta, headers=header)
soup = BeautifulSoup(response.content, 'html.parser')
coupon_link = soup.find(id="couponLink")
return coupon_link['href']
# Adds a list of courses as buttons
# Button-text is list of all courses or searched e-books
# Current-page can be "b-ok", "archive" or "libgen"
def add_buttons(button_text, is_udemy=False, current_page=False):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=4)
if current_page:
pages = {
'b-ok': ['โ ', 'โ', 'โ'],
'archive': ['โ', 'โก', 'โ'],
'libgen': ['โ', 'โ', 'โข']
}
nav = pages[current_page]
markup.add(
types.KeyboardButton('๐'),
types.KeyboardButton(nav[0]),
types.KeyboardButton(nav[1]),
types.KeyboardButton(nav[2])
)
else:
markup.add('๐')
# Add all courses to buttons
# Button-text is list of udemy courses
if is_udemy:
for text in button_text:
markup.add(types.KeyboardButton(course_name(text)))
# Button-text is list of all e-books
else:
for text in button_text:
markup.add(types.KeyboardButton(text))
return markup
def keyboard(one, two, three):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
markup.add(
types.KeyboardButton(one),
types.KeyboardButton(two),
types.KeyboardButton(three)
)
markup.add('๐')
return markup
# Function runs on callback from inline buttons
@bot.callback_query_handler(func=lambda call: True)
def downloader(call):
cid = call.message.chat.id
uid = call.from_user.id
mid = call.message.message_id
# Callback is from admin group (reply to user's feedback button)
# Send a force-reply with user and message id
if str(cid) == group_id:
user_id, message_id = call.data.split("~")
markup = types.ForceReply()
bot.send_message(group_id, user_id + " โข " + message_id, reply_markup=markup)
return
metadata = call.data
site_id, book_link, extention, size = metadata.split('~')
if 'mb' in size:
size_mb = round(float(size.split('mb')[0].strip()))
elif 'kb' in size:
size_mb = 1
# Download link of b-ok
if site_id == "3247":
wait = round(log(size_mb) * 10) + size_mb + 5
if wait > 60:
minute, sec = divmod(wait, 60)
bot.answer_callback_query(call.id, text="Downloading (please wait) ... " + str(minute) + " minute " + str(sec) +" seconds")
else:
bot.answer_callback_query(call.id, text="Downloading (please wait) ... " + str(wait) + " seconds")
bcc_download(uid, book_link, extention)
# Download link of libgen
elif site_id == "5241":
bot.answer_callback_query(call.id, text="Downloading (please wait) ... " + str(round(size_mb + choice([4, 5, 6, 7, 8, 9]))) + " seconds")
libgen_download(uid, book_link, extention, book_size=size_mb)
# Download link of libgen (cloudflare) and convert
elif site_id == "convert":
size = round(float(size))
# Convert files less than 10 MB
if size < 11:
if size < 5:
wait = 48 + size
bot.answer_callback_query(call.id, text=f"Converting (please wait) ... {wait} seconds")
else:
wait = 13 + size
bot.answer_callback_query(call.id, text=f"Converting (please wait) ... 1 minute {wait} seconds")
libgen_download(uid, book_link, extention, cloudflare=True, book_size=size, convert=True)
else:
bot.send_message(user_id, "โ ๏ธ File size too big")
# Fast download
# Search isbn in libgen and download using cloudflare
else:
if size_mb < 100:
wait = round(log(size_mb) * 8) + size_mb + 4
else:
wait = 'โ'
bot.answer_callback_query(call.id, text=f"Downloading (please wait) ... {wait} seconds")
try:
book_link, extention = libgen_search(book_link, filter_with='isbn', file_type=extention)
except ValueError:
bot.send_message(uid, "โ ๏ธ Book not on fast server")
bot.send_message(group_id, f"<b>User ID:</b> hidden\n\n<b>Event: </b>โ ๏ธ Book not on fast server\n\n<b>ISBN: </b>{book_link}")
book_link = None
if book_link:
libgen_download(uid, book_link, extention, cloudflare=True, book_size=size_mb)
# User started the bot
# Sending a command /start to bot runs this function
@bot.message_handler(commands=['start'])
def send_welcome(message):
user_id = str(message.chat.id)
if user_id == group_id:
return
name = get_username(message)[0]
username = get_username(message)[1]
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
book_icon = choice(['๐', '๐', '๐', '๐', '๐', '๐', '๐'])
video_icon = choice(['๐', '๐ฟ'])
itembtn1 = types.KeyboardButton(video_icon + ' Courses')
itembtn2 = types.KeyboardButton(book_icon + ' E-books')
itembtn3 = types.KeyboardButton('Settings')
markup.add(itembtn1, itembtn2, itembtn3)
if str(message.text) == "/start":
bot.send_message(
user_id,
f"Hello <b>{name}</b>๐ค\n\nWelcome to <b>Bookemy</b> ๐ผ\n\n<b>Bookemy</b> ๐ผ makes downloading e-books fast and fun. Just send name of the book to download e.g. <b>Atomic Habits</b> and see the magic",
reply_markup=markup
)
bot.send_message(group_id, f"<b>User ID:</b> {user_id}\n<b>Name: </b>{name}\n<b>Username: </b>{username}\n<b>Permanent link: </b><a href=\"tg://user?id={user_id}\">User</a>\n\n<b>Event: </b>โ๏ธ Started bot")
# Function executes when user sends a message to bot
@bot.message_handler(func=lambda message: True)
def echo_all(message):
user_id, usr_message = str(message.chat.id), str(message.text)
# Message sent in group (admin)
if user_id == group_id:
grp_replied = message.reply_to_message.json['from']['username']
# Check if we are replying to bot
# Multiple admins can reply to each other without bot's interference
if grp_replied == 'Bookemybot':
replied_to = message.reply_to_message.text
usr_id, msg_id = replied_to.split(' โข ')
try:
bot.send_message(usr_id, usr_message + "\n\nโ(@Bookemybot)", reply_to_message_id=msg_id)
except Exception as e:
if 'bot was blocked by the user' in e:
bot.send_message(group_id, "Error: blocked by user")
else:
bot.send_message(group_id, 'โ ๏ธ Something went wrong')
print(e)
return
message_id = str(message.message_id)
name = get_username(message)[0]
username = get_username(message)[1]
num_searches, last_message, user_sites, page_num, member_type, date, info = search(user_id)
today = str(datetime.date.today())
button_list = ['Settings', 'Friends', 'Websites', 'Feedback', 'โช๏ธFeedback', '๐']
# User doesn't exist in database, set defaults
if not member_type:
num_searches = f'0--{today}'
user_sites = '1-1-0'
page_num = '0'
if usr_message in button_list:
usr_message = usr_message.strip('โช๏ธ')
# User doesn't exist in db
if not member_type:
add(user_id, num_searches, usr_message, user_sites, page_num, "free", today, info)
else:
# Update the last message
update(user_id, num_searches, usr_message, user_sites, page_num, member_type, date, info)
if usr_message == "Settings":
markup = keyboard('Friends', 'Websites', 'Feedback')
bot.send_message(user_id, "Select an option:", reply_markup=markup)
elif usr_message == "Feedback":
# User cancelled feedback
if last_message == 'Feedback':
# Update the last message to settings-page
update(user_id, num_searches, 'Settings', user_sites, page_num, member_type, date, info)
markup = keyboard('Friends', 'Websites', 'Feedback')
bot.send_message(user_id, "Feedback cancelled", reply_markup=markup)
else:
markup = keyboard('Friends', 'Websites', 'โช๏ธFeedback')
bot.send_message(user_id, "Send me your message ~", reply_markup=markup)
# Option to add friends & share e-books
elif usr_message == "Friends":
markup = keyboard('New friend', 'Remove a friend', 'Help')
bot.send_message(user_id, "You are friends with ๐ค <b>None</b>", reply_markup=markup)
# Back button
else:
# Cancel feedback
# Update last message to settings
if last_message == 'Feedback':
update(user_id, num_searches, 'Settings', user_sites, page_num, member_type, date, info)
markup = keyboard('Friends', 'Websites', 'Feedback')
bot.send_message(user_id, "Feedback cancelled", reply_markup=markup)
# Home
else:
eatmoji = ['๐','๐','๐','๐','๐','๐','๐','๐','๐','๐
','๐ฅ','๐ฅฌ','๐ฅ','๐','๐ญ','๐','๐','๐','๐ฅช','๐ฎ','๐','๐ฃ','๐ง','๐ฟ','๐ท']
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
book_icon = choice(['๐', '๐', '๐', '๐', '๐', '๐', '๐'])