forked from DropTracker-io/droptracker-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommands.py
More file actions
executable file
·1331 lines (1231 loc) · 63.8 KB
/
Copy pathcommands.py
File metadata and controls
executable file
·1331 lines (1231 loc) · 63.8 KB
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 io import IOBase
import json
import os
import random
import re
from secrets import token_hex
from data.submissions import try_create_player
from db.clan_sync import insert_xf_group
from interactions import AutocompleteContext, BaseContext, GuildText, Permissions, SlashCommand, UnfurledMediaItem, PartialEmoji, ActionRow, Button, ButtonStyle, SlashCommandOption, check, is_owner, Extension, slash_command, slash_option, SlashContext, Embed, OptionType, GuildChannel, SlashCommandChoice
from interactions.api.events import Startup, Component, ComponentCompletion, ComponentError, ModalCompletion, ModalError, MessageCreate
from interactions.models import ContainerComponent, ThumbnailComponent, SeparatorComponent, UserSelectMenu, SlidingWindowSystem, SectionComponent, SeparatorComponent, TextDisplayComponent, ThumbnailComponent, MediaGalleryComponent, MediaGalleryItem, OverwriteType
import interactions
import time
import subprocess
import platform
from db.models import NpcList, Session, User, Group, Guild, Player, Drop, Webhook, session, UserConfiguration, GroupConfiguration
from pb.leaderboards import create_pb_embeds, get_group_pbs
from services import message_handler
from services.components import help_components
from utils.format import format_time_since_update, format_number, get_command_id, get_npc_image_url, replace_placeholders
from utils.wiseoldman import check_user_by_id, check_user_by_username, check_group_by_id, fetch_group_members
from utils.redis import RedisClient
from db.ops import DatabaseOperations, associate_player_ids
from lootboard.generator import generate_server_board, generate_timeframe_board
from lootboard.player_board import generate_player_board
from datetime import datetime, timedelta
from utils.github import GithubPagesUpdater
import asyncio
from utils.sheets import sheet_manager
#from utils.zohomail import send_email
#from xf.xenforo import XenForoAPI
from sqlalchemy import text
#xf_api = XenForoAPI()
sheets = sheet_manager.SheetManager()
redis_client = RedisClient()
db = DatabaseOperations()
# Commands for the general user to interact with the bot
class UserCommands(Extension):
def __init__(self, bot: interactions.Client):
self.bot = bot
self.message_handler = bot.get_ext("services.message_handler")
@slash_command(name="help",
description="View helpful commands/links for the DropTracker")
async def help(self, ctx):
user = session.query(User).filter_by(discord_id=ctx.user.id).first()
if not user:
await try_create_user(ctx=ctx)
user = session.query(User).filter(User.discord_id == ctx.author.id).first()
# help_embed = Embed(title="", description="", color=0x0ff000)
# help_embed.set_author(name="Help Menu",
# url="https://www.droptracker.io/docs",
# icon_url="https://www.droptracker.io/img/droptracker-small.gif")
# help_embed.set_thumbnail(url="https://www.droptracker.io/img/droptracker-small.gif")
# help_embed.add_field(name="Need more help?",
# value=f"View our <#1317873428199637022> to find answers to common questions from our community, or reach out for <#1210765301042380820>")
# help_embed.add_field(name="User Commands:",
# value="" +
# f"- </accounts:{await get_command_id(self.bot, 'accounts')}> - View which RuneScape accounts are associated with your Discord account.\n" +
# f"- </claim-rsn:{await get_command_id(self.bot, 'claim-rsn')}> - Claim a RuneScape character as one that belongs to you.\n")
# help_embed.add_field(name="Group Leader Commands:",
# value="<:info:1263916332685201501> - `Note`: Creating groups **requires** a WiseOldMan group ID! *You can make a group without being in a clan*. [Visit the WOM website to create one](https://wiseoldman.net/groups/create).\n" +
# f"- </create-group:{await get_command_id(self.bot, 'create-group')}> - Create a new group in the DropTracker database to track your clan's drops.\n" +
# f"- </members:{await get_command_id(self.bot, 'members')}> - View a listing of the top members of your group in real-time.\n" +
# f"<:info:1263916332685201501> - All 'Group Leader Commands' require **Administrator** privileges in the Discord server you use them inside of.", inline=False)
# help_embed.add_field(name="Helpful Links",
# value="[Docs](https://www.droptracker.io/docs) | "+
# "[Join our Discord](https://www.droptracker.io/discord) | " +
# "[GitHub](https://www.github.io/joelhalen/droptracker-py) | " +
# "[Patreon](https://www.patreon.com/droptracker)", inline=False)
# int_latency_ms = int(ctx.bot.latency * 1000)
# ext_latency_ms = await get_external_latency()
# help_embed.add_field(name="Latency",
# value=f"Discord API: `{int_latency_ms} ms`\n" +
# f"External: `{ext_latency_ms} ms`", inline=False)
return await ctx.send(components=help_components, ephemeral=True)
@slash_command(name="global-board",
description="View the current global loot leaderboard")
async def global_lootboard_cmd(self, ctx: SlashContext):
embed = await db.get_group_embed(embed_type="lb", group_id=1)
return await ctx.send(f"Here you are!", embeds=embed, ephemeral=True)
pass
@slash_command(name="pingme",
description="Toggle whether or not you want to be pinged when your submissions are sent to Discord")
@slash_option(name="type",
description="Select whether you want to toggle global, or clan-specific pings.",
required=True,
opt_type=OptionType.STRING,
autocomplete=True)
async def pingme_cmd(self, ctx: SlashContext, type: str):
user = session.query(User).filter_by(discord_id=str(ctx.user.id)).first()
if not user:
await try_create_user(ctx=ctx)
user = session.query(User).filter(User.discord_id == ctx.author.id).first()
if type == "global":
user.global_ping = not user.global_ping
session.commit()
if user.global_ping:
embed = Embed(title="Success!",
description=f"You will now be pinged when your submissions are sent to Discord.")
await ctx.send(embed=embed, ephemeral=True)
else:
embed = Embed(title="Success!",
description=f"You will **no longer** be pinged when your submissions are sent to Discord.")
await ctx.send(embed=embed, ephemeral=True)
elif type == "group":
user.group_ping = not user.group_ping
session.commit()
if user.group_ping:
embed = Embed(title="Success!",
description=f"You will now be pinged when your submissions are sent to Discord.")
await ctx.send(embed=embed, ephemeral=True)
else:
embed = Embed(title="Success!",
description=f"You will **no longer** be pinged when your submissions are sent to Discord.")
await ctx.send(embed=embed, ephemeral=True)
elif type == "everywhere":
user.never_ping = not user.never_ping
session.commit()
if user.never_ping:
embed = Embed(title="Success!",
description=f"You will **no longer** be pinged `anywhere` when your submissions are sent to Discord.")
await ctx.send(embed=embed, ephemeral=True)
else:
embed = Embed(title="Success!",
description=f"You **will now be pinged** `anywhere` when your submissions are sent to Discord.")
await ctx.send(embed=embed, ephemeral=True)
@pingme_cmd.autocomplete("type")
async def pingme_autocomplete_type(self, ctx: AutocompleteContext):
string_in = ctx.input_text
await ctx.send(
choices=[
{
"name": f"Globally",
"value": "global"
},
{
"name": f"In my group",
"value": "group"
},
{
"name": f"Everywhere",
"value": "everywhere"
}
]
)
@slash_command(name="hideme",
description="Toggle whether or not you will appear anywhere in the global discord server / side panel / etc.")
@slash_option(name="account",
description="Select which of your accounts you want to hide from our global listings (all for all).",
required=True,
opt_type=OptionType.STRING,
autocomplete=True)
async def hideme_cmd(self, ctx: SlashContext, account: str):
user = session.query(User).filter_by(discord_id=str(ctx.user.id)).first()
if not user:
await try_create_user(ctx=ctx)
user = session.query(User).filter(User.discord_id == ctx.author.id).first()
if account == "all":
user.hidden = not user.hidden
session.commit()
if user.hidden:
embed = Embed(title="Success!",
description=f"All of your accounts will **no longer** be visible in our global listings.")
return await ctx.send(embed=embed, ephemeral=True)
else:
embed = Embed(title="Success!",
description=f"All of your accounts will now **be visible** in our global listings.")
return await ctx.send(embed=embed, ephemeral=True)
else:
player = session.query(Player).filter_by(player_name=account).first()
if not player:
return await ctx.send(f"You don't have any accounts by that name.", ephemeral=True)
player.hidden = not player.hidden
session.commit()
if player.hidden:
embed = Embed(title="Success!",
description=f"Your account, `{player.player_name}` will **no longer** be visible in our global listings.")
return await ctx.send(embed=embed, ephemeral=True)
else:
embed = Embed(title="Success!",
description=f"Your account, `{player.player_name}` will now **be visible** in our global listings.")
return await ctx.send(embed=embed, ephemeral=True)
@hideme_cmd.autocomplete("account")
async def hideme_autocomplete_account(self, ctx: AutocompleteContext):
string_in = ctx.input_text
user = session.query(User).filter_by(discord_id=str(ctx.user.id)).first()
if not user:
# User not found in database
return await ctx.send(
choices=[
{
"name": "All accounts",
"value": "all"
}
]
)
# Query for the user's accounts
accounts = session.query(Player).filter_by(user_id=user.user_id).all()
# Always include "All accounts" option
choices = [
{
"name": "All accounts",
"value": "all"
}
]
# Add player accounts if they exist
if accounts:
choices.extend([
{
"name": account.player_name,
"value": account.player_name
}
for account in accounts
])
return await ctx.send(choices=choices)
@slash_command(name="group-board",
description="View the current group lootboard")
@slash_option(name="start_time",
description="Select the start time you want to view the lootboard for.",
required=False,
opt_type=OptionType.STRING,
autocomplete=True)
@slash_option(name="end_time",
description="Select the end time you want to view the lootboard for.",
required=False,
opt_type=OptionType.STRING,
autocomplete=True)
@slash_option(name="npc",
description="Select the NPC you want to generate a board for exclusively.",
required=False,
opt_type=OptionType.INTEGER,
autocomplete=True)
async def group_lootboard_cmd(self, ctx: SlashContext, start_time: str = None, end_time: str = None, npc: int = None):
message_cont = ""
# Parse start_time
if start_time is None or start_time == "now":
start_datetime = datetime.now() - timedelta(days=7) # Default to 7 days ago
elif start_time == "today":
start_datetime = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
elif start_time == "yesterday":
start_datetime = (datetime.now() - timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
elif start_time == "week":
start_datetime = (datetime.now() - timedelta(days=7)).replace(hour=0, minute=0, second=0, microsecond=0)
elif start_time == "month":
start_datetime = datetime.now().replace(day=1, hour=0, minute=0, second=0, microsecond=0)
elif start_time == "year":
start_datetime = datetime.now().replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0)
else:
try:
# Try to parse custom date format (YYYY-MM-DD)
start_datetime = datetime.strptime(start_time, "%Y-%m-%d")
except ValueError:
start_datetime = datetime.now() - timedelta(days=7)
message_cont += "Invalid start time format. Using default (7 days ago).\n"
# Parse end_time
if end_time is None or end_time == "now":
end_datetime = datetime.now()
elif end_time == "today":
end_datetime = datetime.now().replace(hour=23, minute=59, second=59)
elif end_time == "yesterday":
end_datetime = (datetime.now() - timedelta(days=1)).replace(hour=23, minute=59, second=59)
elif end_time == "week":
# End of the current week (Sunday)
today = datetime.now()
days_until_sunday = 6 - today.weekday() # 6 is Sunday in Python's weekday() (0-6, Monday is 0)
end_datetime = (today + timedelta(days=days_until_sunday)).replace(hour=23, minute=59, second=59)
elif end_time == "month":
# End of the current month
today = datetime.now()
next_month = today.replace(day=28) + timedelta(days=4) # This will never fail
end_datetime = next_month.replace(day=1, hour=0, minute=0, second=0) - timedelta(seconds=1)
else:
try:
# Try to parse custom date format (YYYY-MM-DD)
end_datetime = datetime.strptime(end_time, "%Y-%m-%d").replace(hour=23, minute=59, second=59)
except ValueError:
end_datetime = datetime.now()
message_cont += "Invalid end time format. Using current time.\n"
# Get group information
user = session.query(User).filter_by(discord_id=str(ctx.user.id)).first()
if not user:
return await ctx.send(f"You have not yet registered an account in our database! Try registering first:\n" +
f"</claim-rsn:{await get_command_id(self.bot, 'claim-rsn')}>")
group = None
if ctx.guild:
guild_id = ctx.guild_id
if str(guild_id) == "1172737525069135962":
group_id = 2
else:
group = session.query(Group).filter_by(guild_id=guild_id).first()
if not group:
group = session.query(Group).filter_by(group_id=2).first()
group_id = group.group_id
group_name = group.group_name
# Show loading message
await ctx.defer()
# Get NPC name if specified
npc_name = None
if npc:
npc_obj = session.query(NpcList).filter(NpcList.npc_id == npc).first()
if npc_obj:
npc_name = npc_obj.npc_name
# Generate the lootboard
board = await generate_timeframe_board(
self.bot,
group_id=group_id,
start_time=start_datetime,
end_time=end_datetime,
npc_id=npc
)
print("Board generation called for", group_id, "and npc id", npc)
if board:
lootboard = interactions.File(board)
embed_template = await db.get_group_embed(embed_type="lb", group_id=group_id)
if group_id != 2:
player_wom_ids = await fetch_group_members(group.wom_id)
player_ids = await associate_player_ids(player_wom_ids)
total_tracked = len(player_ids)
else:
total_tracked = session.query(Player.wom_id).count()
next_update = datetime.now() + timedelta(minutes=10)
future_timestamp = int(time.mktime(next_update.timetuple()))
value_dict = {
"{next_refresh}": f"<t:{future_timestamp}:R>",
"{tracked_members}": total_tracked
}
embed = replace_placeholders(embed_template, value_dict)
true_embed = Embed(title=embed.title, description=embed.description)
for field in embed.fields:
if field.name != "Refreshes" and not str(field.value).startswith("<t:"):
true_embed.add_field(name=field.name, value=field.value,inline=field.inline)
await ctx.send(embed=true_embed, files=lootboard)
else:
await ctx.send(f"An error occurred while generating the group lootboard. Please try again later.")
@group_lootboard_cmd.autocomplete("start_time")
async def group_lootboard_autocomplete_start_time(self, ctx: AutocompleteContext):
# Get current date for custom options
now = datetime.now()
yesterday = now - timedelta(days=1)
last_week = now - timedelta(days=7)
last_month = now - timedelta(days=30)
# Create standard choices
choices = [
{
"name": "Today (midnight)",
"value": "today"
},
{
"name": "Yesterday (midnight)",
"value": "yesterday"
},
{
"name": "Last 7 days",
"value": "week"
},
{
"name": "This month (from 1st)",
"value": "month"
},
{
"name": "This year (from Jan 1st)",
"value": "year"
},
{
"name": f"Custom: {yesterday.strftime('%Y-%m-%d')}",
"value": yesterday.strftime("%Y-%m-%d")
},
{
"name": f"Custom: {last_week.strftime('%Y-%m-%d')}",
"value": last_week.strftime("%Y-%m-%d")
},
{
"name": f"Custom: {last_month.strftime('%Y-%m-%d')}",
"value": last_month.strftime("%Y-%m-%d")
}
]
# Filter choices based on user input
if ctx.input_text:
filtered_choices = [
choice for choice in choices
if ctx.input_text.lower() in choice["name"].lower() or ctx.input_text.lower() in choice["value"].lower()
]
# Add custom date if it looks like a date format
if re.match(r"\d{4}-\d{2}-\d{2}", ctx.input_text) or re.match(r"\d{2}-\d{2}-\d{4}", ctx.input_text):
filtered_choices.append({
"name": f"Custom date: {ctx.input_text}",
"value": ctx.input_text
})
await ctx.send(choices=filtered_choices[:25]) # Discord limits to 25 choices
else:
await ctx.send(choices=choices[:25])
@group_lootboard_cmd.autocomplete("end_time")
async def group_lootboard_autocomplete_end_time(self, ctx: AutocompleteContext):
# Get current date for custom options
now = datetime.now()
yesterday = now - timedelta(days=1)
# Create standard choices
choices = [
{
"name": "Now (current time)",
"value": "now"
},
{
"name": "Today (end of day)",
"value": "today"
},
{
"name": "Yesterday (end of day)",
"value": "yesterday"
},
{
"name": "End of this week",
"value": "week"
},
{
"name": "End of this month",
"value": "month"
},
{
"name": f"Custom: {now.strftime('%Y-%m-%d')}",
"value": now.strftime("%Y-%m-%d")
},
{
"name": f"Custom: {yesterday.strftime('%Y-%m-%d')}",
"value": yesterday.strftime("%Y-%m-%d")
}
]
# Filter choices based on user input
if ctx.input_text:
filtered_choices = [
choice for choice in choices
if ctx.input_text.lower() in choice["name"].lower() or ctx.input_text.lower() in choice["value"].lower()
]
# Add custom date if it looks like a date format
if re.match(r"\d{4}-\d{2}-\d{2}", ctx.input_text) or re.match(r"\d{2}-\d{2}-\d{4}", ctx.input_text):
filtered_choices.append({
"name": f"Custom date: {ctx.input_text}",
"value": ctx.input_text
})
await ctx.send(choices=filtered_choices[:25]) # Discord limits to 25 choices
else:
await ctx.send(choices=choices[:25])
@group_lootboard_cmd.autocomplete("npc")
async def group_lootboard_autocomplete_npc(self, ctx: AutocompleteContext):
# List of popular NPCs with their IDs
popular_npcs = [
(8615, "Alchemical Hydra"),
(13668, "Araxxor"),
(11175, "Araxyte"),
(11992, "Artio"),
(13729, "Barrows"),
(8195, "Bryophyta"),
(6503, "Callisto"),
(11993, "Calvar'ion"),
(5862, "Cerberus"),
(13696, "Chambers of Xeric"),
(6619, "Chaos Fanatic"),
(13948, "Clue Scroll (Beginner)"),
(13947, "Clue Scroll (Easy)"),
(13944, "Clue Scroll (Elite)"),
(13945, "Clue Scroll (Hard)"),
(13955, "Clue Scroll (Master)"),
(13946, "Clue Scroll (Medium)"),
(13979, "Coffin (Hallowed Sepulchre)"),
(2205, "Commander Zilyana"),
(319, "Corporeal Beast"),
(6618, "Crazy archaeologist"),
(2267, "Dagannoth Rex"),
(2265, "Dagannoth Supreme"),
(7144, "Demonic gorilla"),
(13680, "Dreadborn Araxyte"),
(12191, "Duke Sucellus"),
(7851, "Dusk"),
(13709, "Elven Crystal Chest"),
(13741, "Fortis Colosseum"),
(2215, "General Graardor"),
(13701, "Herbiboar"),
(8583, "Hespori"),
(8609, "Hydra"),
(3129, "K'ril Tsutsaroth"),
(963, "Kalphite Queen"),
(239, "King Black Dragon"),
(13684, "Kingdom of Miscellania"),
(3162, "Kree'arra"),
(13718, "Larran's big chest"),
(11278, "Nex"),
(12077, "Phantom Muspah"),
(9416, "Phosani's Nightmare"),
(303031, "Revenants"),
(13954, "Reward pool (Tempoross)"),
(7286, "Skotizo"),
(7541, "Tekton"),
(7543, "Tekton (enraged)"),
(13703, "The Gauntlet"),
(13949, "The Hueycoatl"),
(12214, "The Leviathan"),
(9425, "The Nightmare"),
(12204, "The Whisperer"),
(13699, "Theatre of Blood"),
(499, "Thermonuclear smoke devil"),
(13695, "Tombs of Amascut"),
(1676, "Torag the Corrupted"),
(13599, "Tormented Demon"),
(13711, "Unsired"),
(12223, "Vardorvis"),
(6504, "Venenatis"),
(6611, "Vet'ion"),
(8060, "Vorkath"),
(9049, "Zalcano"),
(2042, "Zulrah")
]
# Filter NPCs based on input text
if ctx.input_text:
filtered_npcs = []
for npc_id, npc_name in popular_npcs:
if ctx.input_text.lower() in npc_name.lower():
filtered_npcs.append((npc_id, npc_name))
# Limit to 25 choices for Discord's autocomplete
if len(filtered_npcs) > 25:
filtered_npcs = filtered_npcs[:25]
else:
# Use all popular NPCs if no input, limited to 25
filtered_npcs = popular_npcs[:25]
# Format choices correctly for autocomplete
choices = []
for npc_id, npc_name in filtered_npcs:
choices.append({
"name": npc_name,
"value": npc_id
})
await ctx.send(choices=choices)
@slash_command(name="my-board",
description="View your personal lootboard")
@slash_option(name="start_time",
description="Select the start time you want to view the lootboard for.",
required=False,
opt_type=OptionType.STRING,
autocomplete=True)
@slash_option(name="end_time",
description="Select the end time you want to view the lootboard for.",
required=False,
opt_type=OptionType.STRING,
autocomplete=True)
async def my_board_cmd(self, ctx: SlashContext, start_time: str = None, end_time: str = None):
user = ctx.author
user_id = ctx.author.id
user = session.query(User).filter_by(discord_id=str(user_id)).first()
message_cont = ""
# Parse start_time
if start_time is None or start_time == "now":
start_datetime = datetime.now() - timedelta(days=7) # Default to 7 days ago
elif start_time == "today":
start_datetime = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
elif start_time == "yesterday":
start_datetime = (datetime.now() - timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
elif start_time == "week":
start_datetime = (datetime.now() - timedelta(days=7)).replace(hour=0, minute=0, second=0, microsecond=0)
elif start_time == "month":
start_datetime = datetime.now().replace(day=1, hour=0, minute=0, second=0, microsecond=0)
elif start_time == "year":
start_datetime = datetime.now().replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0)
else:
try:
# Try to parse custom date format (YYYY-MM-DD)
start_datetime = datetime.strptime(start_time, "%Y-%m-%d")
except ValueError:
start_datetime = datetime.now() - timedelta(days=7)
message_cont += "Invalid start time format. Using default (7 days ago).\n"
# Parse end_time
if end_time is None or end_time == "now":
end_datetime = datetime.now()
elif end_time == "today":
end_datetime = datetime.now().replace(hour=23, minute=59, second=59)
elif end_time == "yesterday":
end_datetime = (datetime.now() - timedelta(days=1)).replace(hour=23, minute=59, second=59)
elif end_time == "week":
# End of the current week (Sunday)
today = datetime.now()
days_until_sunday = 6 - today.weekday() # 6 is Sunday in Python's weekday() (0-6, Monday is 0)
end_datetime = (today + timedelta(days=days_until_sunday)).replace(hour=23, minute=59, second=59)
elif end_time == "month":
# End of the current month
today = datetime.now()
next_month = today.replace(day=28) + timedelta(days=4) # This will never fail
end_datetime = next_month.replace(day=1, hour=0, minute=0, second=0) - timedelta(seconds=1)
else:
try:
# Try to parse custom date format (YYYY-MM-DD)
end_datetime = datetime.strptime(end_time, "%Y-%m-%d").replace(hour=23, minute=59, second=59)
except ValueError:
end_datetime = datetime.now()
message_cont += "Invalid end time format. Using current time.\n"
if not user:
return await ctx.send(f"You have not yet registered an account in our database! Try registering first:\n" +
f"</claim-rsn:{await get_command_id(self.bot, 'claim-rsn')}>")
print("User found:", user.user_id)
players = session.query(Player).filter_by(user_id=user.user_id).all()
if len(players) > 1:
message_cont += "You have multiple accounts registered in our database. We are using the first account you registered."
player = players[0]
else:
player = players[0]
# Show loading message
await ctx.defer()
player_board = await generate_player_board(self.bot, player.player_id, start_datetime, end_datetime)
if player_board:
lootboard = interactions.File(player_board)
embed = Embed(title="Your Personal Lootboard", description=message_cont if message_cont else None)
embed.set_footer(text="Powered by the DropTracker | https://www.droptracker.io/")
embed.set_thumbnail(url="https://www.droptracker.io/img/droptracker-small.gif")
# Format dates for display
start_str = start_datetime.strftime("%Y-%m-%d %H:%M")
end_str = end_datetime.strftime("%Y-%m-%d %H:%M")
embed.add_field(
name="Viewing a board for:",
value=f"Player: `{player.player_name}`\n" +
f"Timeframe: `{start_str}` to `{end_str}`"
)
await ctx.send(embed=embed, files=lootboard)
else:
await ctx.send(f"An error occurred while generating your lootboard. Please try again later.")
@my_board_cmd.autocomplete("start_time")
async def my_board_autocomplete_start_time(self, ctx: AutocompleteContext):
# Get current date for custom options
now = datetime.now()
yesterday = now - timedelta(days=1)
last_week = now - timedelta(days=7)
last_month = now - timedelta(days=30)
# Create standard choices
choices = [
{
"name": "Today (midnight)",
"value": "today"
},
{
"name": "Yesterday (midnight)",
"value": "yesterday"
},
{
"name": "Last 7 days",
"value": "week"
},
{
"name": "This month (from 1st)",
"value": "month"
},
{
"name": "This year (from Jan 1st)",
"value": "year"
},
{
"name": f"Custom: {yesterday.strftime('%Y-%m-%d')}",
"value": yesterday.strftime("%Y-%m-%d")
},
{
"name": f"Custom: {last_week.strftime('%Y-%m-%d')}",
"value": last_week.strftime("%Y-%m-%d")
},
{
"name": f"Custom: {last_month.strftime('%Y-%m-%d')}",
"value": last_month.strftime("%Y-%m-%d")
}
]
# Filter choices based on user input
if ctx.input_text:
filtered_choices = [
choice for choice in choices
if ctx.input_text.lower() in choice["name"].lower() or ctx.input_text.lower() in choice["value"].lower()
]
# Add custom date if it looks like a date format
if re.match(r"\d{4}-\d{2}-\d{2}", ctx.input_text) or re.match(r"\d{2}-\d{2}-\d{4}", ctx.input_text):
filtered_choices.append({
"name": f"Custom date: {ctx.input_text}",
"value": ctx.input_text
})
await ctx.send(choices=filtered_choices[:25]) # Discord limits to 25 choices
else:
await ctx.send(choices=choices[:25])
@my_board_cmd.autocomplete("end_time")
async def my_board_autocomplete_end_time(self, ctx: AutocompleteContext):
# Get current date for custom options
now = datetime.now()
yesterday = now - timedelta(days=1)
# Create standard choices
choices = [
{
"name": "Now (current time)",
"value": "now"
},
{
"name": "Today (end of day)",
"value": "today"
},
{
"name": "Yesterday (end of day)",
"value": "yesterday"
},
{
"name": "End of this week",
"value": "week"
},
{
"name": "End of this month",
"value": "month"
},
{
"name": f"Custom: {now.strftime('%Y-%m-%d')}",
"value": now.strftime("%Y-%m-%d")
},
{
"name": f"Custom: {yesterday.strftime('%Y-%m-%d')}",
"value": yesterday.strftime("%Y-%m-%d")
}
]
# Filter choices based on user input
if ctx.input_text:
filtered_choices = [
choice for choice in choices
if ctx.input_text.lower() in choice["name"].lower() or ctx.input_text.lower() in choice["value"].lower()
]
# Add custom date if it looks like a date format
if re.match(r"\d{4}-\d{2}-\d{2}", ctx.input_text) or re.match(r"\d{2}-\d{2}-\d{4}", ctx.input_text):
filtered_choices.append({
"name": f"Custom date: {ctx.input_text}",
"value": ctx.input_text
})
await ctx.send(choices=filtered_choices[:25]) # Discord limits to 25 choices
else:
await ctx.send(choices=choices[:25])
@slash_command(name="accounts",
description="View your currently claimed RuneScape character names, if you have any")
async def user_accounts_cmd(self, ctx):
print("User accounts command...")
user = session.query(User).filter_by(discord_id=str(ctx.user.id)).first()
if not user:
await try_create_user(ctx=ctx)
user = session.query(User).filter(User.discord_id == ctx.author.id).first()
accounts = session.query(Player).filter_by(user_id=user.user_id)
account_names = ""
count = 0
if accounts:
for account in accounts:
count += 1
last_updated_unix = format_time_since_update(account.date_updated)
account_names += f"`" + account.player_name.strip() + f"` (id: {account.player_id})\n> Last updated: {last_updated_unix}\n"
account_emb = Embed(title="Your Registered Accounts:",
description=f"{account_names}(total: `{count}`)")
# TODO - replace /claim-rsn with an actual clickable command
account_emb.add_field(name="/claim-rsn",value="To claim another, you can use the </claim-rsn:1269466219841327108> command.", inline=False)
account_emb.set_footer(text="https://www.droptracker.io/")
await ctx.send(embed=account_emb, ephemeral=True)
@slash_command(name="claim-rsn",
description="Claim ownership of your RuneScape account names in the DropTracker database")
@slash_option(name="rsn",
opt_type=OptionType.STRING,
description="Please type the in-game-name of the account you want to claim, **exactly as it appears**!",
required=True)
async def claim_rsn_command(self, ctx, rsn: str):
user = session.query(User).filter_by(discord_id=str(ctx.user.id)).first()
group = None
if not user:
await try_create_user(ctx=ctx)
user = session.query(User).filter(User.discord_id == ctx.author.id).first()
if ctx.guild:
guild_id = ctx.guild.id
group = session.query(Group).filter(Group.guild_id.ilike(guild_id)).first()
if not group:
group = session.query(Group).filter_by(group_id=2).first()
player = session.query(Player).filter(Player.player_name.ilike(rsn)).first()
## User should be made now
if not player:
try:
wom_data = await check_user_by_username(rsn)
except Exception as e:
print("Couldn't get player data. e:", e)
return await ctx.send(f"An error occurred claiming your account.\n" +
"Try again later, or reach out in our Discord server",
ephemeral=True)
if wom_data:
player, player_name, player_id, log_slots = wom_data
try:
print("Creating a player with user ID", user.user_id, "associated with it")
## We need to create the Player with a temporary acc hash for now
if group:
new_player = Player(wom_id=player_id,
player_name=rsn,
user_id=str(user.user_id),
user=user,
log_slots=log_slots,
group=group,
account_hash=None)
else:
new_player = Player(wom_id=player_id,
player_name=rsn,
user_id=str(user.user_id),
log_slots=log_slots,
account_hash=None,
user=user)
session.add(new_player)
session.commit()
except Exception as e:
print(f"Could not create a new player:", e)
session.rollback()
finally:
return await ctx.send(f"Your account ({player_name}), with ID `{player_id}` has " +
"been added to the database & associated with your Discord account.",ephemeral=True)
else:
return await ctx.send(f"Your account was not found in the WiseOldMan database.\n" +
f"You could try to manually update your account on their website by [clicking here](https://www.wiseoldman.net/players/{rsn}), then try again, or wait a bit.")
else:
joined_time = format_time_since_update(player.date_added)
if player.user:
user: User = player.user
if str(user.discord_id) != str(ctx.user.id):
await ctx.send(f"Uh-oh!\n" +
f"It looks like somebody else may have claimed your account {joined_time}!\n" +
f"<@{player.user.discord_id}> (discord id: {player.user.discord_id}) currently owns it in our database.\n" +
"If this is some type of mistake, please reach out in our discord server:\n" +
"https://www.droptracker.io/discord",
ephemeral=True)
else:
await ctx.send(f"It looks like you've already claimed this account ({player.player_name}) {joined_time}\n" +
"\nSomething not seem right?\n" +
"Please reach out in our discord server:\n" +
"https://www.droptracker.io/discord",
ephemeral=True)
else:
player.user = user
session.commit()
embed = Embed(title="Success!",
description=f"Your in-game name has been successfully associated with your Discord account.\n" +
"That's it!")
embed.add_field(name=f"What's next?",value=f"If you'd like, you can [register an account on our website] to stay informed " +
"on updates & to make your voice heard relating to bugs & suggestions.",inline=False)
embed.set_thumbnail(url="https://www.droptracker.io/img/droptracker-small.gif")
embed.set_footer(text="Powered by the DropTracker | https://www.droptracker.io/")
await ctx.send(embed=embed)
@slash_command(
name="force_msg",
description="Force a re-processing of a webhook message",
default_member_permissions=Permissions.ADMINISTRATOR,
)
@slash_option(
name="message_id",
description="The message ID to re-process",
opt_type=OptionType.STRING,
required=True
)
@slash_option(
name="channel_id",
description="The channel ID the message is inside of",
opt_type=OptionType.STRING,
required=True
)
async def force_msg(self, ctx: SlashContext, channel_id: str, message_id: str):
await ctx.send("Force message re-processing initiated.")
#await message_data_logger.log("force_msg", {"message_id": ctx.message.id, "channel_id": ctx.channel.id})
channel = await ctx.bot.fetch_channel(channel_id)
message = await channel.fetch_message(message_id)
if message:
try:
print("Re-processing message...")
if message.embeds:
for embed in message.embeds:
for field in embed.fields:
if field.name == "player":
field.value = "joelhalen"
elif field.name == "acc_hash":
field.value = "-3718503131431628598"
await self.message_handler.on_message_create(self.message_handler, message)
except Exception as e:
print("Error re-processing message:", e)
await ctx.send(f"Error re-processing message: {e}")
else:
await ctx.send("Message not found.")
@slash_command(name="new_webhook",
description="Generate a new webhook, adding it to the database and the GitHub list.",
default_member_permissions=Permissions.ADMINISTRATOR)
async def new_webhook_generator(self, ctx: SlashContext):
if not str(ctx.user.id) == "528746710042804247":
return await ctx.send("You are not authorized to use this command.", ephemeral=True)
await ctx.defer(ephemeral=True)
for i in range(30):
with Session() as session:
main_parent_ids = [1332506635775770624, 1332506742801694751, 1369779266945814569, 1369779329382482005, 1369803376598192128]
hooks_parent_ids = [1332506904840372237, 1332506935886348339, 1369779098246975638, 1369779125035991171]
hooks_2_parent_ids = [1369777536975900773, 1369777572577284167, 1369778911264641034, 1369778925919670432, 1369778911264641034]
hooks_3_parent_ids = [1369780179064590418, 1369780228930670705, 1369780244583547073, 1369780261000183848, 1369780569080332369]
all_parent_ids = main_parent_ids + hooks_parent_ids + hooks_2_parent_ids + hooks_3_parent_ids
try:
parent_id = random.choice(all_parent_ids)
parent_channel = await ctx.bot.fetch_channel(parent_id)
num = 35
channel_name = f"drops-{num}"
while channel_name in [channel.name for channel in parent_channel.channels]:
num += 1
channel_name = f"drops-{num}"
new_channel: GuildText = await parent_channel.create_text_channel(channel_name)
logo_path = '/store/droptracker/disc/static/assets/img/droptracker-small.gif'
avatar = interactions.File(logo_path)
webhook: interactions.Webhook = await new_channel.create_webhook(name=f"DropTracker Webhooks ({num})", avatar=avatar)
webhook_url = webhook.url
db_webhook = Webhook(webhook_id=str(webhook.id), webhook_url=str(webhook_url))
session.add(db_webhook)
session.commit()
except Exception as e:
await ctx.send(f"Couldn't create a new webhook:{e}",ephemeral=True)
pass
print("Created 30 new webhooks.")
async def is_admin(ctx: BaseContext):
perms_value = ctx.author.guild_permissions.value
print("Guild permissions:", perms_value)
if perms_value & 0x00000008: # 0x8 is the bit flag for administrator
return True
return False
@slash_command(name="update_github",
description="Force an immediate refresh of the GitHub webhooks",
default_member_permissions=Permissions.ADMINISTRATOR)
async def update_github_cmd(self, ctx: SlashContext):
GithubUpdater = GithubPagesUpdater()
await ctx.send("Attempting to update the GitHub webhooks...", ephemeral=True)
try:
await GithubUpdater.update_github_pages()