-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
3225 lines (2635 loc) · 122 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
# Imports
import discord
import json
import os
import io
import berserk
import chessdotcom
import chess
import chess.svg
import stockfish
import platform
import re
import random
import string
import numpy as np
import urllib.request
import time
import aspose.words as aw
from datetime import datetime
from typing import Union
from discord import option, ApplicationContext
from discord.ext import commands
from discord.ext.pages import Paginator, Page
from matplotlib import pyplot as plt
from matplotlib import transforms
from distutils.dir_util import copy_tree, remove_tree
from stockfish import Stockfish
# Load databases
print("[client/startup] Populating databases...")
with open("db/chesscom_users.json", 'r') as f:
cc_user = json.load(f)
with open("config/commands.json", 'r') as f:
commands_db = json.load(f)
with open("config/auth.json", 'r', encoding="utf-8") as f:
auth_config = json.load(f)
# Global variables
intents = discord.Intents.default()
intents.message_content = True
client = discord.Bot(intents=intents)
color = discord.Color.random()
cc = chessdotcom
cc.Client.request_config["headers"]["User-Agent"] = (
"Discord bot by XyrenChess."
)
try:
session = berserk.TokenSession(auth_config["API_TOKEN"])
berserker = berserk.Client(session=session)
commands_db["lcpuzzle"]["disabled"] = 'false'
with open("config/commands.json", 'w+') as f:
json.dump(commands_db, f, indent=4)
except:
print("Error: You have not added a Lichess API token yet. Add one first in 'API_TOKEN' in 'config/auth.json'.")
print("You can get an API token from https://lichess.org/account/oauth/token.")
print('[client] Command /lcpuzzle has been disabled.')
commands_db["lcpuzzle"]["disabled"] = 'true'
with open("config/commands.json", 'w+') as f:
json.dump(commands_db, f, indent=4)
flairs = [
"<:diamond0:1229010811268239400>",
"<:diamond1:1229012475022807191>",
"<:diamond2:1229012509206380555>",
"<:diamond3:1229012532308480100>",
"<:diamond4:1229012556757074022>",
"<:diamond5:1229012590945107989>",
"<:diamond6:1229012630195273819>",
"<:diamond7:1229012658175611012>",
"<:diamond8:1229012680711475340>",
"<:crown0:1229037903695581214>",
"<:crown1:1229037989661904916>",
"<:crown2:1229038014249046017>",
"<:crown3:1229038034960384060>",
"<:crown4:1229038084616753214>",
"<:crown5:1229038105416306849>",
"<:crown6:1229038131555336252>",
"<:crown7:1229038174534111323>",
"<:crown8:1229038204993409097>",
"<:star0:1229041993402028043>",
"<:star1:1229042017116618882>",
"<:star2:1229042061030850652>",
"<:star3:1229042083080306838>",
"<:star4:1229042112922652722>",
"<:star5:1229042137295749120>",
"<:star6:1229042177129185341>",
"<:star7:1229042203335069706>",
"<:star8:1229042224113778800>",
"<:blunder_emote:1229437688537419806>",
"<:brilliant_emote:1229437692056567848>",
"<:knight_fork:1229437621244133427>",
"<:checkmate_king:1230085805201162262>",
"<:wp:1229437684066553916>",
"<:wn:1229437675660906547>",
"<:wb:1229437672439808130>",
"<:wr:1229437679263940772>",
"<:wq:1229437668245639322>",
"<:wk:1229437664491602001>",
"<:bp:1229437681566613636>",
"<:bn:1229437674121592894>",
"<:bb:1229437670652907561>",
"<:br:1229437677464453220>",
"<:bq:1229437666022658242>",
"<:bk:1229437662289727589>",
]
# Check for databases and autogenerate them
if not os.path.isdir("db"):
os.mkdir("db")
os.mkdir("db/cache")
os.mkdir("db/game_archive")
if not os.path.isfile("db/chesscom_users.json"):
with open("db/chesscom_users.json", 'x', encoding="utf-8") as f:
json.dump({}, f)
# Pre-initialization
def save(data: str) -> int:
with open("db/chesscom_users.json", 'w+') as f:
json.dump(data, f, indent=4)
return 0
if platform.system() == 'Windows':
stockfish = Stockfish(path='./stockfish_15.1_win_x64_avx2/stockfish-windows-2022-x86-64-avx2.exe')
commands_db["analyse"]["disabled"] = 'false'
with open("config/commands.json", 'w+') as f:
json.dump(commands_db, f, indent=4)
elif platform.system() == 'Linux':
stockfish = Stockfish(path='./stockfish_15.1_linux_x64/stockfish-ubuntu-20.04-x86-64')
commands_db["analyse"]["disabled"] = 'false'
with open("config/commands.json", 'w+') as f:
json.dump(commands_db, f, indent=4)
else:
print('Error: Failed to start Stockfish as your OS not supported, please try to use another OS instead.') # mac bad
print('[client] Command /analyse has been disabled.')
commands_db["analyse"]["disabled"] = 'true'
with open("config/commands.json", 'w+') as f:
json.dump(commands_db, f, indent=4)
# Events
@client.event
async def on_ready():
print(f"[client] Discord bot user logged in as {client.user.name}.")
print("[client] Ready to accept commands.")
print("-------------")
botactivity = discord.Activity(type=discord.ActivityType.playing, name="Chess.com", state="10+0 Rapid", large_image="chess_com")
await client.change_presence(activity=botactivity, status=discord.Status.streaming)
@client.event
async def on_message(message: discord.Message):
if message.content == "!reload":
if message.author.id == 706697300872921088:
global cc_user, commands_db
with open("db/chesscom_users.json", 'r', encoding="utf-8") as f:
cc_user = json.load(f)
with open("config/commands.json", 'r') as f:
commands_db = json.load(f)
print("[main/!reload] Reloaded database.")
return cc_user, commands_db
else:
print(f"[main/!reload] User {message.author.name} ({message.author.id}) does not have permission to trigger !reload.")
elif message.content == "!clearcache":
if message.author.id == 706697300872921088:
try:
remove_tree("db/cache")
os.mkdir("db/cache")
print("[main/!clearcache] Cleared cache.")
except:
print("[main/!clearcache] Data is being used right now, please try again later.")
else:
print(f"[main/!clearcache] User {message.author.name} ({message.author.id}) does not have permission to trigger !clearcache.")
elif message.content == "!wipe":
if message.author.id == 706697300872921088:
try:
remove_tree("db")
os.mkdir("db")
os.mkdir("db/cache")
os.mkdir("db/game_archive")
print("[main/!wipe] Wiped all data.")
except:
print("[main/!wipe] Data is being used right now, please try again later.")
else:
print(f"[main/!wipe] User {message.author.name} ({message.author.id}) does not have permission to trigger !wipe.")
elif message.content == "!backup":
if message.author.id == 706697300872921088:
copy_tree("db", f"backups/{time.time()}")
print("[main/!backup] Created backup of database.")
else:
print(f"[main/!backup] User {message.author.name} ({message.author.id}) does not have permission to trigger !backup.")
elif message.content == "!recover":
if message.author.id == 706697300872921088:
db = max(os.listdir("backups"))
copy_tree(f"backups/{db}", "db")
print(f"[main/!recover] Recovered from database backup at {db}.")
else:
print(f"[main/!recover] User {message.author.name} ({message.author.id}) does not have permission to trigger !recover.")
elif message.content == "!wipearchive":
if message.author.id == 706697300872921088:
remove_tree("db/game_archive")
os.mkdir("db/game_archive")
print("[main/!wipearchive] Wiped game archive.")
else:
print(f"[main/!wipearchive] User {message.author.name} ({message.author.id}) does not have permission to trigger !wipearchive.")
else:
pass
# Slash commands
@client.slash_command(
name="help",
description="Need some help?"
)
@option(name="detailed", description="Detailed command list.", type=bool, choices=[True, False], default=False)
async def _help(ctx: ApplicationContext, detailed: bool):
await ctx.defer(invisible=True)
if detailed == True:
parsed_desc = ""
for command in commands_db:
if commands_db[command]['disabled'] == 'false':
parsed_desc += f"\n\n**{commands_db[command]['name']}**: {commands_db[command]['description']}\nFormat: /{command} {commands_db[command]['args']}"
else:
pass
localembed = discord.Embed(
title="My Commands",
description=parsed_desc,
color=discord.Color.random()
)
localembed.set_footer(text="`< >`: Required, else optional.")
else:
parsed = ', '.join(commands_db)
localembed = discord.Embed(
title="Commands overview",
description=parsed,
color=discord.Color.random()
)
localembed.set_footer(text="Use `/help detailed: True` for detailed command list.")
await ctx.respond(embed=localembed)
@client.slash_command(
name="ping",
description="Get the bot's latency."
)
async def ping(ctx: ApplicationContext):
await ctx.respond(f'Pong! My current latency is {round(client.latency * 1000)}ms.')
@client.slash_command(
name="code",
description="."
)
@option(name="code", description="Enter code.", type=str)
async def code(ctx: ApplicationContext, code: str):
try:
uname = cc_user[str(ctx.author.id)]["uname"]
uinfo = cc.get_player_profile(uname).json
if code == "IBRS92DVT":
sflair = "<:stockfish_big:1230122081945915423>"
elif code == "N5LVC5JC2":
sflair = "<:gothamknights:1230122050228850811>"
elif code == "7FWOX8STE":
sflair = "<:ethereal:1230122168801562655>"
elif code == "3PWQLLUSF":
sflair = "<:komodo:1230122124547461140>"
elif code == "3JJWF3A03":
sflair = "<:komododragon:1230122147746287656>"
elif code == "ICGM891PL":
sflair = "<:torch:1230122102951120918>"
else:
localembed = discord.Embed(
title=f"Failed!",
description=f"Error: Code does not exist.",
color=discord.Color.random()
)
return await ctx.respond(embed=localembed)
if cc_user[str(ctx.author.id)]["flair"] == sflair:
try:
localembed = discord.Embed(
title=f"{uinfo['player']['name']} ({uname}) {cc_user[str(ctx.author.id)]['flair']}",
description="You have already claimed this hidden flair!",
color=discord.Color.random()
)
except:
localembed = discord.Embed(
title=f"{uname} {cc_user[str(ctx.author.id)]['flair']}",
description="You have already claimed this hidden flair!",
color=discord.Color.random()
)
else:
cc_user[str(ctx.author.id)]["flair"] = sflair
save(cc_user)
try:
localembed = discord.Embed(
title="Wow, you found this hidden flair!",
description=f"Your flair has been set to {cc_user[str(ctx.author.id)]['flair']} !",
color=discord.Color.random()
)
except:
localembed = discord.Embed(
title="Wow, you found this hidden flair!",
description=f"Your flair has been set to {cc_user[str(ctx.author.id)]['flair']} !",
color=discord.Color.random()
)
except:
localembed = discord.Embed(
title="You do not have a connected account.",
description="If this is inaccurate, please report this bug to **xyrenchess**.",
color=discord.Color.random()
)
await ctx.respond(embed=localembed)
@client.slash_command(
name="connect",
description="Connect to your Chess.com account."
)
@option(name="username", description="Your Chess.com username.", type=str)
async def connect(ctx: ApplicationContext, username: str):
await ctx.defer(invisible=True)
try:
pf = cc.get_player_profile(username).json
vcode = ''.join(random.choices(string.ascii_uppercase + string.digits, k=9))
ids = str(ctx.author.id)
cc_user[ids] = {}
cc_user[ids]["uname"] = username
cc_user[ids]["verified"] = "No"
cc_user[ids]["verification_code"] = vcode
cc_user[ids]["premium"] = pf["player"]["status"]
cc_user[ids]["flair"] = "None"
save(cc_user)
user = await client.fetch_user(ctx.author.id)
localembed0 = discord.Embed(
title=f"Connecting user `{username}` to **{ctx.author.name}**.",
description=f"Your one-time verification code is ||`{vcode}`||. Do not give this information to anyone.",
color=discord.Color.random()
)
await user.send(embed=localembed0)
localembed = discord.Embed(
title=f"User `{username}` is being connected to **{ctx.author.name}**.",
description="",
color=discord.Color.random()
)
localembed.add_field(
name="Your one-time verification code has been sent to DM.",
value="Please use `/verify verify` to verify your connected account."
)
localembed.set_footer(text="Do not know what to do? Use `/verify help` for the guide to verify your account.")
await ctx.respond(embed=localembed)
except cc.ChessDotComError:
localembed = discord.Embed(
title=f"User `{username}` does not exist.",
description="If this is inaccurate, please report this bug to **xyrenchess**.",
color=discord.Color.random()
)
await ctx.respond(embed=localembed)
@client.slash_command(
name="verify",
description="Verify your connected Chess.com account."
)
@option(name="action", description="What to do?", type=str, choices=["help", "verify", "newcode"])
async def verify(ctx: ApplicationContext, action: str):
await ctx.defer(invisible=True)
ids = str(ctx.author.id)
if action == "help":
localembed = discord.Embed(
title="Verifying using one-time verification code provided when connecting Chess.com account.",
description="To verify your Chess.com account, follow the instructions below.",
color=discord.Color.random()
)
localembed.add_field(
name="Step 1:",
value="You need to use `/connect {Chess.com_username}`. The bot will send you a one-time verification code in your DM.\nCopy the one-time verification code that is only visible to you.",
inline=False
)
localembed.set_image(url="https://cdn.discordapp.com/attachments/915526429293285466/1229369078171435058/Untitled991.png?ex=662f6e2c&is=661cf92c&hm=dfa5b45b4c38aa64104a0288f7b97ec05dbc77aa74f6791e3fcd8914c385aa6e&")
localembed2 = discord.Embed(
color=discord.Color.random()
)
localembed2.add_field(
name="Step 2:",
value="Open Chess.com and login, and go to settings of your account.",
inline=False
)
localembed2.set_image(url="https://cdn.discordapp.com/attachments/915526429293285466/1228938134511812618/Untitled984.png?ex=662ddcd3&is=661b67d3&hm=e298c9ce5081c374b33d8b4f4de638914648ec034b3474cf515d6a611acee0d2&")
localembed3 = discord.Embed(
color=discord.Color.random()
)
localembed3.add_field(
name="Step 3:",
value="Paste the verification code into the `Location` field and save the settings.",
inline=False
)
localembed3.set_image(url="https://cdn.discordapp.com/attachments/915526429293285466/1228938135359197277/Untitled985.png?ex=662ddcd4&is=661b67d4&hm=84f3c856300bd143d0e67d692ff5c4626f53b438e7a71b503a8714ac13112284&")
localembed4 = discord.Embed(
color=discord.Color.random()
)
localembed4.add_field(
name="Step 4:",
value="Use `/verify verify` to finish the verifying procedure. You may remove the code in your `Location` field after verifying your account.",
inline=False
)
localembed4.add_field(
name="What to do if I lost the verification code?",
value="Use `/verify newcode` to generate a new one-time verification code. You may use the new code to verify your account.",
inline=False
)
localembed4.set_image(url="https://cdn.discordapp.com/attachments/915526429293285466/1229369994542972978/image.png?ex=662f6f07&is=661cfa07&hm=829cfd77d7f7dcb313d74d1743148513d970326c1e356a0b0fedd6b988388deb&")
localembed5 = discord.Embed(
title="Extra!",
description="Verified or not verified?",
color=discord.Color.random()
)
localembed5.add_field(
name="How do I know if a user is verified with their Chess.com account?",
value="Verified users has a \"verified\" badge (<:verified:1228974564630069380>) next to their username, while unverified users has a \"unverified\" badge (<:unverified:1228975990932508692>) visible in their profile.",
inline=False
)
localembed5.set_image(url="https://cdn.discordapp.com/attachments/915526429293285466/1229378408266338364/Untitled995.png?ex=662f76dd&is=661d01dd&hm=129cc20e5daf4b46ce28787e0dc07b066c6011f3c6cd42e480e92b48c81d9379&")
pages = [
Page(embeds=[localembed]),
Page(embeds=[localembed2]),
Page(embeds=[localembed3]),
Page(embeds=[localembed4]),
Page(embeds=[localembed5])
]
paginator = Paginator(pages=pages)
await paginator.respond(ctx.interaction, ephemeral=True)
elif action == "verify":
try:
un = cc_user[ids]["uname"]
verified = cc_user[ids]["verified"]
vc = cc_user[ids]["verification_code"]
pf = cc.get_player_profile(un).json
if verified == "No":
try:
if pf["player"]["location"] == vc:
cc_user[ids]["verified"] = "Yes"
cc_user[ids]["verification_code"] = "**Expired**"
save(cc_user)
localembed = discord.Embed(
title=f"Account `{un}` has been verified successfully!",
description="You may now remove the verification code from your Chess.com profile.",
color=discord.Color.random()
)
else:
cc_user[ids]["verification_code"] = "**Expired**"
save(cc_user)
localembed = discord.Embed(
title="Verification failed!",
description="Error: Verification code mismatched.",
color=discord.Color.random()
)
localembed.add_field(name="How do I fix this?", value="You should get a new one-time verification code with `/verify newcode` and try again.")
localembed.set_footer(text="Old verification code expired!")
except discord.errors.ApplicationCommandInvokeError:
cc_user[ids]["verification_code"] = "**Expired**"
save(cc_user)
localembed = discord.Embed(
title="Verification failed!",
description="Error: No verification code detected.",
color=discord.Color.random()
)
localembed.add_field(name="How do I fix this?", value="You should get a new one-time verification code with `/verify newcode` and try again.")
localembed.set_footer(text="Old verification code expired!")
else:
localembed = discord.Embed(
title=f"Account `{un}` is already verified.",
description="You do not need to verify twice.",
color=discord.Color.random()
)
except:
localembed = discord.Embed(
title="You do not have a connected account.",
description="If this is inaccurate, please report this bug to **xyrenchess**.",
color=discord.Color.random()
)
elif action == "newcode":
try:
verified = cc_user[ids]["verified"]
if verified == "No":
username = cc_user[ids]["uname"]
pf = cc.get_player_profile(username).json
vcode = ''.join(random.choices(string.ascii_uppercase + string.digits, k=9))
cc_user[ids]["verification_code"] = vcode
save(cc_user)
user = await client.fetch_user(ctx.author.id)
localembed0 = discord.Embed(
title="Requested new verification code.",
description=f"Your new one-time verification code is ||`{vcode}`||. Do not give this information to anyone.",
color=discord.Color.random()
)
await user.send(embed=localembed0)
localembed = discord.Embed(
title="Requested new verification code.",
color=discord.Color.random()
)
localembed.add_field(
name="Your new one-time verification code has been sent to DM!",
value="Please check your DM list."
)
await ctx.respond(embed=localembed)
else:
localembed = discord.Embed(
title=f"Account `{un}` is already verified.",
description="You do not need a new verification code.",
color=discord.Color.random()
)
except:
localembed = discord.Embed(
title="You do not have a connected account.",
description="If this is inaccurate, please report this bug to **xyrenchess**.",
color=discord.Color.random()
)
await ctx.respond(embed=localembed)
@client.slash_command(
name="viewprofile",
description="View the profile of a Chess.com user."
)
@option(name="user", description="Specify a user.", type=str)
@option(name="format", description="Specify a format.", type=str, choices=["daily", "rapid", "blitz", "bullet"], default=None)
async def viewprofile(ctx: ApplicationContext, user: str, format: str):
await ctx.defer(invisible=True)
try:
uinfo = cc.get_player_profile(user).json
ustats = cc.get_player_stats(user).json
except:
localembed = discord.Embed(
title="User does not exist.",
description="",
color=discord.Color.random()
)
return await ctx.respond(embed=localembed)
uname = uinfo["player"]["username"]
since = uinfo["player"]["joined"]
lastonline = uinfo["player"]["last_online"]
followers = uinfo["player"]["followers"]
uid = uinfo["player"]["player_id"]
try:
av = uinfo["player"]["avatar"]
except:
av = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQTlCxyf01tNZOzuEuqFgstHMj2EMz8uOjJtrC159vgmg&s"
try:
dailyelo = ustats["stats"]["chess_daily"]["last"]["rating"]
dailybest = ustats["stats"]["chess_daily"]["best"]["rating"]
except:
dailyelo = "*No record*"
dailybest = 0
try:
rapidelo = ustats["stats"]["chess_rapid"]["last"]["rating"]
rapidbest = ustats["stats"]["chess_rapid"]["best"]["rating"]
except:
rapidelo = "*No record*"
rapidbest = 0
try:
blitzelo = ustats["stats"]["chess_blitz"]["last"]["rating"]
blitzbest = ustats["stats"]["chess_blitz"]["best"]["rating"]
except:
blitzelo = "*No record*"
blitzbest = 0
try:
bulletelo = ustats["stats"]["chess_bullet"]["last"]["rating"]
bulletbest = ustats["stats"]["chess_bullet"]["best"]["rating"]
except:
bulletelo = "*No record*"
bulletbest = 0
try:
puzzlepeak = ustats["stats"]["tactics"]["highest"]["rating"]
except:
puzzlepeak = "*No record*"
try:
puzzlerush = ustats["stats"]["puzzle_rush"]["best"]["score"]
except:
puzzlerush = "*No record*"
if format == None:
try:
localembed = discord.Embed(
title=f"{uinfo['player']['name']} ({uname})",
description=f"Member since <t:{since}> | Last online: <t:{lastonline}>",
color=discord.Color.random()
)
except:
localembed = discord.Embed(
title=f"{uname}",
description=f"Member since <t:{since}> | Last online: <t:{lastonline}>",
color=discord.Color.random()
)
localembed.set_thumbnail(url=av)
localembed.add_field(
name="<:followers:1228979708197081179> Followers:",
value=followers
)
localembed.add_field(
name="<:daily:1132115979124617297> Daily:",
value=f"{dailyelo} ({dailybest} peak)"
)
localembed.add_field(
name="<:rapid:1132112926090743940> Rapid:",
value=f"{rapidelo} ({rapidbest} peak)"
)
localembed.add_field(
name="<:blitz:1132113580788031618> Blitz:",
value=f"{blitzelo} ({blitzbest} peak)"
)
localembed.add_field(
name="<:bullet:1132114505262956606> Bullet:",
value=f"{bulletelo} ({bulletbest} peak)"
)
localembed.add_field(
name="<:puzzle:1228978258608132237> Puzzle peak rating:",
value=f"{puzzlepeak}"
)
localembed.add_field(
name="<:puzzlerush:1228972358920962188> Puzzle rush best attempt:",
value=f"{puzzlerush}"
)
await ctx.respond(embed=localembed)
else:
try:
localembed = discord.Embed(
title=f"{uinfo['player']['name']} ({uname})",
description=f"{format.upper()} stats",
color=discord.Color.random()
)
except:
localembed = discord.Embed(
title=f"{uname}",
description=f"{format.upper()} stats",
color=discord.Color.random()
)
localembed.set_thumbnail(url=av)
try:
w = ustats['stats'][f'chess_{format}']['record']['win']
d = ustats['stats'][f'chess_{format}']['record']['draw']
l = ustats['stats'][f'chess_{format}']['record']['loss']
total = w + d + l
if format == "daily":
localembed.add_field(
name="<:daily:1132115979124617297> Daily:",
value=f"Last game played at: <t:{ustats['stats']['chess_daily']['last']['date']}>",
inline=False
)
globals()[format+'elo'] = dailyelo
globals()[format+'best'] = dailybest
elif format == "rapid":
localembed.add_field(
name="<:rapid:1132112926090743940> Rapid:",
value=f"Last game played at: <t:{ustats['stats']['chess_rapid']['last']['date']}>",
inline=False
)
globals()[format+'elo'] = rapidelo
globals()[format+'best'] = rapidbest
elif format == "blitz":
localembed.add_field(
name="<:blitz:1132113580788031618> Blitz:",
value=f"Last game played at: <t:{ustats['stats']['chess_blitz']['last']['date']}>",
inline=False
)
globals()[format+'elo'] = blitzelo
globals()[format+'best'] = blitzbest
elif format == "bullet":
localembed.add_field(
name="<:bullet:1132114505262956606> Bullet:",
value=f"Last game played at: <t:{ustats['stats']['chess_bullet']['last']['date']}>",
inline=False
)
globals()[format+'elo'] = bulletelo
globals()[format+'best'] = bulletbest
except:
localembed.add_field(
name=f"This user has not played any {format} games.",
value=""
)
return await ctx.respond(embed=localembed)
localembed.add_field(
name="Rating:",
value=f"{globals()[format+'elo']} ({globals()[format+'best']} peak)"
)
localembed.add_field(
name="W/D/L (games):",
value=f"{w}/{d}/{l} ({total} games played)",
inline=False
)
localembed.add_field(
name="Rates:",
value=f"{round(w / total * 100, 2)}% **Win**, {round(d / total * 100, 2)}% **Draw**, {round(l / total * 100, 2)}% **Loss**",
inline=False
)
data_stream = io.BytesIO()
label = ['']
fig = plt.figure(figsize=(10, 1))
rot = transforms.Affine2D().rotate_deg(-90)
plt.barh(label, w, 0.1, label='Win', color='green')
plt.barh(label, d, 0.1, left=w, label='Draw', color='grey')
plt.barh(label, l, 0.1, left=np.add(w,d), label='Loss', color='red')
plt.title('Win/Draw/Loss record:', fontsize=15)
plt.savefig(data_stream, format='png', bbox_inches="tight", dpi = 80)
plt.close()
data_stream.seek(0)
chart = discord.File(data_stream,filename="wdl.png")
localembed.set_image(url="attachment:https://wdl.png")
localembed.set_footer(text=f"User id: {uid}")
await ctx.respond(embed=localembed, file=chart)
@client.slash_command(
name="profile",
description="View the profile of a user."
)
@option(name="user", description="Specify a user.", type=discord.User, default=None)
@option(name="format", description="Specify a format.", type=str, choices=["daily", "rapid", "blitz", "bullet"], default=None)
async def profile(ctx: ApplicationContext, user: discord.User, format: str):
await ctx.defer(invisible=True)
if user == None:
user = str(ctx.author.id)
else:
user = str(user.id)
try:
member = cc_user[user]["uname"]
uinfo = cc.get_player_profile(member).json
ustats = cc.get_player_stats(member).json
except:
localembed = discord.Embed(
title="You do not have a connected account.",
description="If this is inaccurate, please report this bug to **xyrenchess**.",
color=discord.Color.random()
)
return await ctx.respond(embed=localembed)
# status = uinfo["player"]["status"]
uname = uinfo["player"]["username"]
since = uinfo["player"]["joined"]
lastonline = uinfo["player"]["last_online"]
followers = uinfo["player"]["followers"]
uid = uinfo["player"]["player_id"]
try:
av = uinfo["player"]["avatar"]
except:
av = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQTlCxyf01tNZOzuEuqFgstHMj2EMz8uOjJtrC159vgmg&s"
try:
dailyelo = ustats["stats"]["chess_daily"]["last"]["rating"]
dailybest = ustats["stats"]["chess_daily"]["best"]["rating"]
except:
dailyelo = "*No record*"
dailybest = 0
try:
rapidelo = ustats["stats"]["chess_rapid"]["last"]["rating"]
rapidbest = ustats["stats"]["chess_rapid"]["best"]["rating"]
except:
rapidelo = "*No record*"
rapidbest = 0
try:
blitzelo = ustats["stats"]["chess_blitz"]["last"]["rating"]
blitzbest = ustats["stats"]["chess_blitz"]["best"]["rating"]
except:
blitzelo = "*No record*"
blitzbest = 0
try:
bulletelo = ustats["stats"]["chess_bullet"]["last"]["rating"]
bulletbest = ustats["stats"]["chess_bullet"]["best"]["rating"]
except:
bulletelo = "*No record*"
bulletbest = 0
try:
puzzlepeak = ustats["stats"]["tactics"]["highest"]["rating"]
except:
puzzlepeak = "*No record*"
try:
puzzlerush = ustats["stats"]["puzzle_rush"]["best"]["score"]
except:
puzzlerush = "*No record*"
if format == None:
if cc_user[user]["flair"] == "None":
flair = "<:placeholder:1229006396150779904>"
else:
flair = cc_user[user]["flair"]
try:
if cc_user[user]["verified"] == "Yes":
localembed = discord.Embed(
title=f"{uinfo['player']['name']} ({uname}) <:verified:1228974564630069380> {flair}",
description=f"Member since <t:{since}> | Last online: <t:{lastonline}>",
color=discord.Color.random()
)
else:
localembed = discord.Embed(
title=f"{uinfo['player']['name']} ({uname}) <:unverified:1228975990932508692> {flair}",
description=f"Member since <t:{since}> | Last online: <t:{lastonline}>",
color=discord.Color.random()
)
except:
if cc_user[user]["verified"] == "Yes":
localembed = discord.Embed(
title=f"{uname} <:verified:1228974564630069380> {flair}",
description=f"Member since <t:{since}> | Last online: <t:{lastonline}>",
color=discord.Color.random()
)
else:
localembed = discord.Embed(
title=f"{uname} <:unverified:1228975990932508692> {flair}",
description=f"Member since <t:{since}> | Last online: <t:{lastonline}>",
color=discord.Color.random()
)
localembed.set_thumbnail(url=av)
localembed.add_field(
name="<:followers:1228979708197081179> Followers:",
value=followers
)
localembed.add_field(
name="<:daily:1132115979124617297> Daily:",
value=f"{dailyelo} ({dailybest} peak)"
)
localembed.add_field(
name="<:rapid:1132112926090743940> Rapid:",
value=f"{rapidelo} ({rapidbest} peak)"
)
localembed.add_field(
name="<:blitz:1132113580788031618> Blitz:",
value=f"{blitzelo} ({blitzbest} peak)"
)
localembed.add_field(
name="<:bullet:1132114505262956606> Bullet:",
value=f"{bulletelo} ({bulletbest} peak)"
)
localembed.add_field(
name="<:puzzle:1228978258608132237> Puzzle peak rating:",
value=f"{puzzlepeak}"
)
localembed.add_field(
name="<:puzzlerush:1228972358920962188> Puzzle rush best attempt:",
value=f"{puzzlerush}"
)
await ctx.respond(embed=localembed)
else:
if cc_user[user]["flair"] == "None":
flair = "<:placeholder:1229006396150779904>"
else:
flair = cc_user[user]["flair"]
try:
if cc_user[user]["verified"] == "Yes":
localembed = discord.Embed(
title=f"{uinfo['player']['name']} ({uname}) <:verified:1228974564630069380> {flair}",
description=f"{format.upper()} stats",
color=discord.Color.random()
)
else:
localembed = discord.Embed(
title=f"{uinfo['player']['name']} ({uname}) <:unverified:1228975990932508692> {flair}",
description=f"{format.upper()} stats",
color=discord.Color.random()
)
except:
if cc_user[user]["verified"] == "Yes":
localembed = discord.Embed(
title=f"{uname} <:verified:1228974564630069380> {flair}",
description=f"{format.upper()} stats",
color=discord.Color.random()
)
else:
localembed = discord.Embed(
title=f"{uname} <:unverified:1228975990932508692> {flair}",