-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
1064 lines (961 loc) · 35.8 KB
/
utils.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 datetime
import io
import re
from unittest import result
import aiofiles
import html5lib
import ksoftapi
from PIL import Image
from bs4 import BeautifulSoup
from typing import Union
import random
import json
import aiohttp
import aiomysql
import discord
from discord.ext import commands
start_time= datetime.datetime.utcnow()
with open('resources/env.json','r') as f:
env=json.load(f)
DB_PASSWORD=env['database']['password']
DB_HOST=env['database']['host']
DB_USER=env['database']['user']
ENV_COLOUR=env['COLOUR']
TOKEN=env['TOKEN']
RAVY_TOKEN=env['ravy']
IMGUR_TOKEN=env['imgur']
WA_TOKEN=env['wa']
GOOGLE_TOKEN=env['google']
CUTTLY_TOKEN=env['cuttly']
CROSS_EMOJI="<:sypher_cross:833930332604465181>"
TICK_EMOJI="<:sypher_tick:833930333434019882>"
ROLL_EMOJI="<a:rolling:909092152062124122>"
SAFE_EMOJI='<:safe:906433431779549206>'
UNSAFE_EMOJI='<:unsafe:906433431750184980>'
NAME_EMOJI='<:name:906790016997523496>'
ID_EMOJI='<:id:906790891702857728>'
HIGHEST_EMOJI='<:highest:906793216286814229>'
DISCORD_EMOJI='<:discord:906795199014006814>'
JOINED_EMOJI='<:joined:906796881097682956>'
SERVER_EMOJI='<:server:906872089456304188>'
MEMBERS_EMOJI='<:members:906860509343653898>'
REGION_EMOJI='<:region:906865086222721085>'
VERIFIED_EMOJI='<:verified:906869707192295484>'
CREATED_EMOJI='<:create:906867172884758548>'
OWNER_EMOJI='<:owner:906864132823875605>'
PREFIX_EMOJI='<:prefix:906871242966065173>'
COLOUR_EMOJI='<:colour:906894560985239572>'
PROPERTIES_EMOJI='<:properties:906898412362924033>'
POSITION_EMOJI='<:position:906913982860898314>'
DEPLOY_EMOJI='<:deploy:907284223159861248>'
WEBSITE_EMOJI='<:website:907289356174262292>'
SUPPORT_EMOJI='<:support:907290900579909632>'
SIGNAL_EMOJI='<:signal:908700939316252722>'
PROCESSOR_EMOJI='<:processor:908701976383070208>'
PING_EMOJI='<a:ping:909030836089815040>'
REMINDER_EMOJI='<a:reminder:909340764616675338>'
VIRUS_EMOJI='<a:virus:919839073064091659>'
CORONA_EMOJI='<:corona:919839072665632780>'
RECOVERED_EMOJI='<:recovered:919839072225222677>'
DEAD_EMOJI='<:dead:919839072380391424>'
TEST_EMOJI='<:test:919839072627859487>'
CASES_EMOJI='<:cases:919839072330088480>'
DEATH_EMOJI='<:death:919839072686596198>'
LOADING_EMOJI='<a:loading:919862408082772028>'
UTILITIES_EMOJI='<:utilities:920557130065514506>'
INVISIBLE_EMOJI='<:invisible:921036945973461012>'
X_EMOJI='<:x_:921251869307830292>'
O_EMOJI='<:o_:921251869014249553>'
EMPTY_EMOJI='<:empty:922046563105263636>'
RED_EMOJI='<:red:922046561884721162>'
YELLOW_EMOJI='<:yellow:922046561763090462>'
ONE_EMOJI='<:one:922056199053131796>'
TWO_EMOJI='<:two:922057775159316480>'
THREE_EMOJI='<:three:922057775314518016>'
FOUR_EMOJI='<:four:922057776719609866>'
FIVE_EMOJI='<:five:922057775981428736>'
SIX_EMOJI='<:six:922057776019177492>'
SEVEN_EMOJI='<:seven:922057775893348372>'
RED_ICON_EMOJI='<:red_icon:922046562203476058>'
YELLOW_ICON_EMOJI='<:yellow_icon:922046561909899265>'
LEFT_END='<:left_end:922335926976397322>'
RIGHT_END='<:right_end:922335929987907594>'
MIDDLE_END='<:middle_end:922335926489858068>'
MODERATE_EMOJI='<:moderate:930024141338333204>'
async def fetch_prefix(id):
pool = await aiomysql.create_pool(host=DB_HOST, user=DB_USER,
password=DB_PASSWORD, db='servers', autocommit=True)
async with pool.acquire() as conn:
async with conn.cursor() as cursor:
try:
await cursor.execute(
f'''SELECT prefix from configurations where guild='{id}';''')
result = await cursor.fetchall()
if not result:
prefix = ';'
else:
prefix = result[0][0]
except:
prefix = ';'
pool.close()
await pool.wait_closed()
return prefix
def regex(string):
r= r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
url = re.findall(r,string)
return [x[0] for x in url]
async def ping_url(url):
u = url
try:
async with aiohttp.ClientSession() as session:
async with session.get(u) as r:
return True
except aiohttp.ClientConnectionError:
return False
def emo(score):
if 90 <= score <= 100:
return f"{TICK_EMOJI}"
if 50 <= score < 90:
return f"{MODERATE_EMOJI}"
if 0 <= score < 50:
return f"{CROSS_EMOJI}"
def fcp(score):
if 0 <= score <= 2:
return f"{TICK_EMOJI}"
if 2 < score <= 4:
return f"{MODERATE_EMOJI}"
if score > 4:
return f"{CROSS_EMOJI}"
def si(score):
if 0 <= score <= 4.3:
return f"{TICK_EMOJI}"
if 4.3< score <= 5.8:
return f"{MODERATE_EMOJI}"
if score > 5.8:
return f"{CROSS_EMOJI}"
def lcps(score):
if 0 <= score <= 2.5:
return f"{TICK_EMOJI}"
if 2.5 < score <= 4:
return f"{MODERATE_EMOJI}"
if score >4:
return f"{CROSS_EMOJI}"
def ti(score):
if 0 <= score <= 3.8:
return f"{TICK_EMOJI}"
if 3.8 < score <=7.3:
return f"{MODERATE_EMOJI}"
if score > 7.3:
return f"{CROSS_EMOJI}"
def tbt(score):
if 0 <= score <= 300:
return f"{TICK_EMOJI}"
if 300 < score <= 600:
return f"{MODERATE_EMOJI}"
if score > 600:
return f"{CROSS_EMOJI}"
def clss(score):
if 0 <= score <= 0.1:
return f"{TICK_EMOJI}"
if 0.1< score <= 0.25:
return f"{MODERATE_EMOJI}"
if score > 0.25:
return f"{CROSS_EMOJI}"
async def light(url):
n=0
while n<=5:
n=n+1
u = f'https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url={url}&key={GOOGLE_TOKEN}'
q = {'strategy': 'DESKTOP',
'category': ['PERFORMANCE', 'ACCESSIBILITY', 'BEST_PRACTICES', 'SEO'], }
try:
async with aiohttp.ClientSession() as session:
async with session.get(u, params=q) as r:
x = await r.read()
y = x.decode('UTF-8')
data = json.loads(y)
fcp_time = data["lighthouseResult"]["audits"]["first-contentful-paint"]["displayValue"]
speed_index = data["lighthouseResult"]["audits"]["speed-index"]["displayValue"]
lcp = data["lighthouseResult"]["audits"]["largest-contentful-paint"]["displayValue"]
time_interactive = data["lighthouseResult"]["audits"]["interactive"]["displayValue"]
blocking_time_duration = data["lighthouseResult"]["audits"]["total-blocking-time"]["displayValue"]
cls = data["lighthouseResult"]["audits"]["cumulative-layout-shift"]["displayValue"]
overall_score = int(data["lighthouseResult"]["categories"]["performance"]["score"] * 100)
performance = data["lighthouseResult"]["categories"]['performance']['score'] * 100
accessibility = data["lighthouseResult"]["categories"]['accessibility']['score'] * 100
bestpractices = data["lighthouseResult"]["categories"]['best-practices']['score'] * 100
seo = data["lighthouseResult"]["categories"]['seo']['score'] * 100
fcp_time = float(fcp_time.replace("\xa0s", ""))
speed_index = float(speed_index.replace("\xa0s", ""))
time_interactive = float(time_interactive.replace("\xa0s", ""))
blocking_time_duration = float(blocking_time_duration.replace("\xa0ms", ""))
lcp = float(lcp.replace("\xa0s", ""))
cls = round(float(cls), 2)
return [fcp_time,speed_index,lcp,time_interactive,blocking_time_duration,cls,performance,accessibility,bestpractices,seo,overall_score]
except:
pass
if n>5:
return None
async def imgurl(image):
url = "https://api.imgur.com/3/image"
payload = {'image': image}
headers = {
'Authorization': f'Client-ID {IMGUR_TOKEN}'
}
try:
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=headers, data=payload) as r:
x=await r.json()
return x
except:
return None
async def get_permissions(member):
pool = await aiomysql.create_pool(host=DB_HOST,
user=DB_USER,
password=DB_PASSWORD, db='servers', autocommit=True)
try:
async with pool.acquire() as conn:
async with conn.cursor() as cursor:
await cursor.execute(f'''SELECT permissions FROM g{member.guild.id} WHERE user_id='{member.id}';''')
result = await cursor.fetchall()
permission = result[0][0]
return permission
except:
return None
async def get_topic():
url="https://www.conversationstarters.com/generator.php"
async with aiohttp.ClientSession() as s:
async with s.get(url) as r:
output=await r.read()
soup = BeautifulSoup(output, 'html5lib')
topics=soup.find("div", {"id": "random"})
return topics.contents[1]
async def get_meme():
try:
async with aiohttp.ClientSession() as cs:
async with cs.get('https://www.reddit.com/r/dankmemes/new.json?sort=hot') as r:
res = await r.json()
result=res['data']['children'][random.randint(0, 25)]['data']
return [f"https://reddit.com{result['permalink']}",result['title'],result['downs'],result['ups'],result['url'],result['num_comments']]
except:
return None
async def get_riddle():
async with aiofiles.open('resources/riddles.json', mode='r') as p:
contents = await p.read()
riddles= json.loads(contents)
riddle=random.choice(list(riddles.keys()))
answer=riddles[riddle]
return [riddle,answer]
async def get_hangman_word():
async with aiofiles.open('resources/hangman.json', mode='r') as p:
contents = await p.read()
words= json.loads(contents)
word=random.choice(words)
return word
async def get_joke():
async with aiofiles.open('resources/jokes.json', mode='r') as p:
contents = await p.read()
jokes= json.loads(contents)
joke= random.choice(jokes)
setup= joke['setup']
punchline= joke['punchline']
return [setup,punchline]
async def extract_member(ctx,member):
if type(member) == str:
u = discord.utils.get(ctx.guild.members, name=str(member))
member=u
elif type(member) == int:
u = discord.utils.get(ctx.guild.members, id=member)
member=u
elif isinstance(member,discord.Member):
pass
else:
member=None
return member
async def extract_role(ctx,role):
if type(role) == str:
u = discord.utils.get(ctx.guild.roles, name=str(role))
role=u
elif type(role) == int:
u = discord.utils.get(ctx.guild.roles, id=role)
role=u
elif isinstance(role,discord.Role):
pass
else:
role=None
return role
async def get_user(bot,id):
u = bot.get_user(id)
if not u:
try:
u = await bot.fetch_user(id)
except discord.NotFound:
return None
return u
async def get_channel(bot,id):
u = bot.get_channel(id)
if not u:
try:
u = await bot.fetch_channel(id)
except discord.NotFound:
return None
return u
async def get_guild(bot,id):
g = bot.get_guild(id)
if not g:
try:
g= await bot.fetch_guild(id)
except discord.NotFound:
return None
return g
async def set_level_role(guild,level,role):
pool = await aiomysql.create_pool(host=DB_HOST, user=DB_USER,
password=DB_PASSWORD, db='servers', autocommit=True)
async with pool.acquire() as conn:
async with conn.cursor() as cursor:
await cursor.execute("show tables;")
result1 = await cursor.fetchall()
if not (f'''r{str(guild.id)}''',) in result1:
await cursor.execute(
f'''CREATE TABLE r{str(guild.id)}(level TEXT,role TEXT);''')
await conn.commit()
await cursor.execute(
f'''SELECT role FROM r{str(guild.id)} WHERE level='{level}';''')
result = await cursor.fetchall()
if not result:
await cursor.execute(
f'''INSERT INTO r{str(guild.id)} VALUES('{level}','{role.id}');''')
await conn.commit()
else:
await cursor.execute(
f'''UPDATE r{str(guild.id)} SET role='{role.id}' WHERE level='{level}';''')
await conn.commit()
async def add_autorole(guild,role):
pool = await aiomysql.create_pool(host=DB_HOST, user=DB_USER,
password=DB_PASSWORD, db='utils', autocommit=True)
async with pool.acquire() as conn:
async with conn.cursor() as cursor:
await cursor.execute(f'''SELECT guild,role from autoroles where guild='{guild.id}' AND role='{role.id}';''')
result1 = await cursor.fetchall()
if result1:
return False
await cursor.execute(
f'''INSERT INTO autoroles VALUES('{guild.id}','{role.id}');''')
await conn.commit()
return True
async def remove_autorole(guild,role):
pool = await aiomysql.create_pool(host=DB_HOST, user=DB_USER,
password=DB_PASSWORD, db='utils', autocommit=True)
async with pool.acquire() as conn:
async with conn.cursor() as cursor:
await cursor.execute(f'''SELECT guild,role from autoroles where guild='{guild.id}' AND role='{role.id}';''')
result1 = await cursor.fetchall()
if not result1:
return False
await cursor.execute(
f'''DELETE FROM autoroles WHERE guild='{guild.id}' AND role='{role.id}';''')
await conn.commit()
return True
async def get_level_role(guild,level):
pool = await aiomysql.create_pool(host=DB_HOST, user=DB_USER,
password=DB_PASSWORD, db='servers', autocommit=True)
async with pool.acquire() as conn:
async with conn.cursor() as cursor:
await cursor.execute("show tables;")
result1 = await cursor.fetchall()
if (f'''r{str(guild.id)}''',) in result1:
await cursor.execute(
f'''SELECT role FROM r{str(guild.id)} WHERE level='{level}';''')
result = await cursor.fetchall()
if not result:
return None
else:
role=guild.get_role(int(result[0][0]))
return role
else:
await cursor.execute(
f'''CREATE TABLE r{str(guild.id)}(level TEXT,role TEXT);''')
await conn.commit()
return None
async def log(bot,member,action):
pool = await aiomysql.create_pool(host=DB_HOST, user=DB_USER,
password=DB_PASSWORD, db='servers', autocommit=True)
async with pool.acquire() as conn:
async with conn.cursor() as cursor:
await cursor.execute(
f'''SELECT logging,logging_channel FROM configurations WHERE guild='{member.guild.id}';''')
result = await cursor.fetchall()
if result:
if result[0][0] == 'True':
channel = await get_channel(bot, int(result[0][1]))
embed = discord.Embed(colour=ENV_COLOUR, description=f'{member.mention} {action}',
timestamp=datetime.datetime.utcnow())
embed.set_author(name=f"{member} | {member.id}",
icon_url=str(member.avatar.with_format('png').url))
await channel.send(embed=embed)
async def extract_info(ctx,bot,input):
if isinstance(input,discord.Member):
return ['member',input]
elif isinstance(input,discord.User):
return ['user',input]
elif isinstance(input,discord.Role):
return ['role',input]
elif type(input)==int:
u = discord.utils.get(ctx.guild.members, id=input)
if u:
return ['member',u]
else:
u=await get_user(bot,input)
if u:
return ['user',u]
else:
if input==ctx.guild.id:
return ['guild',ctx.guild]
else:
r=ctx.guild.get_role(input)
if r:
return ['role',r]
else:
return None
elif type(input)==str:
u = discord.utils.get(ctx.guild.members, name=input)
if u:
return ['member',u]
else:
if input.lower()=='server':
return ['guild',ctx.guild]
else:
r = discord.utils.get(ctx.guild.roles, name=input)
if r:
return ['role',r]
else:
return None
async def extract_duration(args):
duration = None
unit = None
units = ['s', 'sec', 'second', 'seconds', 'm', 'min', 'minute', 'minutes', 'h', 'hour', 'hours', 'd', 'day', 'days',
'w', 'week', 'weeks', 'month', 'months', 'y', 'year', 'years']
if len(args) >= 2:
if args[0].isdigit() and args[1] in units:
if args[1].lower() in ['s', 'sec', 'second', 'seconds']:
unit = 'sec'
duration = int(args[0])
elif args[1].lower() in ['m', 'min', 'minute', 'minutes']:
unit = 'min'
duration = int(args[0])
elif args[1].lower() in ['h', 'hour', 'hours']:
unit = 'hour'
duration = int(args[0])
elif args[1].lower() in ['d', 'day', 'days']:
unit = 'day'
duration = int(args[0])
elif args[1].lower() in ['w', 'week', 'weeks']:
unit = 'week'
duration = int(args[0])
elif args[1].lower() in ['month', 'months']:
unit = 'month'
duration = int(args[0])
elif args[1].lower() in ['y', 'year', 'years']:
unit = 'year'
duration = int(args[0])
if len(args) > 2:
text= ' '.join(args[2:])
else:
text= None
else:
asset = args[0]
duration = ''
unit = ''
for i in range(len(asset)):
if asset[i].isdigit():
duration = duration + asset[i]
else:
unit = asset[i:]
unit = unit.strip()
break
if not duration:
text= ' '.join(args)
duration = None
elif unit in units:
duration = int(duration)
if unit.lower() in ['s', 'sec', 'second', 'seconds']:
unit = 'sec'
elif unit.lower() in ['m', 'min', 'minute', 'minutes']:
unit = 'min'
elif unit.lower() in ['h', 'hour', 'hours']:
unit = 'hour'
elif unit.lower() in ['d', 'day', 'days']:
unit = 'day'
elif unit.lower() in ['w', 'week', 'weeks']:
unit = 'week'
elif unit.lower() in ['month', 'months']:
unit = 'month'
elif unit.lower() in ['y', 'year', 'years']:
unit = 'year'
text= ' '.join(args[1:])
else:
duration = None
text= ' '.join(args)
else:
asset = args[0]
duration = ''
unit = ''
for i in range(len(asset)):
if asset[i].isdigit():
duration = duration + asset[i]
else:
unit = asset[i:]
unit = unit.strip()
break
if not duration:
text= ' '.join(args)
duration = None
elif unit in units:
duration = int(duration)
text= None
if unit.lower() in ['s', 'sec', 'second', 'seconds']:
unit = 'sec'
elif unit.lower() in ['m', 'min', 'minute', 'minutes']:
unit = 'min'
elif unit.lower() in ['h', 'hour', 'hours']:
unit = 'hour'
elif unit.lower() in ['d', 'day', 'days']:
unit = 'day'
elif unit.lower() in ['w', 'week', 'weeks']:
unit = 'week'
elif unit.lower() in ['month', 'months']:
unit = 'month'
elif unit.lower() in ['y', 'year', 'years']:
unit = 'year'
else:
duration = None
text= ' '.join(args)
return [duration,unit,text]
async def ban_info(user):
headers = {'Authorization': f"{RAVY_TOKEN}"}
async with aiohttp.ClientSession() as session:
async with session.get(f"https://ravy.org/api/v1/users/{user.id}/bans", headers=headers) as r:
v = await r.read()
k = json.loads(v)
try:
return k
except:
return None
def partial_emoji_converter(argument: str):
if len(argument) < 5:
# Sometimes unicode emojis are actually more than 1 symbol
return discord.PartialEmoji(name=argument)
match = re.match(r"<(a?):([a-zA-Z0-9\_]+):([0-9]+)>$", argument)
if match is not None:
emoji_animated = bool(match.group(1))
emoji_name = match.group(2)
emoji_id = int(match.group(3))
return discord.PartialEmoji(name=emoji_name, animated=emoji_animated, id=emoji_id)
raise discord.InvalidArgument(f"Failed to convert {argument} to PartialEmoji")
async def get_roast():
async with aiohttp.ClientSession() as session:
async with session.get('https://insult.mattbas.org/api/insult.json') as r:
response= await r.read()
j=json.loads(response)
return j['insult']
async def corona_stats(location=None):
url = 'https://disease.sh/v3/covid-19/all'
if location:
url=f'https://disease.sh/v3/covid-19/countries/{location}'
async with aiohttp.ClientSession() as session:
async with session.get(url) as r:
response= await r.read()
status=r.status
if status==404:
return None
else:
j = json.loads(response)
return j
async def get_urban(query):
q='%20'.join(query)
async with aiohttp.ClientSession() as session:
async with session.get(f'https://api.urbandictionary.com/v0/define?term={q}') as r:
response= await r.read()
d=json.loads(response)
if not d['list']:
return None
definition=d['list'][0]['definition']
return definition
async def wolfram_image(arg):
query = '+'.join(arg.split())
url = f"https://api.wolframalpha.com/v1/simple?i={query}%3F&background=white&foreground=black&units=metric&appid={WA_TOKEN}"
async with aiohttp.ClientSession() as session:
async with session.get(url) as r:
if r.status == 501:
return None
x = await r.read()
f = io.BytesIO(x)
im = Image.open(f)
width, height = im.size
left = 0
top = 70
right = width
bottom = height - 60
buf = io.BytesIO()
im1 = im.crop((left, top, right, bottom))
im1.save(buf, format='png')
byte_im = buf.getvalue()
f = io.BytesIO(byte_im)
return f
async def wolfram(arg):
query = '+'.join(arg.split())
url = f"https://api.wolframalpha.com/v1/result?i={query}%3F&units=metric&appid={WA_TOKEN}"
async with aiohttp.ClientSession() as session:
async with session.get(url) as r:
if r.status==501:
return None
x=await r.read()
f = io.BytesIO(x)
p=f.getvalue()
return str(p)[2:-1]
def is_bot_admin(ctx):
with open('resources/env.json', 'r') as p:
record = json.load(p)
if 'admins' in record:
if ctx.author.id in record['admins']:
return True
else:
setattr(ctx,'failed_check','is_bot_admin')
return False
else:
setattr(ctx, 'failed_check', 'is_bot_admin')
return False
def is_admin():
async def predicate(ctx):
p=False
member=ctx.author
if member.guild_permissions.administrator:
p=True
elif member.id==member.guild.owner_id:
p=True
else:
pool = await aiomysql.create_pool(host=DB_HOST, user=DB_USER,
password=DB_PASSWORD, db='servers', autocommit=True)
async with pool.acquire() as conn:
async with conn.cursor() as cursor:
await cursor.execute("show tables;")
result1 = await cursor.fetchall()
if not (f'''g{str(member.guild.id)}''',) in result1:
await cursor.execute(
f'''CREATE TABLE g{str(member.guild.id)}(user_id TEXT,xp bigint,level TEXT,muted TEXT,permissions TEXT);''')
await cursor.execute(
f'''INSERT INTO g{member.guild.id} values('{member.author.id}',0,'1','False',NULL)''')
await conn.commit()
async with pool.acquire() as conn:
async with conn.cursor() as cursor:
try:
await cursor.execute(
f'''SELECT permissions from g{member.guild.id} where user_id='{member.id}';''')
result = await cursor.fetchall()
if not result:
p = False
setattr(ctx,'failed_check', 'is_admin')
else:
perms = result[0][0]
if 'a' in perms:
p = True
else:
p = False
setattr(ctx, 'failed_check', 'is_admin')
except:
p=False
setattr(ctx, 'failed_check', 'is_admin')
pool.close()
await pool.wait_closed()
return p
return commands.check(predicate)
async def is_mod(ctx):
p = False
member = ctx.author
if member.id == member.guild.owner_id:
p = True
else:
pool = await aiomysql.create_pool(host=DB_HOST, user=DB_USER,
password=DB_PASSWORD, db='servers', autocommit=True)
async with pool.acquire() as conn:
async with conn.cursor() as cursor:
await cursor.execute("show tables;")
result1 = await cursor.fetchall()
if not (f'''g{str(member.guild.id)}''',) in result1:
await cursor.execute(
f'''CREATE TABLE g{str(member.guild.id)}(user_id TEXT,xp bigint,level TEXT,muted TEXT,permissions TEXT);''')
await cursor.execute(
f'''INSERT INTO g{member.guild.id} values('{member.author.id}',0,'1','False',NULL)''')
await conn.commit()
async with pool.acquire() as conn:
async with conn.cursor() as cursor:
try:
await cursor.execute(
f'''SELECT permissions from g{member.guild.id} where user_id='{member.id}';''')
result = await cursor.fetchall()
if not result:
p = False
else:
perms = result[0][0]
if 'm' in perms:
p = True
else:
p = False
except:
p = False
pool.close()
await pool.wait_closed()
return p
def can_kick():
async def predicate(ctx):
p = False
member = ctx.author
if member.id == member.guild.owner_id:
p = True
elif member.guild_permissions.kick_members:
p = True
else:
p=await is_mod(ctx)
if not p:
setattr(ctx,'failed_check', 'can_kick')
return p
return commands.check(predicate)
def can_ban():
async def predicate(ctx):
p = False
member = ctx.author
if member.id == member.guild.owner_id:
p = True
elif member.guild_permissions.ban_members:
p = True
else:
p=await is_mod(ctx)
if not p:
setattr(ctx,'failed_check', 'can_ban')
return p
return commands.check(predicate)
def can_mute():
async def predicate(ctx):
p = False
member = ctx.author
if member.id == member.guild.owner_id:
p = True
elif member.guild_permissions.administrator:
p=True
else:
p=await is_mod(ctx)
if not p:
setattr(ctx,'failed_check','can_mute')
return p
return commands.check(predicate)
def can_lock():
async def predicate(ctx):
p = False
member = ctx.author
if member.id == member.guild.owner_id:
p = True
elif member.guild_permissions.manage_roles:
p=True
else:
p=await is_mod(ctx)
if not p:
setattr(ctx,'failed_check','can_lock')
return p
return commands.check(predicate)
def can_set_slowmode():
async def predicate(ctx):
p = False
member = ctx.author
if member.id == member.guild.owner_id:
p = True
elif member.guild_permissions.manage_channels:
p=True
else:
p=await is_mod(ctx)
if not p:
setattr(ctx,'failed_check','can_set_slowmode')
return p
return commands.check(predicate)
def among_us_host():
async def predicate(ctx):
p = False
member = ctx.author
if member.id == member.guild.owner_id:
p = True
elif member.guild_permissions.mute_members:
p=True
else:
pool = await aiomysql.create_pool(host=DB_HOST, user=DB_USER,
password=DB_PASSWORD, db='servers', autocommit=True)
async with pool.acquire() as conn:
async with conn.cursor() as cursor:
try:
await cursor.execute(
f'''SELECT permissions from g{member.guild.id} where user_id='{member.id}';''')
result = await cursor.fetchall()
if not result:
p = False
setattr(ctx, 'failed_check', 'among_us_host')
else:
perms = result[0][0]
if 'u' in perms:
p = True
else:
p = False
setattr(ctx, 'failed_check', 'among_us_host')
except:
p = False
setattr(ctx, 'failed_check', 'among_us_host')
pool.close()
await pool.wait_closed()
return p
return commands.check(predicate)
HANGMANPICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
def tttMatrix(b):
return [
[b[0], b[1], b[2]],
[b[3], b[4], b[5]],
[b[6], b[7], b[8]]
]
def tttCoordsToIndex(coords):
map = {
(0, 0): 0,
(0, 1): 1,
(0, 2): 2,
(1, 0): 3,
(1, 1): 4,
(1, 2): 5,
(2, 0): 6,
(2, 1): 7,
(2, 2): 8
}
return map[coords]
def tttDoChecks(b):
m = tttMatrix(b)
if tttCheckWin(m, "x"):
return "x"
if tttCheckWin(m, "o"):
return "o"
if tttCheckDraw(b):
return "draw"
return None
def tttFindStreaks(m, xo):
row = [0, 0, 0]
col = [0, 0, 0]
dia = [0, 0]
for y in range(3):
for x in range(3):
if m[y][x] == xo:
row[y] += 1
col[x] += 1
if m[0][0] == xo:
dia[0] += 1
if m[1][1] == xo:
dia[0] += 1
dia[1] += 1
if m[2][2] == xo:
dia[0] += 1
if m[2][0] == xo:
dia[1] += 1
if m[0][2] == xo:
dia[1] += 1
return (row, col, dia)
def tttCheckWin(m, xo):
row, col, dia = tttFindStreaks(m, xo)
dia.append(0)
for i in range(3):
if row[i] == 3 or col[i] == 3 or dia[i] == 3:
return True
return False
def tttCheckDraw(board):