-
Notifications
You must be signed in to change notification settings - Fork 3
/
EmaBot.py
1429 lines (1152 loc) · 70.2 KB
/
EmaBot.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
# _||_ Code Test number 23 _||_
# Exclusive use
import telebot
from telebot import types
import logging, time, sys, os
from API import Img
from language import Lang
import Config
from database import Data
# ================================================== Start of caches ==================================================
registered_users = []
broadcast_ids = []
nsfw_ids = []
Data.regis_users(registered_users)
Data.broadcast_append(broadcast_ids) # This will bring to the broadcast_ids all ids.
Data.mature_enabled_users(nsfw_ids)
# =================================================== End of caches ===================================================
# Bot Token taken by @BotFather
TOKEN = Config.TOKEN
# Listener to see when new messages arrives
def listener(messages):
# When new messages arrive TeleBot will call this function.
for m in messages:
if m.content_type == 'text':
# Print the sent message to the console
print(str(m.chat.first_name) + " [" + str(m.chat.id) + "]: " + m.text)
# print(str(m))
bot = telebot.AsyncTeleBot(TOKEN, skip_pending=True) # register bot token
bot.set_update_listener(listener) # register listener
logger = telebot.logger # set logger
telebot.logger.setLevel(logging.DEBUG) # Outputs debug messages to console.
# Deep linking function
def deep_link(text):
return text.split()[1] if len(text.split()) > 1 else None
@bot.message_handler(commands=['start']) # triggers the message for /start command
def send_welcome(m):
cid = m.chat.id # Chat unique Identifier
match = Data.user_search(str(cid)) # Check user database to see if the user exists
dp_link = deep_link(m.text)
if dp_link: # if /start has a parameter
if dp_link.startswith("share"):
splt = dp_link.split('&')
param = splt[1]
try:
msg = u'Your selected file is ready to be shared!\n' \
u'Tap the button below, select a chat, and then share\n' \
u'your file!'
keyboard = telebot.types.InlineKeyboardMarkup()
button1 = telebot.types.InlineKeyboardButton("Share", switch_inline_query=param)
keyboard.add(button1)
bot.send_message(cid, msg, reply_markup=keyboard)
except Exception as e:
print("An error occurred on inline parameter 'share':", e)
pass
elif dp_link.startswith("id:"):
search_id = dp_link.split(":")[1]
id_handler(m, cid, search_id)
elif dp_link == "activate_membership":
keyboard = telebot.types.InlineKeyboardMarkup(row_width=2)
btn = telebot.types.InlineKeyboardButton("Accept", callback_data="accept_member {id}".format(id=str(cid)))
btn2 = telebot.types.InlineKeyboardButton("Decline", callback_data="decline_member {id}".format(id=str(cid)))
bot.send_message(cid, "Pending moderator approval.")
keyboard.row(btn, btn2)
bot.send_message(Config.MASTER_ID, "User {n} ID: {i} requested membership.".format(n=m.from_user.first_name,
i=str(cid)),
reply_markup=keyboard)
else:
try:
lang = match['language'] # If the user exists, gets it's desired language
bot.send_message(cid, Lang.Lang[lang]['CommandText']['{0}'.format(dp_link)].format(bot_id=Config.BOT_ID),
parse_mode='markdown', disable_web_page_preview=True)
except Exception as e:
bot.reply_to(m, "Ooops, looks like you're not registered. Please tap /start to register.")
print("An Error occurred when processing command /start {0}:".format(dp_link), e)
pass
else:
if not match: # If user couldn't be found in the database
try:
ky = types.ReplyKeyboardRemove(selective=False) # Hides any previous keyboard, if there is
# Adds the user in database
Data.new_user(str(m.from_user.username), str(cid), 'English')
bot.reply_to(m, Lang.Lang['English']['CommandText']['start'].format(name=m.from_user.first_name,
bot_name=Config.BOT_NAME),
parse_mode='markdown', reply_markup=ky)
broadcast_ids.append(str(cid))
registered_users.append(str(cid))
Data.update_registered_users()
Data.update_muted_users()
Data.update_subscribed_users()
Data.update_blocked_users()
except Exception as e:
raise Exception(e)
pass
else:
try:
lang = match['language'] # If the user exists, gets it's desired language
ky = types.ReplyKeyboardRemove(selective=False) # Hides any previous keyboard, if there is
bot.reply_to(m, Lang.Lang[lang]['CommandText']['start_reg'].format(name=m.from_user.first_name),
parse_mode='markdown', reply_markup=ky)
Data.update_registered_users()
Data.update_muted_users()
Data.update_subscribed_users()
Data.update_blocked_users()
except Exception as e:
print("An error occurred when processing the start_reg:", e)
pass
@bot.message_handler(commands=['help']) # sends the help message with buttons
def send_help(m):
cid = m.chat.id
match = Data.user_search(str(cid)) # Check user database to see if the user exists
if not match:
bot.reply_to(m, "Ooops, looks like you're not registered. Please tap /start to register.")
else:
lang = match['language'] # If the user exists, gets it's desired language
keyboard = telebot.types.InlineKeyboardMarkup(row_width=2)
button = telebot.types.InlineKeyboardButton(Lang.Lang[lang]['keyboard']['inline_buttons']['help']['usg_help'],
callback_data='help_use')
button2 = telebot.types.InlineKeyboardButton(Lang.Lang[lang]['keyboard']['inline_buttons']['help']['cmnds'],
callback_data='commands')
button3 = telebot.types.InlineKeyboardButton(Lang.Lang[lang]['keyboard']['inline_buttons']['help']['in_help'],
callback_data='inline_help')
button4 = telebot.types.InlineKeyboardButton(Lang.Lang[lang]['keyboard']['inline_buttons']['help']['tags'],
callback_data='tags')
button5 = telebot.types.InlineKeyboardButton(Lang.Lang[lang]['keyboard']['inline_buttons']['help']['src_id'],
callback_data='source_id')
try:
keyboard.add(button)
keyboard.row(button2, button3)
keyboard.row(button4, button5)
bot.reply_to(m, Lang.Lang[lang]['CommandText']['help'], parse_mode='markdown', reply_markup=keyboard)
except Exception as e:
print("An error occurred when processing /help:", e)
pass
@bot.message_handler(commands=['about']) # sends an message with info about the bot
def send_about(m): # It is interesting to change it to your own info
msg = """Replace me"""
bot.reply_to(m, msg, parse_mode='markdown')
@bot.message_handler(commands=['admin']) # Admin command, for Statistics, and in the future, for broadacsting
def admin(m):
cid = str(m.chat.id) # Chat unique identifier
master = str(Config.MASTER_ID) # The bot owner unique identifier
def send_to_master():
kb = telebot.types.InlineKeyboardMarkup()
kbbtn1 = telebot.types.InlineKeyboardButton("📈 Statistics", callback_data='stats')
kb.add(kbbtn1)
bot.reply_to(m, "Select one of the options below:", reply_markup=kb)
send_to_master() if master == cid else bot.reply_to(m, 'Who are you?') # Sends the message if, and only if,
# The user is the owner
@bot.message_handler(commands=['settings', 'config']) # command triggers for the settings
@bot.message_handler(func=lambda m: m.text == '⚙ Settings') # Not used yet
def settings(m):
cid = m.chat.id
match = Data.user_search(str(cid))
if not match:
bot.reply_to(m, "Ooops, looks like you're not registered. Please tap /start to register.")
else:
lang = match['language']
try:
menu = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True, one_time_keyboard=True)
btn1 = types.KeyboardButton(Lang.Lang[lang]['keyboard']['buttons']['lang'])
btn2 = types.KeyboardButton(Lang.Lang[lang]['keyboard']['buttons']['notif'])
btn3 = types.KeyboardButton('⚠️ Preferences')
btn4 = types.KeyboardButton(Lang.Lang[lang]['keyboard']['buttons']['hide_kb'])
menu.row(btn1, btn2)
menu.add(btn3)
menu.add(btn4)
bot.reply_to(m, Lang.Lang[lang]['keyboard']['messages']['set_opt'], reply_markup=menu)
except Exception as e:
print("An error occurred when processing /settings:", e)
@bot.message_handler(commands=['broadcast'])
def broadcast(m):
kb = types.InlineKeyboardMarkup()
kb1 = types.InlineKeyboardButton("Ok!", callback_data='broadcast_test2')
kb.add(kb1)
max = 10
ttl = 100
msg = ""
for i in range(len(broadcast_ids)):
try:
bot.send_message(broadcast_ids[i],
"Hi! I'm just trying to say here that my new functions are almost ready!\n\n And I'm really sorry for all the inconvenience >.<",
reply_markup=kb)
except Exception as e:
print(e)
Data.toggle_stat_user_blocked(id)
if i == max:
if max == ttl:
print("Sleeping longer...")
time.sleep(10)
ttl += 100
else:
print("Sleeping...")
time.sleep(2)
max += 10
continue
@bot.callback_query_handler(func= lambda call: call.data == "broadcast_test")
def updt_broadcast(call):
if call.message:
if call.data:
bot.edit_message_text("Thank you!", call.message.chat.id, call.message.message_id)
bot.send_message(Config.MASTER_ID, "User {0} Confirmed!".format(call.from_user.first_name))
langs = ['🌐 Language', '🌐 Idioma', '🌐 Lenguaje', '🌐 Sprache', '🌐 Язык', '🌐 Lingua']
@bot.message_handler(commands=['lang', 'language', 'lang_prefs']) # command triggers for the language selector
@bot.message_handler(func=lambda m: m.text in langs) # If the text matches the language selectors
def lang(m):
cid = m.chat.id # Chat unique Identifier
match = Data.user_search(str(cid)) # Check user database to see if the user exists
if not match: # If user not found in the database
bot.reply_to(m, "Ooops, looks like you're not registered. Please tap /start to register.")
else:
lang = match['language']
kb = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True, one_time_keyboard=True)
kbtn1 = types.KeyboardButton("🇧🇷 Português")
kbtn2 = types.KeyboardButton("🇺🇸 English")
kbtn3 = types.KeyboardButton("🇪🇸 Español")
kbtn4 = types.KeyboardButton("🇮🇹 Italiano")
kbtn5 = types.KeyboardButton("🇷🇺 русский")
kbtn6 = types.KeyboardButton("🇩🇪 Deutsche")
kb.add(kbtn2, kbtn1)
kb.row(kbtn3, kbtn4)
kb.row(kbtn5, kbtn6)
try:
bot.reply_to(m, Lang.Lang[lang]['keyboard']['messages']['Lang_pref'],
parse_mode='markdown', reply_markup=kb)
# bot.register_next_step_handler(msg, chosen_lang) # sends the msg, and register the 'chosen_lang' func
except Exception as e: # to be handled next
print("An error occurred when processing 'Language Selector':", e)
pass
select_langs = ["🇧🇷 Português", "🇺🇸 English", "🇪🇸 Español", "🇮🇹 Italiano", "🇷🇺 русский", "🇩🇪 Deutsche"]
@bot.message_handler(func=lambda m: m.text in select_langs)
def chosen_lang(m):
cid = m.from_user.id # Chat unique identifier
text = m.text.split() # Breaks the text, so it returns a list
try:
Data.update_user_language(str(cid), text[1]) # Updates the database with the second item in the list
k = types.ReplyKeyboardRemove(selective=False)
bot.reply_to(m, Lang.Lang[text[1]]['keyboard']['messages']['Chosen_lang'],
parse_mode='markdown', reply_markup=k)
except Exception as e:
bot.reply_to(m, 'Ops, something went wrong. Please try again with /language')
print("An error occurred when processing 'new_user_lang_register':", e)
pass
ntf_string = ['🔔 Notifications', '🔔 Notificações', '🔔 Notificaciones',
'🔔 Benachrichtigungen', '🔔 Оповещения', '🔔 Notifiche']
@bot.message_handler(commands=['notif', 'notifications',])
@bot.message_handler(func=lambda m: m.text in ntf_string)
def send_notif(m):
cid = m.chat.id # Chat unique identifier
match = Data.user_search(str(cid)) # Check user database to see if the user exists
if not match: # If user not found in the database
bot.reply_to(m, "Ooops, looks like you're not registered. Please tap /start to register.")
else:
lang = match['language'] # User language
opt = match['notif'] # User notification choice 'yes/no'"
kb = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
kbtn1 = types.KeyboardButton("⭕️")
kbtn2 = types.KeyboardButton("❌")
if opt == 'Yes': # If the user already has notifications on, it turns off
btn = kbtn1
else: # If the user has notifications off, it turns on
btn = kbtn2
kb.add(btn)
try:
bot.reply_to(m, Lang.Lang[lang]['keyboard']['messages']['notif_pref'],
parse_mode='markdown', reply_markup=kb)
# bot.register_next_step_handler(msg, chosen_notif) # sends the msg, and register the 'chosen_notif' func
except Exception as e: # to be handled next
print("An error occurred when processing 'Notification Selector':", e)
pass
ntf_opt = ["⭕️", "❌"]
@bot.message_handler(func=lambda m: m.text in ntf_opt)
def chosen_notif(m):
cid = m.chat.id # Chat unique identifier
text = m.text
try:
Data.toggle_stat_notifications(str(cid))
if text == "⭕️":
msg = "Disabled!"
broadcast_ids.remove(str(cid))
elif text == "❌":
msg = "Enabled!"
broadcast_ids.append(str(cid))
k = types.ReplyKeyboardRemove(selective=False)
bot.reply_to(m, msg, reply_markup=k)
Data.update_subscribed_users()
Data.update_muted_users()
except Exception as e:
bot.reply_to(m, 'Ops, something went wrong. Please try again with /notif')
print("An error occurred when processing 'notif_prefs':", e)
pass
@bot.message_handler(commands=['nsfw', 'prefs', 'preferences'])
@bot.message_handler(func=lambda m: m.text == '⚠️ Preferences')
def send_prefs(m):
cid = m.chat.id # Chat unique identifier
match = Data.user_search(str(cid)) # Check user database to see if the user exists
if not match: # If user not found in the database
bot.reply_to(m, "Ooops, looks like you're not registered. Please tap /start to register.")
else:
pref = match['nsfw'] # User notification choice 'yes/no'"
kb = types.InlineKeyboardMarkup()
kbtn1 = types.InlineKeyboardButton("Tap to enable Mature Content", callback_data="enable_nsfw")
kbtn2 = types.InlineKeyboardButton("Tap to disable Mature Content", callback_data="disable_nsfw")
if pref == 'Yes': # If the user already has notifications on, it turns off
btn = kbtn2
msg = "Mature content Preference.\n Your current status is: `Enabled`"
else: # If the user has notifications off, it turns on
btn = kbtn1
msg = "Mature content Preference.\n Your current status is: `Disabled`"
kb.add(btn)
try:
bot.reply_to(m, msg, parse_mode='markdown', reply_markup=kb)
except Exception as e:
print("An error occurred when processing 'Notification Selector':", e)
pass
pref = ["enable_nsfw", "disable_nsfw"]
@bot.callback_query_handler(func= lambda call: call.data in pref)
def chosen_prefs(call):
if call.message:
if call.data:
cid = call.message.chat.id
text = call.data
try:
Data.toggle_stat_nsfw(str(cid))
kb = telebot.types.InlineKeyboardMarkup()
if text == pref[1]:
msg = "Disabled mature content."
kbtn1 = types.InlineKeyboardButton("Tap to enable Mature Content", callback_data="enable_nsfw")
kb.add(kbtn1)
nsfw_ids.remove(str(cid))
elif text == pref[0]:
msg = "Enabled mature content."
kbtn1 = types.InlineKeyboardButton("Tap to disable Mature Content", callback_data="disable_nsfw")
kb.add(kbtn1)
nsfw_ids.append(str(cid))
alert = "Warning!\n" \
"Mature content (+18) is now enabled. If it was not supposed to enable this behavior,\n" \
"please use the command /prefs and disable it!"
bot.answer_callback_query(call.id, text=alert, show_alert=True)
bot.edit_message_text(msg, cid, call.message.message_id, reply_markup=kb)
except Exception as e:
bot.send_message(cid, 'Ops, something went wrong. Please try again with /prefs')
print("An error occurred when processing 'nsfw_prefs':", e)
pass
@bot.message_handler(commands=['ping']) # This is just to check if the bot is online. Nothing special
def pong(m):
bot.reply_to(m, 'Pong!')
@bot.message_handler(commands=['commands']) # Commands list
def send_commands(m):
cid = m.chat.id
match = Data.user_search(str(cid)) # Check user database to see if the user exists
if not match: # If user not found in the database
bot.reply_to(m, "Ooops, looks like you're not registered. Please tap /start to register.")
else:
lang = match['language']
try:
bot.reply_to(m, Lang.Lang[lang]['CommandText']['commands'].format(bot_id=Config.BOT_ID),
parse_mode='markdown', disable_web_page_preview=True)
except Exception as e:
print("An error occurred when processing /commands:", e)
pass
@bot.message_handler(commands=['inline_help']) # Sends the Inline help
def send_inline_help(m):
cid = m.chat.id
match = Data.user_search(str(cid)) # Check user database to see if the user exists
if not match: # If user not found in the database
bot.reply_to(m, "Ooops, looks like you're not registered. Please tap /start to register.")
else:
lang = match['language']
try:
bot.reply_to(m,
Lang.Lang[lang]['CommandText']['inline_help'].format(bot_id=Config.BOT_ID),
parse_mode='markdown', disable_web_page_preview=True)
except Exception as e:
print("An Error occurred when processing command /inline_help:", e)
pass
# ============================================== Start of Media Handling ==============================================
def media_handler(m, cid, load_media):
try:
bot.send_chat_action(cid, 'upload_photo') # Sends "uploading photo" chat action
load = Img.post(load_media) # Loads the json object with the query
file = 'http:' + load['file_url'] # The picture url
id = load['id'] # The picture unique identifier, on the server
keyboard = telebot.types.InlineKeyboardMarkup(row_width=4)
button = telebot.types.InlineKeyboardButton(text="💾", url=file) # Download button
button2 = telebot.types.InlineKeyboardButton(text="➕",
callback_data=
load_media + " id={0}".format(id) + ' fav=No') # load more
button3 = telebot.types.InlineKeyboardButton(text="🔘", switch_inline_query="id:{0}".format(id)) # Share
button4 = telebot.types.InlineKeyboardButton(text="⭐️",
callback_data=
'favorite_add={id}&media={md}'.format(id=id, md=load_media))
button5 = telebot.types.InlineKeyboardButton(text="ℹ️", callback_data="info={id}".format(id=id))
try:
keyboard.row(button, button3, button5, button4)
keyboard.add(button2)
if file.endswith('.gif'):
bot.send_document(cid, file, caption='🎴ID: {id}\n'.format(id=id), reply_markup=keyboard)
else:
bot.send_photo(cid, file, caption='🎴ID: {id}\n'.format(id=id), reply_markup=keyboard)
Data.update_media_processed()
except Exception as e:
retry_keyboard = telebot.types.InlineKeyboardMarkup()
retry_button = telebot.types.InlineKeyboardButton(text="🔄 Retry", callback_data=load_media)
retry_keyboard.add(retry_button)
bot.reply_to(m, "Sorry!\n`An unexpected error occurred when processing your request`.\nTry again?",
parse_mode='markdown', reply_markup=retry_keyboard)
print("An error Occurred in /{0}:".format(load_media), e)
pass
except Exception as e:
retry_keyboard = telebot.types.InlineKeyboardMarkup()
retry_button = telebot.types.InlineKeyboardButton(text="🔄 Retry", callback_data=load_media)
retry_keyboard.add(retry_button)
bot.reply_to(m, "Sorry!\n`An unexpected error occurred when processing your request`.\nTry again?",
parse_mode='markdown', reply_markup=retry_keyboard)
print("An Error occurred when loading '{0}' dict:".format(load_media), e)
pass
def inline_media_handler(call, cid, param, call_id, has_favorited):
try:
bot.send_chat_action(cid, 'upload_photo') # Sends "uploading photo" chat action
load = Img.post(param) # Loads the json object with the query
file = 'http:' + load['file_url'] # The picture url
id = load['id'] # The picture unique identifier, on the server
keyboard = telebot.types.InlineKeyboardMarkup(row_width=3)
button = telebot.types.InlineKeyboardButton(text="💾", url=file) # Download button
button2 = telebot.types.InlineKeyboardButton(text="➕",
callback_data=param+" id={0}".format(id)+' fav=No') # load more
button3 = telebot.types.InlineKeyboardButton(text="🔘",
switch_inline_query="id:{0}".format(id)) # Share
button4 = telebot.types.InlineKeyboardButton(text="⭐️",
callback_data=
'favorite_add={id}&media={md}'.format(id=id, md=param))
button5 = telebot.types.InlineKeyboardButton(text="ℹ️", callback_data="info={id}".format(id=id))
try:
keyboard.row(button, button3, button5, button4)
keyboard.add(button2)
if file.endswith('.gif'):
bot.send_document(cid, file, caption='🎴ID: {id}\n'.format(id=id), reply_markup=keyboard)
else:
bot.send_photo(cid, file, caption='🎴ID: {id}\n'.format(id=id), reply_markup=keyboard)
Data.update_media_processed()
except Exception as e:
retry_keyboard = telebot.types.InlineKeyboardMarkup()
retry_button = telebot.types.InlineKeyboardButton(text="🔄 Retry", callback_data=call.data)
retry_keyboard.add(retry_button)
bot.send_message(cid,
"Sorry!\n`An unexpected error occurred when processing your request`.\nTry again?",
parse_mode='markdown', reply_markup=retry_keyboard)
print("An Error occurred in 'more {0}':".format(call.data), e)
pass
try:
load = Img.search_query("id:{0}".format(call_id)) # Loads the json object with the query
file = 'http:' + load[0]['file_url'] # The picture url
keyboard = telebot.types.InlineKeyboardMarkup(row_width=3)
button = telebot.types.InlineKeyboardButton(text="💾", url=file) # Download button
button3 = telebot.types.InlineKeyboardButton(text="🔘",
switch_inline_query='id:{0}'.format(call_id)) # Share
button41 = telebot.types.InlineKeyboardButton(text="⭐️",
callback_data='favorite_add={id}'.format(id=call_id))
button42 = telebot.types.InlineKeyboardButton(text="🌟",
callback_data='favorite_del={id}'.format(id=call_id))
button5 = telebot.types.InlineKeyboardButton(text="ℹ️", callback_data="info={id}".format(id=call_id))
if has_favorited == "Yes":
keyboard.row(button, button3, button5, button42)
else:
keyboard.row(button, button3, button5, button41)
bot.edit_message_reply_markup(cid, call.message.message_id, reply_markup=keyboard)
except Exception as e:
msg = "Woops, I couldn't update your buttons, but don't worry! Your favorite was saved."
bot.answer_callback_query(call.id, text=msg, show_alert=True)
print("An Error occurred when tried to update the fav_btn:", e)
pass
except Exception as e:
retry_keyboard = telebot.types.InlineKeyboardMarkup()
retry_button = telebot.types.InlineKeyboardButton(text="🔄 Retry", callback_data=call.data)
retry_keyboard.add(retry_button)
bot.send_message(cid,
"Sorry!\n`An unexpected error occurred when processing your request`.\nTry again?",
parse_mode='markdown', reply_markup=retry_keyboard)
print("An Error occurred when loading '{0}' dict:".format(call.data), e)
pass
def fav_add(call, cid, match, load_media, id):
try:
if id in match:
bot.answer_callback_query(call.id, text="This file is already on favorites.")
else:
Data.add_favorites(str(cid), id)
bot.answer_callback_query(call.id, text="Added to favorites")
try:
load = Img.search_query("id:{0}".format(id)) # Loads the json object with the query
file = 'http:' + load[0]['file_url'] # The picture url
keyboard = telebot.types.InlineKeyboardMarkup(row_width=3)
button = telebot.types.InlineKeyboardButton(text="💾", url=file) # Download button
button2 = telebot.types.InlineKeyboardButton(text="➕",
callback_data=load_media+" id={0}".format(id)+' fav=Yes') # load more
button3 = telebot.types.InlineKeyboardButton(text="🔘",
switch_inline_query='id:{0}'.format(id)) # Share
button41 = telebot.types.InlineKeyboardButton(text="🌟",
callback_data='favorite_del={id}'.format(id=id))
button42 = telebot.types.InlineKeyboardButton(text="🌟",
callback_data='favorite_del={id}&media={md}'.format(
id=id,
md=load_media))
button5 = telebot.types.InlineKeyboardButton(text="ℹ️", callback_data="info={id}".format(id=id))
if load_media.startswith("True"):
redo_btn = telebot.types.InlineKeyboardButton(text="❌",
callback_data=
"favorite_del={id}&fav_command=True".format(
id=id))
button2 = telebot.types.InlineKeyboardButton(text="🔘",
switch_inline_query="id:{0}".format(id)) # Share
button3 = telebot.types.InlineKeyboardButton(text="ℹ️", callback_data="info={id}".format(id=id))
if load_media.startswith("TrueNEXT"):
obj = load_media.split(":")[1]
button = telebot.types.InlineKeyboardButton(text=">>",
callback_data=
'load_fav {0} id:{1}'.format(obj,
id)) # load more
button4 = telebot.types.InlineKeyboardButton(text="❌",
callback_data=
"favorite_del={id}&fav_command=TrueNEXT:{obj}".format(
id=id, obj=obj))
keyboard.row(button2, button3)
keyboard.add(button4)
keyboard.add(button)
else:
keyboard.row(button2, button3)
keyboard.add(redo_btn)
bot.edit_message_caption(caption="File ID: {0} add back to your favorites".format(id),
message_id=call.message.message_id, chat_id=cid,
reply_markup=keyboard)
else:
if load_media == "":
keyboard.row(button, button3, button5, button41)
else:
keyboard.row(button, button3, button5, button42)
keyboard.add(button2)
bot.edit_message_reply_markup(cid, call.message.message_id, reply_markup=keyboard)
except Exception as e:
msg = "Woops, I couldn't update your buttons, but don't worry! Your favorite was saved."
bot.answer_callback_query(call.id, text=msg, show_alert=True)
print("An Error occurred when tried to update the fav_btn:", e)
pass
except ValueError:
msg = "You already reached your limit of favorites! Go to /favorites to remove some, or" \
"contact @MrHalk for a premium account!"
bot.answer_callback_query(call.id, text=msg, show_alert=True)
except Exception as e:
msg = "Woops, something went wrong! Please try to add this favorite again."
bot.answer_callback_query(call.id, text=msg, show_alert=True)
print("An Error occurred when tried to add a favorite for the user {0}:".format(cid), e)
pass
def fav_del(call, cid, match, load_media, id):
try:
if id not in match:
bot.answer_callback_query(call.id, text="This file was already removed from favorites.")
else:
Data.del_favorites(str(cid), id)
bot.answer_callback_query(call.id, text="Removed from favorites")
try:
load = Img.search_query("id:{0}".format(id)) # Loads the json object with the query
file = 'http:' + load[0]['file_url'] # The picture url
keyboard = telebot.types.InlineKeyboardMarkup(row_width=3)
button = telebot.types.InlineKeyboardButton(text="💾", url=file) # Download button
button2 = telebot.types.InlineKeyboardButton(text="➕",
callback_data=load_media+" id={0}".format(id)+' fav=No') # load more
button3 = telebot.types.InlineKeyboardButton(text="🔘",
switch_inline_query='id:{0}'.format(id)) # Share
button41 = telebot.types.InlineKeyboardButton(text="⭐️",
callback_data='favorite_add={id}'.format(id=id))
button42 = telebot.types.InlineKeyboardButton(text="⭐️",
callback_data='favorite_add={id}&media={md}'.format(
id=id,
md=load_media))
button5 = telebot.types.InlineKeyboardButton(text="ℹ️", callback_data="info={id}".format(id=id))
if load_media.startswith("True"):
if load_media.startswith("TrueNEXT"):
obj = load_media.split(":")[1]
undo_btn = telebot.types.InlineKeyboardButton(text="Undo",
callback_data=
"favorite_add={id}&fav_command=TrueNEXT:{obj}".format(
id=id, obj=obj))
next_button = telebot.types.InlineKeyboardButton(text=">>",
callback_data=
'load_fav {0} id:{1} is_deleted'.format(
obj,
id)) # load more
keyboard.add(undo_btn)
keyboard.add(next_button)
else:
undo_btn = telebot.types.InlineKeyboardButton(text="Undo",
callback_data=
"favorite_add={id}&fav_command=True".format(
id=id))
keyboard.add(undo_btn)
bot.edit_message_caption(caption="File ID: {0} removed from your favorites".format(id),
message_id=call.message.message_id, chat_id=cid,
reply_markup=keyboard)
else:
if load_media == "":
keyboard.row(button, button3, button5, button41)
else:
keyboard.row(button, button3, button5, button42)
keyboard.add(button2)
bot.edit_message_reply_markup(cid, call.message.message_id, reply_markup=keyboard)
except Exception as e:
msg = "Woops, I couldn't update your buttons, but don't worry! Your favorite was saved."
bot.answer_callback_query(call.id, text=msg, show_alert=True)
print("An Error occurred when tried to update the fav_btn:", e)
pass
except Exception as e:
msg = "Woops, something went wrong! Please try to remove this favorite again."
bot.answer_callback_query(call.id, text=msg, show_alert=True)
print("An Error occurred when tried to remove a favorite for the user {0}:".format(cid), e)
pass
def id_handler(m, cid, dp_link):
try:
bot.send_chat_action(cid, 'upload_document') # Sends "uploading photo" chat action
load = Img.search_query("id:{0}".format(dp_link)) # Loads the json object with the query
file = 'http:' + load[0]['file_url'] # The picture url
id = load[0]['id'] # The picture unique identifier, on the server
keyboard = telebot.types.InlineKeyboardMarkup(row_width=4)
btn = telebot.types.InlineKeyboardButton(text="💾", url=file) # Download button
btn2 = telebot.types.InlineKeyboardButton(text="🔘", switch_inline_query="id:{0}".format(id)) # Share
btn3 = telebot.types.InlineKeyboardButton(text="⭐️", callback_data='favorite_add={id}'.format(id=id, ))
btn4 = telebot.types.InlineKeyboardButton(text="ℹ️", callback_data="info={id}".format(id=id))
try:
keyboard.add(btn, btn2, btn4, btn3)
if file.endswith('.gif'):
bot.send_document(cid, file, caption='🎴ID: {id}\n'.format(id=id), reply_markup=keyboard)
"""elif file.endswith('.webm'): # picture.endswith('.mp4'):
bot.send_message(cid, '[🔖]({file})id: {id}\n'.format(id=id, file=file))"""
else:
bot.send_photo(cid, file, caption='🎴ID: {id}\n'.format(id=id), reply_markup=keyboard)
Data.update_media_processed()
except Exception as e:
bot.reply_to(m, "Sorry!\n`An unexpected error occurred when processing your request`.",
parse_mode='markdown')
print("An error Occurred in /id {0}:".format(dp_link), e)
pass
except Exception as e:
bot.reply_to(m, "Sorry!\n`An unexpected error occurred when processing your request`.",
parse_mode='markdown')
print("An Error occurred when loading 'id' dict:", e)
pass
cmnd_list = ['anime', 'ecchi', 'hentai', 'loli', 'yuri', 'sweater_dress', 'yaoi', 'animal_ears']
@bot.message_handler(commands=cmnd_list)
def send_media(m): # All the available media commands
cid = m.chat.id # Chat unique identifier
load_media = m.text.replace("/", "") # Removes the "/" from the command, so it gets as a normal word
if str(cid) not in registered_users:
bot.reply_to(m, "Ooops, looks like you're not registered. Please tap /start to register.")
else:
if load_media not in ['anime', 'animal_ears']:
if str(cid) not in nsfw_ids:
msg = "You are trying to use a Not Safe For Work command, but your configuration has\n" \
"disabled mature content! To use this command, you should first enable\n" \
"mature content view in /preferences."
bot.send_message(cid, msg)
else:
media_handler(m, cid, load_media)
else:
media_handler(m, cid, load_media)
@bot.message_handler(commands=['tag', 'tags'])
def send_tag(m):
bot.reply_to(m, "This command is not set to work now. See /commands")
@bot.message_handler(commands=['id', 'search_id']) # Searches any server id
def send_id_query(m):
cid = m.chat.id # Chat unique identifier
dp_link = deep_link(m.text)
if str(cid) not in registered_users:
bot.reply_to(m, "Ooops, looks like you're not registered. Please tap /start to register.")
else:
if dp_link is None: # if /id has not a parameter
bot.reply_to(m, "Usage:\n `/id [num]` - the num is any number from `1` to `3284774`.", parse_mode='markdown')
else:
id_handler(m, cid, dp_link)
load_type = ['anime', 'ecchi', 'loli', 'hentai', 'yuri', 'sweater_dress', 'yaoi', 'animal_ears']
@bot.callback_query_handler(func=lambda call: call.data.split()[0] in load_type) # Whenever the user taps the "more"
def media_callback(call): # button, it triggers this function
if call.message: # Processes only buttons from messages
if call.data: # If there's any data callback
splt = call.data.split()
param = splt[0]
call_id = splt[1].split('=')[1]
has_favorited = splt[2].split('=')[1]
cid = call.message.chat.id
if param not in ['anime', 'animal_ears']:
if str(cid) not in nsfw_ids:
msg = "You are trying to use a Not Safe For Work button, but your configuration has\n" \
"disabled mature content! To use this button, you should first enable\n" \
"mature content view in /preferences."
bot.send_message(cid, msg)
else:
inline_media_handler(call, cid, param, call_id, has_favorited)
else:
inline_media_handler(call, cid, param, call_id, has_favorited)
@bot.callback_query_handler(func=lambda call: call.data.startswith("info"))
def answer_info(call):
if call.message:
if call.data:
bot.send_chat_action(call.message.chat.id, 'typing')
splt = call.data.split("=")
id = splt[1]
try:
load = Img.search_query("id:{0}".format(id))
width = load[0]["width"]
height = load[0]["height"]
id = load[0]["id"]
view_webpage = 'http://gelbooru.com/index.php?page=post&s=view&id={id}'.format(id=id)
tags = load[0]["tags"]
owner = load[0]["owner"]
rt = load[0]["rating"]
if rt == "s":
rating = "Safe"
elif rt == "q":
rating = "Questionable"
elif rt == "e":
rating = "Explicit"
parent_id = load[0]["parent_id"]
if parent_id is None:
parent_answer = "No"
else:
parent_answer = "_Yes, Parent ID:_ [{0}](http://gelbooru.com/index.php?page=post&s=view&id={0})".format(
parent_id)
msg = Lang.msg['msg']
true_msg = msg.format(id=id, parent_post=parent_answer, W=width, H=height,
Owner=owner, rating=rating, tags=tags)
kb = telebot.types.InlineKeyboardMarkup()
kb1 = telebot.types.InlineKeyboardButton(text="View Web Page", url=view_webpage)
try:
kb.add(kb1)
bot.send_message(call.message.chat.id, true_msg, parse_mode='markdown',
disable_web_page_preview=True, reply_to_message_id=call.message.message_id,
reply_markup=kb)
except Exception as e:
print("Error here bro:", e)
except Exception as e:
print("An error occurred when tried to send info about file id {0}:".format(id), e)
pass
@bot.callback_query_handler(func=lambda call: call.data.startswith("favorite"))
def favs_handler(call):
if call.message:
cid = call.message.chat.id
splt = call.data.split('&')
func = splt[0].split('=')[0] # May be 'favorite_add=' or 'favorite_del='
id = splt[0].split('=')[1] # The file id
load_media = splt[1].split('=')[1] if len(splt) >= 2 else ""
match = Data.search_favorites(str(cid))['favorites']
if func == 'favorite_add':
fav_add(call, cid, match, load_media, id)
elif func == 'favorite_del':
fav_del(call, cid, match, load_media, id)
@bot.message_handler(commands=['favs', 'fav', 'favorites'])
def send_favorites(m):
cid = m.chat.id
if str(cid) not in registered_users:
bot.reply_to(m, "Ooops, looks like you're not registered. Please tap /start to register.")
else:
bot.send_chat_action(cid, 'typing')
try:
user = Data.search_favorites(str(cid))
user_favorites = user['favorites']
limit = user['limit']
count_favs = len(user_favorites)
if limit == "None":
limit_message = u'You are _Premium Member_, no limits applicable to your favorites'
else:
limit_message = u'You still can add _{limit}_ files to your favorites'.format(limit=limit)
msg = u'*Favorites*\n\n' \
u'You have _{count_favs}_ favorites.\n' \
u'{limit_message}\n\n' \
u'Tap the button below to view and manage your favorites.'.format(count_favs=count_favs,
limit_message=limit_message)
keyboard = telebot.types.InlineKeyboardMarkup()
button1 = telebot.types.InlineKeyboardButton("View your favorites ({0})".format(count_favs),
callback_data="load_fav {0} is_init".format(count_favs - 1))
keyboard.add(button1)
bot.reply_to(m, msg, reply_markup=keyboard, parse_mode='markdown')
except Exception as e:
bot.reply_to(m, "Woops! Something weird happened. Please try again or contact @MrHalk for a bug report.")
print("An exception occurred when tried to send 'user_fav_msg':", e)
@bot.callback_query_handler(func=lambda call: call.data.startswith("load_fav"))
def load_favs(call):
if call.message:
if call.data:
splt = call.data.split()
load_obj = int(splt[1])
is_init = splt[2] if "is_init" in splt else ""
is_deleted = splt[3] if "is_deleted" in splt else None
previous_id = splt[2].split(":")[1] if splt[2].startswith("id:") else ""
cid = call.message.chat.id
try:
user = Data.search_favorites(str(cid))
user_favs = user['favorites']