-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.py
2969 lines (2660 loc) · 132 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
import discord
import json
import asyncio
import typing
import os
import textwrap
import datetime
import random
import time
import re
import numpy as np
import flag
import pycountry
import aiohttp
from timeit import default_timer as timer
from math import ceil
from operator import itemgetter
from replit import db
from discord import app_commands
from misc.random_tank_get import get_a_random_tank_emoji
from clients.gooberdash_client import GooberDashClient
from clients.moonrockminers_client import MoonrockMinersClient
from clients.rocketbotroyale_client import RocketBotRoyaleClient
from non_reaction_commands.gooberdash_non_reaction_commands import GooberDash # GD_NRC
from non_reaction_commands.moonrockminers_non_reaction_commands import (
MoonrockMiners,
) # MM_NRC
from non_reaction_commands.rocketbotroyale_non_reaction_commands import (
RocketBotRoyale,
) # RBR_NRC
from non_reaction_commands.server_non_reaction_commands import ServerMisc # Server_NRC
# Get sensitive info
try:
discord_token = os.environ["discord_token"]
rbr_mm_email_password = os.environ["rbr_mm_email_password"]
gd_email = os.environ["gd_email"]
gd_password = os.environ["gd_password"]
except KeyError:
print(
"ERROR: An environment value was not found. Please make sure your environment.json has all the right info or that you have correctly preloaded values into your environment."
)
os._exit(1)
# Set up discord bot
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
rocket_bot_royale_server_config = {}
goober_dash_server_config = {}
# Initialize rocketbot client
moonrock_miners_client = MoonrockMinersClient(
rbr_mm_email_password, rbr_mm_email_password
)
rocket_bot_royale_client = RocketBotRoyaleClient(
rbr_mm_email_password, rbr_mm_email_password
)
goober_dash_client = GooberDashClient(gd_email, gd_password)
os.system("clear")
###################### GOOBER-DASH REACTION COMMANDS START ######################
def largest_power_of_2(n):
power = 1
while power * 2 <= n:
power *= 2
return power
def goober_dash_season_info(season, mode):
duration, start_number, start_time = ([] for i in range(3))
for key in goober_dash_server_config["metadata"]["seasons"]["season_templates"]:
duration.append(key["duration"])
start_number.append(key["start_number"])
start_time.append(key["start_time"])
season_index = np.searchsorted(start_number, season + 1) - 1
season_start_timestamp = (
start_time[season_index]
+ (season - start_number[season_index]) * duration[season_index]
)
season_start = f"{datetime.datetime.utcfromtimestamp(season_start_timestamp):%Y-%m-%d %H:%M:%S} UTC"
season_end_timestamp = season_start_timestamp + duration[season_index]
season_end = f"{datetime.datetime.utcfromtimestamp(season_end_timestamp):%Y-%m-%d %H:%M:%S} UTC"
season_duration = duration[season_index]
if mode == "long":
season_days = f"{season_duration // (24 * 3600)} days {season_duration % (24 * 3600) // 3600} hours"
elif mode == "short":
s = season_duration / (24 * 3600)
season_days = f"{'{:.2f}'.format(s) if isinstance(s, float) else s} days"
current_timestamp = time.time()
if current_timestamp > season_end_timestamp:
status = "\u001b[2;31mEnded\u001b[0m"
else:
status = f"\u001b[2;32mIn progress\u001b[0m ({((current_timestamp - season_start_timestamp)/season_duration)*100:.0f} %)"
if season == goober_dash_current_season:
season_difference = (
current_timestamp - season_start_timestamp
) / season_duration
season_seconds_remaining = (
ceil(season_difference) - season_difference
) * season_duration
day = season_seconds_remaining // (24 * 3600)
hour = season_seconds_remaining % (24 * 3600) // 3600
minute = season_seconds_remaining % (24 * 3600) % 3600 // 60
second = season_seconds_remaining % (24 * 3600) % 3600 % 60
time_remaining = f"{int(day)}d {int(hour)}h {int(minute)}m {int(second)}s"
else:
time_remaining = ""
goober_dash_all_season_info = [
season_start,
season_end,
season_days,
status,
time_remaining,
]
return goober_dash_all_season_info
class goober_dash(app_commands.Group): # GD_RC
"""Goober Dash reaction commands"""
def __init__(self, bot: discord.client):
super().__init__()
async def refresh_config():
"""Refresh Goober Dash game configuration every 10 minutes"""
global goober_dash_server_config
while True:
response = await goober_dash_client.get_config()
goober_dash_server_config = response
# Remove past season keys
global goober_dash_current_season
duration, start_number, start_time = ([] for i in range(3))
for key in goober_dash_server_config["metadata"]["seasons"][
"season_templates"
]:
duration.append(key["duration"])
start_number.append(key["start_number"])
start_time.append(key["start_time"])
def get_current_season(current_timestamp):
index = np.searchsorted(start_time, current_timestamp)
accumulate_start_time = start_time[index - 1]
count = 0
while accumulate_start_time <= current_timestamp:
accumulate_start_time += duration[index - 1]
count += 1
current_season = start_number[index - 1] + count - 1
return current_season
goober_dash_current_season = get_current_season(time.time())
for global_leaderboard in db.prefix("global"):
if str(goober_dash_current_season) not in global_leaderboard:
del db[global_leaderboard]
for local_leaderboard in db.prefix("country"):
if str(goober_dash_current_season) not in local_leaderboard:
del db[local_leaderboard]
await asyncio.sleep(600)
async def public_levels_ratings_update():
"""Refresh Goober Dash public levels ratings every day"""
global goober_dash_server_config
while True:
# Get a list of level_ids
response = await goober_dash_client.official_levels()
levels_info = json.loads(response)["levels"]
level_ids = [level["id"] for level in levels_info]
# Get the rating of each level
for level_id in level_ids:
response2 = await goober_dash_client.level_info(level_id)
map_data = json.loads(response2["payload"])
if "goober_dash_public_levels_ratings_3" not in db.keys():
db["goober_dash_public_levels_ratings_3"] = dict()
db["goober_dash_public_levels_ratings_3"][level_id] = int(
(map_data["rating"] - 1) * 25
)
time.sleep(2)
await asyncio.sleep(86400)
@app_commands.command()
@app_commands.describe(
type="Global Leaderboard / Country or Region Leaderboard",
changes="Only available for Top 50 records of current season, changes since last command used",
country_code="Alpha-2 Country Code (e.g. US = United States)(Local Leaderboard only), default US",
# season="Season 1 or later, default current season",
)
async def leaderboard(
self,
interaction: discord.Interaction,
type: typing.Literal["🌎 Global", "🏳️ Local"],
changes: typing.Literal["Shown", "Hidden"],
country_code: str = "US",
# season: int = -1,
):
"""🔵 Return the specified season leaderboard of Goober Dash of current season"""
await interaction.response.defer(ephemeral=False, thinking=True)
def check(reaction, user):
return user == interaction.user and str(reaction.emoji) in [
"◀️",
"▶️",
"⏪",
"⏹️",
]
# This makes sure nobody except the command sender can interact with the "menu"
# Reassign season if unreasonable
# if season < 1 or season > goober_dash_current_season:
season = goober_dash_current_season
# Season Info
required_season_info = goober_dash_season_info(season, "long")
global all_required_season_info
all_required_season_info = (
f"📓 ***Season Info***:\n```ansi\n{'Start: ':>10}{required_season_info[0]}\n{'End: ':>10}{required_season_info[1]}\n{'Duration: ':>10}{required_season_info[2]}\n{'Status: ':>10}{required_season_info[3]}\n"
+ (
f"{'Ends in: ':>10}{required_season_info[4]}\n"
if season == goober_dash_current_season
else ""
)
+ "```"
)
# Hide changes for past seasons
# if season < goober_dash_current_season:
# changes = "Hidden"
# Get leaderboard info
invalid_country_code = False
if type == "🌎 Global":
leaderboard_id = "global"
embed_title_bracket = type
elif type == "🏳️ Local":
try:
leaderboard_id = f"country.{country_code.upper()}"
country_flag = flag.flagize(f":{country_code.upper()}:")
country_name = pycountry.countries.get(
alpha_2=f"{country_code.upper()}"
).name
embed_title_bracket = (
f"{country_flag} {country_code.upper()} - {country_name}"
)
except AttributeError:
invalid_country_code = True
if not invalid_country_code:
embed_title = f"Goober Dash <:goober:1146508948325814402>\nSeason {season} Leaderboard ({embed_title_bracket}):"
if changes == "Shown":
limit = 100
elif changes == "Hidden":
limit = 25
no_records = False
try:
response = await goober_dash_client.query_leaderboard(
season, leaderboard_id, limit
)
records = response["records"]
except aiohttp.ClientResponseError:
no_records = True
if not invalid_country_code:
if not no_records:
start = records[0]["rank"]
end = records[len(records) - 1]["rank"]
cursor_dict = dict()
cursor_dict[1] = ""
try:
cursor_dict[2] = response["next_cursor"]
next_cursor = True
except Exception:
next_cursor = False
if changes == "Shown":
# Add to replit's database for new keys
new_key_flag = False
if f"{leaderboard_id}.{season}" not in db.keys():
value = dict()
for record in records:
value[record["owner_id"]] = {
"rank": record["rank"],
"score": record["score"],
}
value["last_update_time"] = (
f"{datetime.datetime.utcfromtimestamp(time.time()):%Y-%m-%d %H:%M:%S} UTC"
)
db[record["leaderboard_id"]] = value
new_key_flag = True
# Using f-string spacing to pretty print the leaderboard labels (bold)
message = ""
label = f"{all_required_season_info}\n📊 ***Leaderboard***:```ansi\n\u001b[1m {'Rank:':<9}{'Name:':<21}{'Crowns:'}\u001b[0m\n{'—' * 50}\n"
# Using f-string spacing to pretty print the leaderboard
if len(records) < 50: # Prevent index out of range error
records_range = len(records)
else:
records_range = 50
for i in range(records_range):
# Rank difference
try:
rank_diff = int(records[i]["rank"]) - int(
db[records[i]["leaderboard_id"]][
records[i]["owner_id"]
]["rank"]
)
if rank_diff < 0:
rank_diff_2 = (
f"\u001b[2;32m▲{abs(rank_diff):<3}\u001b[0m"
)
elif rank_diff > 0:
rank_diff_2 = (
f"\u001b[2;31m▼{abs(rank_diff):<3}\u001b[0m"
)
else:
rank_diff_2 = f"{'-':^4}"
except KeyError:
rank_diff_2 = f"{'':<4}" # Not found ind repl.it's database
# Rank (bold)
message += f"{rank_diff_2}\u001b[1m{'#' + str(records[i]['rank']):<5}\u001b[0m "
# Country
message += flag.flagize(
f":{json.loads(records[i]['metadata'])['country']}: "
)
# Name
if "\n" in records[i]["username"]:
response = goober_dash_client.non_async_user_info_2(
records[i]["owner_id"]
)
user_info_2 = response["users"][0]
username = user_info_2["username"]
else:
username = records[i]["username"]
message += f"{username:<21}"
# Crowns difference
try:
crowns_diff = int(records[i]["score"]) - int(
db[records[i]["leaderboard_id"]][
records[i]["owner_id"]
]["score"]
)
if crowns_diff < 0:
crowns_diff_2 = (
f"\u001b[2;31m-{abs(crowns_diff):<4}\u001b[0m"
)
elif crowns_diff > 0:
crowns_diff_2 = (
f"\u001b[2;32m+{abs(crowns_diff):<4}\u001b[0m"
)
else:
crowns_diff_2 = f"{'-':^5}"
except Exception:
crowns_diff_2 = f"{'':<5}"
# Crowns
message += f"{'👑 ' + '{:<6,.0f}'.format(int(records[i]['score']))} {crowns_diff_2}\n"
# Split message
cannot_split = False # Prevent index out of range error
try: # In case there are not enough records
message1 = message[
: [m.start() for m in re.finditer(r"\n", message)][24]
]
message2 = (
message[
([m.start() for m in re.finditer(r"\n", message)][24])
+ 1 :
]
+ "```"
)
except Exception:
cannot_split = True
# Send
if not cannot_split:
cur_page = 1
embed_init = discord.Embed(
title=embed_title,
description=label + message1 + "```",
color=0x55D3FD,
)
embed_init.set_footer(
text=f"Page 1/2: 1 to 25 | Changes since {db[f'{leaderboard_id}.{season}']['last_update_time']}"
)
msg = await interaction.followup.send(embed=embed_init)
msg2 = await interaction.followup.send(
embed=discord.Embed(
description="To be edited...", color=0x55D3FD
)
)
for reaction_emoji in ["◀️", "▶️", "⏹️"]:
await msg.add_reaction(reaction_emoji)
while True:
try:
reaction, user = await client.wait_for(
"reaction_add", timeout=15, check=check
)
# Waiting for a reaction to be added - times out after 15 seconds
if (
str(reaction.emoji) == "▶️" and cur_page == 1
): # Go to Page 2
cur_page += 1
embed_first = discord.Embed(
title=embed_title,
description="\n" + label + message2,
color=0x55D3FD,
)
embed_first.set_footer(
text=f"Page 2/2: 26 to 50 | Changes since {db[f'{leaderboard_id}.{season}']['last_update_time']}"
)
await msg.edit(embed=embed_first)
await msg.remove_reaction(reaction, user)
elif (
str(reaction.emoji) == "◀️" and cur_page == 2
): # Go to Page 1
cur_page -= 1
embed_second = discord.Embed(
title=embed_title,
description="\n" + label + message1 + "```",
color=0x55D3FD,
)
embed_second.set_footer(
text=f"Page 1/2: 1 to 25 | Changes since {db[f'{leaderboard_id}.{season}']['last_update_time']}"
)
await msg.edit(embed=embed_second)
await msg.remove_reaction(reaction, user)
elif (
str(reaction.emoji) == "⏹️"
): # Exit page view and end the loop
await msg.edit(
embed=discord.Embed(
title=embed_title,
description=label + message1 + "```",
color=0x55D3FD,
)
)
embed_second_timeout = discord.Embed(
description="```ansi\n" + message2,
color=0x55D3FD,
)
embed_second_timeout.set_footer(
text=f"Changes since {db[f'{leaderboard_id}.{season}']['last_update_time']}"
)
await msg2.edit(embed=embed_second_timeout)
await msg.clear_reactions()
break
else:
await msg.remove_reaction(reaction, user)
# Removes reactions if invalid
except asyncio.TimeoutError:
await msg.edit(
embed=discord.Embed(
title=embed_title,
description=label + message1 + "```",
color=0x55D3FD,
)
)
embed_second_timeout = discord.Embed(
description="```ansi\n" + message2, color=0x55D3FD
)
embed_second_timeout.set_footer(
text=f"Changes since {db[f'{leaderboard_id}.{season}']['last_update_time']}"
)
await msg2.edit(embed=embed_second_timeout)
await msg.clear_reactions()
break
# Ending the loop if user doesn't react after 15 seconds
elif (
cannot_split
): # Send in 1 message if there are too little records
embed = discord.Embed(
title=embed_title,
description=label + message + "```",
color=0x55D3FD,
)
embed.set_footer(
text=f"Changes since {db[f'{leaderboard_id}.{season}']['last_update_time']}"
)
await interaction.followup.send(embed=embed)
# Update to replit's database for old keys
if (f"{leaderboard_id}.{season}" in db.keys()) and (
not new_key_flag
):
value = dict()
for record in records:
value[record["owner_id"]] = {
"rank": record["rank"],
"score": record["score"],
}
value["last_update_time"] = (
f"{datetime.datetime.utcfromtimestamp(time.time()):%Y-%m-%d %H:%M:%S} UTC"
)
db[record["leaderboard_id"]] = value
elif changes == "Hidden":
def hidden():
# Using f-string spacing to pretty print the leaderboard labels (bold)
message = f"{all_required_season_info}\n📊 ***Leaderboard***:```ansi\n\u001b[1m{'Rank:':<9}{'Name:':<21}{'Crowns:':<8}{'Rounds:':<8}{'C/R:'}\u001b[0m\n{'─' * 52}\n"
# Using f-string spacing to pretty print the leaderboard
for record in records:
# Rank (bold)
message += (
f"\u001b[1m{'#' + str(record['rank']):<5}\u001b[0m "
)
# Country
message += flag.flagize(
f":{json.loads(record['metadata'])['country']}: "
)
# Name
if "\n" in record["username"]:
response = goober_dash_client.non_async_user_info_2(
record["owner_id"]
)
user_info_2 = response["users"][0]
username = user_info_2["username"]
else:
username = record["username"]
message += f"{username:<21}"
# Crowns
message += (
f"{'👑 ' + '{:,}'.format(int(record['score'])):<8}"
)
# Rounds
message += f"{record['num_score']:<7}"
# C/R
message += (
f"{int(record['score'])/int(record['num_score']):.2f}\n"
)
message += "```"
return message
# Send
cur_page = 1
embed_init = discord.Embed(
title=embed_title, description=hidden(), color=0x55D3FD
)
embed_init.set_footer(
text=f"Page {cur_page:<2}: {start:<4} to {end:<4}"
)
msg = await interaction.followup.send(embed=embed_init)
for reaction_emoji in ["◀️", "▶️", "⏪", "⏹️"]:
await msg.add_reaction(reaction_emoji)
while True:
try:
reaction, user = await client.wait_for(
"reaction_add", timeout=15, check=check
)
# Waiting for a reaction to be added - times out after 15 seconds
if str(reaction.emoji) == "▶️" and next_cursor: # Next page
cur_page += 1
response = await goober_dash_client.query_leaderboard(
season, leaderboard_id, limit, cursor_dict[cur_page]
)
records = response["records"]
start = records[0]["rank"]
end = records[len(records) - 1]["rank"]
try:
cursor_dict[cur_page + 1] = response["next_cursor"]
except Exception:
next_cursor = False # Does not exist
embed_next = discord.Embed(
title=embed_title,
description=hidden(),
color=0x55D3FD,
)
embed_next.set_footer(
text=f"Page {cur_page:<2}: {start:<4} to {end:<4}"
)
await msg.edit(embed=embed_next)
await msg.remove_reaction(reaction, user)
elif (
str(reaction.emoji) == "◀️" and cur_page > 1
): # Previous page
cur_page -= 1
response = await goober_dash_client.query_leaderboard(
season, leaderboard_id, limit, cursor_dict[cur_page]
)
records = response["records"]
start = records[0]["rank"]
end = records[len(records) - 1]["rank"]
embed_prev = discord.Embed(
title=embed_title,
description=hidden(),
color=0x55D3FD,
)
embed_prev.set_footer(
text=f"Page {cur_page:<2}: {start:<4} to {end:<4}"
)
await msg.edit(embed=embed_prev)
await msg.remove_reaction(reaction, user)
elif (
str(reaction.emoji) == "⏪" and cur_page != 1
): # First page
cur_page = 1
next_cursor = True
response = await goober_dash_client.query_leaderboard(
season, leaderboard_id, limit, cursor_dict[cur_page]
)
records = response["records"]
start = records[0]["rank"]
end = records[len(records) - 1]["rank"]
embed_first = discord.Embed(
title=embed_title,
description=hidden(),
color=0x55D3FD,
)
embed_first.set_footer(
text=f"Page {cur_page:<2}: {start:<4} to {end:<4}"
)
await msg.edit(embed=embed_first)
await msg.remove_reaction(reaction, user)
elif (
str(reaction.emoji) == "⏹️"
): # Exit page view and end the loop
response = await goober_dash_client.query_leaderboard(
season, leaderboard_id, 50
)
records = response["records"]
embed = discord.Embed(
title=embed_title,
description=hidden(),
color=0x55D3FD,
)
await msg.edit(embed=embed)
await msg.clear_reactions()
break
else:
await msg.remove_reaction(reaction, user)
# Removes reactions if invalid
except asyncio.TimeoutError:
response = await goober_dash_client.query_leaderboard(
season, leaderboard_id, 50
)
records = response["records"]
embed_2 = discord.Embed(
title=embed_title, description=hidden(), color=0x55D3FD
)
await msg.edit(embed=embed_2)
await msg.clear_reactions()
break
# Ending the loop if user doesn't react after 15 seconds
else:
embed_init = discord.Embed(
title=embed_title,
description="```No records found```",
color=0x55D3FD,
)
await interaction.followup.send(embed=embed_init)
else:
await interaction.followup.send(
embed=discord.Embed(color=0xFF0000, title="❌ Invalid Country Code ❌")
)
@app_commands.command()
@app_commands.describe(
levels="View particular group of levels only or All levels",
sorted_by="Sort the list of Goober Dash official levels by desired values (Rating updates daily)",
order="Sorted by Ascending or Descending order",
)
async def official_levels(
self,
interaction: discord.Interaction,
levels: typing.Literal[
"Lobby Levels only",
"32-player Levels only",
"16-player Levels only",
"8-player Levels only",
"Knockout Levels only",
"All Levels",
],
sorted_by: typing.Literal[
"Name",
"Game Mode (Mode)",
"Player Count (#)",
"Theme",
"Rating (👍%)",
"Update Time (Update)",
],
order: typing.Literal["🔺 Ascending", "🔻 Descending"],
):
"""🔵 Return the a list of offical levels of Goober Dash, sorted by various values"""
await interaction.response.defer(ephemeral=False, thinking=True)
def check(reaction, user):
return user == interaction.user and str(reaction.emoji) in [
"◀️",
"▶️",
"⏪",
"⏹️",
]
# This makes sure nobody except the command sender can interact with the "menu"
response = await goober_dash_client.official_levels()
data = json.loads(response)
count_lobby = sum(
1 for level in data["levels"] if level["game_mode"] == "Lobby"
)
count_knockout = sum(
1 for level in data["levels"] if level["game_mode"] == "Knockout"
)
count_8 = sum(
1
for level in data["levels"]
if largest_power_of_2(level["player_count"]) == 8
and level["game_mode"] == "Race"
)
count_16 = sum(
1
for level in data["levels"]
if largest_power_of_2(level["player_count"]) == 16
and level["game_mode"] == "Race"
)
count_32 = sum(
1
for level in data["levels"]
if largest_power_of_2(level["player_count"]) == 32
and level["game_mode"] == "Race"
)
count_total = count_lobby + count_knockout + count_8 + count_16 + count_32
sorted_by_list = [
"Name",
"Game Mode (Mode)",
"Player Count (#)",
"Theme",
"Rating (👍%)",
"Update Time (Update)",
]
levels_info = json.loads(response)["levels"]
level_ids, names, game_modes, player_counts, themes, ratings, update_times = (
[] for i in range(7)
)
for level in levels_info:
game_mode = level["game_mode"]
player_count = (
4
if game_mode == "Knockout"
else largest_power_of_2(level["player_count"])
)
type = game_mode + str(player_count)
levels_type = {
"Lobby Levels only": "Lobby32",
"32-player Levels only": "Race32",
"16-player Levels only": "Race16",
"8-player Levels only": "Race8",
"Knockout Levels only": "Knockout4",
}
if levels != "All Levels" and levels_type[levels] != type:
continue
else:
level_ids.append(level["id"])
names.append(level["name"])
game_modes.append(game_mode)
player_counts.append(player_count)
themes.append(level["theme"].title())
try:
ratings.append(
db["goober_dash_public_levels_ratings_3"][level["id"]]
)
except Exception:
ratings.append("-1")
update_times.append(level["update_time"])
a = np.stack(
(
level_ids,
names,
game_modes,
player_counts,
themes,
ratings,
update_times,
),
axis=1,
) # 2d-array which stores all levels_info
b = a.astype("object")
b[:, 3] = b[:, 3].astype("int") # fix player_counts data type issue
b[:, 5] = b[:, 5].astype("int") # fix level_rating data type issue
column_index = sorted_by_list.index(sorted_by) + 1
if levels == "Lobby Levels only": # filter levels
b = b[np.in1d(b[:, 2], np.asarray(["Lobby"]))]
elif levels == "32-player Levels only":
b = b[np.in1d(b[:, 2], np.asarray(["Race"]))]
b = b[np.in1d(b[:, 3], np.asarray([32]))]
elif levels == "16-player Levels only":
b = b[np.in1d(b[:, 3], np.asarray([16]))]
elif levels == "8-player Levels only":
b = b[np.in1d(b[:, 3], np.asarray([8]))]
elif levels == "Knockout Levels only":
b = b[np.in1d(b[:, 2], np.asarray(["Knockout"]))]
c = b[b[:, column_index].argsort(), :] # sort by columns
c = c[::-1] if order == "🔻 Descending" else c # reverse order (if necessary)
message = ""
length = len(c)
for i in c: # i = level
lines = textwrap.wrap(i[1], 19, break_long_words=False)
message += f"{lines[0]:<20}{i[2]:<9}{i[3]:<3}{i[4]:<8}"
if i[5] != -1:
if i[5] < 76: # Yellow
color_code = 33
else: # Green
color_code = 32
message += f"\u001b[2;{color_code}m" + f"{i[5]:<5}" + "\u001b[0m"
else:
message += f"{'N.A.':<5}"
message += f"{datetime.datetime.fromisoformat(i[6].replace('Z', '+00:00').split('.')[0]).strftime('%Y-%m-%d')}\n"
lines_index = 1
while True:
try:
message += f"{lines[lines_index]}\n"
except IndexError:
break
lines_index += 1
# Split the message every 25 lines to a list
message_list_25 = re.findall("((?:[^\n]+\n?){1,25})", message)
message_list_25 = [message] if len(message_list_25) == 0 else message_list_25
# Split the message every 50 lines to a list
message_list_50 = re.findall("((?:[^\n]+\n?){1,50})", message)
message_list_50 = [message] if len(message_list_50) == 0 else message_list_50
# Title for embed
if sorted_by == "Game Mode (Mode)":
sorted_by_rennamed = "Game Mode"
elif sorted_by == "Player Count (#)":
sorted_by_rennamed = "Player Count"
elif sorted_by == "Rating (👍%)":
sorted_by_rennamed = "Rating"
elif sorted_by == "Update Time (Update)":
sorted_by_rennamed = "Update Time"
else:
sorted_by_rennamed = sorted_by
embed_title = f"Goober Dash <:goober:1146508948325814402>\nOfficial Levels ({levels})\n(Sorted by {sorted_by_rennamed} - {order} order):"
# Label for embed
# General Info Section
label = f"📓 ***General Info***:```ansi\n\u001b[1m{'Mode':^16}{'Players':^14}{'Number of Levels':^23}\u001b[0m\n{'—' * 53}\n"
label += f"{'Lobby':^16}{'32':^14}{count_lobby:^23}\n"
label += f"{'Race':^16}{'32':^14}{count_32:^23}\n"
label += f"{'Race':^16}{'16':^14}{count_16:^23}\n"
label += f"{'Race':^16}{'8':^14}{count_8:^23}\n"
label += f"{'Knockout':^16}{'4':^14}{count_knockout:^23}\n"
label += f" Total {count_total} Levels ".center(53, "*")
label += "\n```\n"
# Levels Info Section
label += f"🗒️ ***Levels Info***:```ansi\n\u001b[1m{'Name ':<20}{'Mode ':<9}{'# ':<3}{'Theme ':<8}{'👍% ':<4}{'Update '}\u001b[0m\n{'—' * 55}\n"
if sorted_by == "Game Mode (Mode)":
target = "Mode"
elif sorted_by == "Player Count (#)":
target = "#"
elif sorted_by == "Rating (👍%)":
target = "👍%"
elif sorted_by == "Update Time (Update)":
target = "Update"
else:
target = sorted_by
index = label.index(target) + len(target)
arrow = (
"\u001b[2;31m" + ("▼" if order == "🔻 Descending" else "▲") + "\u001b[0m"
)
label = label[:index] + arrow + label[index + 1 :]
def hidden(i):
# the labels and the genral info section
message = label
# the official map info list
message += message_list_25[i]
message += "```"
return message
# Send
cur_page = 1
embed_init = discord.Embed(
title=embed_title, description=hidden(cur_page - 1), color=0x55D3FD
)
embed_init.set_footer(
text=f"Page {cur_page:<2}: 1 to {length if cur_page*25 > length else cur_page*25}"
)
msg = await interaction.followup.send(embed=embed_init)
for reaction_emoji in ["◀️", "▶️", "⏪", "⏹️"]:
await msg.add_reaction(reaction_emoji)
global next_cursor
next_cursor = True
while True:
try:
reaction, user = await client.wait_for(
"reaction_add", timeout=15, check=check
)
# Waiting for a reaction to be added - times out after 15 seconds
if str(reaction.emoji) == "▶️" and next_cursor: # Next page
cur_page += 1
try:
description = hidden(cur_page - 1)
except IndexError:
cur_page -= 1
next_cursor = False
if next_cursor:
embed_next = discord.Embed(
title=embed_title, description=description, color=0x55D3FD
)
embed_next.set_footer(
text=f"Page {cur_page:<2}: {(cur_page-1)*25+1} to {length if cur_page*25 > length else cur_page*25}"
)
await msg.edit(embed=embed_next)
await msg.remove_reaction(reaction, user)
elif str(reaction.emoji) == "◀️" and cur_page > 1: # Previous page
cur_page -= 1
embed_prev = discord.Embed(
title=embed_title,
description=hidden(cur_page - 1),
color=0x55D3FD,
)
embed_prev.set_footer(
text=f"Page {cur_page:<2}: {(cur_page-1)*25+1} to {length if cur_page*25 > length else cur_page*25}"
)
await msg.edit(embed=embed_prev)
await msg.remove_reaction(reaction, user)
elif str(reaction.emoji) == "⏪" and cur_page != 1: # First page
cur_page = 1
next_cursor = True
embed_first = discord.Embed(
title=embed_title,
description=hidden(cur_page - 1),
color=0x55D3FD,
)
embed_first.set_footer(
text=f"Page {cur_page:<2}: {(cur_page-1)*25+1} to {length if cur_page*25 > length else cur_page*25}"
)
await msg.edit(embed=embed_first)
await msg.remove_reaction(reaction, user)
elif str(reaction.emoji) == "⏹️": # Exit page view and end the loop
embed = discord.Embed(
title=embed_title,
description=label + message_list_50[0] + "```",