-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
3931 lines (3739 loc) · 202 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
#!/usr/bin/env python3
import asyncio
import datetime
import importlib
import importlib.util
import inspect
import json
import logging
import os
import sys
import time
import traceback
from typing import Union
import discord
from discord.ext import commands
conff = 'conf.json'
dataf = 'data.json'
langfold = 'languages'
logfold: str = 'logs'
modfold = 'mods'
conf = {}
data = {}
lang = {}
# Logic primitives
class Never:
pass
class Forever:
pass
class Partially:
pass
class State:
def __init__(self, state: bool):
self.state = bool(state)
def __bool__(self):
return self.state
def __repr__(self):
if self.state:
return 'On'
else:
return 'Off'
def __str__(self):
if self.state:
return 'On'
else:
return 'Off'
# TODO: move templates to the separate file
# Default configuration.
ctfd = open('conftemplate.json')
conftemplate = json.loads(ctfd.read())
ctfd.close()
# Default language (english)
ltfd = open('langtemplate.json')
langtemplate = json.loads(ltfd.read())
ltfd.close()
# Used to validate all keys
# 'key': class or dict
# The validator DOES NOT ALLOW LISTS!
langvalid = {
'name': str,
'contents': {
'formats': {
'date_format': str,
'duration': {
'seconds': {
"1": str
},
'secs': {
"1": str
},
'minutes': {
"1": str
},
'mins': {
"1": str
},
'hours': {
"1": str
},
'hs': {
"1": str
},
'days': {
"1": str
},
'ds': {
"1": str
},
'weeks': {
"1": str
},
'ws': {
"1": str
},
'months': {
"1": str
},
'mons': {
"1": str
},
'years': {
"1": str
},
'ys': {
"1": str
},
'direction': {
'before': str,
'after': str
}
},
'days_of_week': {
"1": str,
"2": str,
"3": str,
"4": str,
"5": str,
"6": str,
"7": str
},
'dow': {
"1": str,
"2": str,
"3": str,
"4": str,
"5": str,
"6": str,
"7": str
},
'months': {
"1": str,
"2": str,
"3": str,
"4": str,
"5": str,
"6": str,
"7": str,
"8": str,
"9": str,
"10": str,
"11": str,
"12": str
},
'mons': {
'1': str,
'2': str,
'3': str,
'4': str,
'5': str,
'6': str,
'7': str,
'8': str,
'9': str,
'10': str,
'11': str,
'12': str
},
'logic': {
'true': str,
'false': str,
'partially': str,
'none': str
},
'date_relative': {
'today': str,
'tomorrow': str,
'yesterday': str,
'never': str,
'forever': str,
'now': str,
'in_exact_time': str
},
'switch': {
'on': str,
'off': str
}
},
'messages': {
'check_failures': {
'definitions': {
'AuthorBan': dict,
'AuthorAdministrationBan': dict,
'AuthorBanHere': dict,
'AuthorBanGuild': dict,
'GuildAdminBan': dict,
'GuildAdminBanHere': dict,
'GuildAdminBlockChannel': dict,
'GuildAdminBlockCategory': dict,
'NotOwner': dict,
'InsufficientPoints': dict,
'InsufficientGuildPoints': dict,
'NoPrivateMessage': dict,
'PrivateMessageOnly': dict,
'MissingPermissions': dict,
'BotMissingPermissions': dict,
'NSFWChannelRequired': dict,
'NotAllowed': dict,
'NotAllowedBypass': dict,
'MissingRole': dict,
'BotMissingRole': dict,
'MissingAnyRole': dict,
'BotMissingAnyRole': dict,
}
},
'command_errors': {
'definitions': {
'MissingRequiredArgument': dict,
'TooManyArguments': dict,
'UnexpectedQuoteError': dict,
'InvalidEndOfQuotedStringError': dict,
'ExpectedClosingQuoteError': dict,
'CommandNotFound': dict,
'DisabledCommand': dict,
'CommandOnCooldown': dict,
'InvalidDuration': dict,
'InvalidNumber': dict,
'Busy': dict
}
},
'common_errors': {
'definitions': {
'Forbidden': dict,
'NotFound': dict
}
},
'custom_errors': {
'definitions': {
'no_langs': dict,
'non_abanned': dict,
'non_banned': dict,
'non_aadminbanned': dict,
'non_abanned_guild': dict,
'non_banned_here': dict,
'no_ban_self': dict,
'no_ban_guild_owner': dict,
'no_ban_higher_lpl': dict,
'no_block_channel': dict,
'no_block_category': dict,
'abort_nothing': dict,
'no_with_owner': dict,
'no_with_higher_lpl': dict
}
},
'response': {
'description': str,
'definitions': {
'lang': dict,
'lang_of_user': dict,
'lang_of_guild': dict,
'notify_channel': dict
}
},
'info': {
'definitions': {
'abort': dict,
'lang_list': dict,
'lang_set': dict,
'lang_set_user': dict,
'lang_set_guild': dict,
'authorban_banned': dict,
'authorban_unbanned': dict,
'authorban_list': dict,
'authorban_banned_here': dict,
'authorban_unbanned_here': dict,
'authorban_places_list': dict,
'authoradminban_banned': dict,
'authoradminban_unbanned': dict,
'authoradminban_list': dict,
'authorban_banned_guild': dict,
'authorban_unbanned_guild': dict,
'authorban_guild_list': dict,
'guild_admin_ban': dict,
'guild_admin_ban_here': dict,
'guild_admin_unban': dict,
'guild_admin_unban_here': dict,
'guild_admin_ban_list': dict,
'guild_admin_channel_blocked': dict,
'guild_admin_category_blocked': dict,
'guild_admin_channel_unblocked': dict,
'guild_admin_category_unblocked': dict,
'lpl_set': dict,
'lpl_role_set': dict,
'remote_toggle': dict,
'remote_list': dict,
'notify_channel_set': dict
}
},
'notifications': {
'definitions': {
'authorban_banned': dict,
'authorban_unbanned': dict,
'authorban_banned_here': dict,
'authorban_unbanned_here': dict,
'authoradminban_banned_ownerdm': dict,
'authoradminban_unbanned_ownerdm': dict,
'authoradminban_banned': dict,
'authoradminban_unbanned': dict,
'authorban_banned_guild_ownerdm': dict,
'authorban_unbanned_guild_ownerdm': dict,
'authorban_banned_guild': dict,
'authorban_unbanned_guild': dict,
'guild_admin_ban': dict,
'guild_admin_unban': dict,
'guild_admin_ban_here': dict,
'moderator_warning': dict
}
}
},
'permissions': {
'create_instant_invite': str,
'kick_members': str,
'ban_members': str,
'administrator': str,
'manage_channels': str,
'manage_guild': str,
'add_reactions': str,
'view_audit_log': str,
'priority_speaker': str,
'stream': str,
'read_messages': str,
'send_messages': str,
'send_tts_messages': str,
'manage_messages': str,
'embed_links': str,
'attach_files': str,
'read_message_history': str,
'mention_everyone': str,
'external_emojis': str,
'connect': str,
'speak': str,
'mute_members': str,
'deafen_members': str,
'use_voice_activation': str,
'change_nickname': str,
'manage_nicknames': str,
'manage_roles': str,
'manage_webhooks': str,
'manage_emojis': str
},
'audit_log_actions': {
'guild_update': str,
'channel_create': str,
'channel_update': str,
'channel_delete': str,
'overwrite_create': str,
'overwrite_update': str,
'overwrite_delete': str,
'kick': str,
'member_prune': str,
'ban': str,
'unban': str,
'member_update': str,
'member_role_update': str,
'role_create': str,
'role_update': str,
'role_delete': str,
'invite_create': str,
'invite_update': str,
'invite_delete': str,
'webhook_create': str,
'webhook_update': str,
'webhook_delete': str,
'emoji_create': str,
'emoji_update': str,
'emoji_delete': str,
'message_delete': str
},
'audit_log_action_category': {
'create': str,
'update': str,
'delete': str
}
}
}
# Exceptions
class ProcessingIdle(commands.CheckFailure):
# This shouldn't send any error messages, it just blocks the command
pass
class AuthorBan(commands.CheckFailure):
def __init__(self, description=None, *, reason='Not defined', date_exp=Never):
super().__init__(description)
self.reason = reason
self.date_exp = date_exp
class AuthorBanHere(commands.CheckFailure):
def __init__(self, description=None, *, reason='Not defined', date_exp=Never):
super().__init__(description)
self.reason = reason
self.date_exp = date_exp
class AuthorAdministrationBan(commands.CheckFailure):
def __init__(self, description=None, *, reason='Not defined', date_exp=Never):
super().__init__(description)
self.reason = reason
self.date_exp = date_exp
class AuthorBanGuild(commands.CheckFailure):
def __init__(self, description=None, *, reason='Not defined', date_exp=Never):
super().__init__(description)
self.reason = reason
self.date_exp = date_exp
# --- DEPRECATED (however they have been removed from validator) --- #
class AuthorBanCategory(commands.CheckFailure):
def __init__(self, description=None, *, reason='Not defined', date_exp=Never):
super().__init__(description)
self.reason = reason
self.date_exp = date_exp
class AuthorBanRole(commands.CheckFailure):
def __init__(self, description=None, *, reason='Not defined', date_exp=Never):
super().__init__(description)
self.reason = reason
self.date_exp = date_exp
class AuthorBanChannel(commands.CheckFailure):
def __init__(self, description=None, *, reason='Not defined', date_exp=Never):
super().__init__(description)
self.reason = reason
self.date_exp = date_exp
# ------------------------------------------------------------------ #
class GuildAdminBan(commands.CheckFailure):
def __init__(self, description=None, *, reason='Not defined', date_exp=Never):
super().__init__(description)
self.reason = reason
self.date_exp = date_exp
class GuildAdminBanHere(commands.CheckFailure):
def __init__(self, description=None, *, reason='Not defined', date_exp=Never):
super().__init__(description)
self.reason = reason
self.date_exp = date_exp
class GuildAdminBlockChannel(commands.CheckFailure):
pass
class GuildAdminBlockCategory(commands.CheckFailure):
pass
class InsufficientPoints(commands.CheckFailure):
def __init__(self, description=None, *, insuf=0, price=0):
super().__init__(description)
self.insuf = insuf
self.price = price
class InsufficientGuildPoints(commands.CheckFailure):
def __init__(self, description=None, *, insuf=0, price=0):
super().__init__(description)
self.insuf = insuf
self.price = price
class NotAllowed(commands.CheckFailure):
pass
class NotAllowedBypass(commands.CheckFailure):
pass
class IncorrectDuration(commands.CommandError):
def __init__(self, description=None, *, node=""):
super().__init__(description)
self.node = node
class InvalidNumber(commands.CommandError):
def __init__(self, description=None, *, invalid_number=0):
super().__init__(description)
self.invalid_number = invalid_number
class Busy(commands.CommandError):
pass
class NotFound(discord.NotFound):
def __init__(self, response, message, item=""):
self.response = response
self.item = item
self.message = message
# NotFound exceptions DEPRECATED
# class UserNotFound(commands.CommandError):
# def __init__(self, description=None, *, name=""):
# self.name = name
# class MemberNotFound(commands.CommandError):
# def __init__(self, description=None, *, name=""):
# self.name = name
# class RoleNotFound(commands.CommandError):
# def __init__(self, description=None, *, name=""):
# self.name = name
# class GuildNotFound(commands.CommandError):
# def __init__(self, description=None, *, name=""):
# self.name = name
# class ChannelNotFound(commands.CommandError):
# def __init__(self, description=None, *, name=""):
# self.name = name
# class VoiceChannelNotFound(commands.CommandError):
# def __init__(self, description=None, *, name=""):
# self.name = name
# class EmojiNotFound(commands.CommandError):
# def __init__(self, description=None, *, name=""):
# self.name = name
# class MessageNotFound(commands.CommandError):
# def __init__(self, description=None, *, id=0):
# self.id = id
# class InviteNotFound(commands.CommandError):
# def __init__(self, description=None, *, name=""):
# self.name = name
logger = logging.getLogger('discord')
# Basic shortcut functions
def enzero(num, count=2):
snum = str(num)
if len(snum) >= count:
return snum
return '0' * (count - len(snum)) + snum
def nearList(order, num):
_ord = [int(x) for x in order]
_ord.sort(reverse=True)
for x in _ord:
if num >= x:
return x
return None
#
def loadConf():
logger.info('Loading configuration file...')
global conf
try:
if os.path.isfile(conff):
fl = open(conff, 'r')
conf = json.loads(fl.read())
else:
fl = open(conff, 'x')
fl.write(json.dumps(conftemplate, indent=True))
fl.close()
print('The example configuration has been created, enter bot token in them')
exit(0)
except json.JSONDecodeError as exc:
print('The configuration file is broken.')
print(exc)
print('Please check the correctness of the configuration: ' + os.path.abspath(conff))
fl.close()
exit(1)
else:
logger.info('Successfully read the config')
fl.close()
def loadData():
logger.info('Loading data...')
global data
try:
if not os.path.isfile(dataf):
print('It seems that data file has never been created, creating an empty file.')
datafile = open(dataf, 'x')
# TODO
data_tmpl = {'templates': {'guilds': [], 'roles': [], 'channels': []}, 'user_data': {}, 'guild_data': {}}
datafile.write(json.dumps(data_tmpl, indent=True))
datafile.close()
data = data_tmpl
else:
datafile = open(dataf, 'r')
data = json.loads(datafile.read())
except json.JSONDecodeError as exc:
print('The data file is broken.')
print(exc)
print('Please check the correctness of the configuration: ' + os.path.abspath(dataf))
exit(1)
else:
logger.info('Successfully read the data')
datafile.close()
def validateLang(langdict, c_langvalid, prefix=''):
_missing_fields = []
_insuf_fields = []
for entry in c_langvalid.keys():
assert not type(
c_langvalid[entry]) == 'list', 'The language validate template is damaged, it shouldn\'t contain any lists'
if not str(entry) in langdict.keys():
_missing_fields.append(prefix + str(entry))
else:
if c_langvalid[entry].__class__.__name__ == 'dict':
# this is a section, perform recursion.
if langdict[str(entry)].__class__.__name__ != 'dict':
_insuf_fields.append(
prefix + entry + '("dict" expected, got "%s")' % langdict[entry].__class__.__name__)
_rmf, _rif = validateLang(langdict[entry], c_langvalid[entry], prefix + str(entry) + '.')
_missing_fields.extend(_rmf)
_insuf_fields.extend(_rif)
elif langdict[entry].__class__ != c_langvalid[entry]:
# if the node is not a section, then just validate the type.
_insuf_fields.append(prefix + str(entry) + '("%s" expected, got "%s")' % (
c_langvalid[entry].__name__, langdict[entry].__class__.__name__))
return _missing_fields, _insuf_fields
def loadLangs():
logger.info('Loading language settings...')
if not os.path.isdir(langfold):
print('FATAL: %s directory not found!' % langfold)
logger.critical('Directory "%s" was not found!' % langfold)
return False
else:
if 'default_lang' not in conf:
logger.warning('The "default_lang" option is not set in the configuration, using "en_US" as the default.')
conf['default_lang'] = "en_US"
_files = []
with os.scandir(langfold) as files:
file: os.DirEntry
for file in files:
if file.name.endswith('.json') and file.is_file():
_files.append(file)
if 'en_US.json' not in [x.name for x in _files]:
print(
'No language settings was found! Generating default language file...\n - You can copy&paste, '
'rename it and edit them to create your own translation.')
logger.error(
'Directory "%s" does not contain any language sets! Loading default built-in language...' % langfold)
_missing_fields, _insuf_fields = validateLang(langtemplate, langvalid)
if _missing_fields or _insuf_fields:
logger.critical('Correctness test failed. Missing nodes (%d): %s | Insufficient nodes (%d): %s.' % (
len(_missing_fields), ', '.join(_missing_fields), len(_insuf_fields), ', '.join(_insuf_fields)))
print('FATAL: The program is corrupted (the language template is invalid). Please check the log.')
return False
lang['en_US'] = langtemplate
lang['default'] = lang['en_US']
logger.info('Dumping built-in language into "%s" ...' % os.path.abspath(langfold))
langfl = open(langfold + '/en_US.json', 'x')
langfl.write(json.dumps(langtemplate, indent=True))
langfl.close()
logger.info('Successfully created default language.')
return True
# We're allowed to start bot.
if not conf['default_lang'] + '.json' in [x.name for x in _files]:
print('Language settings "%s" was not found! Please check your configuration!' % (
conf['default_lang'] + '.json'))
logger.critical('Directory "%s" does not contain the "%s" file, check your configuration!' % (
langfold, conf['default_lang'] + '.json'))
return False
else:
_error_enc = False
logger.info('Reading language content...')
for file in _files:
# fl = None
# ld = None
try:
langfl = open(langfold + '/' + file.name, 'r')
ld = json.loads(langfl.read())
except json.JSONDecodeError as exc:
_exctext = traceback.format_exc()
print('Error: language file "%s" is damaged.\n%s' % (file.name, _exctext))
logger.critical('Language file "%s" is corrupted and unable to load. Exception traceback:\n%s' % (
file.name, _exctext))
print(exc)
print('It is strongly recommended to turn your bot off.')
langfl.close()
_error_enc = True
else:
_flabel = file.name.split('.')[0]
# We are successfully got the language content, so we can validate them with validator pattern
# and by recursive function. The validation is need to keep out our program from KeyError or
# TypeError exceptions and notify the bot's owner about missing translation.
logger.info('Validating %s...' % _flabel)
_missing_fields, _insuf_fields = validateLang(ld, langvalid)
if len(_missing_fields) + len(_insuf_fields) > 0:
logger.critical(
'Correctness test failed. Missing nodes (%d): %s | Insufficient nodes (%d): %s.' % (
len(_missing_fields), ', '.join(_missing_fields), len(_insuf_fields),
', '.join(_insuf_fields)))
print('%s: lang file is invalid. Please check the log.' % _flabel)
_error_enc = True
else:
lang[_flabel] = ld
logger.info('Successful correctness test! Language "%s" loaded.' % _flabel)
if conf['default_lang'] not in lang:
return False
lang['default'] = lang[conf['default_lang']] # self-reference
return not _error_enc
class GuildConverter(commands.Converter):
def __init__(self):
commands.Converter.__init__(self)
async def convert(self, ctx, arg):
if ctx.guild and (arg == "" or arg == "-"):
return ctx.guild
# arg = str(arg)
if arg.isnumeric():
# search by id
for guild in ctx.bot.get_visible_guilds(ctx.author):
# print(str(guild.id))
if str(guild.id) == arg:
return guild
# search by name
for guild in ctx.bot.get_visible_guilds(ctx.author):
# print(str(guild.name))
if guild.name == arg:
return guild
# failed, raise
raise commands.BadArgument('Guild with name "%s" not found.' % arg, arg)
class PtDiscordBot(commands.Bot):
def debug_print(self, message, where='unknown'):
if where in self.debug_prints:
if self.debug_prints[where]:
logger.debug(where + ": " + str(message))
print(where + ": " + str(message))
else:
if self.debug_prints['other']:
logger.debug('(missing key %s): ' % where + str(message))
print('(missing key %s): ' % where + str(message))
def __init__(self, logger_obj: logging.Logger, conf_obj: dict, data_dict: dict, lang_dict: dict, *args, **kwargs):
super().__init__(*args, **kwargs)
self.debug_prints = {"checks": False, "author_commands": True, "guild_owner_commands": True,
"message_rendering": False, "unknown": False, "other": True}
self.logger = logger_obj
self.conf = conf_obj
self.data = data_dict
self.mods = []
self.modfold = modfold
self.mod_dict = {}
self.mod_exc_dict = {}
self.lang = lang_dict
self.langfold = langfold
self.validateLang = validateLang
self.loadLangs = loadLangs
self.tasks = {'ab': {}, 'aab': {}, 'abh': {}, 'abg': {}, 'gab': {}, 'gabh': {}, 'sched': {}, 'longcmd': {}}
self.local_tz: datetime.timezone = datetime.timezone(datetime.timedelta(seconds=0))
self.loadMods()
# Global checks
@self.check
def check_author_ban(ctx):
"""Example of date:
{
'user_data': {
'1002868442760284': {
'author_ban': {
'reason': 'Bot abuse',
'date_exp': {
'year': 2019,
'month': 10,
'day': 15,
'hour': 10,
'minute': 0
}
}
}
}
}
"""
self.debug_print('Checking for author ban', 'checks')
self.debug_print('ctx.author.id = %s, self.owner_id = %s' % (ctx.author.id, self.owner_id), 'checks')
# I'll always pass the bot author through, even if it is banned.
if ctx.author.id == self.owner_id:
self.debug_print('is the owner', 'checks')
return True
else:
self.debug_print('not owner', 'checks')
try:
if self.data['user_data'][str(ctx.author.id)]['author_ban']:
self.debug_print("%s has author-ban" % ctx.author.id, 'checks')
if 'date_exp' in self.data['user_data'][str(ctx.author.id)]['author_ban']:
date_exp = datetime.datetime(
**self.data['user_data'][str(ctx.author.id)]['author_ban']['date_exp'])
self.debug_print('date_exp present: %s' % date_exp, 'checks')
else:
self.debug_print('date_exp not present', 'checks')
date_exp = Never
if 'reason' in self.data['user_data'][str(ctx.author.id)]['author_ban']:
reason = self.data['user_data'][str(ctx.author.id)]['author_ban']['reason']
self.debug_print('reason present: %s' % reason, 'checks')
else:
self.debug_print('reason not present', 'checks')
reason = '--'
raise AuthorBan('You have been banned by author. Reason: %s' % reason, reason=reason,
date_exp=date_exp)
else:
return True
except (AttributeError, KeyError) as exc:
self.debug_print('check passed due to the missing fields: %s' % exc, 'checks')
return True
@self.check
def check_author_ban_here(ctx):
"""Example of data:
REDO:
{
'user_data': {
'1002868442760284': {
'author_ban_places': {
'25245794287592487': {
'23847239857948759': {
'reason': 'Command spam',
'date_exp': {
'year': 9999,
'month': 2,...
}
}
}
}
}
}
}
"""
# I'll always pass the bot author through, even if it is banned.
self.debug_print('checking for author ban in specific channel, here: %s' % ctx.channel.id, 'checks')
if ctx.author.id == self.owner_id or not ctx.guild:
self.debug_print('it is the owner of the bot', 'checks')
return True
self.debug_print('not the owner', 'checks')
try:
if self.data['user_data'][str(ctx.author.id)]['author_ban_places']:
# check if we have the guild.
self.debug_print('this user has some banned places', 'checks')
place = self.data['user_data'][str(ctx.author.id)]['author_ban_places'][str(ctx.guild.id)][
str(ctx.channel.id)]
self.debug_print('we have this ban in the database', 'checks')
# if we didn't got a KeyError exception, we ran on the place.
if 'date_exp' in place:
date_exp = datetime.datetime(**place['date_exp'])
self.debug_print('date_exp present: %s' % date_exp, 'checks')
else:
self.debug_print('date_exp is not present', 'checks')
date_exp = Never
if 'reason' in place:
reason = place['reason']
self.debug_print('reason is present: %s' % reason, 'checks')
else:
self.debug_print('reason is not present', 'checks')
reason = '--'
self.debug_print('author ban here check failed', 'checks')
raise AuthorBanHere('You have been banned by author in that place. Reason: %s' % reason,
reason=reason, date_exp=date_exp)
else:
self.debug_print('this user doesn\'t have any banned place', 'checks')
return True
except (AttributeError, KeyError) as exc:
self.debug_print('This check passed due to some fields are missing: %s' % exc, 'checks')
return True
@self.check
def check_author_ban_guild(ctx):
self.debug_print('check if the guild banned', 'checks')
if not ctx.guild:
self.debug_print('command used in DMs, check passed', 'checks')
return True
try:
if self.data['guild_data'][str(ctx.guild.id)]['author_ban']:
self.debug_print('yeah, this guild (ID %s, name %s) is banned' % (ctx.guild.id, ctx.guild.name),
'checks')
if 'date_exp' in self.data['guild_data'][str(ctx.guild.id)]['author_ban']:
date_exp = datetime.datetime(
**self.data['guild_data'][str(ctx.guild.id)]['author_ban']['date_exp'])
self.debug_print('date_exp is present: %s' % date_exp, 'checks')
else:
self.debug_print('date_exp is not present', 'checks')
date_exp = Never
if 'reason' in self.data['guild_data'][str(ctx.guild.id)]['author_ban']:
reason = self.data['guild_data'][str(ctx.guild.id)]['author_ban']['reason']
self.debug_print('reason is present: %s' % reason, 'checks')
else:
self.debug_print('reason is not present', 'checks')
reason = '--'
self.debug_print('author ban guild check failed', 'checks')
raise AuthorBanGuild('This guild has been banned by the author. Reason: %s' % reason, reason=reason,
date_exp=date_exp)
except (AttributeError, KeyError) as exc:
self.debug_print(
'Guild (ID %s, name %s) is not banned, check passed: %s' % (ctx.guild.id, ctx.guild.name, exc),
'checks')
return True
@self.check
def check_guild_admin_ban_here(ctx):
self.debug_print('check if the user (ID %s, name %s#%s) is banned on specific place by moderator.' % (
ctx.author.id, ctx.author.name, ctx.author.discriminator), 'checks')
if not ctx.guild:
self.debug_print('test passed because command issued at DMs', 'checks')
return True
if ctx.author.id == self.owner_id and 'owner_permission_bypass' in self.conf:
self.debug_print('author is the bot owner', 'checks')
if bool(self.conf['owner_permission_bypass']):
self.debug_print('passing this check because owner_permission_bypass enabled', 'checks')
return True
try:
if ctx.guild.owner_id == ctx.author.id:
self.debug_print('passing this check because the author is the guild owner', 'checks')
return True
if str(ctx.author.id) in self.data['guild_data'][str(ctx.guild.id)]['placebanned_users'][
str(ctx.channel.id)]:
self.debug_print('this user is banned on channel (ID %s, name %s) of the guild (ID %s, name %s)' % (
ctx.channel.id, ctx.channel.name, ctx.guild.id, ctx.guild.name), 'checks')
_ban = self.data['guild_data'][str(ctx.guild.id)]['placebanned_users'][str(ctx.channel.id)][
str(ctx.author.id)]
if 'date_exp' in _ban:
date_exp = datetime.datetime(**_ban['date_exp'])
self.debug_print('date_exp is present: %s' % date_exp, 'checks')
else:
date_exp = Never
self.debug_print('date_exp is not present', 'checks')
if 'reason' in _ban:
reason = _ban['reason']
self.debug_print('reason is present: %s' % reason, 'checks')
else:
reason = '--'
self.debug_print('reason is not present', 'checks')
self.debug_print('guild admin ban here check failed', 'checks')
raise GuildAdminBanHere(
'You have been banned by the guild\'s administrator here. Reason: %s' % reason, reason=reason,
date_exp=date_exp)
except (AttributeError, KeyError) as exc:
self.debug_print('check passed due to the missing fields: %s' % exc, 'checks')
return True
@self.check
def check_guild_admin_block_category(ctx):
self.debug_print('checking if the category of channels is blocked', 'checks')
if ctx.author.id == self.owner_id and 'owner_permission_bypass' in self.conf:
self.debug_print('bot owner issued the command', 'checks')
if bool(self.conf['owner_permission_bypass']):
self.debug_print('check passed because owner_permission_bypass enabled', 'checks')
return True
if not ctx.guild:
self.debug_print('check passed because command issued in DM\'s', 'checks')
return True
try:
if ctx.guild.owner_id == ctx.author.id:
self.debug_print('check passed: guild owner uses the command', 'checks')
return True
if ctx.channel.category_id in self.data['guild_data'][str(ctx.guild.id)]['denied_categories']:
self.debug_print(
'this category (ID %s, name %s) is blocked on the guild (ID %s, name %s), guild admin block '
'category check failed' % (
ctx.channel.category_id, ctx.channel.category.name, ctx.guild.id, ctx.guild.name), 'checks')
raise GuildAdminBlockCategory('You cannot use bot commands here.')
else:
self.debug_print('check passed: this category is not blocked', 'checks')
return True
except (AttributeError, KeyError) as exc:
self.debug_print('check passed: some of the fields are missing: %s' % exc, 'checks')
return True
@self.check
def check_guild_admin_block_channel(ctx):
self.debug_print('check if this channel is blocked on the guild', 'checks')
if not ctx.guild:
self.debug_print('check skipped: command used in DMs', 'checks')
return True
if ctx.author.id == self.owner_id and 'owner_permission_bypass' in self.conf:
self.debug_print('author is the bot owner', 'checks')