forked from thomas-xin/Miza
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.py
More file actions
3529 lines (3140 loc) · 116 KB
/
common.py
File metadata and controls
3529 lines (3140 loc) · 116 KB
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 smath
from smath import *
MultiAutoImporter(
"psutil",
"subprocess",
"tracemalloc",
"zipfile",
"urllib",
"nacl",
"discord",
"asyncio",
"json",
"orjson",
"aiohttp",
"threading",
"shutil",
"filetype",
"inspect",
pool=import_exc,
_globals=globals(),
)
PROC = psutil.Process()
quit = lambda *args, **kwargs: force_kill(PROC)
BOT = [None]
tracemalloc.start()
from zipfile import ZipFile
import urllib.request, urllib.parse
import nacl.secret
utils = discord.utils
reqs = alist(requests.Session() for i in range(6))
url_parse = urllib.parse.quote_plus
url_unparse = urllib.parse.unquote_plus
escape_markdown = utils.escape_markdown
escape_mentions = utils.escape_mentions
escape_everyone = lambda s: s#s.replace("@everyone", "@\xadeveryone").replace("@here", "@\xadhere")
escape_roles = lambda s: s#escape_everyone(s).replace("<@&", "<@\xad&")
DISCORD_EPOCH = 1420070400000 # 1 Jan 2015
MIZA_EPOCH = 1577797200000 # 1 Jan 2020
time_snowflake = lambda dt, high=None: utils.time_snowflake(dt, high) if type(dt) is not int else getattr(dt, "id", None) or dt
def id2ts(id):
i = (id >> 22) + (id & 0xFFF)
try:
j = i + (id & 0xFFF) / 0x1000
except OverflowError:
return (i + DISCORD_EPOCH) // 1000
return (j + DISCORD_EPOCH) / 1000
def id2td(id):
i = (id >> 22) + (id & 0xFFF)
try:
j = i + (id & 0xFFF) / 0x1000
except OverflowError:
return i // 1000
return j / 1000
def snowflake_time(id):
i = getattr(id, "id", None)
if i is None:
i = id
if type(i) is int:
return utc_dft(id2ts(i))
return i
snowflake_time_2 = lambda id: datetime.datetime.fromtimestamp(id2ts(id))
snowflake_time_3 = utils.snowflake_time
ip2int = lambda ip: int.from_bytes(b"\x00" + bytes(int(i) for i in ip.split(".")), "big")
api = "v10"
# Main event loop for all asyncio operations.
try:
eloop = asyncio.get_event_loop()
except:
eloop = asyncio.new_event_loop()
__setloop__ = lambda: asyncio.set_event_loop(eloop)
__setloop__()
emptyfut = fut_nop = asyncio.Future(loop=eloop)
fut_nop.set_result(None)
newfut = concurrent.futures.Future()
newfut.set_result(None)
def as_fut(obj):
if obj is None:
return emptyfut
fut = asyncio.Future()
eloop.call_soon_threadsafe(fut.set_result, obj)
return fut
class EmptyContext(contextlib.AbstractContextManager):
__enter__ = lambda self, *args: self
__exit__ = lambda *args: None
__aenter__ = lambda self, *args: as_fut(self)
__aexit__ = lambda *args: emptyfut
emptyctx = EmptyContext()
SEMS = {}
# Manages concurrency limits, similar to asyncio.Semaphore, but has a secondary threshold for enqueued tasks, as well as an optional rate limiter.
class Semaphore(contextlib.AbstractContextManager, contextlib.AbstractAsyncContextManager, contextlib.ContextDecorator, collections.abc.Callable):
__slots__ = ("limit", "buffer", "fut", "active", "passive", "rate_limit", "rate_bin", "last", "trace", "weak")
def __init__(self, limit=256, buffer=32, delay=0.05, rate_limit=None, randomize_ratio=2, last=False, trace=False, weak=False):
self.limit = limit
self.buffer = buffer
self.active = 0
self.passive = 0
self.rate_limit = rate_limit
self.rate_bin = deque()
self.fut = concurrent.futures.Future()
self.fut.set_result(None)
self.last = last
self.trace = trace and inspect.stack()[1]
self.weak = weak
def __str__(self):
classname = str(self.__class__).replace("'>", "")
classname = classname[classname.index("'") + 1:]
return f"<{classname} object at {hex(id(self)).upper().replace('X', 'x')}>: {self.active}/{self.limit}, {self.passive}/{self.buffer}, {len(self.rate_bin)}/{self.rate_limit}"
async def _update_bin_after_a(self, t):
await asyncio.sleep(t)
self._update_bin()
def _update_bin_after(self, t):
time.sleep(t)
self._update_bin()
def _update_bin(self):
if self.rate_limit:
try:
if self.last:
if self.rate_bin and time.time() - self.rate_bin[-1] >= self.rate_limit:
self.rate_bin.clear()
else:
while self.rate_bin and time.time() - self.rate_bin[0] >= self.rate_limit:
self.rate_bin.popleft()
except IndexError:
pass
if len(self.rate_bin) < self.limit:
try:
self.fut.set_result(None)
except concurrent.futures.InvalidStateError:
pass
if self.weak and not self.rate_bin:
SEMS.pop(id(self), None)
return self.rate_bin
def delay_for(self, seconds=0):
t = utc() + seconds
for i in range(self.limit):
self.rate_bin.append(t)
for i in range(len(self.rate_bin) - self.limit):
self.rate_bin.popleft()
return self
def enter(self):
if self.trace:
self.trace = inspect.stack()[2]
self.active += 1
if self.rate_limit:
self._update_bin().append(time.time())
if self.weak:
SEMS[id(self)] = self
return self
def check_overflow(self):
if self.passive >= self.buffer:
raise SemaphoreOverflowError(f"Semaphore object of limit {self.limit} overloaded by {self.passive}")
def __enter__(self):
if self.is_busy():
self.check_overflow()
self.passive += 1
while self.is_busy():
self.fut.result()
self.passive -= 1
return self.enter()
def __exit__(self, *args):
self.active -= 1
if self.rate_bin:
t = self.rate_bin[0 - self.last] + self.rate_limit - time.time()
if t > 0:
if get_event_loop().is_running():
create_task(self._update_bin_after_a(t))
else:
create_future_ex(self._update_bin_after, t)
else:
self._update_bin()
elif self.active < self.limit:
try:
self.fut.set_result(None)
except concurrent.futures.InvalidStateError:
pass
async def __aenter__(self):
if self.is_busy():
self.check_overflow()
self.passive += 1
while self.is_busy():
if self.fut.done():
await asyncio.sleep(0.08)
else:
await wrap_future(self.fut)
self.passive -= 1
self.enter()
return self
def __aexit__(self, *args):
self.__exit__()
return emptyfut
def wait(self):
while self.is_busy():
self.fut.result()
async def __call__(self):
while self.is_busy():
if self.fut.done():
await asyncio.sleep(0.08)
else:
await wrap_future(self.fut)
acquire = __call__
def is_active(self):
return self.active or self.passive
def is_busy(self):
return self.active >= self.limit or self.rate_limit and len(self._update_bin()) >= self.limit
@property
def busy(self):
return self.is_busy()
class SemaphoreOverflowError(RuntimeError):
__slots__ = ()
# A context manager that sends exception tracebacks to stdout.
class TracebackSuppressor(contextlib.AbstractContextManager, contextlib.AbstractAsyncContextManager, contextlib.ContextDecorator, collections.abc.Callable):
def __init__(self, *args, **kwargs):
self.exceptions = args + tuple(kwargs.values())
def __exit__(self, exc_type, exc_value, exc_tb):
if exc_type and exc_value:
for exception in self.exceptions:
if issubclass(type(exc_value), exception):
return True
try:
raise exc_value
except:
print_exc()
return True
def __aexit__(self, *args):
return as_fut(self.__exit__(*args))
__call__ = lambda self, *args, **kwargs: self.__class__(*args, **kwargs)
tracebacksuppressor = TracebackSuppressor()
# A context manager that delays the return of a function call.
class Delay(contextlib.AbstractContextManager, contextlib.AbstractAsyncContextManager, contextlib.ContextDecorator, collections.abc.Callable):
def __init__(self, duration=0):
self.duration = duration
self.start = utc()
def __call__(self):
return self.exit()
def __exit__(self, *args):
remaining = self.duration - utc() + self.start
if remaining > 0:
time.sleep(remaining)
async def __aexit__(self, *args):
remaining = self.duration - utc() + self.start
if remaining > 0:
await asyncio.sleep(remaining)
# A context manager that monitors the amount of time taken for a designated section of code.
class MemoryTimer(contextlib.AbstractContextManager, contextlib.AbstractAsyncContextManager, contextlib.ContextDecorator, collections.abc.Callable):
timers = cdict()
@classmethod
def list(cls):
return "\n".join(str(name) + ": " + str(duration) for duration, name in sorted(((mean(v), k) for k, v in cls.timers.items()), reverse=True))
def __init__(self, name=None):
self.name = name
self.start = utc()
def __call__(self):
return self.exit()
def __exit__(self, *args):
taken = utc() - self.start
try:
self.timers[self.name].append(taken)
except KeyError:
self.timers[self.name] = t = deque(maxlen=8)
t.append(taken)
def __aexit__(self, *args):
self.__exit__()
return emptyfut
# Repeatedly retries a synchronous operation, with optional break exceptions.
def retry(func, *args, attempts=5, delay=1, exc=(), **kwargs):
for i in range(attempts):
t = utc()
try:
return func(*args, **kwargs)
except BaseException as ex:
if i >= attempts - 1 or ex in exc:
raise
remaining = delay - utc() + t
if remaining > 0:
time.sleep(delay)
# Repeatedly retries a asynchronous operation, with optional break exceptions.
async def aretry(func, *args, attempts=5, delay=1, exc=(), **kwargs):
for i in range(attempts):
t = utc()
try:
return await func(*args, **kwargs)
except BaseException as ex:
if i >= attempts - 1 or ex in exc:
raise
remaining = delay - utc() + t
if remaining > 0:
await asyncio.sleep(delay)
# For compatibility with versions of asyncio and concurrent.futures that have the exceptions stored in a different module
T0 = TimeoutError
try:
T1 = asyncio.exceptions.TimeoutError
except AttributeError:
try:
T1 = asyncio.TimeoutError
except AttributeError:
T1 = TimeoutError
try:
T2 = concurrent.futures._base.TimeoutError
except AttributeError:
try:
T2 = concurrent.futures.TimeoutError
except AttributeError:
T2 = TimeoutError
try:
ISE = asyncio.exceptions.InvalidStateError
except AttributeError:
ISE = asyncio.InvalidStateError
class ArgumentError(LookupError):
__slots__ = ()
class TooManyRequests(PermissionError):
__slots__ = ()
class CommandCancelledError(RuntimeError):
__slots__ = ()
python = sys.executable
with open("auth.json", "rb") as f:
AUTH = eval(f.read())
enc_key = None
with tracebacksuppressor:
enc_key = AUTH["encryption_key"]
if not enc_key:
enc_key = AUTH["encryption_key"] = as_str(base64.b64encode(randbytes(32)).rstrip(b"="))
with open("auth.json", "w", encoding="utf-8") as f:
json.dump(AUTH, f, indent=4)
enc_key += "=="
if (len(enc_key) - 1) & 3 == 0:
enc_key += "="
enc_box = nacl.secret.SecretBox(base64.b64decode(enc_key)[:32])
encrypt = lambda s: b">~MIZA~>" + enc_box.encrypt(s if type(s) in (bytes, memoryview) else str(s).encode("utf-8"))
def decrypt(s):
if type(s) not in (bytes, memoryview):
s = str(s).encode("utf-8")
if s[:8] == b">~MIZA~>":
return enc_box.decrypt(s[8:])
raise ValueError("Data header not found.")
def zip2bytes(data):
if not hasattr(data, "read"):
data = io.BytesIO(data)
with zipfile.ZipFile(data, allowZip64=True, strict_timestamps=False) as z:
return z.read(z.namelist()[0])
def bytes2zip(data, lzma=False):
b = io.BytesIO()
ctype = zipfile.ZIP_LZMA if lzma else zipfile.ZIP_DEFLATED
with ZipFile(b, "w", compression=ctype, allowZip64=True) as z:
z.writestr("D", data=data)
return b.getbuffer()
# Safer than raw eval, more powerful than json.loads
def eval_json(s):
if type(s) is memoryview:
s = bytes(s)
try:
return orjson.loads(s)
except:
pass
try:
return safe_eval(s)
except:
pass
raise
def select_and_loads(s, mode="safe", size=None):
if not s:
raise ValueError("Data must not be empty.")
if size and size < len(s):
raise OverflowError("Data input size too large.")
if type(s) is str:
s = s.encode("utf-8")
if mode != "unsafe":
try:
s = decrypt(s)
except ValueError:
pass
except:
raise
else:
time.sleep(0.1)
b = io.BytesIO(s)
if zipfile.is_zipfile(b):
if len(s) > 1048576:
print(f"Loading zip file of size {len(s)}...")
b.seek(0)
with ZipFile(b, allowZip64=True, strict_timestamps=False) as z:
n = z.namelist()[0]
if size:
x = z.getinfo(n).file_size
if size < x:
raise OverflowError(f"Data input size too large ({x} > {size}).")
s = z.read(n)
data = None
with tracebacksuppressor:
if s[0] == 128:
data = pickle.loads(s)
if data is None:
if mode == "unsafe":
s = s.strip(b"\x00")
if not s:
raise FileNotFoundError
data = eval(compile(s, "<loader>", "eval", optimize=2, dont_inherit=False))
else:
if b"{" in s:
s = s[s.index(b"{"):s.rindex(b"}") + 1]
data = orjson.loads(s)
return data
def select_and_dumps(data, mode="safe", compress=True):
if mode == "unsafe":
s = pickle.dumps(data)
if len(s) > 32768 and compress:
t = bytes2zip(s, lzma=len(s) < 16777216)
if len(t) < len(s):
s = t
return s
try:
s = orjson.dumps(data)
except:
s = None
if len(s) > 262144:
t = bytes2zip(s, lzma=False)
if len(t) < len(s):
s = t
return s
class FileHashDict(collections.abc.MutableMapping):
sem = Semaphore(64, 128, 0.3, 1)
cache_size = 4096
def __init__(self, *args, path="", **kwargs):
if not kwargs and len(args) == 1:
self.data = args[0]
else:
self.data = dict(*args, **kwargs)
self.path = path.rstrip("/")
self.modified = set()
self.deleted = set()
self.iter = None
if self.path and not os.path.exists(self.path):
os.mkdir(self.path)
self.iter = []
__hash__ = lambda self: lambda self: hash(self.path)
__str__ = lambda self: self.__class__.__name__ + "(" + str(self.data) + ")"
__repr__ = lambda self: self.__class__.__name__ + "(" + str(self.full) + ")"
__call__ = lambda self, k: self.__getitem__(k)
__len__ = lambda self: len(self.keys())
__contains__ = lambda self, k: (k in self.data or k in self.keys()) and k not in self.deleted
__eq__ = lambda self, other: self.data == other
__ne__ = lambda self, other: self.data != other
def key_path(self, k):
return f"{self.path}/{k}"
@property
def full(self):
out = {}
waits = set()
for k in self.keys():
try:
out[k] = self.data[k]
except KeyError:
out[k] = create_future_ex(self.__getitem__, k)
waits.add(k)
for k in waits:
out[k] = out[k].result()
return out
def keys(self):
if self.iter is None or self.modified or self.deleted:
gen = (try_int(i) for i in os.listdir(self.path) if not i.endswith("\x7f") and i not in self.deleted)
if self.modified:
gen = set(gen)
gen.update(self.modified)
self.iter = alist(gen)
return self.iter
def values(self):
for k in self.keys():
with suppress(KeyError):
yield self[k]
def items(self):
for k in self.keys():
with suppress(KeyError):
yield (k, self[k])
def __iter__(self):
return iter(self.keys())
def __reversed__(self):
return reversed(self.keys())
def __getitem__(self, k):
if k in self.deleted:
raise KeyError(k)
with suppress(KeyError):
return self.data[k]
fn = self.key_path(k)
if not os.path.exists(fn):
fn += "\x7f\x7f"
if not os.path.exists(fn):
raise KeyError(k)
with self.sem:
with open(fn, "rb") as f:
s = f.read()
data = BaseException
with tracebacksuppressor:
data = select_and_loads(s, mode="unsafe")
if data is BaseException:
fn = fn.rstrip("\x7f")
for file in sorted(os.listdir("backup"), reverse=True):
with tracebacksuppressor:
if file.endswith(".wb"):
s = subprocess.check_output([sys.executable, "neutrino.py", "../backup/" + file, "-f", fn.split("/", 1)[-1]], cwd="misc")
else:
with zipfile.ZipFile("backup/" + file, allowZip64=True, strict_timestamps=False) as z:
s = z.read(fn)
data = select_and_loads(s, mode="unsafe")
self.modified.add(k)
print(f"Successfully recovered backup of {fn} from {file}.")
break
if data is BaseException:
raise KeyError(k)
self.data[k] = data
return data
def __setitem__(self, k, v):
with suppress(ValueError):
k = int(k)
self.deleted.discard(k)
self.data[k] = v
self.modified.add(k)
def get(self, k, default=None):
with suppress(KeyError):
return self[k]
return default
def pop(self, k, *args, force=False):
fn = self.key_path(k)
try:
if force:
out = self[k]
self.deleted.add(k)
return self.data.pop(k, out)
self.deleted.add(k)
return self.data.pop(k, None)
except KeyError:
if not os.path.exists(fn):
if args:
return args[0]
raise
self.deleted.add(k)
if args:
return self.data.pop(k, args[0])
return self.data.pop(k, None)
__delitem__ = pop
def popitem(self, k):
try:
return self.data.popitem(k)
except KeyError:
out = self[k]
self.pop(k)
return (k, out)
def discard(self, k):
with suppress(KeyError):
return self.pop(k)
def setdefault(self, k, v):
try:
return self[k]
except KeyError:
self[k] = v
return v
def update(self, other):
self.modified.update(other)
self.update(other)
return self
def clear(self):
if self.iter:
self.iter.clear()
self.modified.clear()
self.data.clear()
with suppress(FileNotFoundError):
shutil.rmtree(self.path)
os.mkdir(self.path)
return self
def __update__(self):
modified = frozenset(self.modified)
if modified:
self.iter = None
self.modified.clear()
for k in modified:
fn = self.key_path(k)
try:
d = self.data[k]
except KeyError:
self.deleted.add(k)
continue
s = select_and_dumps(d, mode="unsafe", compress=True)
with self.sem:
safe_save(fn, s)
deleted = list(self.deleted)
if deleted:
self.iter = None
self.deleted.clear()
for k in deleted:
self.data.pop(k, None)
fn = self.key_path(k)
with suppress(FileNotFoundError):
os.remove(fn)
with suppress(FileNotFoundError):
os.remove(fn + "\x7f")
with suppress(FileNotFoundError):
os.remove(fn + "\x7f\x7f")
while len(self.data) > self.cache_size:
with suppress(RuntimeError):
self.data.pop(next(iter(self.data)))
return modified.union(deleted)
def safe_save(fn, s):
if os.path.exists(fn):
with open(fn + "\x7f", "wb") as f:
f.write(s)
with tracebacksuppressor(FileNotFoundError):
os.remove(fn + "\x7f\x7f")
if os.path.exists(fn) and not os.path.exists(fn + "\x7f\x7f"):
os.rename(fn, fn + "\x7f\x7f")
os.rename(fn + "\x7f", fn)
else:
with open(fn, "wb") as f:
f.write(s)
# Decodes HTML encoded characters in a string.
def html_decode(s):
while len(s) > 7:
try:
i = s.index("&#")
except ValueError:
break
try:
if s[i + 2] == "x":
base = 16
p = i + 3
else:
base = 10
p = i + 2
for a in range(p, p + 16):
c = s[a]
if c == ";":
v = int(s[p:a], base)
break
elif not c.isnumeric() and c not in "abcdefABCDEF":
break
c = chr(v)
s = s[:i] + c + s[a + 1:]
except (ValueError, NameError, IndexError):
s = s[:i + 1] + "\u200b" + s[i + 1:]
continue
s = s.replace("\u200b", "").replace("&", "&").replace("<", "<").replace(">", ">")
return s.replace(""", '"').replace("'", "'")
def restructure_buttons(buttons):
if not buttons:
return buttons
if issubclass(type(buttons[0]), collections.abc.Mapping):
b = alist()
while buttons:
b.append(buttons[:5])
buttons = buttons[5:]
buttons = b
used_custom_ids = set()
for row in buttons:
for button in row:
if "type" not in button:
button["type"] = 2
if "name" in button:
button["label"] = button.pop("name")
if "label" in button:
button["label"] = lim_str(button["label"], 80)
try:
if type(button["emoji"]) is str:
button["emoji"] = cdict(id=None, name=button["emoji"])
elif not issubclass(type(button["emoji"]), collections.abc.Mapping):
emoji = button["emoji"]
button["emoji"] = cdict(name=emoji.name, id=emoji.id, animated=getattr(emoji, "animated", False))
except KeyError:
pass
if "url" in button:
button["style"] = 5
elif "custom_id" not in button:
if "id" in button:
button["custom_id"] = button["id"]
else:
button["custom_id"] = custom_id = button.get("label")
if not custom_id:
if button.get("emoji"):
button["custom_id"] = min_emoji(button["emoji"])
else:
button["custom_id"] = 0
elif type(button["custom_id"]) is not str:
button["custom_id"] = as_str(button["custom_id"])
if "custom_id" in button:
while button["custom_id"] in used_custom_ids:
if "?" in button["custom_id"]:
spl = button["custom_id"].rsplit("?", 1)
button["custom_id"] = spl[0] + f"?{int(spl[-1]) + 1}"
else:
button["custom_id"] = button["custom_id"] + "?0"
used_custom_ids.add(button["custom_id"])
if "style" not in button:
button["style"] = 1
if button.get("emoji"):
if button["emoji"].get("label") == "▪️":
button["disabled"] = True
return [dict(type=1, components=row) for row in buttons]
async def interaction_response(bot, message, content=None, embed=None, embeds=(), components=None, buttons=None, ephemeral=False):
if getattr(message, "deferred", False):
return interaction_patch(bot, message, content, embed, embeds, components, buttons, ephemeral)
if hasattr(embed, "to_dict"):
embed = embed.to_dict()
if embed:
embeds = astype(embeds, list)
embeds.append(embed)
if not getattr(message, "int_id", None):
message.int_id = message.id
if not getattr(message, "int_token", None):
message.int_token = message.slash
ephemeral = ephemeral and 64
resp = await Request(
f"https://discord.com/api/{api}/interactions/{message.int_id}/{message.int_token}/callback",
data=orjson.dumps(dict(
type=4,
data=dict(
flags=ephemeral,
content=content,
embeds=embeds,
components=components or restructure_buttons(buttons),
),
)),
method="POST",
authorise=True,
aio=True,
)
# print("INTERACTION_RESPONSE", resp)
bot = BOT[0]
if resp:
if bot:
M = bot.ExtendedMessage.new
else:
M = discord.Message
message = M(state=bot._state, channel=message.channel, data=eval_json(resp))
bot.add_message(message, files=False, force=True)
# else:
# m = bot.GhostMessage()
# m.id = message.id
# m.content = content
# m.embeds = embeds
# m.ephemeral = ephemeral
# if getattr(message, "slash", False):
# m.slash = message.slash
# bot.add_message(message, files=False, force=True)
return message
async def interaction_patch(bot, message, content=None, embed=None, embeds=(), components=None, buttons=None, ephemeral=False):
if hasattr(embed, "to_dict"):
embed = embed.to_dict()
if embed:
embeds = astype(embeds, list)
embeds.append(embed)
if not getattr(message, "int_id", None):
message.int_id = message.id
if not getattr(message, "int_token", None):
message.int_token = message.slash
ephemeral = ephemeral and 64
resp = await Request(
f"https://discord.com/api/{api}/interactions/{message.int_id}/{message.int_token}/callback",
data=orjson.dumps(dict(
type=7,
data=dict(
flags=ephemeral,
content=content,
embeds=embeds,
components=components or restructure_buttons(buttons),
),
)),
method="POST",
authorise=True,
aio=True,
)
# print("INTERACTION_PATCH", resp)
bot = BOT[0]
if resp:
if bot:
M = bot.ExtendedMessage.new
else:
M = discord.Message
message = M(state=bot._state, channel=message.channel, data=eval_json(resp))
bot.add_message(message, files=False, force=True)
else:
message.content = content or message.content
message.embeds = [discord.Embed.from_dict(embed)] if embed else message.embeds
return message
# Escapes syntax in code highlighting markdown.
ESCAPE_T = {
"[": "⦍",
"]": "⦎",
"@": "@",
"`": "",
";": ";",
}
__emap = "".maketrans(ESCAPE_T)
ESCAPE_T2 = {
"@": "@",
"`": "",
"#": "♯",
";": ";",
}
__emap2 = "".maketrans(ESCAPE_T2)
# Discord markdown format helper functions
no_md = lambda s: str(s).translate(__emap)
clr_md = lambda s: str(s).translate(__emap2)
sqr_md = lambda s: f"[{no_md(s)}]" if not isinstance(s, discord.abc.GuildChannel) else f"[#{no_md(s)}]"
def italics(s):
if type(s) is not str:
s = str(s)
if "*" not in s:
s = f"*{s}*"
return s
def bold(s):
if type(s) is not str:
s = str(s)
if "**" not in s:
s = f"**{s}**"
return s
single_md = lambda s: f"`{s}`"
code_md = lambda s: f"```\n{s}```" if s else "``` ```"
py_md = lambda s: f"```py\n{s}```" if s else "``` ```"
ini_md = lambda s: f"```ini\n{s}```" if s else "``` ```"
css_md = lambda s, force=False: (f"```css\n{s}```".replace("'", "\u2019").replace('"', "\u201d") if force else ini_md(s)) if s else "``` ```"
fix_md = lambda s: f"```fix\n{s}```" if s else "``` ```"
# Discord object mention formatting
user_mention = lambda u_id: f"<@{u_id}>"
user_pc_mention = lambda u_id: f"<@!{u_id}>"
channel_mention = lambda c_id: f"<#{c_id}>"
role_mention = lambda r_id: f"<@&{r_id}>"
channel_repr = lambda s: as_str(s) if not isinstance(s, discord.abc.GuildChannel) else str(s)
# Counts the number of lines in a file.
def line_count(fn):
with open(fn, "r", encoding="utf-8") as f:
data = f.read()
return (len(data), data.count("\n") + 1)
# Checks if a file is a python code file using its filename extension.
is_code = lambda fn: str(fn).endswith(".py") or str(fn).endswith(".pyw")
def touch(file):
with open(file, "ab"):
pass
get_folder_size = lambda path=".": sum(get_folder_size(f.path) if f.is_dir() else f.stat().st_size for f in os.scandir(path))
# Checks if an object can be used in "await" operations.
awaitable = lambda obj: hasattr(obj, "__await__") or issubclass(type(obj), asyncio.Future) or issubclass(type(obj), asyncio.Task) or inspect.isawaitable(obj)
# Async function that waits for a given time interval if the result of the input coroutine is None.
async def wait_on_none(coro, seconds=0.5):
resp = await coro
if resp is None:
await asyncio.sleep(seconds)
return resp
# Recursively iterates through an iterable finding coroutines and executing them.
async def recursive_coro(item):
if not issubclass(type(item), collections.abc.MutableSequence):
return item
for i, obj in enumerate(item):
if awaitable(obj):
if not issubclass(type(obj), asyncio.Task):
item[i] = create_task(obj)
elif issubclass(type(obj), collections.abc.MutableSequence):
item[i] = create_task(recursive_coro(obj))
for i, obj in enumerate(item):
if hasattr(obj, "__await__"):
with suppress():
item[i] = await obj
return item