-
Notifications
You must be signed in to change notification settings - Fork 22
/
bot.py
8984 lines (8576 loc) · 297 KB
/
bot.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
# Lou invaded, on the 1st August 2020 this became my territory *places flag* B3
# 11th of September 2023 she invaded again with 10x gay energy and stole your baby niece *places updated flag* B3
#!/usr/bin/python3
import os
print("BOT:", __name__)
if __name__ != "__mp_main__":
os.environ["IS_BOT"] = "1"
from misc import common, asyncs
from misc.common import * # noqa: F403
import pdb
# import asyncio
# import collections
# import contextlib
# import datetime
# import json
# import pdb
# import subprocess
# import sys
# import time
# import discord
# import orjson
# import psutil
# import misc.common as common
# from collections import deque
# from concurrent.futures import Future
# from math import inf, ceil, log10
# from misc.asyncs import asubmit, csubmit, esubmit, tsubmit, gather, eloop, get_event_loop, Semaphore, SemaphoreOverflowError
# from misc.smath import xrand
# from misc.types import cdict, fdict, fcdict, mdict, alist, azero, round_min, full_prune, suppress, tracebacksuppressor
# from misc.util import AUTH, TEMP_PATH, FAST_PATH, PORT, PROC, EvalPipe, python, utc, T, lim_str, regexp, Request, reqs, is_strict_running, force_kill
# from misc.common import api, get_colour_list, load_emojis, load_timezones, touch, BASE_LOGO, closing, MemoryTimer
# import tracemalloc
# tracemalloc.start()
ADDRESS = AUTH.get("webserver_address") or "0.0.0.0"
if ADDRESS == "0.0.0.0":
ADDRESS = "127.0.0.1"
if __name__ != "__mp_main__":
esubmit(get_colour_list)
esubmit(load_emojis)
esubmit(load_timezones)
class Bot(discord.AutoShardedClient, contextlib.AbstractContextManager, collections.abc.Callable):
"Main class containing all global bot data."
github = AUTH.get("github") or "https://github.com/thomas-xin/Miza"
rcc_invite = AUTH.get("rcc_invite") or "https://discord.gg/cbKQKAr"
discord_icon = BASE_LOGO
twitch_url = "https://www.twitch.tv/-"
webserver = AUTH.get("webserver") or "https://mizabot.xyz"
kofi_url = AUTH.get("kofi_url") or "https://ko-fi.com/waveplasma/tiers"
rapidapi_url = AUTH.get("rapidapi_url") or "https://rapidapi.com/thomas-xin/api/miza"
raw_webserver = AUTH.get("raw_webserver") or "https://api.mizabot.xyz"
heartbeat_rec = "heartbeat.tmp"
heartbeat_ack = "heartbeat_ack.tmp"
restart = "restart.tmp"
shutdown = "shutdown.tmp"
activity = 0
caches = ("guilds", "channels", "users", "roles", "emojis", "messages", "members", "attachments", "banned", "colours")
statuses = (discord.Status.online, discord.Status.idle, discord.Status.dnd, discord.Streaming, discord.Status.invisible)
# Default command prefix
prefix = AUTH.get("prefix", "~")
# This is a fixed ID apparently
deleted_user = 456226577798135808
_globals = globals()
intents = discord.Intents(
guilds=True,
members=True,
bans=True,
emojis=True,
webhooks=True,
voice_states=True,
presences=False,
messages=True,
reactions=True,
typing=True,
)
intents.value |= 32768 # message content intent because discord dumb
allowed_mentions = discord.AllowedMentions(
everyone=False,
users=True,
roles=False,
replied_user=False,
)
connect_ready = Future()
full_ready = Future()
socket_responses = deque(maxlen=256)
premium_server = 247184721262411776
premium_roles = {
1052645637033824346: 1,
1052645761638215761: 2,
1052647823188967444: 3,
}
active_categories = set(AUTH.setdefault("active_categories", ["MAIN", "STRING", "ADMIN", "VOICE", "IMAGE", "WEBHOOK", "FUN"]))
def __init__(self, cache_size=65536, timeout=24):
"Initializes client (first in __mro__ of class inheritance)"
self.start_time = utc()
shard_fut = esubmit(
Request,
f"https://discord.com/api/{api}/gateway/bot",
authorise=True,
json=True,
)
self.cache_size = cache_size
# Base cache: contains all other caches
self.cache = fcdict((c, fdict()) for c in self.caches)
self.timeout = timeout
self.set_classes()
self.bot = self
self.client = super()
self.closing = False
self.closed = False
self.loaded = False
# Channel-Webhook cache: for accessing all webhooks for a channel.
self.cw_cache = cdict()
self.usernames = {}
self.events = mdict()
self.react_sem = cdict()
self.mention = ()
self.user_loader = set()
self.users_updated = True
self.guilds_updated = True
self.update_semaphore = Semaphore(2, 1)
self.ready_semaphore = Semaphore(1, inf)
self.guild_semaphore = Semaphore(5, inf, rate_limit=5)
self.load_semaphore = Semaphore(5, inf, rate_limit=1)
self.user_semaphore = Semaphore(64, inf, rate_limit=8)
self.cache_semaphore = Semaphore(1, 1, rate_limit=30)
self.command_semaphore = Semaphore(262144, 16384, rate_limit=30)
print("Time:", datetime.datetime.now())
print("Initializing...")
# O(1) time complexity for searching directory
directory = frozenset(os.listdir())
if "saves" not in directory:
os.mkdir("saves")
if not os.path.exists("saves/filehost"):
os.mkdir("saves/filehost")
for k in ("attachments", "audio", "filehost"):
if not os.path.exists(f"{TEMP_PATH}/{k}"):
os.mkdir(f"{TEMP_PATH}/{k}")
if not os.path.exists(f"{FAST_PATH}/{k}"):
os.mkdir(f"{FAST_PATH}/{k}")
try:
self.token = AUTH["discord_token"]
except KeyError:
print("ERROR: discord_token not found. Unable to login.")
self.setshutdown(force=True)
try:
owner_id = AUTH["owner_id"]
if type(owner_id) not in (list, tuple):
owner_id = (owner_id,)
self.owners = alist(int(i) for i in owner_id)
except KeyError:
self.owners = alist()
print("WARNING: owner_id not found. Unable to locate owner.")
# Initialize rest of bot variables
self.proc = PROC
self.guild_count = 0
self.updated = False
self.started = False
self.bot_ready = False
self.ready = False
self.initialisation_complete = False
self.status_iter = xrand(4)
self.curr_state = azero(4)
self.ip = "127.0.0.1"
self.audio = None
self.embed_senders = cdict()
# Assign bot cache to global variables for convenience
globals().update(self.cache)
modload = self.get_modules()
self.modload = csubmit(gather(*modload))
tsubmit(self.heartbeat_loop)
data = shard_fut.result()
self.wss = data["url"]
x = AUTH.get("guild_count", 1)
s = max(1, data["shards"])
shards = max(1, ceil(x / log10(x) / 100 / s)) * s
print("Automatic shards:", shards)
assert data["session_start_limit"]["remaining"] > shards
self.monkey_patch()
super().__init__(
loop=eloop,
_loop=eloop,
max_messages=256,
heartbeat_timeout=64,
chunk_guilds_at_startup=False,
guild_ready_timeout=16,
intents=self.intents,
allowed_mentions=self.allowed_mentions,
assume_unsync_clock=True,
)
self.shard_count = shards
self.set_client_events()
with suppress(AttributeError):
csubmit(super()._async_setup_hook())
globals()["messages"] = self.messages = self.MessageCache()
__str__ = lambda self: str(self.user) if T(self).get("user") else object.__str__(self)
__repr__ = lambda self: repr(self.user) if T(self).get("user") else object.__repr__(self)
__call__ = lambda self: self
__exit__ = lambda self, *args, **kwargs: self.close()
def __getattr__(self, key):
try:
return object.__getattribute__(self, key)
except AttributeError:
pass
if key == "user":
return self.__getattribute__("_user")
for attr in ("_connection", "user", "proc"):
this = self.__getattribute__(attr)
try:
return getattr(this, key)
except AttributeError:
pass
raise AttributeError(key)
def __dir__(self):
data = set(object.__dir__(self))
data.update(dir(self._connection))
data.update(dir(self.user))
data.update(dir(self.proc))
return data
@property
def maintenance(self):
return "blacklist" in self.data and self.data.blacklist.get(0)
def guild_shard(self, g_id):
return (g_id >> 22) % self.shard_count
# Waits an amount of seconds and shuts down.
def setshutdown(self, delay=None, force=False):
if delay:
time.sleep(delay)
if force:
touch(self.shutdown)
# force_kill(self.proc)
def command_options(self, command):
accepts_attachments = False
out = deque()
if command.schema:
for k, v in command.schema.items():
if not isinstance(v, cdict):
raise TypeError(k, v)
desc = lim_str((v.get("description") or v.type) + (f', e.g. "{v.example}"' if v.get("example") else ""), 100)
arg = cdict(
type=3,
name=k,
description=desc,
)
if v.type in ("url", "image", "visual", "video", "audio", "media"):
accepts_attachments = True
if v.get("required") or v.get("required_slash"):
arg.required = True
if v.get("multiple"):
continue
if v.type == "enum":
options = sorted(v.validation.get("enum") or v.validation.accepts)
if len(options) <= 25:
arg.choices = [dict(name=opt, value=opt) for opt in options]
elif len(arg.description) < 100:
argf = ",".join(map(str, options))
arg.description = lim_str(arg.description + f"; one of ({argf})", 100, mode="left")
elif v.type == "integer":
arg.type = 4
if v.get("validation") and isinstance(v.validation, str):
lx, rx = v.validation.split(",")
mx, Mx = round_min(lx[1:]), round_min(rx[:-1])
arg.min_value = mx
arg.max_value = Mx
elif v.type == "bool":
arg.type = 5
elif v.type == "user":
arg.type = 6
elif v.type == "channel":
arg.type = 7
elif v.type == "role":
arg.type = 8
elif v.type == "mentionable":
arg.type = 9
elif v.type == "number":
arg.type = 10
if v.get("validation") and isinstance(v.validation, str):
lx, rx = v.validation.split(",")
mx, Mx = round_min(lx[1:]), round_min(rx[:-1])
arg.min_value = mx
arg.max_value = Mx
out.append(arg)
else:
for i in command.usage.split():
with tracebacksuppressor:
arg = dict(type=3, name=i, description=i)
if i.endswith("?"):
arg["description"] = "[optional] " + arg["description"][:-1]
elif i.endswith("*"):
arg["description"] = "[zero or more] " + arg["description"][:-1]
else:
if i.endswith("+"):
arg["description"] = "[one or more] " + arg["description"][:-1]
arg["required"] = True
# if not default and usage.count(" "):
# arg["default"] = default = True
arg["description"] = lim_str(arg["description"], 100)
if i.startswith("<"):
s = i[1:].split(":", 1)[-1].rsplit(">", 1)[0]
formats = regexp(r"[\w\-\[\]]+(?:\((?:\?:)?[\w\'\-\|\[\]]+\))?").findall(s)
for fmt in formats:
a = dict(arg)
if "(" not in fmt:
name = fmt
if fmt == "user":
a["type"] = 9
a["description"] = "user"
elif fmt == "id":
a["type"] = 4
a["description"] = "integer"
else:
a["description"] = "string"
else:
name, opts = fmt.split("(", 1)
if "|" not in opts:
a["type"] = 5
a["description"] = "bool"
elif opts.startswith("?:"):
a["description"] = "(" + opts[2:].rstrip(")") + ")"
else:
opts = opts.rstrip(")").split("|")
a["choices"] = [dict(name=opt, value=opt) for opt in opts]
a["description"] = "choice"
if "[" in name:
name, d = name.split("[", 1)
a["description"] += " [" + d
a["name"] = name
out.append(a)
continue
if arg["name"] == "user":
arg["type"] = 9
elif arg["name"] == "url":
accepts_attachments = True
out.append(arg)
if accepts_attachments:
arg = dict(type=11, name="attachment", description="Attachment in place of URL")
out.append(arg)
return sorted(out, key=lambda arg: not arg.get("required"))
slash_sem = Semaphore(5, 256, rate_limit=5)
@tracebacksuppressor
def create_command(self, data):
with self.slash_sem:
for i in range(16):
resp = reqs.next().post(
f"https://discord.com/api/{api}/applications/{self.id}/commands",
headers={"Content-Type": "application/json", "Authorization": "Bot " + self.token},
data=json_dumps(data),
timeout=30,
)
if resp.status_code == 429:
time.sleep(20)
continue
if resp.status_code not in range(200, 400):
print("\n", data, " ", ConnectionError(f"Error {resp.status_code}", resp.text), "\n", sep="")
print("SLASH CREATE:", resp.text)
return
def update_slash_commands(self):
print("Updating global slash commands...")
with tracebacksuppressor:
resp = reqs.next().get(
f"https://discord.com/api/{api}/applications/{self.id}/commands",
headers=dict(Authorization="Bot " + self.token),
timeout=30,
)
if resp.status_code not in range(200, 400):
raise ConnectionError(f"Error {resp.status_code}", resp.text)
commands = dict((int(c["id"]), c) for c in resp.json() if str(c.get("application_id")) == str(self.id))
if commands:
print(f"Successfully loaded {len(commands)} application command{'s' if len(commands) != 1 else ''}.")
for catg in self.categories.values():
if not AUTH.get("slash_commands"):
break
for command in catg:
with tracebacksuppressor:
if T(command).get("msgcmd"):
aliases = command.msgcmd if type(command.msgcmd) is tuple else (command.parse_name(),)
for name in aliases:
command_data = dict(name=name, type=3)
found = False
for i, curr in list(commands.items()):
if curr["name"] == name and curr["type"] == command_data["type"]:
found = True
commands.pop(i)
break
if not found:
print(f"creating new message command {command_data['name']}...")
print(command_data)
esubmit(self.create_command, command_data, priority=True)
if T(command).get("usercmd"):
aliases = command.usercmd if type(command.usercmd) is tuple else (command.parse_name(),)
for name in aliases:
command_data = dict(name=name, type=2)
found = False
for i, curr in list(commands.items()):
if curr["name"] == name and curr["type"] == command_data["type"]:
found = True
commands.pop(i)
break
if not found:
print(f"creating new user command {command_data['name']}...")
print(command_data)
esubmit(self.create_command, command_data, priority=True)
if T(command).get("slash"):
aliases = command.slash if type(command.slash) is tuple else (command.parse_name(),)
for name in (full_prune(i) for i in aliases):
description = lim_str(command.parse_description(), 100)
options = self.command_options(command)
command_data = dict(name=name, description=description, type=1)
if options:
command_data["options"] = options
found = False
for i, curr in list(commands.items()):
if curr["name"] == name and curr["type"] == command_data["type"]:
compare = self.command_options(command)
if curr["description"] != description or (compare and curr["options"] != compare or not compare and curr.get("options")):
print(curr)
print(f"{curr['name']}'s slash command does not match, removing...")
with self.slash_sem:
for att in range(16):
resp = reqs.next().delete(
f"https://discord.com/api/{api}/applications/{self.id}/commands/{curr['id']}",
headers=dict(Authorization="Bot " + self.token),
timeout=30,
)
if resp.status_code == 429:
time.sleep(att + 1)
continue
if resp.status_code not in range(200, 400):
raise ConnectionError(f"Error {resp.status_code}", resp.text)
break
else:
# print(f"{curr['name']}'s slash command matches, ignoring...")
found = True
commands.pop(i, None)
break
if not found:
print(f"creating new slash command {command_data['name']}...")
print(command_data)
esubmit(self.create_command, command_data)
with self.slash_sem:
time.sleep(1)
for curr in commands.values():
with tracebacksuppressor:
print(curr)
print(f"{curr['name']}'s application command does not exist, removing...")
resp = reqs.next().delete(
f"https://discord.com/api/{api}/applications/{self.id}/commands/{curr['id']}",
headers=dict(Authorization="Bot " + self.token),
timeout=30,
)
if resp.status_code not in range(200, 400):
raise ConnectionError(f"Error {resp.status_code}", resp.text)
async def create_main_website(self, first=False):
if first:
print("Generating command json...")
j = {}
for category in ("MAIN", "STRING", "ADMIN", "VOICE", "IMAGE", "FUN", "OWNER", "NSFW", "MISC"):
k = j[category] = {}
if category not in self.categories:
continue
for command in self.categories[category]:
c = k[command.parse_name()] = dict(
aliases=[n.strip("_") for n in command.alias],
description=command.parse_description(),
usage=command.usage,
level=str(command.min_level),
rate_limit=str(command.rate_limit),
example=T(command).get("example", []),
timeout=str(T(command).get("_timeout_", 1) * self.timeout),
)
for attr in ("flags", "server_only", "slash"):
with suppress(AttributeError):
c[attr] = command.attr
with open("misc/web/static/HELP.json", "w", encoding="utf-8") as f:
json.dump(j, f, indent="\t")
server = None
server_start_sem = Semaphore(1, 0, rate_limit=5)
def start_webserver(self):
if self.closing:
return
with self.server_start_sem:
if self.server:
self.server.terminate()
if os.path.exists("misc/x_server.py") and PORT:
print("Starting webserver...")
self.server = EvalPipe.connect(
[python, "-m", "misc.x_server", "6562"],
6562,
glob=globals(),
)
else:
self.server = None
def start_audio_client(self):
if self.audio:
self.audio.terminate()
if os.path.exists("misc/x_audio.py"):
print("Starting audio client...")
self.audio = AudioClientInterface.connect(
[python, "-m", "misc.x_audio", "6561"],
6561,
glob=globals(),
)
else:
self.audio = None
def run(self):
"Starts up client."
print("Logging in...")
try:
self.audio_client_start = asubmit(self.start_audio_client, priority=1)
loop = get_event_loop()
with closing(loop):
with tracebacksuppressor:
loop.run_until_complete(self.start(self.token))
with tracebacksuppressor:
loop.run_until_complete(self.close())
for t in asyncio.all_tasks(loop):
with tracebacksuppressor:
t.cancel()
finally:
self.setshutdown()
def print(self, *args, sep=" ", end="\n"):
"A reimplementation of the print builtin function."
sys.__stdout__.write(str(sep).join(str(i) for i in args) + end)
def close(self):
"Closes the bot, preventing all events."
self.closing = True
self.closed = True
return csubmit(super().close())
@tracebacksuppressor(SemaphoreOverflowError)
async def garbage_collect(self, obj):
"A garbage collector for empty and unassigned objects in the database."
if not self.ready or hasattr(obj, "no_delete") or not any(hasattr(obj, i) for i in ("guild", "user", "channel", "garbage")) and not getattr(obj, "garbage_collect", None):
return
with MemoryTimer(f"{obj.name}-gc"):
async with obj._garbage_semaphore:
data = obj.data
if getattr(obj, "garbage_collect", None):
return await obj.garbage_collect()
if len(data) <= 1024:
keys = data.keys()
else:
low = xrand(ceil(len(data) / 1024)) << 10
keys = astype(data, alist).view[low:low + 1024]
for key in keys:
if getattr(obj, "unloaded", False):
return
if not key or isinstance(key, str):
continue
try:
# Database keys may be user, guild, or channel IDs
if getattr(obj, "channel", False):
d = self.get_channel(key)
elif getattr(obj, "user", False):
d = await self.fetch_user(key)
else:
if not data[key]:
raise LookupError
with suppress(KeyError):
d = self.cache.guilds[key]
continue
d = await self.fetch_messageable(key)
if d is not None:
continue
except Exception:
print_exc()
print(f"Deleting {key} from {obj}...")
data.pop(key, None)
@tracebacksuppressor
async def send_event(self, ev, *args, exc=False, **kwargs):
"Calls a bot event, triggered by client events or others, across all bot databases. Calls may be sync or async."
if self.closed:
return
with MemoryTimer(f"{ev}-event"):
ctx = emptyctx if exc else tracebacksuppressor
events = self.events.get(ev, ())
if len(events) == 1:
with ctx:
return await asubmit(events[0](*args, **kwargs))
return
futs = [asubmit(func(*args, **kwargs)) for func in events]
with ctx:
return await gather(*futs)
@tracebacksuppressor(default=[])
async def get_full_invites(self, guild):
"Gets the full list of invites from a guild, if applicable."
member = guild.get_member(self.id)
if member.guild_permissions.create_instant_invite:
invitedata = await Request(
f"https://discord.com/api/{api}/guilds/{guild.id}/invites",
authorise=True,
aio=True,
json=True,
)
invites = [cdict(invite) for invite in invitedata]
return sorted(invites, key=lambda invite: (invite.max_age == 0, -abs(invite.max_uses - invite.uses), len(invite.url)))
return []
def get_first_sendable(self, guild, member):
"Gets the first accessable text channel in the target guild."
if member is None:
return guild.owner
found = {}
for channel in sorted(guild.text_channels, key=lambda c: c.id):
if channel.permissions_for(member).send_messages:
with suppress(ValueError):
rname = full_prune(channel.name).replace("-", " ").replace("_", " ").split(maxsplit=1)[0]
i = ("miza", "bots", "bot", "general").index(rname)
if i < min(found):
found[i] = channel
if found:
return found[min(found)]
channel = guild.system_channel
if channel is None or not channel.permissions_for(member).send_messages:
channel = guild.rules_channel
if channel is None or not channel.permissions_for(member).send_messages:
for channel in sorted(guild.text_channels, key=lambda c: c.id):
if channel.permissions_for(member).send_messages:
return channel
return guild.owner
return channel
def in_cache(self, o_id):
"Returns a discord object if it is in any of the internal cache."
cache = self.cache
try:
return cache.users[o_id]
except KeyError:
pass
try:
return cache.channels[o_id]
except KeyError:
pass
try:
return cache.guilds[o_id]
except KeyError:
pass
try:
return cache.roles[o_id]
except KeyError:
pass
try:
return cache.emojis[o_id]
except KeyError:
pass
try:
return self.data.mimics[o_id]
except KeyError:
pass
async def fetch_messageable(self, s_id):
"Fetches either a user or channel object from ID, using the bot cache when possible."
if not isinstance(s_id, int):
try:
s_id = int(s_id)
except (ValueError, TypeError):
raise TypeError(f"Invalid messageable identifier: {s_id}")
with suppress(KeyError):
return self.get_user(s_id)
with suppress(KeyError):
return self.cache.channels[s_id]
try:
user = await super().fetch_user(s_id)
except (LookupError, discord.NotFound):
channel = await super().fetch_channel(s_id)
self.cache.channels[s_id] = channel
return channel
self.cache.users[s_id] = user
return user
async def _fetch_user(self, u_id):
"Fetches a user from ID, using the bot cache when possible."
async with self.user_semaphore:
user = await super().fetch_user(u_id)
self.cache.users[u_id] = user
return user
def fetch_user(self, u_id):
with suppress(KeyError):
user = as_fut(self.get_user(u_id))
if user and T(user).get("_avatar") != self.discord_icon:
return user
u_id = verify_id(u_id)
if not isinstance(u_id, int):
raise TypeError(f"Invalid user identifier: {u_id}")
return self._fetch_user(u_id)
async def auser2cache(self, u_id):
with suppress(discord.NotFound):
self.cache.users[u_id] = await super().fetch_user(u_id)
def user2cache(self, data):
users = self.cache.users
u_id = int(data["id"])
if u_id not in users:
if isinstance(data, dict):
with tracebacksuppressor:
if "s" in data:
s = data.pop("s")
if "#" in s:
data["username"], data["discriminator"] = s.rsplit("#", 1)
else:
data["username"] = s
data["discriminator"] = 0
else:
if data.get("discriminator") not in (None, 0, "0"):
s = data["username"] + "#" + data["discriminator"]
else:
s = data["username"]
self.usernames[s] = users[u_id] = self._state.store_user(data)
return
self.user_loader.add(u_id)
def update_users(self):
if self.user_loader:
if not self.user_semaphore.busy:
u_id = self.user_loader.pop()
if u_id not in self.cache.users:
csubmit(self.auser2cache(u_id))
def get_user(self, u_id, replace=False):
"Gets a user from ID, using the bot cache."
if not isinstance(u_id, int):
try:
u_id = int(u_id)
except (ValueError, TypeError):
user = self.user_from_identifier(u_id)
if user is not None:
return user
if "#" in u_id:
raise LookupError(f"User identifier not found: {u_id}")
u_id = verify_id(u_id)
if not isinstance(u_id, int):
raise TypeError(f"Invalid user identifier: {u_id}")
with suppress(KeyError):
return self.cache.users[u_id]
if u_id == self.deleted_user:
user = self.GhostUser()
user.system = True
user.name = "Deleted User"
user.nick = "Deleted User"
user.id = u_id
else:
try:
user = super().get_user(u_id)
if user is None:
raise LookupError
except LookupError:
if replace:
return self.get_user(self.deleted_user)
raise KeyError("Target user ID not found.")
self.cache.users[u_id] = user
return user
async def find_users(self, argl, args, user, guild, roles=False):
if not argl and not args:
return (user,)
if argl:
users = {}
for u_id in argl:
u = await self.fetch_user_member(u_id, guild)
users[u.id] = u
return users.values()
u_id = verify_id(args.pop(0))
if isinstance(u_id, int) and guild:
role = guild.get_role(u_id)
if role is not None:
if roles:
return (role,)
try:
return role.members
except AttributeError:
return [member for member in guild._members.values() if u_id in member._roles]
if isinstance(u_id, str) and "@" in u_id and ("everyone" in u_id or "here" in u_id):
return await self.get_full_members(guild)
u = await self.fetch_user_member(u_id, guild)
return (u,)
def user_from_identifier(self, u_id):
spl = u_id.split()
for i in range(len(spl)):
uid = " ".join(spl[i:])
try:
return self.usernames[uid]
except KeyError:
pass
async def fetch_user_member(self, u_id, guild=None):
u_id = verify_id(u_id)
if isinstance(u_id, int):
try:
user = self.cache.users[u_id]
except KeyError:
try:
user = await self.fetch_user(u_id)
except discord.NotFound:
if guild and "webhooks" in self.data:
for channel in guild.text_channels:
webhooks = await self.data.webhooks.get(channel)
try:
return [w for w in webhooks if w.id == u_id][0]
except IndexError:
pass
raise
with suppress():
if guild:
member = guild.get_member(user.id)
if member is not None:
return member
with suppress():
return self.get_member(u_id, guild, find_others=False)
return user
user = self.user_from_identifier(u_id)
if user is not None:
if guild is None:
return user
member = guild.get_member(user.id)
if member is not None:
return member
return user
return await self.fetch_member_ex(u_id, guild)
async def get_full_members(self, guild):
members = guild._members.values()
if "bans" in self.data:
members = set(members)
for b in self.data.bans.get(guild.id, ()):
try:
user = await self.fetch_user(b.get("u", self.deleted_user))
except LookupError:
user = self.cache.users[self.deleted_user]
members.add(user)
return members
async def query_members(self, members, query, fuzzy=0.5):
query = str(query)
fuz_base = None if fuzzy is None else 0
with suppress(LookupError):
return await str_lookup(
members,
query,
qkey=userQuery1,
ikey=userIter1,
loose=False,
fuzzy=fuz_base,
)
with suppress(LookupError):
return await str_lookup(
members,
query,
qkey=userQuery2,
ikey=userIter2,
fuzzy=fuz_base,
)
with suppress(LookupError):
return await str_lookup(
members,
query,
qkey=userQuery3,
ikey=userIter3,
fuzzy=fuz_base,
)
with suppress(LookupError):
return await str_lookup(
members,
query,
qkey=userQuery4,
ikey=userIter4,
fuzzy=fuzzy,
)
raise LookupError(f"No results for {query}.")
async def fetch_member_ex(self, u_id, guild=None, allow_banned=True, fuzzy=1 / 3):
"Fetches a member in the target server by ID or name lookup."
if not isinstance(u_id, int) and u_id.isnumeric():
with suppress(TypeError, ValueError):
u_id = int(u_id)
member = None
if isinstance(u_id, int) and guild:
member = guild.get_member(u_id)
if member is None:
if isinstance(u_id, int):
with suppress(LookupError):
if guild:
member = await self.fetch_member(u_id, guild)
if member is None:
with suppress(LookupError):
member = await self.fetch_user(u_id)
if member is None:
if not guild:
u_id = full_prune(str(u_id))
members = [u for u in bot.cache.users if full_prune(u.name) == u_id or T(u).get("global_name") and full_prune(u.global_name) == u_id]
elif allow_banned:
members = await self.get_full_members(guild)
else:
members = guild.members
if not members:
members = guild.members = await guild.fetch_members(limit=None)
guild._members.update({m.id: m for m in members})
return await self.query_members(members, u_id, fuzzy=fuzzy)
return member
def fetch_member(self, u_id, guild=None, find_others=False):
"Fetches the first seen instance of the target user as a member in any shared server."
return asubmit(self.get_member, u_id, guild, find_others)
def get_member(self, u_id, guild=None, find_others=True):
if not isinstance(u_id, int):
try:
u_id = int(u_id)
except (ValueError, TypeError):
raise TypeError(f"Invalid user identifier: {u_id}")
if find_others:
with suppress(LookupError):
member = self.cache.members[u_id].guild.get_member(u_id)
if member is None:
raise LookupError
return member
g = self.cache.guilds
if guild is None:
if find_others:
guilds = deque(self.cache.guilds.values())
else:
return self.cache.users[u_id]
else:
if find_others:
guilds = deque(g[i] for i in g if g[i].id != guild.id)
guilds.appendleft(guild)
else:
guilds = [guild]
member = None
for guild in guilds:
member = guild.get_member(u_id)
if member is not None:
break
if member is None:
raise LookupError("Unable to find member data.")
if find_others:
self.cache.members[u_id] = member
return member
async def fetch_guild(self, g_id, follow_invites=True):
"Fetches a guild from ID, using the bot cache when possible."
if not isinstance(g_id, int):
try:
g_id = int(g_id)
except (ValueError, TypeError):
if follow_invites:
try:
# Parse and follow invites to get partial guild info
invite = await super().fetch_invite(g_id.strip("< >"))
g = invite.guild
with suppress(KeyError):
return self.cache.guilds[g.id]
if not hasattr(g, "member_count"):
guild = cdict(ghost=True, member_count=invite.approximate_member_count)
for at in ('banner', 'created_at', 'description', 'features', 'icon', 'id', 'name', 'splash', 'verification_level'):
setattr(guild, at, getattr(g, at))
guild.member_count = getattr(invite, "approximate_member_count", None)
guild.icon_url = str(guild.icon)
else:
guild = g
return guild
except (discord.NotFound, discord.HTTPException) as ex:
raise LookupError(str(ex))
raise TypeError(f"Invalid server identifier: {g_id}")
with suppress(KeyError):
return self.cache.guilds[g_id]
try:
guild = super().get_guild(g_id)
if guild is None:
raise LookupError
except LookupError:
guild = await super().fetch_guild(g_id)