-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcommands.py
3233 lines (2654 loc) · 164 KB
/
commands.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
'''
Created on Jun 26, 2021
@author: willg
'''
#Bot internal imports - stuff we coded
import ComponentPaginator
from Placement import Placement
import WiimmfiSiteFunctions
import Room
import ServerFunctions
import ImageCombine
import War
import TagAIShell
import ScoreKeeper as SK
import UserDataProcessing
import TableBot
from TableBot import ChannelBot
import UtilityFunctions
import MiiPuller
import Race
import MogiUpdate
import Lounge
import TableBotExceptions
import common
import api.api_common
import Components
from data_tracking import DataTracker
import SmartTypes
import TimerDebuggers
import api.api_common as api_common
import api.api_channelbot_interface as cb_interface
from api import api_data_builder
import Stats
#Other library imports, other people codes
import asyncio
import random
import math
import time
from tabulate import tabulate
from typing import Dict, List, Set, Union, Tuple
from collections.abc import Callable
import urllib
import copy
import dill as pkl
import subprocess
import gc
from builtins import staticmethod
import itertools
import discord
import os
from datetime import datetime
import re
import traceback
import json
vr_is_on = False
USE_ALTERNATIVE_MII_RENDERING = True
async def send_missing_permissions(channel:discord.TextChannel, content=None, delete_after=7):
try:
return await channel.send("I'm missing permissions. Contact your admins. The bot needs these additional permissions:\n- Send Messages\n- Add Reactions (for pages)\n- Manage Messages (to remove reactions)", delete_after=delete_after)
except discord.errors.Forbidden: #We can't send messages
pass
#Method looks up the given name to see if any known FCs are on the table and returns the index of the player if it is found
#If the given name was a number, checks to see if the number is actually on the player list and returns the integer version of that index if it is found
#If no FCs of the given player were found on the table, or if the integer given is out of range, an error message is returned
#Returns playerNumber, errorMessage - errorMessage will be None is a playerNumber is found. playerNumber will be None if no playerNumber could be found.
def get_player_number_in_room(message: discord.Message, name: str, room: TableBot.Room.Room, server_prefix: str, command_name: str):
players = room.get_sorted_player_list()
playerNum = None
to_find = SmartTypes.SmartLookupTypes(name, allowed_types=SmartTypes.SmartLookupTypes.PLAYER_LOOKUP_TYPES)
#If they gave us an integer and it is not a discord ID, check if it's on the list
if not to_find.is_discord_id() and UtilityFunctions.isint(name):
playerNum = int(name)
if playerNum < 1 or playerNum > len(players):
return None, f"The player number must be between 1 and {len(players)}. Do `{server_prefix}{command_name}` for an example on how to use this command."
else:
return playerNum, None
descriptive, pronoun = to_find.get_clean_smart_print(message)
player_fcs = to_find.get_fcs()
if player_fcs is None:
return None, f"Could not find any FCs for {descriptive}, have {pronoun} verified an FC in Lounge?"
for playerNum_, (fc, _) in enumerate(players, 1):
if fc in player_fcs:
playerNum = playerNum_
break
if playerNum is None:
return None, f"""Could not find {descriptive} in this room."""
return playerNum, None
raise TableBotExceptions.UnreachableCode()
async def mkwx_check(message, error_message):
if common.is_bot_owner(message.author):
return True
if common.DISABLE_MKWX_COMMANDS:
raise TableBotExceptions.CommandDisabled(error_message)
if common.LIMIT_MKWX_COMMANDS:
if common.LIMITED_SERVER_IDS is not None and message.guild.id in common.LIMITED_SERVER_IDS:
return True
if common.LIMITED_CHANNEL_IDS is not None and message.channel.id in common.LIMITED_CHANNEL_IDS:
return True
raise TableBotExceptions.CommandDisabled(error_message)
async def tabling_disabled_check(message, error_message):
if common.is_bot_owner(message.author):
return True
if common.SW_DISABLED:
raise TableBotExceptions.CommandDisabled(error_message)
def get_room_not_loaded_message(server_prefix: str, is_lounge_server=False, custom_message=None, incorrect_use=False):
BULLET_POINT = '\u2022'
ROOM_LOAD_EXAMPLES = [
# Example goal: starting a table with teams, starting a table for yourself
f" {BULLET_POINT} Table a 2v2 room with 5 teams that you're in: `{server_prefix}sw 2v2 5`",
# Example goal: starting an FFA table, starting a table for a player who isn't registered in Lounge
f" {BULLET_POINT} Table an FFA room with 12 players that the FC 1000-2010-9010 is in: `{server_prefix}sw FFA 12 1000-2010-9010`",
# Example goal: starting a table for a player who is registered in Lounge, show that spaces are allowed, show that capitalization does not matter
f""" {BULLET_POINT} Table a 3v3 room with 2 teams that someone with the Lounge name "Jack Ryan" (mention them in the command if you don't know their Lounge name) is in: `{server_prefix}sw 3v3 2 Jack ryan`""",
# Example goal: starting a table for a room that has ended
f" {BULLET_POINT} Has the room already ended? Use the `/page playername` command, find the room on the website that you want to table, then use the rxx number in the URL (eg r4203018): `{server_prefix}sw 2v2 6 r4203018`"
]
example_str = "**Here are some examples to get you started:\n**" + "\n".join(ROOM_LOAD_EXAMPLES)
if custom_message is not None:
return custom_message.replace("{server_prefix}", server_prefix)
elif incorrect_use:
return f"Hmm, that's not how to use this command. {example_str}"
elif is_lounge_server:
return f"Table has not been started! Use the command `{server_prefix}sw mogiformat numberofteams` to start a table.\n\n{example_str}"
else:
return f"Table has not been started! Use the command `{server_prefix}sw warformat numberofteams (LoungeName/rxx/FC) (gps=numberOfGPs) (psb=on/off) (miis=yes/no)` to start a table.\n\n{example_str}"
def ensure_table_loaded_check(channel_bot: TableBot.ChannelBot, server_prefix: str, is_lounge_server=False, custom_message=None):
if channel_bot.is_table_loaded():
return True
error_message = get_room_not_loaded_message(server_prefix, is_lounge_server, custom_message)
raise TableBotExceptions.TableNotLoaded(error_message)
def lower_args(args: List[str]) -> List[str]:
'''Takes a list of strings and returns a list with those strings in lower case form'''
return [arg.lower() for arg in args]
async def download_table_picture(message, table_sorted_data: Dict, image_url: str, table_image_path: str):
image_download_success = await common.download_image(image_url, table_image_path)
if image_download_success:
Stats.add_lorenzi_picture_count()
else:
await message.channel.send("Could not download table picture. Using backup table picture generation.")
image_download_success = api_data_builder.generate_table_picture(table_sorted_data, table_image_path)
if image_download_success:
Stats.add_local_picture_count()
else:
raise TableBotExceptions.BackupPictureGeneratorFailed("Back up table generator failed. Shouldn't happen.")
"""============== Bot Owner only commands ================"""
#TODO: Refactor these - target the waterfall-like if-statements
class BotOwnerCommands:
"""There is no point to this class, other than for organization purposes.
This class contains all of the commands that are private and only available to me"""
@staticmethod
def is_bot_owner_check(author: discord.User, failure_message: str) -> bool:
if not common.is_bot_owner(author):
raise TableBotExceptions.NotBadWolf(failure_message)
return True
@staticmethod
async def set_api_url(message: discord.Message, args: List[str]):
BotOwnerCommands.is_bot_owner_check(message.author, "cannot set public API URL")
if len(args) != 2:
await message.channel.send(f"Here's how to use this command: `?{args[0]} public_api_url`")
return
public_api_url = args[1]
common.modify_property({"public_api_url": public_api_url})
await common.safe_send(message, f"Public API URL set to <{public_api_url}>")
@staticmethod
async def reload_properties(message: discord.Message):
BotOwnerCommands.is_bot_owner_check(message.author, "cannot reload properties")
common.reload_properties()
api.api_common.reload_properties()
await common.safe_send(message, "properties.json reloaded")
@staticmethod
async def get_logs_command(message: discord.Message):
BotOwnerCommands.is_bot_owner_check(message.author, "cannot give logs")
if os.path.exists(common.ERROR_LOGS_FILE):
await message.channel.send(file=discord.File(common.ERROR_LOGS_FILE))
if os.path.exists(common.MESSAGE_LOGGING_FILE):
await message.channel.send(file=discord.File(common.MESSAGE_LOGGING_FILE))
if os.path.exists(common.FULL_MESSAGE_LOGGING_FILE):
await message.channel.send(file=discord.File(common.FULL_MESSAGE_LOGGING_FILE))
Stats.save_metadata()
await common.safe_send_file(message, '\n'.join([f'{k} {v}' for k,v in Stats.meta['command_count'].items()]))
#Adds or removes a discord ID to/from the bot admins
@staticmethod
async def bot_admin_change(message: discord.Message, args: List[str], adding=True):
if len(args) != 2:
await message.channel.send(f"Here's how to use this command: `?{args[0]} discordID`")
return
admin_id = args[1]
smart_type = SmartTypes.SmartLookupTypes(admin_id, allowed_types={SmartTypes.SmartLookupTypes.DISCORD_ID})
if not smart_type.is_discord_id():
await message.channel.send(f"{admin_id} is not a valid discord ID.")
return
admin_id = smart_type.modified_original
success = UtilityFunctions.addBotAdmin(admin_id) if adding else UtilityFunctions.removeBotAdmin(admin_id)
if success:
add_or_remove = "Added" if adding else "Removed"
await message.channel.send(f"{add_or_remove} discord ID {admin_id} as a bot admin.")
else:
await message.channel.send("Something went wrong. Try again.")
@staticmethod
async def add_bot_admin_command(message: discord.Message, args: List[str]):
BotOwnerCommands.is_bot_owner_check(message.author, "cannot add bot admin")
await BotOwnerCommands.bot_admin_change(message, args, adding=True)
@staticmethod
async def remove_bot_admin_command(message: discord.Message, args: List[str]):
BotOwnerCommands.is_bot_owner_check(message.author, "cannot remove bot admin")
await BotOwnerCommands.bot_admin_change(message, args, adding=False)
@staticmethod
async def server_process_memory_command(message: discord.Message):
BotOwnerCommands.is_bot_owner_check(message.author, "cannot show server memory usage")
command_output = subprocess.check_output('top -b -o +%MEM | head -n 22', shell=True, text=True)
await message.channel.send(command_output)
@staticmethod
async def garbage_collect_command(message: discord.Message):
BotOwnerCommands.is_bot_owner_check(message.author, "cannot garbage collect")
gc.collect()
global USE_ALTERNATIVE_MII_RENDERING
USE_ALTERNATIVE_MII_RENDERING = not USE_ALTERNATIVE_MII_RENDERING
await message.channel.send("Collected")
@staticmethod
async def total_clear_command(message: discord.Message, lounge_update_data: Lounge.Lounge):
BotOwnerCommands.is_bot_owner_check(message.author, "cannot clear lounge table submission cooldown tracking")
lounge_update_data.update_cooldowns.clear()
await message.channel.send("Cleared.")
@staticmethod
async def dump_data_command(message: discord.Message, data_dump_function: Callable):
BotOwnerCommands.is_bot_owner_check(message.author, "cannot dump data")
successful = await UserDataProcessing.dump_data()
data_dump_function()
if successful:
await message.channel.send("Completed.")
else:
await message.channel.send("Failed.")
"""================ Bot Admin Commands =================="""
class BotAdminCommands:
"""There is no point to this class, other than for organization purposes.
This class contains the commands that only Bot Admins can do"""
@staticmethod
async def add_sha_track(message: discord.Message, args: List[str]):
BotAdminCommands.is_sha_adder_check(message.author, "cannot add sha track")
if len(args) < 3:
await message.channel.send("Requires 2 args `SHA, track_name`")
return
track_sha = args[1]
given_track_name = " ".join(args[2:])
if not UtilityFunctions.is_hex(track_sha):
await message.channel.send(f"The given track is not an SHA: {track_sha}")
return
if track_sha in Race.sha_track_name_mappings:
await message.channel.send(f"The given track is already in SHA mappings with the following name: {track_sha}\nOverwriting...")
Race.sha_track_name_mappings[track_sha] = given_track_name
await message.channel.send(f"Added: {track_sha} -> {given_track_name}")
@staticmethod
async def remove_sha_track(message: discord.Message, args: List[str]):
BotAdminCommands.is_sha_adder_check(message.author, "cannot remove sha track")
if len(args) != 2:
await message.channel.send("Requires 1 args `SHA`")
return
track_sha = args[1]
if not UtilityFunctions.is_hex(track_sha):
await message.channel.send(f"The given track is not an SHA: {track_sha}")
return
if track_sha not in Race.sha_track_name_mappings:
await message.channel.send(f"The given track is not in SHA mappings. Current mappings: {' | '.join([str(k)+' : '+str(v) for k,v in Race.sha_track_name_mappings.items()])}")
return
removed_track_name = Race.sha_track_name_mappings.pop(track_sha)
await message.channel.send(f"Removed: {track_sha} -> {removed_track_name}")
@staticmethod
def is_bot_admin_check(author: discord.User, failure_message: str) -> bool:
if not common.is_bot_admin(author):
raise TableBotExceptions.NotBotAdmin(failure_message)
return True
@staticmethod
def is_sha_adder_check(author: discord.User, failure_message: str) -> bool:
if not (common.is_bot_admin(author) or common.is_sha_adder(author)):
raise TableBotExceptions.NotBotAdmin(failure_message)
return True
@staticmethod
async def blacklisted_word_change(message: discord.Message, args: List[str], adding=True):
if len(args) < 2:
to_send = "Give a word to blacklist." if adding else "Specify a word to remove from the blacklist."
await message.channel.send(to_send)
return
if len(args) > 2:
await message.channel.send("The given word cannot have spaces.")
return
word = args[1]
success = UtilityFunctions.add_blacklisted_word(word) if adding else UtilityFunctions.remove_blacklisted_word(word)
if success:
to_send = f"Blacklisted the word: {word}" if adding else f"Removed this word from the blacklist: {word}"
await message.channel.send(to_send)
else:
await message.channel.send("Something went wrong. Try again.")
@staticmethod
async def remove_blacklisted_word_command(message: discord.Message, args: List[str]):
BotAdminCommands.is_bot_admin_check(message.author, "cannot remove blacklisted word")
await BotAdminCommands.blacklisted_word_change(message, args, adding=False)
@staticmethod
async def add_blacklisted_word_command(message: discord.Message, args: List[str]):
BotAdminCommands.is_bot_admin_check(message.author, "cannot add blacklisted word")
await BotAdminCommands.blacklisted_word_change(message, args, adding=True)
@staticmethod
async def blacklist_user_command(message: discord.Message, args: List[str]):
BotAdminCommands.is_bot_admin_check(message.author, "cannot blacklist user")
if len(args) < 2:
await message.channel.send(f"Give a Discord ID to blacklist. If you do not specify a reason for blacklisting a user, the given discord ID will be **removed** from the blacklist. To blacklist a discord ID, give a reason. `?{args[0]} <discordID> (reason)`")
return
discord_id = args[1]
reason = " ".join(args[2:])
smart_type = SmartTypes.SmartLookupTypes(discord_id, allowed_types={SmartTypes.SmartLookupTypes.DISCORD_ID})
if not smart_type.is_discord_id():
await message.channel.send(f"{discord_id} is not a valid discord ID.")
return
discord_id = smart_type.modified_original
success = UserDataProcessing.add_Blacklisted_user(discord_id, reason)
if not success:
await message.channel.send("Blacklist failed.")
return
if reason:
await message.channel.send(f"Blacklisted the discord id {discord_id}")
else:
await message.channel.send(f"Removed the discord id {discord_id} from the blacklist")
@staticmethod
async def change_ctgp_region_command(message: discord.Message, args: List[str], remove=False):
BotAdminCommands.is_bot_admin_check(message.author, "cannot change CTGP CTWW region")
if len(args) != 2:
await message.channel.send(f"You must give a new CTGP region to use for displaying CTGP WWs. For example, `?{args[0]} vs_40`")
else:
ctgp_region = args[1]
if remove:
Race.remove_ctgp_region(ctgp_region)
else:
Race.add_ctgp_region(ctgp_region)
await message.channel.send(f"CTGP region `{ctgp_region}` {'removed' if remove else 'added'}.\nCurrent CTGP regions: {sorted(Race.CTGP_CTWW_REGIONS)}")
@staticmethod
async def global_vr_command(message: discord.Message, on=True):
BotAdminCommands.is_bot_admin_check(message.author, "cannot change vr on/off")
global vr_is_on
vr_is_on = on
dump_vr_is_on()
await message.channel.send(f"Turned ?vr {'on' if on else 'off'}.")
"""================ Statistic Commands =================="""
class StatisticCommands:
"""This class houses all the commands relating to getting data for the meta and players"""
valid_rt_options = {"rt","rts","regular","regulars","regulartrack","regulartracks"}
valid_ct_options = {"ct","cts","custom","customs","customtrack","customtracks"}
valid_rt_tiers = ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8"]
valid_ct_tiers = ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8"]
rt_number_tracks = 15
ct_number_tracks = 15
rt_min_count = 1
ct_min_count = 2
min_leaderboard_count_rt = 10
min_leaderboard_count_ct = 5
leaderboard_players_per_page = 15
@staticmethod
def filter_out_bad_tracks(track_data:list, is_top_tracks=True) -> list:
if not is_top_tracks:
return [r for r in track_data if (len(r[0]) > 0 and not UtilityFunctions.is_hex(r[0]))]
return [r for r in track_data if r[0]]
@staticmethod
def validate_rts_cts_arg(arg: str) -> Union[Tuple[bool, None], Tuple[None, str]]:
is_ct = None
if arg.lower() in StatisticCommands.valid_rt_options:
is_ct = False
elif arg.lower() in StatisticCommands.valid_ct_options:
is_ct = True
if is_ct is None:
return None, f"{UtilityFunctions.clean_for_output(arg)} is not a valid option. Put in **rt** or **ct**."
return is_ct, None
@staticmethod
def validate_tier_arg(arg: str, is_ct: bool) -> Union[Tuple[int, None], Tuple[None, str]]:
original_arg = arg
rt_ct_error_string = "CT" if is_ct else "RT"
arg = arg.lower()
tier = None
if not is_ct and arg in StatisticCommands.valid_rt_tiers:
tier = int(arg.strip("t"))
elif is_ct and arg in StatisticCommands.valid_ct_tiers:
tier = int(arg.strip("t"))
if tier is None:
return None, f"{UtilityFunctions.clean_for_output(original_arg)} is not a valid {rt_ct_error_string} tier. Valid options for {rt_ct_error_string} tier are: {', '.join(StatisticCommands.valid_ct_tiers) if is_ct else ', '.join(StatisticCommands.valid_rt_tiers)}"
return tier, None
@staticmethod
def validate_days_arg(arg: str) -> Union[Tuple[int, None], Tuple[None, str]]:
original_arg = arg
arg = arg.lower().replace("d", "")
days = None
if UtilityFunctions.isint(arg):
days = int(arg)
if days < 1:
None, f"{UtilityFunctions.clean_for_output(original_arg)} was given as the number of days, but it must be 1 or more"
else:
return days, None
return None, f"{UtilityFunctions.clean_for_output(original_arg)} must be the number of days"
@staticmethod
def validate_tracks_args(args: List[str]) -> Tuple:
if len(args) < 2:
return None, None, None, "Please specify for **rts** or **cts**."
is_ct, error_message = StatisticCommands.validate_rts_cts_arg(args[1])
if is_ct is None:
return None, None, None, error_message
if len(args) == 2:
return is_ct, None, None, None
if len(args) == 3:
tier, tier_error_message = StatisticCommands.validate_tier_arg(args[2], is_ct)
days = None
if tier is None:
days, _ = StatisticCommands.validate_days_arg(args[2])
if tier is None and days is None:
return is_ct, None, None, f"{UtilityFunctions.clean_for_output(args[2])} is not a tier nor is it a number of days."
if tier is not None:
return is_ct, tier, None, None
if days is not None:
return is_ct, None, days, None
if len(args) > 3: #They specified a tier and a days filter
tier, tier_error_message = StatisticCommands.validate_tier_arg(args[2], is_ct)
if tier is None:
return is_ct, None, None, tier_error_message
days, days_error_message = StatisticCommands.validate_days_arg(args[3])
if days is None:
return is_ct, tier, None, days_error_message
return is_ct, tier, days, None
raise TableBotExceptions.UnreachableCode()
@staticmethod
def parse_track_type(command: str) -> Tuple[Union[bool, None], str]:
is_ct = None
rt_regex = f"\s({'|'.join(StatisticCommands.valid_rt_options)})(\s|$)"
ct_regex = f"\s({'|'.join(StatisticCommands.valid_ct_options)})(\s|$)"
if re.search(rt_regex,command):
is_ct = False
command = re.sub(rt_regex," ",command)
if re.search(ct_regex,command):
is_ct = True
command = re.sub(ct_regex," ",command)
return is_ct, command
@staticmethod
def parse_track_args(command: str, is_ct=False) -> Tuple[Union[int, None], Union[int, None], Union[int, None], Union[str, None]]:
min_leaderboard_count = 0
min_regex = '(min|min_count|min_races|min_plays)=(\d+)'
if m := re.search(min_regex,command):
min_leaderboard_count = int(m.group(2))
command = re.sub(min_regex,"",command)
tier = None
valid_tiers = StatisticCommands.valid_ct_tiers if (is_ct) else StatisticCommands.valid_rt_tiers
tiers_regex = f"({'|'.join(valid_tiers)})"
if m := re.search(tiers_regex,command):
tier = int(m.group()[1:])
command = re.sub(tiers_regex,"",command)
days_regex = '\s\d+d'
days = None
matches = re.findall(days_regex,command)
if len(matches) > 0:
match = matches[-1].strip()
if 'd' in match:
match = match[:-1]
days = int(match)
command = command.replace(matches[-1],"")
rest = None
split = command.split(" ")
if len(split) > 1:
rest = " ".join(split[1:])
return tier, days, min_leaderboard_count, rest
@staticmethod
def format_tracks_played_result(result:list, offset, total_races_played, is_ct:bool, is_top_tracks:bool, tier:int, number_of_days:int) -> str:
tracks_played_str = '{:>2} {:<25} | {:<12} | {:<1}\n'.format("#", "Track Name", "Times Played", "Track Played Percentage")
for list_num, (track_full_name, track_fixed_name, times_played) in (enumerate(result, offset)):
proportion_played = round((times_played / total_races_played)*100, 2)
if not is_ct and track_fixed_name.startswith("Wii "):
track_fixed_name = track_fixed_name[4:]
tracks_played_str += "{:>3} {:<25} | {:<12} | {:<.2f}%\n".format(str(list_num)+".", track_fixed_name, times_played, proportion_played)
message_title = (" Most Played" if is_top_tracks else " Least Played") + (" Custom Tracks" if is_ct else " Regular Tracks")
if tier is not None:
message_title += f" in Tier {tier}"
if number_of_days is not None:
message_title += f" in the Last {number_of_days} Day{'' if number_of_days == 1 else 's'}"
return f"**{message_title}**\n```\n{tracks_played_str}```"
@staticmethod
async def get_track_name(track_lookup): # TODO: This method returns multiple types (Tuple and List) which is probably a mistake
for track_name, value in Race.track_name_abbreviation_mappings.items():
try:
if isinstance(value, tuple):
abbrevs = value[0]
if isinstance(abbrevs, str):
abbrevs = [abbrevs]
else:
abbrevs = [value]
abbrevs = [x.lower() for x in abbrevs]
if track_lookup in abbrevs:
return track_name, track_name.replace("(Nintendo)", "").strip(), False
except:
pass
track_list = await DataTracker.DataRetriever.get_track_list()
for (track_name, url, fixed_track_name, is_ct, track_name_lookup) in track_list:
if not is_ct:
if track_lookup in track_name_lookup:
return track_name, fixed_track_name, False
latest_version = -1
latest_track = [None, None, None]
for (track_name, url, fixed_track_name, is_ct, track_name_lookup) in track_list:
if track_lookup in track_name_lookup:
try:
v = int(url.split("/i/")[1])
except:
v = 0
if v > latest_version:
latest_version = v
latest_track = [track_name, fixed_track_name, True]
# if latest_track[0] and "(" in latest_track[0]:
# latest_track[1] = latest_track[0][:latest_track[0].index("(")].strip()
return latest_track
@staticmethod
async def popular_tracks_command(message: discord.Message, args: List[str], server_prefix: str, is_top_tracks=True):
error_message = f"""Here are 3 examples of how to use this command:
Most played CTs of all time: `{server_prefix}{args[0]} ct`
Most played RTs in the past week: `{server_prefix}{args[0]} rt 7d`
Most played RTs in tier 4 during the last 5 days: `{server_prefix}{args[0]} rt t4 5d`"""
is_ct, tier, number_of_days, specific_error = StatisticCommands.validate_tracks_args(args)
if specific_error is not None:
full_error_message = f"**Error:** {specific_error}\n\n{error_message}"
await message.channel.send(full_error_message)
return
tracks_played = await DataTracker.DataRetriever.get_tracks_played_count(is_ct, tier, number_of_days)
number_tracks = StatisticCommands.ct_number_tracks if is_ct else StatisticCommands.rt_number_tracks
total_races_played = sum(track_data[2] for track_data in tracks_played)
num_pages = math.ceil(len(tracks_played)/number_tracks)
if not is_top_tracks:
tracks_played = list(reversed(tracks_played))
tracks_played = StatisticCommands.filter_out_bad_tracks(tracks_played, is_top_tracks)
def get_page_callback(page):
return StatisticCommands.format_tracks_played_result(tracks_played[page*number_tracks:(page+1)*number_tracks],
page * number_tracks + 1,
total_races_played,
is_ct, is_top_tracks, tier=tier,
number_of_days=number_of_days)
pages = [get_page_callback(page) for page in range(int(num_pages))]
paginator = ComponentPaginator.MessagePaginator(pages, show_indicator=True, timeout=common.embed_page_time.seconds)
await paginator.send(message)
@staticmethod
async def player_tracks_command(message: discord.Message, args: List[str], server_prefix: str, sort_asc=False):
adjective = "worst" if sort_asc else "best"
command_name = args[0]
error_message = f"""Here are examples of how to use this command:
- Your {adjective} RTs: `{server_prefix}{command_name} rt`
- Somebody else's {adjective} RTs: `{server_prefix}{command_name} rt [player_name]`
- Your {adjective} RTs in the past week: `{server_prefix}{command_name} rt 7d`
- Your {adjective} RTs in Tier 4: `{server_prefix}{command_name} rt t4`
- Your {adjective} CTs with at least 10 plays: `{server_prefix}{command_name} ct min=10`
"""
def get_full_error_message(specific_error: str) -> str:
return f"**Error:** {specific_error}\n\n{error_message}"
is_ct, rest = StatisticCommands.parse_track_type(" ".join(args).lower())
# if is_ct is None:
# is_ct = False
tier, number_of_days, min_count, rest = StatisticCommands.parse_track_args(rest, is_ct)
if is_ct is None:
await message.channel.send(get_full_error_message("Please specify for **rts** or **cts**."))
return
if not rest:
rest = SmartTypes.create_you_discord_id(message.author.id)
smart_type = SmartTypes.SmartLookupTypes(rest, allowed_types=SmartTypes.SmartLookupTypes.PLAYER_LOOKUP_TYPES)
await smart_type.lounge_api_update()
descriptive, pronoun = smart_type.get_clean_smart_print(message)
fcs = smart_type.get_fcs()
lounge_name = smart_type.get_lounge_name()
if lounge_name is None:
lounge_name = descriptive
if fcs is None:
await message.channel.send(get_full_error_message(f"Could not find any FCs for {descriptive}, have {pronoun} verified an FC in Lounge?"))
return
if not min_count:
min_count = StatisticCommands.ct_min_count if is_ct else StatisticCommands.rt_min_count
best_tracks = await DataTracker.DataRetriever.get_best_tracks(fcs, is_ct, tier, number_of_days, sort_asc, min_count)
filter_descriptor = ""
if tier is not None:
filter_descriptor += f" in T{tier}"
if number_of_days is not None:
filter_descriptor += f" in the Last {number_of_days} Day{'' if number_of_days == 1 else 's'}"
if len(best_tracks) == 0:
await message.channel.send(f"No data was found for {lounge_name}{filter_descriptor.lower()}.")
return
best_tracks = StatisticCommands.filter_out_bad_tracks([list(t) for t in best_tracks])
for i, track in enumerate(best_tracks,1):
if not is_ct and track[0].startswith("Wii "):
track[0] = track[0][4:]
track[0] = f"{str(i) + ('. ' if i < 10 else '.')} {track[0]}"
secs = track[3]
track[3] = f'{int(secs // 60)}:{round(secs % 60):02}'
headers = ['+ Track Name', 'Avg Pts', 'Avg Place', 'Best Time', "# Plays"]
tracks_per_page = StatisticCommands.ct_number_tracks if is_ct else StatisticCommands.rt_number_tracks
num_pages = math.ceil(len(best_tracks)/tracks_per_page)
def get_page_callback(page):
table = tabulate(best_tracks[page*tracks_per_page:(page+1)*tracks_per_page], headers, tablefmt="simple",floatfmt=".2f",colalign=["left"], stralign="right")
message_title = f'{"Worst" if sort_asc else "Best"} {"CTs" if is_ct else "RTs"} for {lounge_name}'
message_title += filter_descriptor
message_title += f' [Min {min_count} Plays]'
return f'```diff\n- {message_title}\n\n{table}```'
pages = [get_page_callback(page) for page in range(int(num_pages))]
paginator = ComponentPaginator.MessagePaginator(pages, show_indicator=True, timeout=common.embed_page_time.seconds)
await paginator.send(message)
@staticmethod
async def top_players_command(message: discord.Message, args: List[str], server_prefix: str):
command_name = args[0]
error_message = f"""Here are examples of how to use this command:
- Top Maple Treeway players: `{server_prefix}{command_name} treeway`
- Top BC3 players in Tier 5: `{server_prefix}{command_name} bc3 t5`
- Top BC3 players with at least 20 plays: `{server_prefix}{command_name} bc3 min=20`
- Top BC3 players during the last week: `{server_prefix}{command_name} bc3 7d`
"""
tier,number_of_days,min_count,track_lookup_name = StatisticCommands.parse_track_args(" ".join(args).lower())
if not track_lookup_name:
await message.channel.send(
f"Please specify a track name. \n\n" + error_message)
return
track_name, fixed_track_name, is_ct = await StatisticCommands.get_track_name(track_lookup_name.lower().replace(" ", ""))
if not track_name:
await message.channel.send(f"No track named `{UtilityFunctions.clean_for_output(track_lookup_name)}` found. \n\n" + error_message)
return
if not min_count:
min_count = StatisticCommands.min_leaderboard_count_ct if is_ct else StatisticCommands.min_leaderboard_count_rt
top_players = await DataTracker.DataRetriever.get_top_players(fixed_track_name, tier, number_of_days, min_count)
fixed_track_name = fixed_track_name.replace("Wii","").strip()
filter_descriptor = ""
if tier is not None:
filter_descriptor += f" in T{tier}"
if number_of_days is not None:
filter_descriptor += f" in the Last {number_of_days} Day{'' if number_of_days == 1 else 's'}"
if len(top_players) == 0:
await message.channel.send(f"No qualifying players were found for track `{fixed_track_name}`{filter_descriptor} "
f"(minimum {min_count} races played).\n\n" + error_message)
return
top_players = [list(t) for t in top_players]
for i, player in enumerate(top_players, 1):
player[0] = UserDataProcessing.get_lounge(player[0])
player[0] = f"{str(i) + ('. ' if i < 10 else '.')} {player[0]}"
secs = int(player[3])
player[3] = f'{int(secs // 60)}:{int(secs % 60):02}'
headers = ['+ Player', 'Avg Pts', 'Avg Place', 'Best Time', "# Plays"]
players_per_page = StatisticCommands.leaderboard_players_per_page
num_pages = math.ceil(len(top_players) / players_per_page)
def get_page_callback(page):
table = tabulate(top_players[page*players_per_page: (page+1)*players_per_page],
headers, tablefmt="simple", floatfmt=".2f", colalign=["left"], stralign="right")
message_title = f"Top Lounge {fixed_track_name} Players"
message_title += filter_descriptor
message_title += f' [Min {min_count} Plays]'
return f'```diff\n- {message_title}\n\n{table}```'
pages = [get_page_callback(page) for page in range(int(num_pages))]
paginator = ComponentPaginator.MessagePaginator(pages, show_indicator=True, timeout=common.embed_page_time.seconds)
await paginator.send(message)
@staticmethod
async def record_command(message: discord.Message, args: List[str], server_prefix: str): # TODO: This might have broken with new case for args
command_name = args[0]
error_message = f"Usage: `{server_prefix}{command_name} player_name (other_player_name) (num_days)`"
if len(args) == 1:
await message.channel.send(error_message)
return
command = " ".join(args[1:])
days = None
matches = [x[0] for x in re.findall(r'((^|\s)\d+d?($|\s))',command)]
if len(matches) > 0:
match = matches[-1].strip()
if 'd' in match:
match = match[:-1]
days = int(match)
command = command.replace(matches[-1],"")
self_comparison = True
players = command.split()
# users have to enter names with spaces removed
if len(players) > 1:
self_comparison = False
player_did = str(UserDataProcessing.get_DiscordID_By_LoungeName(players[0]))
if not player_did:
await message.channel.send(f"No player found with name {UtilityFunctions.clean_for_output(players[0])}.\n" + error_message)
return
opponent_name = players[1]
else:
opponent_name = command.strip()
player_did = str(message.author.id)
if len(opponent_name) == 0:
await message.channel.send("Please specify a player name. " + error_message)
return
opponent_did = UserDataProcessing.get_DiscordID_By_LoungeName(opponent_name)
if not opponent_did:
await message.channel.send(f"No player found with name {UtilityFunctions.clean_for_output(opponent_name)}.\n" + error_message)
return
if player_did == opponent_did:
await message.channel.send(f"You can not compare your record against yourself.\n" + error_message)
return
rt_result = await DataTracker.DataRetriever.get_record(player_did, opponent_did, days)
ct_result = await DataTracker.DataRetriever.get_record(player_did, opponent_did, days, is_ct=True)
(rt_total, rt_wins), (ct_total, ct_wins) = rt_result[0], ct_result[0]
if rt_total+ct_total == 0:
await message.channel.send(f"{'You have' if self_comparison else f'{players[0]} has'} played no races against {UtilityFunctions.clean_for_output(opponent_name)}.")
return
rt_losses = rt_total-rt_wins
ct_losses = ct_total-ct_wins
rt_record = "No record" if rt_total == 0 else f"{rt_wins} Wins — {rt_losses} Losses"
ct_record = "No record" if ct_total == 0 else f"{ct_wins} Wins — {ct_losses} Losses"
await message.channel.send(f"RT: {rt_record}\nCT: {ct_record}")
"""================== Other Commands ===================="""
#TODO: Refactor these - target the waterfall-like if-statements
class OtherCommands:
"""There is no point to this class, other than for organization purposes.
This class contains all of the non administrative "stateless" commands"""
@staticmethod
async def stats_command(message: discord.Message, client: common.client):
num_wars = client.getNumActiveWars()
stats_str = Stats.stats(num_wars, client)
if stats_str is None:
await message.channel.send("Error fetching stats. Try again.")
else:
await message.channel.send(stats_str)
@staticmethod
async def get_flag_command(message: discord.Message, args: List[str], server_prefix: str):
to_load = SmartTypes.create_you_discord_id(message.author.id)
if len(args) > 1:
to_load = " ".join(args[1:])
smart_type = SmartTypes.SmartLookupTypes(to_load, allowed_types=SmartTypes.SmartLookupTypes.PLAYER_LOOKUP_TYPES)
await smart_type.lounge_api_update()
descriptive, pronoun = smart_type.get_clean_smart_print(message)
discord_id = smart_type.get_discord_id()
if discord_id is None:
await message.channel.send(f"Could not find a discord ID for {descriptive}, have {pronoun} verified an FC in Lounge?")
return
flag = smart_type.get_country_flag()
if flag is None:
adverb = "do not" if descriptive == 'you' else 'does not'
await message.channel.send(f"{SmartTypes.capitalize(descriptive)} {adverb} have a flag set. To set {SmartTypes.possessive(pronoun)} flag for tables, {descriptive} should use `{server_prefix}setflag flagcode`. Flagcodes can be found at: {common.LORENZI_FLAG_PAGE_URL_NO_PREVIEW}")
return
image_name = f"{flag}.png"
if flag.startswith("cl_") and flag.endswith("u"): #Remap this specific flag code to a specific picture
image_name += 'cl_C3B1u.png'
embed = discord.Embed(title=f"{SmartTypes.capitalize(SmartTypes.possessive(descriptive))} flag", colour = discord.Colour.dark_blue(), description=flag)
file = discord.File(f"{common.FLAG_IMAGES_PATH}{image_name}", filename=image_name)
embed.set_thumbnail(url=f"attachment://{image_name}")
await message.channel.send(file=file, embed=embed)
@staticmethod
async def set_flag_command(message: discord.Message, args: List[str]):
author_id = message.author.id
flag_code = args[1].lower() if len(args) > 1 else None
if flag_code is None or flag_code == "none":
UserDataProcessing.add_flag(author_id, "")
await message.channel.send(f"Your flag was successfully removed. If you want to add a flag again in the future, pick a flag code from this website: {common.LORENZI_FLAG_PAGE_URL_NO_PREVIEW}")
return
if flag_code not in UserDataProcessing.valid_flag_codes:
await message.channel.send(f"This is not a valid flag code. For a list of flags and their codes, please visit: {common.LORENZI_FLAG_PAGE_URL_NO_PREVIEW}")
return
UserDataProcessing.add_flag(author_id, flag_code)
await message.channel.send("Your flag was successfully added and will now be displayed on tables.")
@staticmethod
async def lounge_name_command(message: discord.Message, args: List[str]):
to_load = SmartTypes.create_you_discord_id(message.author.id)
if len(args) > 1:
to_load = " ".join(args[1:])
smart_type = SmartTypes.SmartLookupTypes(to_load, allowed_types=SmartTypes.SmartLookupTypes.PLAYER_LOOKUP_TYPES)
await smart_type.lounge_api_update()
lounge_name = smart_type.get_lounge_name()
fcs = smart_type.get_fcs()
descriptive, pronoun = smart_type.get_clean_smart_print(message)
if fcs is None or lounge_name is None:
await message.channel.send(f"Could not find a lounge name for {descriptive}, have {pronoun} verified an FC in Lounge?")
return
await message.channel.send(f"{SmartTypes.possessive(SmartTypes.capitalize(descriptive))} Lounge name is: **{lounge_name}**")
@staticmethod
async def fc_command(message: discord.Message, args: List[str]):
to_load = SmartTypes.create_you_discord_id(message.author.id)
if len(args) > 1:
to_load = " ".join(args[1:])
smart_type = SmartTypes.SmartLookupTypes(to_load, allowed_types=SmartTypes.SmartLookupTypes.PLAYER_LOOKUP_TYPES)
await smart_type.lounge_api_update()
fcs = smart_type.get_fcs()
if fcs is None:
descriptive, pronoun = smart_type.get_clean_smart_print(message)
await message.channel.send(f"Could not find any FCs for {descriptive}, have {pronoun} verified an FC in Lounge?")
return
await message.channel.send(fcs[0])
@staticmethod
async def player_page_command(message: discord.Message, args: List[str]):
to_load = SmartTypes.create_you_discord_id(message.author.id)
if len(args) > 1:
to_load = " ".join(args[1:])
smart_type = SmartTypes.SmartLookupTypes(to_load, allowed_types=SmartTypes.SmartLookupTypes.PLAYER_LOOKUP_TYPES)
descriptive, pronoun = smart_type.get_clean_smart_print(message)
await smart_type.lounge_api_update()
fcs = smart_type.get_fcs()
if fcs is None:
await message.channel.send(f"Could not find any FCs for {descriptive}, have {pronoun} verified an FC in Lounge?")
return
players_pages = [f"{WiimmfiSiteFunctions.SUB_MKWX_URL}p{MiiPuller.fc_to_pid(fc)}" for fc in fcs]
player_pages_str = "\n".join(players_pages)
if smart_type.is_fc():
to_send = f"""{SmartTypes.capitalize(SmartTypes.possessive(descriptive))} player page:\n\n{player_pages_str}"""
else:
to_send = f"""{SmartTypes.capitalize(SmartTypes.possessive(descriptive))} player pages, sorted by most recent usage:\n\n{player_pages_str}"""
await message.channel.send(to_send)
@staticmethod
async def mii_command(message: discord.Message, args: List[str]):
if common.MII_COMMAND_DISABLED and not common.is_bot_owner(message.author):
await message.channel.send("To ensure Table Bot remains stable and can access the website, miis have been disabled at this time.")
return
await mkwx_check(message, "Mii command disabled.")
if cooldown:=mii_cooldown_check(message.author.id):
return await message.channel.send(f"{message.author.mention}, wait {common.MII_COOLDOWN-cooldown:.1f} seconds before using this command again.")
to_load = SmartTypes.create_you_discord_id(message.author.id)
if len(args) > 1:
to_load = " ".join(args[1:])
smart_type = SmartTypes.SmartLookupTypes(to_load, allowed_types=SmartTypes.SmartLookupTypes.PLAYER_LOOKUP_TYPES)
await smart_type.lounge_api_update()
fcs = smart_type.get_fcs()
# common.client.mii_cooldowns[message.author.id] = time.monotonic()
descriptive, pronoun = smart_type.get_clean_smart_print(message)
if fcs is None:
await message.channel.send(f"Could not find any FCs for {descriptive}, have {pronoun} verified an FC in Lounge?")
return
FC = fcs[0]
mii_dict = await MiiPuller.get_miis([FC], str(message.id))
common.client.mii_cooldowns[message.author.id] = time.monotonic()
if isinstance(mii_dict, str):
await message.channel.send(mii_dict)
return
if mii_dict is None or (isinstance(mii_dict, dict) and FC not in mii_dict):
await message.channel.send("There was a problem trying to get the mii. Try again later.")
return
mii = mii_dict[FC]
if isinstance(mii, str):
await message.channel.send(str)