forked from Sonnet-Discord/sonnet-py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
907 lines (652 loc) · 28.9 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
# Check to ensure we don't import this file
if __name__ != "__main__":
import warnings
warnings.warn("LeXdPyK is not meant to be imported")
# Measure boot time
import time
kernel_start = time.monotonic()
# Intro
print("Booting LeXdPyK")
# Import core systems
import os, importlib, sys, io, traceback
# Import sub dependencies
import glob, json, hashlib, logging, getpass, datetime, argparse
# Import typing support
from typing import List, Optional, Any, Tuple, Dict, Union, Type, Protocol
# Start Discord.py
import discord, asyncio
# Initialize logger
logger = logging.getLogger('discord')
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)
# Initialize kernel workspace
sys.path.insert(1, os.getcwd() + '/cmds')
sys.path.insert(1, os.getcwd() + '/common')
sys.path.insert(1, os.getcwd() + '/libs')
sys.path.insert(1, os.getcwd() + '/dlibs')
intents = discord.Intents.default()
intents.typing = False
intents.presences = True
intents.guilds = True
intents.members = True
intents.reactions = True
# Initialize Discord Client.
Client = discord.Client(status=discord.Status.online, intents=intents)
# Define token encryption system "miniflip"
class miniflip:
__slots__ = "_width", "_passkey"
def __init__(self, password: str):
key = hashlib.sha512(password.encode("utf8")).digest()
self._width = 8
self._passkey = [int.from_bytes(key[i:i + self._width], "little") for i in range(0, len(key), self._width)]
def _btod(self, data: bytes) -> List[int]:
return [int.from_bytes(data[i:i + self._width], "little") for i in range(0, len(data), self._width)]
def _dtob(self, data: List[int]) -> bytes:
out = []
for chunk in data:
out.extend([(chunk >> (8 * i) & 0xff) for i in range(self._width)])
return bytes(out)
def _encrypt(self, data: bytes) -> bytes:
ndata = self._btod(data)
for i in self._passkey:
ndata = [chunk ^ i for chunk in ndata]
return self._dtob(ndata)
def _decrypt(self, data: bytes) -> bytes:
ndata = self._btod(data)
for i in self._passkey[::-1]:
ndata = [i ^ chunk for chunk in ndata]
return self._dtob(ndata)
def encrypt(self, indata: str) -> bytes:
data = indata.encode("utf8")
data = self._encrypt(data)[::-1]
data = self._encrypt(data)
data = self._encrypt(data)[::-1]
return data
def decrypt(self, data: bytes) -> Optional[str]:
data = self._decrypt(data)[::-1]
data = self._decrypt(data)
data = self._decrypt(data)[::-1]
try:
return data.rstrip(b"\x00").decode("utf8")
except UnicodeDecodeError:
return None
# Define ramfs
class ram_filesystem:
__slots__ = "data_table", "directory_table"
def __init__(self) -> None:
self.directory_table: Dict[str, "ram_filesystem"] = {}
self.data_table: Dict[str, Any] = {}
def __enter__(self) -> "ram_filesystem":
return self
def _parsedirlist(self, dirstr: Optional[str], dirlist: Optional[List[str]], allowNone: bool = False) -> List[str]:
if dirlist is None and dirstr is not None:
return dirstr.split("/")
elif dirlist is not None:
return dirlist
elif allowNone:
return []
raise TypeError("No dirstr or dirlist passed")
def mkdir(self, dirstr: Optional[str] = None, dirlist: Optional[List[str]] = None) -> "ram_filesystem":
# Make fs list
make_dir = self._parsedirlist(dirstr, dirlist)
path: "ram_filesystem" = self
for item in make_dir:
# If the current dir doesn't exist then create it
try:
path = path.directory_table[item]
except KeyError:
path.directory_table[item] = path = ram_filesystem()
return path
def remove_f(self, dirstr: Optional[str] = None, dirlist: Optional[List[str]] = None) -> Any:
remove_item = self._parsedirlist(dirstr, dirlist)
path: "ram_filesystem" = self
for i, item in enumerate(remove_item):
try:
if i < len(remove_item) - 1:
path = path.directory_table[item]
else:
del path.data_table[item]
except KeyError:
raise FileNotFoundError(f"No such filepath: {'/'.join(remove_item)}")
return path
def read_f(self, dirstr: Optional[str] = None, dirlist: Optional[List[str]] = None) -> Any:
file_to_open = self._parsedirlist(dirstr, dirlist)
path: "ram_filesystem" = self
for i, item in enumerate(file_to_open):
try:
if i < len(file_to_open) - 1:
path = path.directory_table[item]
else:
return path.data_table[item]
except KeyError:
raise FileNotFoundError("No such filepath: {'/'.join(file_to_open)}")
def create_f(self, dirstr: Optional[str] = None, dirlist: Optional[List[str]] = None, f_type: Optional[Type[Any]] = None, f_args: Optional[List[Any]] = None) -> Any:
f_type = io.BytesIO if f_type is None else f_type
f_args = [] if f_args is None else f_args
file_to_write = self._parsedirlist(dirstr, dirlist)
path: "ram_filesystem" = self
for i, item in enumerate(file_to_write):
if i < len(file_to_write) - 1:
try:
path = path.directory_table[item]
except KeyError:
path.directory_table[item] = path = ram_filesystem()
else:
f = path.data_table[item] = f_type(*f_args)
return f
def rmdir(self, dirstr: Optional[str] = None, dirlist: Optional[List[str]] = None) -> None:
directory_to_delete = self._parsedirlist(dirstr, dirlist)
path: "ram_filesystem" = self
for i, item in enumerate(directory_to_delete):
try:
if i < len(directory_to_delete) - 1:
path = path.directory_table[item]
else:
del path.directory_table[item]
except KeyError:
raise FileNotFoundError(f"No such filepath: {'/'.join(directory_to_delete)}")
def ls(self, dirstr: Optional[str] = None, dirlist: Optional[List[str]] = None) -> Tuple[List[str], List[str]]:
folderpath = self._parsedirlist(dirstr, dirlist, allowNone=True)
path: "ram_filesystem" = self
for item in folderpath:
try:
path = path.directory_table[item]
except KeyError:
raise FileNotFoundError(f"No such filepath: {'/'.join(folderpath)}")
return list(path.data_table), list(path.directory_table)
def tree(self, dirstr: Optional[str] = None, dirlist: Optional[List[str]] = None) -> Any:
folderpath = self._parsedirlist(dirstr, dirlist, allowNone=True)
path: "ram_filesystem" = self
for item in folderpath:
try:
path = path.directory_table[item]
except KeyError:
raise FileNotFoundError(f"No such filepath: {'/'.join(folderpath)}")
datamap: Tuple[List[str], Dict[str, Any]] = (list(path.data_table), {})
for folder in path.directory_table:
datamap[1][folder] = path.directory_table[folder].tree()
return datamap
# Import blacklist
try:
with open("common/blacklist.json", "r", encoding="utf-8") as blacklist_file:
blacklist = json.load(blacklist_file)
# Ensures blacklist properly init
assert isinstance(blacklist["guild"], list)
assert isinstance(blacklist["user"], list)
except FileNotFoundError:
blacklist = {"guild": [], "user": []}
with open("common/blacklist.json", "w", encoding="utf-8") as blacklist_file:
json.dump(blacklist, blacklist_file)
# Define debug commands
command_modules: List[Any] = []
command_modules_dict: Dict[str, Any] = {}
dynamiclib_modules: List[Any] = []
dynamiclib_modules_dict: Dict[str, Any] = {}
# Initialize ramfs, kernel ramfs
ramfs = ram_filesystem()
kernel_ramfs = ram_filesystem()
# Define kernel syntax error
class KernelSyntaxError(SyntaxError):
pass
# Import configs
from LeXdPyK_conf import BOT_OWNER as KNOWN_OWNER
UNKNOWN_OWNER: Any = KNOWN_OWNER
BOT_OWNER: List[int]
if isinstance(UNKNOWN_OWNER, (str, int)):
BOT_OWNER = [int(UNKNOWN_OWNER)] if UNKNOWN_OWNER else []
elif isinstance(UNKNOWN_OWNER, (list, tuple)):
BOT_OWNER = [int(i) for i in UNKNOWN_OWNER]
else:
BOT_OWNER = []
def kernel_load_command_modules(args: List[str] = []) -> Optional[Tuple[str, List[Exception]]]:
print("Loading Kernel Modules")
# Globalize variables
global command_modules, command_modules_dict, dynamiclib_modules, dynamiclib_modules_dict
command_modules = []
command_modules_dict = {}
dynamiclib_modules = []
dynamiclib_modules_dict = {}
importlib.invalidate_caches()
# Init return state
err: List[Tuple[Exception, str]] = []
# Init imports
for f in filter(lambda f: f.startswith("cmd_") and f.endswith(".py"), os.listdir('./cmds')):
print(f)
try:
command_modules.append(importlib.import_module(f[:-3]))
except Exception as e:
err.append((e, f[:-3]), )
for f in filter(lambda f: f.startswith("dlib_") and f.endswith(".py"), os.listdir("./dlibs")):
print(f)
try:
dynamiclib_modules.append(importlib.import_module(f[:-3]))
except Exception as e:
err.append((e, f[:-3]), )
# Update hashmaps
for module in command_modules:
try:
command_modules_dict.update(module.commands)
except AttributeError:
err.append((KernelSyntaxError("Missing commands"), module.__name__), )
for module in dynamiclib_modules:
try:
dynamiclib_modules_dict.update(module.commands)
except AttributeError:
err.append((KernelSyntaxError("Missing commands"), module.__name__), )
if err: return ("\n".join([f"Error importing {i[1]}: {type(i[0]).__name__}: {i[0]}" for i in err]), [i[0] for i in err])
else: return None
def regenerate_ramfs(args: List[str] = []) -> Optional[Tuple[str, List[Exception]]]:
global ramfs
ramfs = ram_filesystem()
return None
def regenerate_kernel_ramfs(args: List[str] = []) -> Optional[Tuple[str, List[Exception]]]:
global kernel_ramfs
kernel_ramfs = ram_filesystem()
return None
def kernel_reload_command_modules(args: List[str] = []) -> Optional[Tuple[str, List[Exception]]]:
print("Reloading Kernel Modules")
# Init vars
global command_modules, command_modules_dict, dynamiclib_modules, dynamiclib_modules_dict
command_modules_dict = {}
dynamiclib_modules_dict = {}
# Init ret state
err = []
# Update set
for i in range(len(command_modules)):
try:
command_modules[i] = (importlib.reload(command_modules[i]))
except Exception as e:
err.append([e, command_modules[i].__name__])
for i in range(len(dynamiclib_modules)):
try:
dynamiclib_modules[i] = (importlib.reload(dynamiclib_modules[i]))
except Exception as e:
err.append([e, dynamiclib_modules[i].__name__])
# Update hashmaps
for module in command_modules:
try:
command_modules_dict.update(module.commands)
except AttributeError:
err.append([KernelSyntaxError("Missing commands"), module.__name__])
for module in dynamiclib_modules:
try:
dynamiclib_modules_dict.update(module.commands)
except AttributeError:
err.append([KernelSyntaxError("Missing commands"), module.__name__])
# Regen tempramfs
regenerate_ramfs()
if err: return ("\n".join([f"Error reimporting {i[1]}: {type(i[0]).__name__}: {i[0]}" for i in err]), [i[0] for i in err])
else: return None
def kernel_blacklist_guild(args: List[str] = []) -> Optional[Tuple[str, List[Exception]]]:
try:
blacklist["guild"].append(int(args[0]))
except (ValueError, IndexError):
return "Asking value is not INT", []
with open("common/blacklist.json", "w", encoding="utf-8") as blacklist_file:
json.dump(blacklist, blacklist_file)
return None
def kernel_blacklist_user(args: List[str] = []) -> Optional[Tuple[str, List[Exception]]]:
try:
blacklist["user"].append(int(args[0]))
except (ValueError, IndexError):
return "Asking value is not INT", []
with open("common/blacklist.json", "w", encoding="utf-8") as blacklist_file:
json.dump(blacklist, blacklist_file)
return None
def kernel_unblacklist_guild(args: List[str] = []) -> Optional[Tuple[str, List[Exception]]]:
try:
if int(args[0]) in blacklist["guild"]:
del blacklist["guild"][blacklist["guild"].index(int(args[0]))]
else:
return "Item is not blacklisted", []
except (ValueError, IndexError):
return "Asking value is not INT", []
with open("common/blacklist.json", "w", encoding="utf-8") as blacklist_file:
json.dump(blacklist, blacklist_file)
return None
def kernel_unblacklist_user(args: List[str] = []) -> Optional[Tuple[str, List[Exception]]]:
try:
if int(args[0]) in blacklist["user"]:
del blacklist["user"][blacklist["user"].index(int(args[0]))]
else:
return "Item is not blacklisted", []
except (ValueError, IndexError):
return "Asking value is not INT", []
with open("common/blacklist.json", "w", encoding="utf-8") as blacklist_file:
json.dump(blacklist, blacklist_file)
return None
def kernel_logout(args: List[str] = []) -> Optional[Tuple[str, List[Exception]]]:
asyncio.create_task(Client.close())
return None
def kernel_drop_dlibs(args: List[str] = []) -> Optional[Tuple[str, List[Exception]]]:
global dynamiclib_modules, dynamiclib_modules_dict
dynamiclib_modules = []
dynamiclib_modules_dict = {}
return None
def kernel_drop_cmds(args: List[str] = []) -> Optional[Tuple[str, List[Exception]]]:
global command_modules, command_modules_dict
command_modules = []
command_modules_dict = {}
return None
def logging_toggle(args: List[str] = []) -> Optional[Tuple[str, List[Exception]]]:
if logger.isEnabledFor(10):
logger.setLevel(20)
return "Logging at L20", []
else:
logger.setLevel(10)
return "Logging at L10", []
class DebugCallable(Protocol):
def __call__(self, args: List[str] = []) -> Optional[Tuple[str, List[Exception]]]:
return None
# Generate debug command subset
debug_commands: Dict[str, DebugCallable] = {}
debug_commands["debug-add-guild-blacklist"] = kernel_blacklist_guild
debug_commands["debug-add-user-blacklist"] = kernel_blacklist_user
debug_commands["debug-remove-guild-blacklist"] = kernel_unblacklist_guild
debug_commands["debug-remove-user-blacklist"] = kernel_unblacklist_user
debug_commands["debug-modules-load"] = kernel_load_command_modules
debug_commands["debug-modules-reload"] = kernel_reload_command_modules
debug_commands["debug-logout-system"] = kernel_logout
debug_commands["debug-drop-ramfs"] = regenerate_ramfs
debug_commands["debug-drop-kramfs"] = regenerate_kernel_ramfs
debug_commands["debug-drop-modules"] = kernel_drop_dlibs
debug_commands["debug-drop-commands"] = kernel_drop_cmds
debug_commands["debug-toggle-logging"] = logging_toggle
# A object used to pass error messages from the kernel callers to the event handlers
class errtype:
__slots__ = "err", "errmsg"
def __init__(self, err: Exception, argtype: str):
self.err = err
owner: str = f"<@!{BOT_OWNER[0]}>" if BOT_OWNER else "BOT OWNER"
self.errmsg = f"FATAL ERROR in {argtype}\nPlease contact {owner}\nErr: `{type(err).__name__}: {err}`"
traceback.print_exception(type(self.err), self.err, self.err.__traceback__)
with open("err.log", "a+", encoding="utf-8") as logfile:
logfile.write(f"AT {time.strftime('%a, %d %b %Y %H:%M:%S', datetime.datetime.now(datetime.timezone.utc).utctimetuple())}:\n")
logfile.write("".join(traceback.format_exception(type(self.err), self.err, self.err.__traceback__)))
# KeyError sentinel so we don't catch KeyError
class KernelKeyError(KeyError):
pass
# Catch errors
@Client.event
async def on_error(event: str, *args: Any, **kwargs: Any) -> None:
raise
async def do_event(event: Any, args: Tuple[Any, ...]) -> None:
await event(
*args,
client=Client,
ramfs=ramfs,
bot_start=bot_start_time,
command_modules=[command_modules, command_modules_dict],
dynamiclib_modules=[dynamiclib_modules, dynamiclib_modules_dict],
kernel_version=version_info,
kernel_ramfs=kernel_ramfs
)
async def event_call(argtype: str, *args: Any) -> Optional[errtype]:
etypes = []
try:
# Do hash lookup with KeyError
# Separate from running function so we do not catch a KeyError deeper in the stack
try:
func = dynamiclib_modules_dict[argtype]
except KeyError:
raise KernelKeyError
await do_event(func, args)
# Check for KernelKeyError before checking for Exception (inherits from)
except KernelKeyError:
pass
except Exception as e:
etypes.append(errtype(e, argtype))
call = 0
while True:
exname = f"{argtype}-{call}"
# If there is no hash then break the loop
try:
func = dynamiclib_modules_dict[exname]
except KeyError:
break
try:
await do_event(func, args)
except Exception as e:
etypes.append(errtype(e, exname))
call += 1
if etypes:
return etypes[0]
else:
return None
async def safety_check(guild: Optional[discord.Guild] = None, guild_id: Optional[int] = None, user: Optional[Union[discord.User, discord.Member]] = None, user_id: Optional[int] = None) -> bool:
if guild: guild_id = guild.id
if user: user_id = user.id
if user_id and user_id in blacklist["user"] and guild_id:
try:
user = await Client.fetch_user(user_id)
except discord.errors.HTTPException:
return False
try:
guild = await Client.fetch_guild(guild_id)
except discord.errors.HTTPException:
return False
try:
await guild.ban(user, reason="LeXdPyK: SYSTEM LEVEL BLACKLIST", delete_message_days=0)
except discord.errors.Forbidden:
blacklist["guild"].append(guild_id)
try:
await guild.leave()
return False
except discord.errors.HTTPException:
pass
except discord.errors.HTTPException:
return False
return False
if guild_id and guild_id in blacklist["guild"]:
try:
guild = await Client.fetch_guild(guild_id)
except discord.errors.HTTPException:
return False
try:
await guild.leave()
return False
except discord.errors.HTTPException:
pass
return False
return True
async def sendable_send(sendable: Any, message: str) -> None:
if isinstance(sendable, (discord.TextChannel, discord.DMChannel)):
try:
await sendable.send(message)
except discord.errors.HTTPException:
pass
@Client.event
async def on_connect() -> None:
await event_call("on-connect")
@Client.event
async def on_disconnect() -> None:
await event_call("on-disconnect")
@Client.event
async def on_ready() -> None:
await event_call("on-ready")
@Client.event
async def on_resumed() -> None:
await event_call("on-resumed")
@Client.event
async def on_message(message: discord.Message) -> None:
args = message.content.split(" ")
# If bot owner run a debug command
if len(args) >= 2 and args[0] in debug_commands:
if message.author.id in BOT_OWNER and args[1].strip("<@!>") == str(Client.user.id):
if e := debug_commands[args[0]](args[2:]):
await message.channel.send(e[0])
for i in e[1]:
errtype(i, "")
else:
await sendable_send(message.channel, "Debug command returned no error status")
return
if await safety_check(guild=message.guild, user=message.author):
if err := await event_call("on-message", message):
await sendable_send(message.channel, err.errmsg)
@Client.event
async def on_message_delete(message: discord.Message) -> None:
if await safety_check(guild=message.guild, user=message.author):
if e := await event_call("on-message-delete", message):
await sendable_send(message.channel, e.errmsg)
@Client.event
async def on_bulk_message_delete(messages: List[discord.Message]) -> None:
if await safety_check(guild=messages[0].guild, user=messages[0].author):
if e := await event_call("on-bulk-message-delete", messages):
await sendable_send(messages[0].channel, e.errmsg)
@Client.event
async def on_raw_message_delete(payload: discord.RawMessageDeleteEvent) -> None:
if await safety_check(guild_id=payload.guild_id):
if e := await event_call("on-raw-message-delete", payload):
await sendable_send(Client.get_channel(payload.channel_id), e.errmsg)
@Client.event
async def on_raw_bulk_message_delete(payload: discord.RawBulkMessageDeleteEvent) -> None:
if await safety_check(guild_id=payload.guild_id):
if e := await event_call("on-raw-bulk-message-delete", payload):
await sendable_send(Client.get_channel(payload.channel_id), e.errmsg)
@Client.event
async def on_message_edit(old_message: discord.Message, message: discord.Message) -> None:
if await safety_check(guild=message.guild, user=message.author):
if e := await event_call("on-message-edit", old_message, message):
await sendable_send(message.channel, e.errmsg)
@Client.event
async def on_raw_message_edit(payload: discord.RawMessageUpdateEvent) -> None:
if e := await event_call("on-raw-message-edit", payload):
await sendable_send(Client.get_channel(payload.channel_id), e.errmsg)
@Client.event
async def on_reaction_add(reaction: discord.Reaction, user: Union[discord.Member, discord.User]) -> None:
if await safety_check(guild=reaction.message.guild, user=user):
if e := await event_call("on-reaction-add", reaction, user):
await sendable_send(reaction.message.channel, e.errmsg)
@Client.event
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent) -> None:
if await safety_check(guild_id=payload.guild_id, user_id=payload.user_id):
if e := await event_call("on-raw-reaction-add", payload):
await sendable_send(Client.get_channel(payload.channel_id), e.errmsg)
@Client.event
async def on_reaction_remove(reaction: discord.Reaction, user: Union[discord.Member, discord.User]) -> None:
if await safety_check(guild=reaction.message.guild, user=user):
if e := await event_call("on-reaction-remove", reaction, user):
await sendable_send(reaction.message.channel, e.errmsg)
@Client.event
async def on_raw_reaction_remove(payload: discord.RawReactionActionEvent) -> None:
if await safety_check(guild_id=payload.guild_id, user_id=payload.user_id):
if e := await event_call("on-raw-reaction-remove", payload):
await sendable_send(Client.get_channel(payload.channel_id), e.errmsg)
@Client.event
async def on_reaction_clear(message: discord.Message, reactions: List[discord.Reaction]) -> None:
if await safety_check(guild=message.guild, user=message.author):
if e := await event_call("on-reaction-clear", message, reactions):
await sendable_send(message.channel, e.errmsg)
@Client.event
async def on_raw_reaction_clear(payload: discord.RawReactionClearEvent) -> None:
if await safety_check(guild_id=payload.guild_id):
if e := await event_call("on-raw-reaction-clear", payload):
await sendable_send(Client.get_channel(payload.channel_id), e.errmsg)
@Client.event
async def on_reaction_clear_emoji(reaction: discord.Reaction) -> None:
if await safety_check(guild=reaction.message.guild):
if e := await event_call("on-reaction-clear-emoji", reaction):
await sendable_send(reaction.message.channel, e.errmsg)
@Client.event
async def on_raw_reaction_clear_emoji(payload: discord.RawReactionClearEvent) -> None:
if await safety_check(guild_id=payload.guild_id):
if e := await event_call("on-raw-reaction-clear-emoji", payload):
await sendable_send(Client.get_channel(payload.channel_id), e.errmsg)
@Client.event
async def on_member_join(member: discord.Member) -> None:
if await safety_check(user=member, guild=member.guild):
await event_call("on-member-join", member)
@Client.event
async def on_member_remove(member: discord.Member) -> None:
if await safety_check(guild=member.guild):
await event_call("on-member-remove", member)
@Client.event
async def on_member_update(before: discord.Member, after: discord.Member) -> None:
if await safety_check(user=before, guild=before.guild):
await event_call("on-member-update", before, after)
@Client.event
async def on_guild_join(guild: discord.Guild) -> None:
if await safety_check(guild=guild):
await event_call("on-guild-join", guild)
@Client.event
async def on_guild_remove(guild: discord.Guild) -> None:
await event_call("on-guild-remove", guild)
@Client.event
async def on_guild_update(before: discord.Guild, after: discord.Guild) -> None:
if await safety_check(guild=before):
await event_call("on-guild-update", before, after)
@Client.event
async def on_member_ban(guild: discord.Guild, user: discord.User) -> None:
if await safety_check(guild=guild):
await event_call("on-member-ban", guild, user)
@Client.event
async def on_member_unban(guild: discord.Guild, user: discord.User) -> None:
if await safety_check(guild=guild, user=user):
await event_call("on-member-unban", guild, user)
def gentoken() -> str:
TOKEN = getpass.getpass("Enter TOKEN: ")
passwd = getpass.getpass("Enter TOKEN password: ")
if passwd != getpass.getpass("Confirm TOKEN password: "):
print("ERROR: passwords do not match")
raise ValueError
with open(".tokenfile", "wb") as tokenfile:
encryptor = miniflip(passwd)
tokenfile.write(encryptor.encrypt(TOKEN))
return TOKEN
# Main function, handles userland startup
def main(args: List[str]) -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--log-debug", action="store_true", help="makes the logging module start in debug mode")
parser.add_argument("--generate-token", action="store_true", help="discards the current token file if there is one, and generates a new encrypted tokenfile")
parser.add_argument("--version", "-v", action="store_true", help="print version info and exit")
parsed = parser.parse_args()
if parsed.version:
import platform
pyver = f"{platform.python_implementation()} {platform.python_version()}"
print(f"{version_info} @ {os.getcwd()}\n{pyver} @ {sys.executable}")
return 0
# Set Loglevel
loglevel = logging.DEBUG if parsed.log_debug else logging.INFO
logger.setLevel(loglevel)
# Get token from environment variables.
TOKEN: Optional[str] = os.environ.get('SONNET_TOKEN') or os.environ.get('RHEA_TOKEN')
# Generate tokenfile
if parsed.generate_token:
try:
TOKEN = gentoken()
except ValueError:
return 1
# Load token
if TOKEN is None and os.path.isfile(".tokenfile"):
tokenfile = open(".tokenfile", "rb")
encryptor = miniflip(getpass.getpass("Enter TOKEN password: "))
TOKEN = encryptor.decrypt(tokenfile.read())
tokenfile.close()
if TOKEN is None:
print("Invalid TOKEN password")
return 1
# Load command modules
if e := kernel_load_command_modules():
print(e[0])
# Start bot
if TOKEN:
try:
Client.run(TOKEN, reconnect=True)
except discord.errors.LoginFailure:
print("Invalid token passed")
return 1
else:
print("You need a token set in SONNET_TOKEN or RHEA_TOKEN environment variables, or a encrypted token in .tokenfile, to use sonnet")
return 1
# Clear cache at exit
for i in glob.glob("datastore/*.cache.db"):
os.remove(i)
print("\rCache Cleared, Thank you for Using Sonnet")
return 0
# Define version info and start time
version_info: str = "LeXdPyK 1.4.10"
bot_start_time: float = time.time()
if __name__ == "__main__":
print(f"Booted kernel in {(time.monotonic()-kernel_start)*1000:.0f}ms")
sys.exit(main(sys.argv))