-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathbadges.py
1251 lines (1128 loc) · 48.1 KB
/
badges.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
from dateutil import tz
from common import *
from cogs.trade import db_cancel_trade, get_offered_and_requested_badge_names
import queries.badge_completion as queries_badge_completion
from queries.badge_scrap import *
from queries.wishlist import *
from utils.badge_utils import *
from utils.check_channel_access import access_check
from utils.string_utils import *
# _____ __ .__ __
# / _ \ __ ___/ |_ ____ ____ ____ _____ ______ | | _____/ |_ ____
# / /_\ \| | \ __\/ _ \_/ ___\/ _ \ / \\____ \| | _/ __ \ __\/ __ \
# / | \ | /| | ( <_> ) \__( <_> ) Y Y \ |_> > |_\ ___/| | \ ___/
# \____|__ /____/ |__| \____/ \___ >____/|__|_| / __/|____/\___ >__| \___ >
# \/ \/ \/|__| \/ \/
async def all_badges_autocomplete(ctx:discord.AutocompleteContext):
return [badge['badge_name'] for badge in await db_get_all_badge_info() if ctx.value.lower() in badge['badge_name'].lower()]
async def scrapper_autocomplete(ctx:discord.AutocompleteContext):
first_badge = ctx.options["first_badge"]
second_badge = ctx.options["second_badge"]
third_badge = ctx.options["third_badge"]
user_badges = await db_get_user_unlocked_badges(ctx.interaction.user.id)
filtered_badges = [first_badge, second_badge, third_badge] + [b['badge_name'] for b in await db_get_special_badges()]
filtered_badge_names = [badge['badge_name'] for badge in user_badges if badge['badge_name'] not in filtered_badges]
return [b for b in filtered_badge_names if ctx.value.lower() in b.lower()]
badge_group = bot.create_group("badges", "Badge Commands!")
# _________.__
# / _____/| |__ ______ _ __ ____ _____ ______ ____
# \_____ \ | | \ / _ \ \/ \/ // ___\\__ \ / ___// __ \
# / \| Y ( <_> ) /\ \___ / __ \_\___ \\ ___/
# /_______ /|___| /\____/ \/\_/ \___ >____ /____ >\___ >
# \/ \/ \/ \/ \/ \/
@badge_group.command(
name="showcase",
description="Show off all your badges! Please be mindful of posting very large collections publicly."
)
@option(
name="public",
description="Show to public?",
required=True,
choices=[
discord.OptionChoice(
name="No",
value="no"
),
discord.OptionChoice(
name="Yes",
value="yes"
)
]
)
@option(
name="filter",
description="Show only Locked, Unlocked, or Special badges?",
required=False,
choices=[
discord.OptionChoice(
name="Unlocked",
value="unlocked"
),
discord.OptionChoice(
name="Locked",
value="locked"
),
discord.OptionChoice(
name="Special",
value="special"
)
]
)
@option(
name="sortby",
description="Sort your showcase",
required=False,
choices=[
discord.OptionChoice(
name="Date Ascending",
value="date_ascending"
),
discord.OptionChoice(
name="Date Descending",
value="date_descending"
),
discord.OptionChoice(
name="Unlocked First",
value="locked_first"
),
discord.OptionChoice(
name="Special First",
value="special_first"
),
]
)
@option(
name="color",
description="Which colorscheme would you like?",
required=False,
choices = [
discord.OptionChoice(name=color_choice, value=color_choice.lower())
for color_choice in ["Green", "Orange", "Purple", "Teal"]
]
)
async def showcase(ctx:discord.ApplicationContext, public:str, filter:str, sortby:str, color:str):
public = (public == "yes")
await ctx.defer(ephemeral=not public)
if filter is not None:
if filter == 'unlocked':
title = f"{remove_emoji(ctx.author.display_name)}'s Badge Collection - Unlocked"
user_badges = await db_get_user_unlocked_badges(ctx.author.id)
elif filter == 'locked':
title = f"{remove_emoji(ctx.author.display_name)}'s Badge Collection - Locked"
user_badges = await db_get_user_locked_badges(ctx.author.id)
elif filter == 'special':
title = f"{remove_emoji(ctx.author.display_name)}'s Badge Collection - Special"
user_badges = await db_get_user_special_badges(ctx.author.id)
else:
title = f"{remove_emoji(ctx.author.display_name)}'s Badge Collection"
user_badges = await db_get_user_badges(ctx.author.id, sortby)
if not user_badges:
await ctx.followup.send(embed=discord.Embed(
title="No Badges To Showcase!",
description="You don't appear to either have any badges, or any that match this filter!",
color=discord.Color.red()
)
)
return
# Set up text values for paginated pages
total_badges_cnt = len(await db_get_all_badge_info())
user_badges_cnt = len(user_badges)
collected = f"{user_badges_cnt} TOTAL ON THE USS HOOD"
filename_prefix = f"badge_list_{ctx.author.id}-page-"
if sortby is not None:
if sortby == 'date_ascending':
title += " - Date Ascending"
elif sortby == 'date_descending':
title += " - Date Descending"
elif sortby == 'locked_first':
title += " - Locked First"
elif sortby == 'special_first':
title += " - Title First"
if color:
await db_set_user_badge_page_color_preference(ctx.author.id, "showcase", color)
badge_images = await generate_paginated_badge_images(ctx.author, 'showcase', user_badges, total_badges_cnt, title, collected, filename_prefix)
embed = discord.Embed(
title=f"Badge Collection",
description=f"{ctx.author.mention} has collected {user_badges_cnt} of {total_badges_cnt}!",
color=discord.Color.blurple()
)
# If we're doing a public display, use the images directly
# Otherwise private displays can use the paginator
if not public:
buttons = [
pages.PaginatorButton("prev", label=" ⬅ ", style=discord.ButtonStyle.primary, disabled=bool(user_badges_cnt <= 30), row=1),
pages.PaginatorButton(
"page_indicator", style=discord.ButtonStyle.gray, disabled=True, row=1
),
pages.PaginatorButton("next", label=" ➡ ", style=discord.ButtonStyle.primary, disabled=bool(user_badges_cnt <= 30), row=1),
]
pages_list = [
pages.Page(files=[image], embeds=[embed])
for image in badge_images
]
paginator = pages.Paginator(
pages=pages_list,
show_disabled=True,
show_indicator=True,
use_default_buttons=False,
custom_buttons=buttons,
loop_pages=True
)
await paginator.respond(ctx.interaction, ephemeral=True)
else:
# We can only attach up to 10 files per message, so if it's public send them in chunks
file_chunks = [badge_images[i:i + 10] for i in range(0, len(badge_images), 10)]
for chunk_index, chunk in enumerate(file_chunks):
# Only post the embed on the last chunk
if chunk_index + 1 == len(file_chunks):
await ctx.followup.send(embed=embed, files=chunk)
else:
await ctx.followup.send(files=chunk)
# _________ __
# / _____/ _____/ |_ ______
# \_____ \_/ __ \ __\/ ___/
# / \ ___/| | \___ \
# /_______ /\___ >__| /____ >
# \/ \/ \/
@badge_group.command(
name="sets",
description="Show off sets of your badges! Please be mindful of posting very large sets publicly."
)
@option(
name="public",
description="Show to public?",
required=True,
choices=[
discord.OptionChoice(
name="No",
value="no"
),
discord.OptionChoice(
name="Yes",
value="yes"
)
]
)
@option(
name="category",
description="Which category of set?",
required=True,
choices=[
discord.OptionChoice(
name="Affiliation",
value="affiliation"
),
discord.OptionChoice(
name="Franchise",
value="franchise"
),
discord.OptionChoice(
name="Time Period",
value="time_period"
),
discord.OptionChoice(
name="Type",
value="type"
)
]
)
@option(
name="selection",
description="Which one?",
required=True,
autocomplete=autocomplete_selections
)
@option(
name="color",
description="Which colorscheme would you like?",
required=False,
choices = [
discord.OptionChoice(name=color_choice, value=color_choice.lower())
for color_choice in ["Green", "Orange", "Purple", "Teal"]
]
)
@commands.check(access_check)
async def sets(ctx:discord.ApplicationContext, public:str, category:str, selection:str, color:str):
public = bool(public == "yes")
await ctx.defer(ephemeral=not public)
category_title = category.replace("_", " ").title()
if category == 'affiliation':
user_set_badges = await db_get_badges_user_has_from_affiliation(ctx.author.id, selection)
all_set_badges = await db_get_all_affiliation_badges(selection)
elif category == 'franchise':
user_set_badges = await db_get_badges_user_has_from_franchise(ctx.author.id, selection)
all_set_badges = await db_get_all_franchise_badges(selection)
elif category == 'time_period':
user_set_badges = await db_get_badges_user_has_from_time_period(ctx.author.id, selection)
all_set_badges = await db_get_all_time_period_badges(selection)
elif category == 'type':
user_set_badges = await db_get_badges_user_has_from_type(ctx.author.id, selection)
all_set_badges = await db_get_all_type_badges(selection)
else:
await ctx.followup.send("Select a category", ephemeral=True)
return
if not all_set_badges:
await ctx.followup.send(
embed=discord.Embed(
title=f"Your entry was not in the list of {category_title}s!",
color=discord.Color.red()
), ephemeral=True
)
return
set_badges = []
for badge in all_set_badges:
result = await db_get_badge_locked_status_by_name(ctx.author.id, badge['badge_name'])
locked = result['locked'] if result else False
record = {
'badge_name': badge['badge_name'],
'badge_filename': badge['badge_filename'],
'special': badge['special'],
'locked': locked,
'in_user_collection': badge['badge_name'] in [b['badge_name'] for b in user_set_badges]
}
set_badges.append(record)
user_set_badge_cnt = len([b for b in set_badges if b['in_user_collection']])
user_all_badge_cnt = await db_get_badge_count_for_user(ctx.author.id)
# Set up text values for paginated pages
title = f"{remove_emoji(ctx.author.display_name)}'s Badge Set: {category_title} - {selection}"
collected = f"{user_set_badge_cnt} OF {len(set_badges)}"
filename_prefix = f"badge_set_{ctx.author.id}_{selection.lower().replace(' ', '-').replace('/', '-')}-page-"
if color:
await db_set_user_badge_page_color_preference(ctx.author.id, "sets", color)
badge_images = await generate_paginated_badge_images(ctx.author, 'sets', set_badges, user_all_badge_cnt, title, collected, filename_prefix)
embed = discord.Embed(
title=f"Badge Set: **{category_title}** - **{selection}**",
description=f"{ctx.author.mention} has collected {user_set_badge_cnt} of {len(set_badges)}!",
color=discord.Color.blurple()
)
# If we're doing a public display, use the images directly
# Otherwise private displays can use the paginator
if not public:
buttons = [
pages.PaginatorButton("prev", label=" ⬅ ", style=discord.ButtonStyle.primary, disabled=bool(len(set_badges) <= 30), row=1),
pages.PaginatorButton(
"page_indicator", style=discord.ButtonStyle.gray, disabled=True, row=1
),
pages.PaginatorButton("next", label=" ➡ ", style=discord.ButtonStyle.primary, disabled=bool(len(set_badges) <= 30), row=1),
]
set_pages = [
pages.Page(files=[image], embeds=[embed])
for image in badge_images
]
paginator = pages.Paginator(
pages=set_pages,
show_disabled=True,
show_indicator=True,
use_default_buttons=False,
custom_buttons=buttons,
loop_pages=True
)
await paginator.respond(ctx.interaction, ephemeral=True)
else:
# We can only attach up to 10 files per message, so if it's public send them in chunks
file_chunks = [badge_images[i:i + 10] for i in range(0, len(badge_images), 10)]
for chunk_index, chunk in enumerate(file_chunks):
# Only post the embed on the last chunk
if chunk_index + 1 == len(file_chunks):
await ctx.followup.send(embed=embed, files=chunk, ephemeral=False)
else:
await ctx.followup.send(files=chunk, ephemeral=False)
# _________ .__ __ .__
# \_ ___ \ ____ _____ ______ | | _____/ |_|__| ____ ____
# / \ \/ / _ \ / \\____ \| | _/ __ \ __\ |/ _ \ / \
# \ \___( <_> ) Y Y \ |_> > |_\ ___/| | | ( <_> ) | \
# \______ /\____/|__|_| / __/|____/\___ >__| |__|\____/|___| /
# \/ \/|__| \/ \/
@badge_group.command(
name="completion",
description="Get a report of how close to completion you are on various sets."
)
@option(
name="public",
description="Show to public?",
required=True,
choices=[
discord.OptionChoice(
name="No",
value="no"
),
discord.OptionChoice(
name="Yes",
value="yes"
)
]
)
@option(
name="category",
description="Which category of set?",
required=True,
choices=[
discord.OptionChoice(
name="Affiliation",
value="affiliation"
),
discord.OptionChoice(
name="Franchise",
value="franchise"
),
discord.OptionChoice(
name="Time Period",
value="time_period"
),
discord.OptionChoice(
name="Type",
value="type"
)
]
)
@option(
name="color",
description="Which colorscheme would you like?",
required=False,
choices = [
discord.OptionChoice(name=color_choice, value=color_choice.lower())
for color_choice in ["Green", "Orange", "Purple", "Teal"]
]
)
@commands.check(access_check)
async def completion(ctx:discord.ApplicationContext, public:str, category:str, color:str):
public = bool(public == "yes")
await ctx.defer(ephemeral=not public)
all_badges = os.listdir("./images/badges/")
user_badges = await db_get_user_badges(ctx.author.id)
# Pull data using the queries.
all_rows = []
if category == 'affiliation':
all_rows = await queries_badge_completion.by_affiliation(ctx.author.id)
elif category == 'franchise':
all_rows = await queries_badge_completion.by_franchise(ctx.author.id)
elif category == 'time_period':
all_rows = await queries_badge_completion.by_time_period(ctx.author.id)
elif category == 'type':
all_rows = await queries_badge_completion.by_type(ctx.author.id)
all_rows = await _append_featured_completion_badges(ctx.author.id, all_rows, category)
# Format data for the returned embed
category_title = category.replace('_', ' ').title()
total_badges = len(all_badges)
title = f"{remove_emoji(ctx.author.display_name)}'s Badge Completion - {category_title}"
collected = f"{len(user_badges)} TOTAL ON THE USS HOOD"
filename_prefix = f"badge_set_completion_{ctx.author.id}_affiliations-page-"
if color:
await db_set_user_badge_page_color_preference(ctx.author.id, "sets", color)
completion_images = await generate_paginated_set_completion_images(ctx.author, all_rows, total_badges, title, collected, filename_prefix)
embed = discord.Embed(
title=f"Badge Set Completion - {category_title}",
description=f"{ctx.author.mention}'s Current Set Completion Progress",
color=discord.Color.blurple()
)
# If we're doing a public display, use the images directly
# Otherwise private displays can use the paginator
if not public:
buttons = [
pages.PaginatorButton("prev", label=" ⬅ ", style=discord.ButtonStyle.primary, disabled=bool(len(all_rows) <= 7), row=1),
pages.PaginatorButton(
"page_indicator", style=discord.ButtonStyle.gray, disabled=True, row=1
),
pages.PaginatorButton("next", label=" ➡ ", style=discord.ButtonStyle.primary, disabled=bool(len(all_rows) <= 7), row=1),
]
set_pages = [
pages.Page(files=[image], embeds=[embed])
for image in completion_images
]
paginator = pages.Paginator(
pages=set_pages,
show_disabled=True,
show_indicator=True,
use_default_buttons=False,
custom_buttons=buttons,
loop_pages=True
)
await paginator.respond(ctx.interaction, ephemeral=True)
else:
# We can only attach up to 10 files per message, so if it's public send them in chunks
file_chunks = [completion_images[i:i + 10] for i in range(0, len(completion_images), 10)]
for chunk_index, chunk in enumerate(file_chunks):
# Only post the embed on the last chunk
if chunk_index + 1 == len(file_chunks):
await ctx.followup.send(embed=embed, files=chunk, ephemeral=not public)
else:
await ctx.followup.send(files=chunk, ephemeral=not public)
async def _append_featured_completion_badges(user_id, report, category):
if category == "affiliation":
badges = await db_get_random_badges_from_user_by_affiliations(user_id)
elif category == "franchise":
badges = await db_get_random_badges_from_user_by_franchises(user_id)
elif category == "time_period":
badges = await db_get_random_badges_from_user_by_time_periods(user_id)
elif category == "type":
badges = await db_get_random_badges_from_user_by_types(user_id)
else:
badges = {}
for r in report:
if r['name'] in badges:
r['featured_badge'] = badges.get(r['name'])
return report
# _________
# / _____/ ________________ ______ ______ ___________
# \_____ \_/ ___\_ __ \__ \ \____ \\____ \_/ __ \_ __ \
# / \ \___| | \// __ \| |_> > |_> > ___/| | \/
# /_______ /\___ >__| (____ / __/| __/ \___ >__|
# \/ \/ \/|__| |__| \/
class ScrapButton(discord.ui.Button):
def __init__(self, user_id, badge_to_add, badges_to_scrap):
self.user_id = user_id
self.badge_to_add = badge_to_add
self.badges_to_scrap = badges_to_scrap
super().__init__(
label=" Scrap ",
style=discord.ButtonStyle.primary,
row=2
)
async def callback(self, interaction: discord.Interaction):
# Re-check conditions to ensure this action is still valid
# Ensure user still owns the badges
user_badges = await db_get_user_badges(self.user_id)
user_badge_filenames = [b['badge_filename'] for b in user_badges]
owned_user_badges = [b for b in self.badges_to_scrap if b['badge_filename'] in user_badge_filenames]
# Ensure they haven't performed another scrap within the time period
time_check_fail = True
last_scrap_time = await db_get_scrap_last_timestamp(self.user_id)
if last_scrap_time:
to_zone = tz.tzlocal()
last_scrap_time.replace(tzinfo=to_zone)
current_time = datetime.now()
if last_scrap_time.date() < current_time.date():
time_check_fail = False
else:
time_check_fail = False
if (len(owned_user_badges) != 3) or (time_check_fail):
await interaction.response.edit_message(
embed=discord.Embed(
title="Error",
description=f"There's been a problem with this scrap request.\n\nEither you no longer possess the badges outlined or another scrap has been performed in the intervening time.",
color=discord.Color.red()
),
view=None,
attachments=[]
)
else:
await interaction.response.edit_message(
embed=discord.Embed(
title="Scrapper initiated!",
description="Your badges are being broken down into their constituent components.\nJust a moment please...",
color=discord.Color.teal()
),
view=None,
attachments=[]
)
# Cancel any existing trades that may be out requesting or offering these badges from this user
trades_to_cancel = await db_get_trades_to_cancel_from_scrapped_badges(self.user_id, self.badges_to_scrap)
await _cancel_invalid_scrapped_trades(trades_to_cancel)
# Do the actual scrappage
await db_perform_badge_scrap(self.user_id, self.badge_to_add, self.badges_to_scrap)
# Housekeeping
# Clear any badges from the users wishlist that the user may now possess
await db_purge_users_wishlist(self.user_id)
# Post message about successful scrap
scrapper_gif = await generate_badge_scrapper_result_gif(self.user_id, self.badge_to_add, self.badges_to_scrap)
scrap_complete_messages = [
"{} reaches into AGIMUS' warm scrap hole and pulls out a shiny new badge!",
"{} uses the Scrap-o-matic! Three old badges become one shiny new badge. That's science, baby!",
"{} has replicator rations to spare, so they've scrapped some old badges for a new one!",
"{} performs some strange gestures in front of the replicator. They hold a new badge above their head!",
"{} adds 3 old crusty badges to the scrapper, and yanks out a new shiny badge!",
"{} is using the scrapper on the clock. Don't tell the captain!",
"{} is donating three old badges to the void, and gets a brand new badge in return!",
"{} suspiciously shoves three badges into the slot and hastily pulls a fresh badge out, hoping you didn't see anything.",
"Scrap complete! {} has recycled three old badges into one new badge!",
"{} has used the badge scrapper! Tonight is the night when 3 become 1 🎶"
]
embed = discord.Embed(
title="Scrap complete!",
description=random.choice(scrap_complete_messages).format(interaction.user.mention),
color=discord.Color.teal()
)
embed.add_field(
name="Scrapped badges: ❌",
value="\n".join(["~~"+b['badge_name']+"~~" for b in self.badges_to_scrap]),
inline=False
)
embed.add_field(
name="New badge: 🆕",
value=f"🌟 **{self.badge_to_add['badge_name']}** [(badge details)]({self.badge_to_add['badge_url']})",
inline=False
)
embed.set_image(url=f"attachment://scrap_{self.user_id}.gif")
await interaction.channel.send(embed=embed, file=scrapper_gif)
class CancelScrapButton(discord.ui.Button):
def __init__(self):
super().__init__(
label=" Cancel ",
style=discord.ButtonStyle.red,
row=2
)
async def callback(self, interaction:discord.Interaction):
await interaction.response.edit_message(
embed=discord.Embed(
title="Scrap cancelled!",
description="You may initiate a new scrap with `/badges scrap` at any time.",
color=discord.Color.teal()
),
view=None,
attachments=[]
)
class ScrapCancelView(discord.ui.View):
def __init__(self, user_id, badge_to_add, badges_to_scrap):
super().__init__()
self.add_item(CancelScrapButton())
self.add_item(ScrapButton(user_id, badge_to_add, badges_to_scrap))
@badge_group.command(
name="scrap",
description="Turn in 3 unlocked badges for 1 new random badge. One scrap allowed every 24 hours."
)
@option(
name="first_badge",
description="First badge to scrap",
required=True,
autocomplete=scrapper_autocomplete
)
@option(
name="second_badge",
description="Second badge to scrap",
required=True,
autocomplete=scrapper_autocomplete
)
@option(
name="third_badge",
description="Third badge to scrap",
required=True,
autocomplete=scrapper_autocomplete
)
@commands.check(access_check)
async def scrap(ctx:discord.ApplicationContext, first_badge:str, second_badge:str, third_badge:str):
"""
This function executes the scrap for the /badge scrap command
:param ctx:
:param first_badge: The name of the first badge to scrap.
:param second_badge: The name of the second badge to scrap.
:param third_badge: The name of the third badge to scrap.
:return:
"""
await ctx.defer(ephemeral=True)
user_id = ctx.interaction.user.id
selected_badges = [first_badge, second_badge, third_badge]
unlocked_user_badges = await db_get_user_unlocked_badges(user_id)
unlocked_user_badge_names = [b['badge_name'] for b in unlocked_user_badges]
selected_user_badges = [b for b in selected_badges if b in unlocked_user_badge_names]
if len(selected_user_badges) != 3:
await ctx.followup.send(embed=discord.Embed(
title="Invalid Selection",
description=f"You must own all of the badges you've selected to scrap and they must be unlocked!",
color=discord.Color.red()
), ephemeral=True)
return
if len(selected_user_badges) > len(set(selected_user_badges)):
await ctx.followup.send(embed=discord.Embed(
title="Invalid Selection",
description=f"All badges selected must be unique!",
color=discord.Color.red()
), ephemeral=True)
return
restricted_badges = [b for b in selected_user_badges if b in [b['badge_name'] for b in await db_get_special_badges()]]
if restricted_badges:
await ctx.followup.send(embed=discord.Embed(
title="Invalid Selection",
description=f"You cannot scrap the following: {','.join(restricted_badges)}!",
color=discord.Color.red()
), ephemeral=True)
return
# If all basics checks pass,
# check that they're within the allowed time window
last_scrap_time = await db_get_scrap_last_timestamp(user_id)
if last_scrap_time:
time_check_fail = True
to_zone = tz.tzlocal()
last_scrap_time.replace(tzinfo=to_zone)
current_time = datetime.now()
current_time.replace(tzinfo=to_zone)
if last_scrap_time.date() < current_time.date():
time_check_fail = False
if time_check_fail:
midnight_tomorrow = current_time.date() + timedelta(days=1)
midnight_tomorrow = datetime.combine(midnight_tomorrow, datetime.min.time())
humanized_time_left = humanize.precisedelta(midnight_tomorrow - current_time, suppress=["days"])
await ctx.followup.send(embed=discord.Embed(
title="Scrapper recharging, please wait.",
description=f"Reset time at Midnight Pacific ({humanized_time_left} left).",
color=discord.Color.red()
), ephemeral=True)
return
# If time check okay, select a new random badge
all_possible_badges = [b['badge_name'] for b in await db_get_all_badge_info()]
special_badge_names = [b['badge_name'] for b in await db_get_special_badges()]
# Don't give them a badge they already have or a special badge
all_user_badge_names = [b['badge_name'] for b in await db_get_user_badges(user_id)]
valid_choices = [b for b in all_possible_badges if b not in all_user_badge_names and b not in special_badge_names]
if len(valid_choices) == 0:
await ctx.respond(embed=discord.Embed(
title="You already have *ALL BADGES!?!*",
description=f"Amazing! You've collected every unique badge we have, so scrapping is unnecessary. Get it player.",
color=discord.Color.random()
), ephemeral=True)
return
badge_choice = random.choice(valid_choices)
badge_to_add = await db_get_badge_info_by_name(badge_choice)
badges_to_scrap = [await db_get_badge_info_by_name(b) for b in selected_user_badges]
# Check for wishlist badges
wishlist_matches = [await db_get_wishlist_badge_matches(b['badge_filename']) for b in badges_to_scrap]
wishlist_matches_groups = [m for m in wishlist_matches if m]
# Generate Animated Scrapper Gif
scrapper_confirm_gif = await generate_badge_scrapper_confirmation_gif(user_id, badges_to_scrap)
# Create the first page
scrap_embed_description = "** This cannot be undone.\n**" + str("\n".join(selected_user_badges))
if len(wishlist_matches_groups):
scrap_embed_description += "\n\n**NOTE:** One or more of the badges you're looking to scrap are on other user's wishlists! Check the following pages for more details, you may want to reach out to see if they'd like to trade!"
scrap_embed = discord.Embed(
title="Are you sure you want to scrap these badges?",
description=scrap_embed_description,
color=discord.Color.teal()
)
scrap_embed.set_image(url=f"attachment://scrap_{user_id}-confirm.gif")
scrap_page = pages.Page(
embeds=[scrap_embed],
files=[scrapper_confirm_gif]
)
# Iterate over any wishlist matches if present and add them to paginator pages
scrapper_pages = [scrap_page]
for wishlist_matches in wishlist_matches_groups:
if len(wishlist_matches):
badge_filename = wishlist_matches[0]['badge_filename']
badge_info = await db_get_badge_info_by_filename(badge_filename)
users = [await bot.current_guild.fetch_member(m['user_discord_id']) for m in wishlist_matches]
wishlist_match_embed = discord.Embed(
title=f"The following users want {badge_info['badge_name']}",
description="\n".join([u.mention for u in users]),
color=discord.Color.teal()
)
scrapper_pages.append(wishlist_match_embed)
# Send scrapper paginator
view = ScrapCancelView(user_id, badge_to_add, badges_to_scrap)
paginator = pages.Paginator(
pages=scrapper_pages,
custom_buttons=[
pages.PaginatorButton("prev", label=" ⬅ ", style=discord.ButtonStyle.primary, row=1),
pages.PaginatorButton(
"page_indicator", style=discord.ButtonStyle.gray, disabled=True, row=1
),
pages.PaginatorButton("next", label=" ➡ ", style=discord.ButtonStyle.primary, row=1),
],
use_default_buttons=False,
custom_view=view
)
await paginator.respond(ctx.interaction, ephemeral=True)
async def _cancel_invalid_scrapped_trades(trades_to_cancel):
# Iterate through to cancel
for trade in trades_to_cancel:
await db_cancel_trade(trade)
requestee = await bot.current_guild.fetch_member(trade['requestee_id'])
requestor = await bot.current_guild.fetch_member(trade['requestor_id'])
offered_badge_names, requested_badge_names = await get_offered_and_requested_badge_names(trade)
# Give notice to Requestee
user = await get_user(requestee.id)
if user["receive_notifications"]:
try:
requestee_embed = discord.Embed(
title="Trade Canceled",
description=f"Just a heads up! Your pending trade initiated by {requestor.mention} was canceled because one or more of the badges involved were scrapped!",
color=discord.Color.purple()
)
requestee_embed.add_field(
name=f"Offered by {requestor.display_name}",
value=offered_badge_names
)
requestee_embed.add_field(
name=f"Requested from {requestee.display_name}",
value=requested_badge_names
)
requestee_embed.set_footer(
text="Note: You can use /settings to enable or disable these messages."
)
await requestee.send(embed=requestee_embed)
except discord.Forbidden as e:
logger.info(f"Unable to send trade cancelation message to {requestee.display_name}, they have their DMs closed.")
pass
# Give notice to Requestor
user = await get_user(requestor.id)
if user["receive_notifications"]:
try:
requestor_embed = discord.Embed(
title="Trade Canceled",
description=f"Just a heads up! Your pending trade requested from {requestee.mention} was canceled because one or more of the badges involved were scrapped!",
color=discord.Color.purple()
)
requestor_embed.add_field(
name=f"Offered by {requestor.display_name}",
value=offered_badge_names
)
requestor_embed.add_field(
name=f"Requested from {requestee.display_name}",
value=requested_badge_names
)
requestor_embed.set_footer(
text="Note: You can use /settings to enable or disable these messages."
)
await requestor.send(embed=requestor_embed)
except discord.Forbidden as e:
logger.info(f"Unable to send trade cancelation message to {requestor.display_name}, they have their DMs closed.")
pass
# .____ __
# | | ____ ____ | | ____ ________
# | | / _ \ / _ \| |/ / | \____ \
# | |__( <_> | <_> ) <| | / |_> >
# |_______ \____/ \____/|__|_ \____/| __/
# \/ \/ |__|
@badge_group.command(
name="lookup",
description="Look up information about a specific badge"
)
@option(
name="public",
description="Show to public?",
required=True,
choices=[
discord.OptionChoice(
name="No",
value="no"
),
discord.OptionChoice(
name="Yes",
value="yes"
)
]
)
@option(
name="name",
description="Which badge do you want to look up?",
required=True,
autocomplete=all_badges_autocomplete
)
async def badge_lookup(ctx:discord.ApplicationContext, public:str, name:str):
"""
This function executes the lookup for the /badge lookup command
:param ctx:
:param name: The name of the badge to be looked up.
:return:
"""
public = bool(public == "yes")
await ctx.defer(ephemeral=not public)
logger.info(f"{Fore.CYAN}Firing /badge lookup command for '{name}'!{Fore.RESET}")
if name not in [b['badge_name'] for b in await db_get_all_badge_info()]:
await ctx.followup.send(
embed=discord.Embed(
title="Could Not Find This Badge",
description=f"**{name}** does not appear to exist!",
color=discord.Color.red()
), ephemeral=True
)
return
badge = await db_get_badge_info_by_name(name)
badge_count = await db_get_badge_count_by_filename(badge['badge_filename'])
affiliations = [
a['affiliation_name']
for a in await db_get_badge_affiliations_by_badge_name(name)
]
types = [
t['type_name']
for t in await db_get_badge_types_by_badge_name(name)
]
description = f"Quadrant: **{badge['quadrant']}**\n"
description += f"Time Period: **{badge['time_period']}**\n"
if affiliations:
description += f"Affiliations: **{', '.join(affiliations)}**\n"
if types:
description += f"Types: **{', '.join(types)}**\n"
description += f"Franchise: **{badge['franchise']}**\n"
description += f"Reference: **{badge['reference']}**\n\n"
description += f"Total number collected on The USS Hood: **{badge_count}**\n\n"
description += f"{badge['badge_url']}"
embed = discord.Embed(
title=f"{badge['badge_name']}",
description=description,
color=discord.Color.random() # jp00p made me do it
)
discord_image = discord.File(fp=f"./images/badges/{badge['badge_filename']}", filename=badge['badge_filename'].replace(',','_'))
embed.set_image(url=f"attachment://{badge['badge_filename'].replace(',','_')}")
if not public:
user_discord_id = ctx.author.id
user_badges = await db_get_user_badges(user_discord_id)
if name in [b['badge_name'] for b in user_badges]:
locked_status = await db_get_badge_locked_status_by_name(user_discord_id, name)
if locked_status['locked']:
badge_status = "LOCKED"
else:
badge_status = "UNLOCKED"
else:
wishlist_badges = await db_get_user_wishlist_badges(user_discord_id)
if name in [b['badge_name'] for b in wishlist_badges]:
badge_status = "WISHLISTED"
else:
badge_status = "NOT OWNED"
embed.set_footer(text=f"\n\nBadge Status for {ctx.author.display_name}: {badge_status}")
await ctx.followup.send(embed=embed, file=discord_image, ephemeral=not public)
# _________ __ __ .__ __ .__
# / _____// |______ _/ |_|__| _______/ |_|__| ____ ______
# \_____ \\ __\__ \\ __\ |/ ___/\ __\ |/ ___\ / ___/
# / \| | / __ \| | | |\___ \ | | | \ \___ \___ \
# /_______ /|__| (____ /__| |__/____ > |__| |__|\___ >____ >
# \/ \/ \/ \/ \/
@badge_group.command(
name="statistics",
description="See the server-wide badge statistics"
)
async def badge_statistics(ctx:discord.ApplicationContext):
"""
slash command to get common badge stats
"""
emoji_numbers = ["0️⃣", "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣"]
results = {}
results = await run_badge_stats_queries()
total_badges = "".join(emoji_numbers[int(n)] for n in list(str(results['total_badges'][0]['count'])))
badges_today = "".join(emoji_numbers[int(n)] for n in list(str(results['badges_today'][0]['count'])))
top_collectors = [res for res in results["top_collectors"]]
top_collected = [res for res in results["most_collected"]]
top_wishlisted = [res for res in results["most_wishlisted"]]
top_locked = [res for res in results["most_locked"]]
embed = discord.Embed(color=discord.Color.random(), description="", title="")
embed.add_field(name=f"{get_emoji('combadge')} Total badges collected\non the USS Hood", value=f"{total_badges}\n⠀", inline=True)
embed.add_field(name="⠀", value="⠀", inline=True)
embed.add_field(name=f"{get_emoji('combadge')} Badges collected in\nthe last 24 hours", value=f"{badges_today}\n⠀", inline=True)
embed.add_field(name=f"{get_emoji('combadge')} Top 5 most collected", value=str("\n".join(f"{t['badge_name']} ({t['count']})" for t in top_collected)), inline=True)
embed.add_field(name="⠀", value="⠀", inline=True)
embed.add_field(name=f"{get_emoji('combadge')} Top 5 badge collectors", value=str("\n".join(f"{t['name']} ({t['count']})" for t in top_collectors)), inline=True)
embed.add_field(name=f"{get_emoji('combadge')} Top 5 most wishlisted", value=str("\n".join(f"{t['badge_name']} ({t['count']})" for t in top_wishlisted)), inline=True)
embed.add_field(name="⠀", value="⠀", inline=True)
embed.add_field(name=f"{get_emoji('combadge')} Top 5 most locked", value=str("\n".join(f"{t['badge_name']} ({t['count']})" for t in top_locked)), inline=True)
await ctx.respond(embed=embed, ephemeral=False)
# ________.__ _____ __
# / _____/|__|/ ____\/ |_
# / \ ___| \ __\\ __\
# \ \_\ \ || | | |