-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.py
1476 lines (1124 loc) · 48.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
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import discord, os, glob, re, json, logging
from typing import Any
from discord.ext import tasks
from dotenv import load_dotenv
from ruamel.yaml import YAML, constructor
from datetime import datetime, timedelta, timezone
import emoji as emojilib
logging.basicConfig(filename="bot.log", encoding="utf-8", format="%(asctime)s - %(levelname)s: %(message)s", level=logging.DEBUG)
logging.info("Startup")
def utcnow() -> datetime:
logging.debug("Retreived UTC time")
return datetime.now(timezone.utc)
def format_timedelta(td: timedelta, smallest_unit="s") -> str:
result = str(td)
match smallest_unit:
case "s": result = re.sub(r"\.\d+", "", str(td))
case "m": result = re.sub(r":\d+\.\d+", "", str(td))
case "h": result = re.sub(r":\d+:\d+\.\d+", "", str(td))
logging.debug("Converted timedelta to string with '%s' as the smallest unit: %s", smallest_unit, result)
return result
def string_to_timedelta(string: str) -> timedelta:
weeks = re.findall(r"(\d+) ?w(?:eeks?)?", string, re.IGNORECASE)
days = re.findall(r"(\d+) ?d(?:ays?)?", string, re.IGNORECASE)
hours = re.findall(r"(\d+) ?h(?:ours?)?", string, re.IGNORECASE)
minutes = re.findall(r"(\d+) ?m(?:in|minutes?)?", string, re.IGNORECASE)
seconds = re.findall(r"(\d+) ?s(?:ec|econds?)?", string, re.IGNORECASE)
w = int(weeks[0]) if weeks else 0
d = int(days[0]) if days else 0
h = int(hours[0]) if hours else 0
m = int(minutes[0]) if minutes else 0
s = int(seconds[0]) if seconds else 0
result = timedelta(
weeks=w,
days=d,
hours=h,
minutes=m,
seconds=s
)
logging.debug("Converted string to timedelta: '%s' -> %s", string, result)
return result
# https://discord.com/developers/docs/reference#message-formatting-timestamp-styles
def timestamp(dt: datetime, mode: str = "") -> str:
result: str = ""
if not mode: result = f"<t:{int(dt.timestamp())}>"
else: result = f"<t:{int(dt.timestamp())}:{mode}>"
logging.debug("Converted datetime to timestamp: %s -> %s", dt, result)
return result
# ---------- Load Token ---------- #
load_dotenv()
TOKEN = os.getenv("TOKEN")
# ---------- Load YAML ---------- #
yaml_files: list[str] = []
for pattern in ["*.yml", "*.yaml"]:
yaml_files += glob.glob(pattern)
if yaml_files:
logging.info("Found the following YAML files: %s", yaml_files)
else:
logging.critical("Could not find any YAML files")
raise FileNotFoundError("Could not find any YAML files.")
for path in yaml_files:
logging.info("Trying to load: %s", path)
try:
with open(path, encoding="utf8") as f:
yaml = YAML(typ="safe").load(f)
except constructor.DuplicateKeyError: # Top notch error handling
logging.critical("YAML contains duplicate keys")
raise constructor.DuplicateKeyError("Duplicate keys are not supported.")
except Exception as e:
logging.critical(e)
raise e
if yaml:
logging.info("Loaded: %s", path)
break
# I feel like errors have so much more to offer while Im just using them to print a message...
if not yaml:
logging.critical("YAML is empty")
raise SyntaxError("YAML file is empty.")
if not isinstance(yaml, dict):
logging.critical("YAML is not a dictionary")
raise TypeError("YAML is not a dictionary.")
print(f"Executing {path}")
logging.info("Executing: %s", path)
# ---------- Assign Intents ---------- #
intents = discord.Intents.default()
if "intents" in yaml:
logging.info("Setting intents")
if not isinstance(yaml["intents"], list):
logging.critical("Intents are of type '%s' and not 'list'", type(yaml["intents"]))
raise TypeError("Intents must be a list of strings.")
for intent in yaml["intents"]:
logging.info("Enabling intent: %s", intent)
if not isinstance(intent, str):
logging.critical("Intent is not string")
raise TypeError("Intents must be string values")
if not hasattr(intents, intent):
logging.critical("Intent is invalid")
raise ValueError(f"'{intent}' is not a valid intent.")
exec(f"intents.{intent} = True")
logging.info("Finished setting intents")
else: logging.info("YAML does not contain intents")
client = discord.Client(intents=intents)
# ---------- Create Variables ---------- #
yaml_variables: list[str] = []
if "variables" in yaml:
logging.info("Assigning variables")
for var in yaml["variables"]:
logging.info("Assiging: %s", var)
if not isinstance(var, str):
logging.critical("Variable is not a string")
raise SyntaxError("Variable names must be string.")
if not re.fullmatch(r"[A-z_][A-z0-9_]*", var):
logging.critical("Invalid variable name")
raise SyntaxError(f"'{var}' is not a valid variable name. It can only contain letters, numbers and underscores. It cannot start with a number.")
yaml_variables.append(var)
logging.info("Value: %s", repr(yaml["variables"][var]))
exec(f'{var} = {repr(yaml["variables"][var])}')
else: logging.info("YAML does not contain variables")
# ---------- Guild With More Stats ---------- #
# Guild has slots which makes it hard to extend, hopefully this works
class Guild(discord.Guild):
def __init__(self, guild: discord.Guild) -> None:
logging.debug("Converting discord.Guild to Guild: %s", guild)
if not guild: return
self.role_count = len(guild.roles)
self.category_count = len(guild.categories)
self.forum_count = len(guild.forums)
self.channel_count = len(guild.channels)
self.emoji_count = len(guild.emojis)
self.event_count = len(guild.scheduled_events)
self.stage_channel_count = len(guild.stage_channels)
self.stage_instance_count = len(guild.stage_instances)
self.sticker_count = len(guild.stickers)
self.text_channel_count = len(guild.text_channels)
self.thread_count = len(guild.threads)
self.voice_channel_count = len(guild.voice_channels)
for key in guild.__slots__:
setattr(self, key, getattr(guild, key))
# ---------- JSON ---------- #
class SaveHandler:
path = ""
data = {
"messages": {},
"timers": []
}
def __init__(self, path: str) -> None:
logging.info("Initialising the SaveHandler")
self.path = path
logging.info("Trying to load: %s", path)
try:
with open(path) as f:
self.data = json.load(f)
except Exception as e:
logging.warn("Loading failed: %s", e)
self.save()
def save(self) -> None:
logging.info("Saving: %s", self.path)
logging.debug("Data: %s", self.data)
with open(self.path, "w") as f:
json.dump(self.data, f, indent=4)
logging.debug("Saved")
# I cant specify that func should be a Function because pyton has no forward declaration :(
async def get_message(self, func) -> discord.Message:
logging.info("Retreiving message: %s", func.execution_path if func else "None")
if not func:
logging.error("Invalid function")
return None
if "messages" not in self.data:
logging.warn("Does not contain any messages")
return None
if func.execution_path not in self.data["messages"]:
logging.warn("Does not contain message: %s", func.execution_path)
return None
msg = self.data["messages"][func.execution_path]
logging.debug("Found message: %s", msg)
if "channel" not in msg:
logging.error("Message does not contain a channel")
return None
if "id" not in msg:
logging.error("Message does not contain an ID")
return None
channel = await func.get_channel(msg["channel"])
if not channel:
logging.error("Could not find channel: %s", msg["channel"])
return None
try:
message = await channel.fetch_message(msg["id"])
except discord.NotFound:
logging.error("Could not find message: %s", msg["id"])
return None
except Exception as e: logging.error(e)
return message
def save_msg(self, func) -> None:
logging.info("Saving message: %s", func.execution_path if func else "None")
if not func:
logging.error("Invalid function")
return
if not hasattr(func, "msg"):
logging.error("Function does not have message")
return
if not func.msg:
logging.error("Invalid message")
return
if "messages" not in self.data:
logging.debug("Created a dictionary for messages in data")
self.data["messages"] = {}
self.data["messages"][func.execution_path] = {
"channel": func.msg.channel.id,
"id": func.msg.id
}
self.save()
def save_timer(self, func) -> None:
logging.info("Saving timer: %s", func.execution_path if func else "None")
if not func:
logging.error("Invalid function")
return
if not hasattr(func, "time"):
logging.error("Function does not have time")
return
if not hasattr(func, "do"):
logging.error("Timer does not have functions")
return
if not func.time:
logging.error("Invalid time")
return
if "timers" not in self.data:
logging.debug("Created a list for timers in data")
self.data["timers"] = []
self.data["timers"].append({
"func": func.execution_path,
"channel": func.channel.id if func.channel else None,
"user": func.user.id if func.user else None,
"guild": func.guild.id if func.guild else None,
"time": func.time.isoformat() if func.time else None,
"do": func.do
})
self.save()
def remove_timer_by_path(self, execution_path: str) -> None:
logging.log("Removing timer: %s", execution_path)
found = False
for x in self.get_timers():
if x["func"] == execution_path:
found = True
self.data["timers"].remove(x)
logging.info("Removed timer")
break
if found: self.save()
else: logging.warn("Could not find timer")
def remove_timers(self, timers: list[dict]) -> None:
logging.log("Removing timers: %s", [x.get("func") for x in timers])
for x in timers:
self.data["timers"].remove(x)
self.save()
def get_timers(self) -> list[dict]:
value = self.data.get("timers", [])
logging.debug("Retreiving timers: %s", value)
return value
save_data = SaveHandler("data.json")
# ---------- Functions ---------- #
# Functions should probably have their own file but Im too lazy
# Abstract-ish (you can instantiate it but it will convert itself to the correct type)
class Function:
channel: discord.TextChannel = None
user: discord.Member | discord.User = None
guild: discord.Guild = None
raw_function = {}
function_name = ""
execution_path = ""
additional_variables = {}
def __init__(self, raw_function: dict = None, channel: discord.TextChannel = None, user: discord.Member | discord.User = None, guild: discord.Guild = None, execution_path: str = "") -> None:
logging.info("Initialising function: %s", execution_path)
logging.debug("Raw function: %s", raw_function)
logging.debug("Channel: %s", channel)
logging.debug("User: %s", user)
logging.debug("Guild: %s", guild)
self.channel = None
self.user = None
self.guild = None
self.raw_function = {}
self.function_name = ""
self.execution_path = ""
self.additional_variables = {}
if not raw_function:
logging.error("Invalid Function")
return
if not isinstance(raw_function, dict):
logging.error("Function is of type '%s' and 'dict'", type(raw_function))
return
self.channel = channel
self.user = user
if guild: self.guild = Guild(guild)
elif isinstance(user, discord.Member):
self.guild = Guild(user.guild)
logging.debug("Assigned guild through user: %s", user.guild)
self.raw_function = raw_function
self.function_name = list(raw_function.keys())[0]
self.execution_path = execution_path + " -> " + self.function_name
self.assign_type(self.function_name)
def assign_type(self, function_name: str) -> bool:
logging.debug("Assigning function type: %s", function_name)
match function_name.lower().replace(" ", "_"):
case "add_role" | "add_roles": self.__class__ = FunctionAddRoles
case "remove_role" | "remove_roles": self.__class__ = FunctionRemoveRoles
case "set_variable" | "set_variables": self.__class__ = FunctionSetVariable
case "update_roles": self.__class__ = FunctionUpdateRoles
case "update_message": self.__class__ = FunctionUpdateMessage
case "send_message": self.__class__ = FunctionSendMessage
case "response": self.__class__ = FunctionResponseMessage
case "wait": self.__class__ = FunctionWait
case "condition": self.__class__ = FunctionCondition
case _:
logging.error("Invalid function: %s", function_name)
return False
logging.debug("Assigned type: %s", self.__class__)
return True
# virtual
async def find_arguments(self, arguments) -> None:
logging.debug("Assigning arguments: %s", arguments)
# virtual
async def execute(self) -> bool:
logging.info("Executing: %s", self.execution_path)
await self.find_arguments(self.raw_function[self.function_name])
return False
async def get_user(self, id: int | str) -> discord.Member | discord.User:
logging.info("Rerieving user: %s", id)
if not id:
logging.warn("No ID")
return None
if isinstance(id, str):
var = id.replace(" ", "_")
if var in yaml_variables:
logging.debug("Resolving variable")
return await self.get_user(eval(var))
if id.startswith("@"): id = id[1:]
if self.guild:
logging.debug("Checking guild members")
if isinstance(id, int):
user = self.guild.get_member(id)
if not user: user = await self.guild.fetch_member(id)
return user
elif not isinstance(id, str):
logging.error("User is not int or string")
return None
if id.lower() == "user":
logging.debug("Returning self.user")
return self.user
return self.guild.get_member_named(id)
else:
if isinstance(id, int):
user = client.get_user(id)
if not user: user = await client.fetch_user(id)
return user
elif not isinstance(id, str):
logging.error("User is not int or string")
return
for user in client.users:
if str(user) == id: return user
if user.name == id: return user
for user in client.get_all_members():
if str(user) == id: return user
if user.name == id: return user
if user.nick == id: return user
def get_role(self, id: int | str) -> discord.Role:
logging.info("Rerieving role: %s", id)
if not id:
logging.warn("No ID")
return None
if isinstance(id, str):
var = id.replace(" ", "_")
if var in yaml_variables:
logging.debug("Resolving variable")
return self.get_role(eval(var))
if id.startswith("@"): id = id[1:]
if not self.guild:
logging.warn("Does not have guild")
if self.user:
logging.debug("Checking mutual guilds")
for guild in self.user.mutual_guilds:
if isinstance(id, int):
role = guild.get_role(id)
if role:
logging.debug("Found role")
return role
for role in guild.roles:
if role.name == id:
logging.debug("Found role")
return role
logging.warn("Could not find role")
return None
else:
logging.warn("Does not have guild or user")
return None
if isinstance(id, int):
role = self.guild.get_role(id)
if role: logging.debug("Found role")
else: logging.warn("Could not find role")
return role
for role in self.guild.roles:
if role.name == id:
logging.debug("Found role")
return role
logging.warn("Could not find role")
return None
async def get_channel(self, id: int | str):
logging.info("Rerieving channel: %s", id)
if not id:
logging.warn("No ID")
return None
if isinstance(id, int):
channel = client.get_channel(id)
if channel: return channel
channel = await client.fetch_channel(id)
return channel
if not isinstance(id, str):
logging.error("Channel is not int or string")
return None
var = id.replace(" ", "_")
if var in yaml_variables:
logging.debug("Resolving variable")
return await self.get_channel(eval(var))
if id.startswith("#"): id = id[1:]
for channel in client.get_all_channels():
if channel.name == id: return channel
logging.warn("Could not find channel")
return None
def get_colour(self, id: int | str) -> int:
logging.info("Rerieving colour: %s", id)
if not id:
logging.warn("No ID")
return None
if isinstance(id, int):
logging.debug("Colour is int, returning as is")
return id
if id in yaml_variables:
logging.debug("Resolving variable")
return self.get_colour(eval(id))
logging.warn("Could not find colour")
return None
def get_emoji(self, id: int | str) -> discord.Emoji | str:
logging.info("Rerieving emoji: %s", id)
if not id:
logging.warn("No ID")
return None
emoji = None
if isinstance(id, str):
if emojilib.is_emoji(id):
logging.debug("Emoji is native, returning as is")
return id
name = re.match(r":(.+):", id)
if name: id = name.group(1)
guilds = [self.guild]
guilds += client.guilds
for guild in guilds:
if not guild: continue
if isinstance(id, int):
emoji = discord.utils.get(guild.emojis, id=id)
elif isinstance(id, str):
emoji = discord.utils.get(guild.emojis, name=id)
else: break
if emoji: return emoji
logging.warn("Could not find emoji")
return None
async def get_server(self, id: int | str) -> Guild:
logging.info("Rerieving server: %s", id)
if not id:
logging.warn("No ID")
return None
if isinstance(id, int):
server = client.get_guild(id)
if server: return Guild(server)
server = await client.fetch_guild(id)
if server: return Guild(server)
logging.warn("Could not find server")
return None
if not isinstance(id, str):
logging.warn("Server is not int or string")
return None
if id in yaml_variables:
logging.debug("Resolving variable")
return await self.get_server(eval(id))
for server in client.guilds:
if server.name == id: return Guild(server)
logging.warn("Could not find server")
return None
def evaluate(self, _string: str, **kwargs) -> Any:
logging.info("Evaluating: %s", _string)
if not _string:
logging.warn("Nothing to evaluate")
return _string
for _key in self.additional_variables:
exec(f"{_key} = self.additional_variables[{repr(_key)}]")
for _key in self.__dict__:
if _key == "additional_variables": continue
exec(f"{_key} = self.{_key}")
for _key in kwargs:
exec(f"{_key} = {repr(kwargs[_key])}")
try:
result = eval(_string)
logging.info("Evaluated: %s", result)
return result
except Exception as e:
logging.error(e)
return None
def evaluate_string(self, _string: str) -> str:
logging.info("Evaluating as string: %s", _string)
if not _string:
logging.warn("Nothing to evaluate")
return _string
for _dictionary in [self.__dict__, self.additional_variables]:
for _key in _dictionary:
exec(f"{_key} = self.{_key}")
try:
result = eval(f"f{repr(_string)}")
logging.info("Evaluated: %s", result)
return result
except Exception as e:
logging.error(e)
return ""
def evaluate_condition(self, condition: dict) -> dict:
logging.info("Evaluating condition: %s", condition.get("if"))
if self.evaluate(condition.get("if")):
logging.info("True")
logging.debug("Data: %s", condition.get("do"))
return condition.get("do", {"?":{}})
logging.info("False")
logging.debug("Data: %s", condition.get("else"))
return condition.get("else", {"?":{}})
async def aexec(self, code: str) -> None:
logging.info("Async execution: %s", code)
try:
# Make an async function with the code and `exec` it
exec(
'async def __exec(self):\n' +
''.join(f'\n {l}' for l in code.split('\n'))
)
await locals()["__exec"](self)
except Exception as e:
logging.error(e)
async def refresh(self) -> None:
logging.info("Refresing function: %s", self.execution_path)
if self.guild:
logging.debug("Refresing guild: %s", self.guild)
self.guild = await self.get_server(self.guild.id)
if self.channel:
logging.debug("Refresing channel: %s", self.channel)
self.channel = await self.get_channel(self.channel.id)
if self.user:
logging.debug("Refresing user: %s", self.user)
self.user = await self.get_user(self.user.id)
class FunctionCondition(Function):
async def execute(self) -> bool:
await super().execute()
code = self.evaluate_condition(self.raw_function[self.function_name])
await run_code("do", self.channel, self.user, self.guild, {"do": code}, self.execution_path + " -> ", self.additional_variables)
# Abstract
class FunctionRoles(Function):
target: discord.Member = None
roles: list[discord.Role] = []
reason: str = None
async def find_arguments(self, arguments) -> None:
self.target = None
self.roles = []
self.reason = None
if not self.guild: return
if not isinstance(arguments, dict):
arguments = {"roles": arguments}
self.target = await self.get_user(arguments.get("target", None))
if not self.target:
if not isinstance(self.user, discord.Member): return
self.target = self.user
for key in ["role", "roles"]:
if key not in arguments: continue
value = arguments[key]
# if instance is string evaluate it
if isinstance(value, str):
try:
value = int(value)
except:
role = self.get_role(value)
if role:
self.roles.append(role)
continue
value = self.evaluate(value)
if isinstance(value, list):
for role_id in value:
try:
role_id = int(role_id)
except: pass
role = self.get_role(role_id)
if role: self.roles.append(role)
else:
role = self.get_role(value)
if role: self.roles.append(role)
self.reason = arguments.get("reason", None)
async def execute(self) -> bool:
await super().execute()
if not self.target: return False
if not self.roles: return False
return True
class FunctionAddRoles(FunctionRoles):
async def execute(self) -> bool:
if not await super().execute(): return False
await self.target.add_roles(*self.roles, reason=self.reason)
return True
class FunctionRemoveRoles(FunctionRoles):
async def execute(self) -> bool:
if not await super().execute(): return False
await self.target.remove_roles(*self.roles, reason=self.reason)
return True
class FunctionUpdateRoles(Function):
target: discord.Member = None
add: list[discord.Role] = []
remove: list[discord.Role] = []
reason: str = None
async def find_arguments(self, arguments) -> None:
self.target = None
self.add = []
self.remove = []
self.reason = None
await super().find_arguments(arguments)
self.target = await self.get_user(arguments.get("target", None))
if not self.target:
if not isinstance(self.user, discord.Member):
if self.user and self.guild:
self.user = self.guild.get_member(self.user.id)
else: return
self.target = self.user
for key in ["add", "remove"]:
if key not in arguments: continue
value = arguments[key]
if isinstance(value, str):
try:
value = int(value)
except:
role = self.get_role(value)
if role:
exec(f"self.{key}.append(role)")
continue
value = self.evaluate(value)
if isinstance(value, list):
for role_id in value:
try:
role_id = int(role_id)
except: pass
role = self.get_role(role_id)
if role: exec(f"self.{key}.append(role)")
else:
role = self.get_role(value)
if role: exec(f"self.{key}.append(role)")
self.reason = arguments.get("reason", None)
async def execute(self) -> bool:
await super().execute()
if not self.target: return False
remove_roles: set[discord.Role] = set(self.remove) - set(self.add)
remove_roles.intersection_update(self.target.roles)
add_roles: set[discord.Role] = set(self.add) - set(self.target.roles)
if remove_roles:
await self.target.remove_roles(*remove_roles, reason=self.reason)
if add_roles:
await self.target.add_roles(*add_roles, reason=self.reason)
return True
class FunctionSetVariable(Function):
variables: list[str] = []
evaluate_values: bool = False
arguments: dict = {}
async def find_arguments(self, arguments) -> None:
self.variables = []
self.evaluate_values = False
self.arguments = arguments
if not isinstance(arguments, dict):
raise TypeError(f"'{arguments}' is not a dict.\nTrace: {self.execution_path}")
for var in arguments:
if var == "evaluate":
self.evaluate_values = arguments[var]
continue
if var.replace(" ", "_") not in yaml_variables:
raise NameError(f"{var} is not defined.\nTrace: {self.execution_path}")
self.variables.append(var)
async def execute(self) -> bool:
await super().execute()
if not self.variables: return False
for var in self.variables:
var_name = var.replace(" ", "_")
if self.evaluate_values: await self.aexec(f"global {var_name}; {var_name} = {self.arguments[var]}")
else: await self.aexec(f"global {var_name}; {var_name} = {repr(self.arguments[var])}")
return True
# Abstract
class FunctionMessage(Function):
content = ""
tts: bool = False
embed: discord.Embed = None
embeds: list[discord.Embed] = []
file: discord.File = None
files: list[discord.File] = []
delete_after: float = None
allowed_mentions: discord.AllowedMentions = None
reference = None
mention_author: bool = None
view: discord.ui.View = None
stickers = None
suppress_embeds: bool = False
silent: bool = False
has_condition: bool = False
msg: discord.Message = None
async def send(self) -> discord.Message:
if not self.channel: return None
args = {
"tts": self.tts,
"delete_after": self.delete_after,
"allowed_mentions": self.allowed_mentions,
"reference": self.reference,
"mention_author": self.mention_author,
"stickers": self.stickers,
"suppress_embeds": self.suppress_embeds,
"view": self.view,
"silent": self.silent
}
if self.file: args["file"] = self.file
elif self.files: args["files"] = self.files
if self.embed: args["embed"] = self.embed
elif self.embeds: args["embeds"] = self.embeds
self.msg = await self.channel.send(self.content, **args)
def get_edit_args(self) -> dict:
args = {}
if self.file: args["attachments"] = self.file
elif self.files: args["attachments"] = self.files
for key in ["content", "embed", "embeds", "view", "delete_after", "allowed_mentions"]:
if key == "embeds" and "embed" in args: continue
value = getattr(self, key)
if value: args[key] = value
return args
async def edit(self):
if not self.msg: return
self.msg = await self.msg.edit(**self.get_edit_args())
def compare_to(self, msg: discord.Message) -> bool:
if self.view: return False
if msg.content != self.content: return False
if len(msg.embeds) == 1:
if msg.embeds[0] != self.embed: return False
elif msg.embeds != self.embeds: return False
if self.file: return [self.file] == msg.attachments
return self.files == msg.attachments
async def find_arguments(self, arguments) -> None:
self.content = ""
self.tts = False
self.embed = None
self.embeds = []
self.file = None
self.files = []
self.delete_after = None
self.allowed_mentions = None
self.reference = None
self.mention_author = None
self.view = None
self.stickers = None
self.suppress_embeds = False
self.silent = False
self.has_condition = False
if isinstance(arguments, str):
self.content = arguments
return
if "channel" in arguments:
self.channel = await self.get_channel(arguments["channel"])
if "content" not in arguments: raise SyntaxError(f"Message does not have any content.\nTrace: {self.execution_path}")
if isinstance(arguments["content"], str): arguments["content"] = [{"text": arguments["content"]}]
if not isinstance(arguments["content"], list): raise TypeError(f"Content must be string or a list.\nTrace: {self.execution_path} -> content")
view = VeiwGenerator(self)
content_count: dict[str, int] = {}
for item in arguments["content"]:
if item and isinstance(item, dict) and "condition" in item:
item = self.evaluate_condition(item["condition"])
self.has_condition = True
if not item: continue
if not isinstance(item, dict): raise TypeError(f"Message content must be dictionaries.\nTrace: {self.execution_path} -> content -> ?\n{item}")
content_name = str(list(item.keys())[0])
content_type = content_name.lower().replace(" ", "_")
trace = self.execution_path + " -> content -> " + content_name
if content_type not in content_count: content_count[content_type] = 1
else:
content_count[content_type] += 1
trace += " " + str(content_count[content_name])
match content_type:
case "text": self.content = self.evaluate_string(item["text"])
case "embed": self.embeds.append(self.create_embed(item["embed"], trace))
case "select": view.add_select(item[content_name], trace)
case "button": view.add_button(item[content_name], trace)
case _: raise NameError(f"'{content_name}' is not a recognised message content type.\nTrace: {self.execution_path} -> content -> ?")
if self.embeds and len(self.embeds) == 1: self.embed = self.embeds.pop()
if self.files and len(self.files) == 1: self.file = self.files.pop()
if view.is_valid(): self.view = view.view