-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathDot 3 Github.py
837 lines (704 loc) · 41.9 KB
/
Dot 3 Github.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
import nextcord
from nextcord.ext import commands, tasks
import json
import time
import os
import asyncio
from datetime import datetime, timedelta, timezone
#from datetime import timedelta
# Load DISCORD_TOKEN etc from .env if it exists.
# Alternatively, these can be put in environment variables.
from dotenv import load_dotenv
load_dotenv()
intents = nextcord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents, default_guild_ids=[int(id) for id in os.environ["GUILDS"].split(",")])
# File paths in the same directory as the script
livequeue_file_path = os.path.join(os.path.dirname(__file__), "Livequeue.json")
cooldowns_file_path = os.path.join(os.path.dirname(__file__), "Cooldowns.json")
pings_file_path = os.path.join(os.path.dirname(__file__), "Pings.json")
active_st_file_path = os.path.join(os.path.dirname(__file__), "ActiveStorytellers.json")
New_ST_Exceptions_path = os.path.join(os.path.dirname(__file__), "NewSTExceptions.json")
# Define global cooldown durations (40 hours in seconds)
BEGINNER_COOLDOWN_DURATION = 144000
PICKUP_COOLDOWN_DURATION = 144000
ANY_COOLDOWN_DURATION = 144000
REMOVECOOLDOWN_COOLDOWN_DURATION = 5184000 # 60 Days
RE_RACK_TIMER_DURATION = 2400 # 40 minutes
# Define cooldown duration for leaving the queue (1 hour in seconds)
LEAVE_COOLDOWN_DURATION = 3600
# Define global merged status, games running status, and timer
MERGED = True
GAMES_RUNNING = False
TIMEOUT_TIMER = 300 # 5 minutes
# Channel IDs
BEGINNER_CHANNEL_ID = int(os.environ['BEGINNER_CHANNEL_ID'])
PICKUP_CHANNEL_ID = int(os.environ['PICKUP_CHANNEL_ID'])
MERGED_CHANNEL_ID = PICKUP_CHANNEL_ID
# Ensure the files exist
for file_path in [livequeue_file_path, cooldowns_file_path, active_st_file_path]:
if not os.path.exists(file_path):
with open(file_path, 'w') as file:
json.dump({}, file)
def load_json(file_path):
try:
with open(file_path, 'r') as file:
return json.load(file)
except (json.JSONDecodeError, FileNotFoundError):
return {}
def save_json(file_path, data):
with open(file_path, 'w') as file:
json.dump(data, file, indent=4)
# Initialize in-memory queue, cooldowns, and active storytellers
queue = load_json(livequeue_file_path)
cooldowns = load_json(cooldowns_file_path)
pings = load_json(pings_file_path)
active_storytellers = load_json(active_st_file_path)
New_ST_Exceptions = load_json(New_ST_Exceptions_path)
def is_active_storyteller(user_id):
# Return false if all active STs are of queue type "Extra"
if all(st["QueueType"] == "Extra" for st in active_storytellers.values()):
return False
return str(user_id) in active_storytellers
def add_active_storyteller(user, queue_type):
if queue_type == "Any":
queue_type = queue[str(user.id)]["QueueType"]
active_storytellers[str(user.id)] = {
"DisplayName": user.display_name,
"Discord_ID": user.id,
"User_Image_URL": str(user.display_avatar.url),
"QueueType": queue_type
}
save_json(active_st_file_path, active_storytellers)
def remove_active_storyteller(user_id):
if str(user_id) in active_storytellers:
del active_storytellers[str(user_id)]
save_json(active_st_file_path, active_storytellers)
def update_queue_positions():
sorted_queue = sorted(queue.values(), key=lambda x: x["Merged_Queue_Position"])
for idx, entry in enumerate(sorted_queue):
entry["Merged_Queue_Position"] = idx + 1
save_json(livequeue_file_path, queue)
async def remove_queue(user_id):
current_time = int(time.time())
if str(user_id) in queue:
if str(user_id) not in cooldowns:
cooldowns[str(user_id)] = {
"DisplayName": queue[str(user_id)]["DisplayName"],
"Discord_ID": user_id,
"User_Image_URL": queue[str(user_id)]["User_Image_URL"],
"Cooldown": 0,
"removeCooldown_Cooldown": 0
}
cooldowns[str(user_id)]["Cooldown"] = current_time + BEGINNER_COOLDOWN_DURATION
del queue[str(user_id)]
update_queue_positions()
save_json(cooldowns_file_path, cooldowns)
save_json(livequeue_file_path, queue)
@bot.event
async def on_ready():
print(f'Bot connected as {bot.user}. This bot is a member of the following guilds:')
for g in bot.guilds:
print(f'* {g.name}')
check_queue.start()
@bot.slash_command(name="join", description="Join the Live Queue")
async def join(
interaction: nextcord.Interaction,
queue_type: str = nextcord.SlashOption(
name="queue_type",
description="Type of queue",
choices={"Beginner": "Beginner", "Pickup": "Pickup", "Any": "Any"},
required=True,
),
notes: str = nextcord.SlashOption(
name="notes",
description="Additional notes",
required=True,
)
):
user = interaction.user
current_time = time.time()
join_threshold = datetime.now(timezone.utc) - timedelta(weeks=2)
if user.joined_at > join_threshold and user.id not in New_ST_Exceptions:
await interaction.response.send_message(f"{user.display_name} you must be on the server for more than 2 weeks to storytell on the server.")
return
# Check if the user is on cooldown
if str(user.id) in cooldowns and cooldowns[str(user.id)]["Cooldown"] > current_time:
await interaction.response.send_message("You are currently on cooldown and cannot join the queue.")
return
# Check if the user is on cooldown
if str(user.id) in queue:
await interaction.response.send_message("You are currently in the queue and cannot re-join the queue.")
return
merged_queue_position = len(queue) + 1
new_entry = {
"DisplayName": user.display_name,
"Discord_ID": user.id,
"User_Image_URL": str(user.display_avatar.url),
"QueueType": queue_type,
"Merged_Queue_Position": merged_queue_position,
"Notes": notes
}
cooldown_entry = {
"DisplayName": user.display_name,
"Discord_ID": user.id,
"User_Image_URL": str(user.display_avatar.url),
"Cooldown": 0,
"removeCooldown_Cooldown": 0
}
queue[str(user.id)] = new_entry
cooldowns[str(user.id)] = cooldown_entry
await interaction.response.send_message(f"{user.display_name} has been added to the queue.")
@bot.slash_command(name="setdmalerts", description="Set your DM alerts preferences.")
async def set_dm_alerts(
interaction: nextcord.Interaction,
next_in_queue: str = nextcord.SlashOption(
name="next_in_queue", description="Notify when you are about to ST", choices={"Yes": "Yes", "No": "No"}, required=True),
second_in_queue: str = nextcord.SlashOption(
name="second_in_queue", description="Notify when second in queue", choices={"Yes": "Yes", "No": "No"}, required=True),
merge_split: str = nextcord.SlashOption(
name="merge_split", description="Notify on merge or split", choices={"Yes": "Yes", "No": "No"}, required=True),
earlier_queue_members_leaving: str = nextcord.SlashOption(
name="earlier_queue_members_leaving", description="Notify if earlier queue members leave", choices={"Yes": "Yes", "No": "No"}, required=True)
):
user = interaction.user
preferences = {
"Next_in_Queue": next_in_queue,
"2nd_in_Queue": second_in_queue,
"Merge_Split": merge_split,
"Earlier_Queue_members_leaving": earlier_queue_members_leaving
}
pings[str(user.id)] = preferences
await interaction.response.send_message(f"Your preferences have been updated", ephemeral=True)
@bot.slash_command(name="list", description="List the current queue(s)")
async def list_queue(interaction: nextcord.Interaction):
sorted_queue = sorted(queue.values(), key=lambda x: x["Merged_Queue_Position"])
channel_to_send = interaction.channel
if not GAMES_RUNNING:
embed = nextcord.Embed(title="Games Currently Paused")
embed.add_field(name="Games are currently paused, please use `/resume` to restart the queue", value="----------", inline=False)
t = '\n'.join(
[f'[{str(entry["QueueType"])[0]}] {entry["DisplayName"]} | {str(entry["Notes"])[:100] if entry["Notes"] else "None"}' for entry in sorted_queue])
embed.add_field(name="Current Queue", value=t, inline=False)
await interaction.response.send_message(embed=embed)
return
if MERGED:
embed = nextcord.Embed(title="Merged Queue List")
t = '\n'.join(
[f'[{str(entry["QueueType"])[0]}] {entry["DisplayName"]} | {str(entry["Notes"])[:100] if entry["Notes"] else "None"}' for entry in sorted_queue])
embed.add_field(name="Current Queue", value=t, inline=False)
await interaction.response.send_message(embed=embed)
else:
beginner_any_queue = [entry for entry in sorted_queue if entry["QueueType"] in ["Beginner", "Any"]]
pickup_any_queue = [entry for entry in sorted_queue if entry["QueueType"] in ["Pickup", "Any"]]
embed = nextcord.Embed(title="Beginner/Any Queue List")
t = '\n'.join(
[f'[{str(entry["QueueType"])[0]}] {entry["DisplayName"]} | {str(entry["Notes"])[:100] if entry["Notes"] else "None"}' for entry in beginner_any_queue])
embed.add_field(name="Current Queue", value=t, inline=False)
await interaction.response.send_message(embed=embed)
embed = nextcord.Embed(title="Pickup/Any Queue List")
t = '\n'.join(
[f'[{str(entry["QueueType"])[0]}] {entry["DisplayName"]} | {str(entry["Notes"])[:100] if entry["Notes"] else "None"}' for entry in pickup_any_queue])
embed.add_field(name="Current Queue", value=t, inline=False)
await channel_to_send.send(embed=embed)
@bot.slash_command(name="leave", description="Leave the queue if you're signed up")
async def leave_queue(interaction: nextcord.Interaction):
user = interaction.user
current_time = int(time.time())
if str(user.id) in queue:
queue_type = queue[str(user.id)]["QueueType"]
cooldowns[str(user.id)]["Cooldown"] = current_time + LEAVE_COOLDOWN_DURATION
del queue[str(user.id)]
update_queue_positions()
if queue_type == "Beginner":
channel = bot.get_channel(BEGINNER_CHANNEL_ID)
elif queue_type == "Pickup":
channel = bot.get_channel(PICKUP_CHANNEL_ID)
else:
channel = bot.get_channel(MERGED_CHANNEL_ID)
for userID in queue:
if pings[userID]["Earlier_Queue_members_leaving"] == "Yes":
member = bot.fetch_user(userID)
await member.send("Someone ahead of you has left the queue, please check how this effects you and your ability to ST")
await channel.send(f"{user.display_name} has been removed from the queue and is on cooldown until <t:{current_time + LEAVE_COOLDOWN_DURATION}:f>.")
await interaction.response.send_message("You have left the queue.", ephemeral=True)
else:
await interaction.response.send_message("You are not in the queue.")
@bot.slash_command(name="removefromqueue", description="Removes player from queue")
async def removefromqueue(interaction: nextcord.Interaction, user: nextcord.Member):
current_time = int(time.time())
if str(user.id) in queue:
queue_type = queue[str(user.id)]["QueueType"]
cooldowns[str(user.id)]["Cooldown"] = current_time + LEAVE_COOLDOWN_DURATION
del queue[str(user.id)]
update_queue_positions()
if queue_type == "Beginner":
channel = bot.get_channel(BEGINNER_CHANNEL_ID)
elif queue_type == "Pickup":
channel = bot.get_channel(PICKUP_CHANNEL_ID)
else:
channel = bot.get_channel(MERGED_CHANNEL_ID)
for userID in queue:
if pings[userID]["Earlier_Queue_members_leaving"] == "Yes":
member = bot.fetch_user(userID)
await member.send("Someone ahead of you has left the queue, please check how this effects you and your ability to ST")
await channel.send(f"{user.display_name} has been removed from the queue and is on cooldown until <t:{current_time + LEAVE_COOLDOWN_DURATION}:f>.")
await interaction.response.send_message(f"You removed {user.display_name} the queue.", ephemeral=True)
else:
await interaction.response.send_message(f"{user.display_name} is not in the queue.")
@bot.slash_command(name="debug", description="Used for testing purposes")
async def debug(interaction: nextcord.Interaction, member: nextcord.Member):
await interaction.response.send_message(f"B_Queue ID: {BEGINNER_CHANNEL_ID}, P_Queue ID: {PICKUP_CHANNEL_ID}, A_Queue ID: {MERGED_CHANNEL_ID}")
@bot.slash_command(name="check", description="Check your cooldown status")
async def check_cooldown(interaction: nextcord.Interaction):
user = interaction.user
current_time = int(time.time())
if str(user.id) in cooldowns and cooldowns[str(user.id)]["Cooldown"] > current_time:
timestamp = cooldowns[str(user.id)]["Cooldown"]
await interaction.response.send_message(f"You are still on cooldown until <t:{timestamp}:f>")
else:
await interaction.response.send_message("You are not on cooldown.")
@bot.slash_command(name="save", description="Save the queue to the JSON file")
async def save(interaction: nextcord.Interaction):
save_json(livequeue_file_path, queue)
save_json(cooldowns_file_path, cooldowns)
save_json(pings_file_path, pings)
save_json(active_st_file_path, active_storytellers)
save_json(New_ST_Exceptions_path, New_ST_Exceptions)
await interaction.response.send_message("The queue, cooldowns, and active storytellers have been saved to the JSON files.")
@bot.slash_command(name="load", description="Load the queue from the JSON file")
async def load(interaction: nextcord.Interaction):
global queue
global cooldowns
global active_storytellers
global New_ST_Exceptions
global pings
queue = load_json(livequeue_file_path)
cooldowns = load_json(cooldowns_file_path)
pings = load_json(pings_file_path)
active_storytellers = load_json(active_st_file_path)
New_ST_Exceptions = load_json(New_ST_Exceptions_path)
await interaction.response.send_message("The queue, cooldowns, and active storytellers have been loaded from the JSON files.")
@bot.slash_command(name="split", description="Split the merged queue into Beginner / Pickup Games")
async def split(interaction: nextcord.Interaction):
global MERGED
MERGED = False
for userID in queue:
if pings[userID]["Merge_Split"] == "Yes":
member = bot.fetch_user(userID)
await member.send("The Queue has been Split, please check how this effects your ability to ST")
await interaction.response.send_message("The queue has been split into Beginner / Pickup Games.")
@bot.slash_command(name="merge", description="Merge Beginner / Pickup Games into one Queue")
async def merge(interaction: nextcord.Interaction):
global MERGED
MERGED = True
for userID in queue:
if pings[userID]["Merge_Split"] == "Yes":
member = bot.fetch_user(userID)
await member.send("The Queue has been Merged, please check how this effects your ability to ST")
await interaction.response.send_message("The queue has been merged into one Queue.")
@bot.slash_command(name="pause", description="Pause the queue if there aren't enough players")
async def pause(interaction: nextcord.Interaction):
global GAMES_RUNNING
GAMES_RUNNING = False
await interaction.response.send_message("The games have been paused.")
@bot.slash_command(name="resume", description="Resume the queue when enough players are around")
async def resume(interaction: nextcord.Interaction):
global GAMES_RUNNING
GAMES_RUNNING = True
await interaction.response.send_message("The games have been resumed.")
@bot.slash_command(name="finish", description="Finish your turn and leave the queue")
async def finish(interaction: nextcord.Interaction):
global BEGINNER_CHANNEL_ID
global PICKUP_CHANNEL_ID
global MERGED_CHANNEL_ID
user = interaction.user
QueueType = active_storytellers[str(user.id)]["QueueType"]
if is_active_storyteller(user.id):
remove_active_storyteller(user.id)
await interaction.response.send_message(f"{user.display_name} has finished their game, please wait whilst the next ST is alerted. Feedback Form: https://docs.google.com/forms/d/e/1FAIpQLSduvl3LXwlenwc-uomQhiMY4iKOtjvSEF4jVezQMJGvATltQQ/viewform")
update_queue_positions()
if QueueType == "Beginner":
BEGINNER_CHANNEL_ID = interaction.channel.id
MERGED_CHANNEL_ID = interaction.channel.id
elif QueueType == "Pickup":
PICKUP_CHANNEL_ID = interaction.channel.id
MERGED_CHANNEL_ID = interaction.channel.id
return BEGINNER_CHANNEL_ID, PICKUP_CHANNEL_ID, MERGED_CHANNEL_ID
else:
await interaction.response.send_message("You are not active in the queue.")
@bot.slash_command(name="forcefinish", description="Force finish a user's turn")
async def forcefinish(interaction: nextcord.Interaction, player: nextcord.Member):
global BEGINNER_CHANNEL_ID
global PICKUP_CHANNEL_ID
global MERGED_CHANNEL_ID
QueueType = active_storytellers[str(player.id)]["QueueType"]
if is_active_storyteller(player.id):
remove_active_storyteller(player.id)
await interaction.response.send_message(f"{player.display_name} has been force finished and removed from the queue. Feedback Form: https://docs.google.com/forms/d/e/1FAIpQLSduvl3LXwlenwc-uomQhiMY4iKOtjvSEF4jVezQMJGvATltQQ/viewform")
update_queue_positions()
if QueueType == "Beginner":
BEGINNER_CHANNEL_ID = interaction.channel.id
MERGED_CHANNEL_ID = interaction.channel.id
elif QueueType == "Pickup":
PICKUP_CHANNEL_ID = interaction.channel.id
MERGED_CHANNEL_ID = interaction.channel.id
return BEGINNER_CHANNEL_ID, PICKUP_CHANNEL_ID, MERGED_CHANNEL_ID
else:
await interaction.response.send_message(f"{player.display_name} is not active in the queue.")
@bot.slash_command(name="activests", description="List current Storytellers")
async def active_sts(interaction: nextcord.Interaction):
embed = nextcord.Embed(title="Active Storytellers")
for st in active_storytellers.values():
embed.add_field(name=st["DisplayName"], value=f"Queue Type: {st['QueueType']}", inline=False)
await interaction.response.send_message(embed=embed)
@bot.slash_command(name="adminremovecooldown", description="Remove a user's cooldown")
async def removecooldown(interaction: nextcord.Interaction, player: nextcord.Member = None):
current_time = int(time.time())
if player is None:
player = interaction.user
if str(player.id) in cooldowns:
cooldowns[str(player.id)]["Cooldown"] = current_time
await interaction.response.send_message(f"{player.display_name}'s cooldown has been removed.")
else:
await interaction.response.send_message(f"{player.display_name} does not have a cooldown.")
@bot.slash_command(name="removecooldown", description="Remove a your cooldown if you missed your turn (Usable once per 60 days)")
async def removecooldown(interaction: nextcord.Interaction):
current_time = int(time.time())
player = interaction.user
if str(player.id) in cooldowns:
cooldowns[str(player.id)]["Cooldown"] = current_time
cooldowns[str(player.id)]["removeCooldown_Cooldown"] = current_time + REMOVECOOLDOWN_COOLDOWN_DURATION
await interaction.response.send_message(f"{player.display_name}'s cooldown has been removed and they cannot remove their cooldown again until <t:{current_time + REMOVECOOLDOWN_COOLDOWN_DURATION}:f>.")
else:
await interaction.response.send_message(f"{player.display_name} does not have a cooldown.")
@bot.slash_command(name="addcooldown", description="Add a cooldown to a user")
async def addcooldown(interaction: nextcord.Interaction, player: nextcord.Member, hours: int):
current_time = int(time.time())
if str(player.id) in cooldowns:
cooldowns[str(player.id)]["Cooldown"] = current_time + hours * 3600
else:
cooldown_entry = {
"DisplayName": player.display_name,
"Discord_ID": player.id,
"User_Image_URL": str(player.display_avatar.url),
"Cooldown": current_time + hours * 3600,
"removeCooldown_Cooldown": 0
}
cooldowns[str(player.id)] = cooldown_entry
await interaction.response.send_message(f"{player.display_name}'s cooldown has been set to <t:{current_time + hours * 3600}:f>.")
@bot.slash_command(name="allow", description="Bypasses the 2 week waiting period for new STs")
async def addcooldown(interaction: nextcord.Interaction, player: nextcord.Member):
entry = {
"DisplayName": player.display_name,
"Discord_ID": player.id,
"User_Image_URL": str(player.display_avatar.url),
"Added By Name": interaction.user.display_name,
"Added By ID": interaction.user.id
}
New_ST_Exceptions[str(player.id)] = entry
await interaction.response.send_message(f"{player.display_name} may now join the Queue.")
@bot.slash_command(name="removeremovecooldowncooldown", description="Remove a user's removeCooldown_Cooldown")
async def removeremovecooldowncooldown(interaction: nextcord.Interaction, player: nextcord.Member):
current_time = int(time.time())
if str(player.id) in cooldowns:
cooldowns[str(player.id)]["removeCooldown_Cooldown"] = current_time
await interaction.response.send_message(f"{player.display_name}'s removeCooldown_Cooldown has been removed.")
else:
await interaction.response.send_message(f"{player.display_name} is not in the queue.")
@bot.slash_command(name="startextra", description="Starts an extra game if next in queue")
async def startextra(interaction: nextcord.Interaction):
user = interaction.user
eligible = False
if MERGED:
# Find the lowest merged queue position that is not Active_ST
sorted_queue = sorted(queue.values(), key=lambda x: x["Merged_Queue_Position"])
if sorted_queue and sorted_queue[0]["Discord_ID"] == user.id and not is_active_storyteller(user.id):
eligible = True
else:
# Find the lowest queue position for beginner, pickup, or any that is not Active_ST
beginner_queue = [entry for entry in queue.values() if entry["QueueType"] in ["Beginner", "Any"]]
pickup_queue = [entry for entry in queue.values() if entry["QueueType"] in ["Pickup", "Any"]]
sorted_beginner_queue = sorted(beginner_queue, key=lambda x: x["Merged_Queue_Position"])
sorted_pickup_queue = sorted(pickup_queue, key=lambda x: x["Merged_Queue_Position"])
if (sorted_beginner_queue and sorted_beginner_queue[0]["Discord_ID"] == user.id and not is_active_storyteller(user.id)) or \
(sorted_pickup_queue and sorted_pickup_queue[0]["Discord_ID"] == user.id and not is_active_storyteller(user.id)):
eligible = True
if eligible:
add_active_storyteller(user, "Extra")
await remove_queue(user.id)
await interaction.response.send_message(f"{user.display_name} is now active and has been removed from the queue.")
# Notify user after 40 minutes
await asyncio.sleep(RE_RACK_TIMER_DURATION)
await interaction.channel.send(f"{user.mention}, the Re-rack timer has expired.")
else:
await interaction.response.send_message("You are not eligible to start extra.")
@bot.slash_command(name="setposition", description="Move a player to the top of the merged queue")
async def setposition(interaction: nextcord.Interaction, player: nextcord.Member, position: int):
if str(player.id) in queue:
queue[str(player.id)]["Merged_Queue_Position"] = position - 0.5
update_queue_positions()
await interaction.response.send_message(f"{player.display_name} has been moved to position {position} of the merged queue.")
else:
await interaction.response.send_message(f"{player.display_name} is not in the queue.")
@bot.slash_command(name="addplayer", description="Force add a player to the queue")
async def addplayer(interaction: nextcord.Interaction, player: nextcord.Member, queue_type: str = nextcord.SlashOption(
name="queue_type",
description="Type of queue",
choices={"Beginner": "Beginner", "Pickup": "Pickup", "Any": "Any"},
required=True), notes: str = "Mod Added to Queue"):
merged_queue_position = len(queue) + 1
new_entry = {
"DisplayName": player.display_name,
"Discord_ID": player.id,
"User_Image_URL": str(player.display_avatar.url),
"QueueType": queue_type,
"Merged_Queue_Position": merged_queue_position,
"Notes": notes[:128]
}
cooldown_entry = {
"DisplayName": player.display_name,
"Discord_ID": player.id,
"User_Image_URL": str(player.display_avatar.url),
"Cooldown": 0,
"removeCooldown_Cooldown": 0
}
queue[str(player.id)] = new_entry
cooldowns[str(player.id)] = cooldown_entry
update_queue_positions()
await interaction.response.send_message(f"{player.display_name} has been added to the queue.")
@bot.slash_command(name="setqueue", description="Set the queue for a specific type")
async def setqueue(interaction: nextcord.Interaction, queue_type: str = nextcord.SlashOption(
name="queue_type",
description="Type of queue",
choices={"Beginner": "Beginner", "Pickup": "Pickup", "Any": "Any"},
required=True), player1: nextcord.Member = None, player2: nextcord.Member = None, player3: nextcord.Member = None, player4: nextcord.Member = None, player5: nextcord.Member = None, player6: nextcord.Member = None, player7: nextcord.Member = None, player8: nextcord.Member = None, player9: nextcord.Member = None, player10: nextcord.Member = None):
players = [player for player in [player1, player2, player3, player4, player5, player6, player7, player8, player9, player10] if player is not None]
# Remove all players from the current queue type
for user_id in list(queue.keys()):
if queue[user_id]["QueueType"] == queue_type:
del queue[user_id]
# Add mentioned users to the queue
for idx, player in enumerate(players):
merged_queue_position = len(queue) + 1
new_entry = {
"DisplayName": player.display_name,
"Discord_ID": player.id,
"User_Image_URL": str(player.display_avatar.url),
"QueueType": queue_type,
"Merged_Queue_Position": merged_queue_position,
"Notes": "Mod Added to Queue"
}
cooldown_entry = {
"DisplayName": player.display_name,
"Discord_ID": player.id,
"User_Image_URL": str(player.display_avatar.url),
"Cooldown": 0,
"removeCooldown_Cooldown": 0
}
cooldowns[str(player.id)] = cooldown_entry
queue[str(player.id)] = new_entry
update_queue_positions()
await interaction.response.send_message(f"The queue for {queue_type} has been updated with the mentioned players.")
async def start_user(interaction, user):
add_active_storyteller(user, queue[str(user.id)]["QueueType"])
await remove_queue(user.id)
await interaction.response.send_message(f"{user.display_name} is now active.", ephemeral=False)
#await check_queue()
# Notify user after 40 minutes
await asyncio.sleep(RE_RACK_TIMER_DURATION)
await interaction.channel.send(f"{user.mention}, the Re-rack timer has expired.")
@bot.slash_command(name="start", description="Start a game if you're next to ST")
async def start(interaction: nextcord.Interaction):
user = interaction.user
await start_user(interaction, user)
@bot.slash_command(name="forcestart", description="Force start a user")
async def forcestart(interaction: nextcord.Interaction, player: nextcord.Member):
await start_user(interaction, player)
@tasks.loop(seconds=10) # Adjust the interval as needed
async def check_queue():
if not GAMES_RUNNING:
return
if MERGED:
# Check for Active_ST in the merged queue
for entry in active_storytellers.values():
if is_active_storyteller(entry["Discord_ID"]):
return
# Find the first user in the merged queue
sorted_queue = sorted(queue.values(), key=lambda x: x["Merged_Queue_Position"])
if sorted_queue:
user_id = sorted_queue[0]["Discord_ID"]
if str(user_id) in queue:
user = await bot.fetch_user(user_id)
channel = bot.get_channel(MERGED_CHANNEL_ID)
initial_merged_state = MERGED
queue[str(user.id)]["QueueType"] = "Pickup"
embed = nextcord.Embed(title=f"Game Notification for {queue[str(user_id)]['QueueType']} Queue", description=f"{user.mention}, it's your turn!")
embed.set_thumbnail(url=user.display_avatar.url)
timeout_timestamp = int(time.time()) + TIMEOUT_TIMER
embed.add_field(name="Notes:", value=f"{queue[str(user_id)]['Notes']}", inline=False)
embed.add_field(name="Action Required", value=f"Please choose to start or leave the queue. Timeout <t:{timeout_timestamp}:R>", inline=False)
view = nextcord.ui.View()
start_button = nextcord.ui.Button(label="Start", style=nextcord.ButtonStyle.green)
leave_button = nextcord.ui.Button(label="Leave", style=nextcord.ButtonStyle.red)
async def start_callback(interaction: nextcord.Interaction):
if interaction.user.id == user.id and str(user.id) in queue:
await start_user(interaction, user)
#await interaction.message.edit(view=None)
else:
await interaction.response.send_message("You are not authorized to use this button.", ephemeral=True)
async def leave_callback(interaction: nextcord.Interaction):
if interaction.user.id == user.id and str(user.id) in queue:
await leave_queue(interaction, user_id=user.id)
#await check_queue()
await interaction.message.edit(view=None)
else:
await interaction.response.send_message("You are not authorized to use this button.", ephemeral=True)
start_button.callback = start_callback
leave_button.callback = leave_callback
view.add_item(start_button)
view.add_item(leave_button)
await channel.send(embed=embed, view=view)
await channel.send(f"{user.mention}, it's your turn!")
if pings[str(user.id)]['Next_in_Queue'] == "Yes":
await user.send("You are now the required ST on the unofficial, Please ensure you press the START Button to begin")
try:
next_user_id = sorted_queue[1]["Discord_ID"]
next_user = await bot.fetch_user(next_user_id)
await channel.send(f"{next_user.mention}, You are 2nd in the queue!")
if pings[str(next_user.id)]['2nd_in_Queue'] == "Yes":
await next_user.send("You are 2nd in the queue on the unofficial, please be ready for your turn")
except:
await channel.send("Queue is empty after you.")
for i in range(100):
if str(user.id) in queue and not is_active_storyteller(user.id):
await asyncio.sleep(TIMEOUT_TIMER/100) # Wait for 5 minutes
else:
return
# Check if the user is still first in queue and the merge state has not changed
if MERGED == initial_merged_state and str(user.id) in queue and not is_active_storyteller(user.id) and GAMES_RUNNING is True:
await channel.send(f"{user.mention}, You did not reply in time, your space has been skipped")
await remove_queue(user_id=user.id)
#await check_queue()
else:
# Check for Active_ST in the beginner queue
beginner_active_sts = [st for st in active_storytellers.values() if st["QueueType"] in ["Beginner", "Any"]]
if not beginner_active_sts:
beginner_queue = [entry for entry in queue.values() if entry["QueueType"] in ["Beginner", "Any"]]
sorted_beginner_queue = sorted(beginner_queue, key=lambda x: x["Merged_Queue_Position"])
if sorted_beginner_queue:
user_id = sorted_beginner_queue[0]["Discord_ID"]
if str(user_id) in queue:
user = await bot.fetch_user(user_id)
channel = bot.get_channel(BEGINNER_CHANNEL_ID)
initial_merged_state = MERGED
queue[str(user.id)]["QueueType"] = "Beginner"
embed = nextcord.Embed(title=f"Game Notification for {queue[str(user_id)]['QueueType']} Queue", description=f"{user.mention}, it's your turn!")
embed.set_thumbnail(url=user.display_avatar.url)
timeout_timestamp = int(time.time()) + TIMEOUT_TIMER
embed.add_field(name="Notes:", value=f"{queue[str(user_id)]['Notes']}", inline=False)
embed.add_field(name="Action Required", value=f"Please choose to start or leave the queue. Timeout at <t:{timeout_timestamp}:R>", inline=False)
view = nextcord.ui.View()
start_button = nextcord.ui.Button(label="Start", style=nextcord.ButtonStyle.green)
leave_button = nextcord.ui.Button(label="Leave", style=nextcord.ButtonStyle.red)
async def start_callback(interaction: nextcord.Interaction):
if interaction.user.id == user.id and str(user.id) in queue:
await start_user(interaction, user)
#await interaction.message.edit(view=None)
else:
await interaction.response.send_message("You are not authorized to use this button.", ephemeral=True)
async def leave_callback(interaction: nextcord.Interaction):
if interaction.user.id == user.id and str(user.id) in queue:
await leave_queue(interaction, user_id=user.id)
#await interaction.message.edit(view=None)
#await check_queue()
else:
await interaction.response.send_message("You are not authorized to use this button.", ephemeral=True)
start_button.callback = start_callback
leave_button.callback = leave_callback
view.add_item(start_button)
view.add_item(leave_button)
await channel.send(embed=embed, view=view)
await channel.send(f"{user.mention}, it's your turn!")
if pings[str(user.id)]['Next_in_Queue'] == "Yes":
await user.send("You are now the required ST on the unofficial, Please ensure you press the START Button to begin")
try:
next_user_id = sorted_beginner_queue[1]["Discord_ID"]
next_user = await bot.fetch_user(next_user_id)
await channel.send(f"{next_user.mention}, You are 2nd in the queue!")
if pings[str(next_user.id)]['2nd_in_Queue'] == "Yes":
await next_user.send("You are 2nd in the queue on the unofficial, please be ready for your turn")
except:
await channel.send("Queue is empty after you.")
for i in range(100):
if str(user.id) in queue and not is_active_storyteller(user.id):
await asyncio.sleep(TIMEOUT_TIMER/100) # Wait for 5 minutes
else:
return
# Check if the user is still first in queue and the merge state has not changed
if MERGED == initial_merged_state and str(user.id) in queue and not is_active_storyteller(user.id) and GAMES_RUNNING is True:
await channel.send(f"{user.mention}, You did not reply in time, your space has been skipped")
await remove_queue(user_id=user.id)
#await check_queue()
# Check for Active_ST in the pickup queue
pickup_active_sts = [st for st in active_storytellers.values() if st["QueueType"] in ["Pickup", "Any"]]
if not pickup_active_sts:
pickup_queue = [entry for entry in queue.values() if entry["QueueType"] in ["Pickup", "Any"]]
sorted_pickup_queue = sorted(pickup_queue, key=lambda x: x["Merged_Queue_Position"])
if sorted_pickup_queue:
user_id = sorted_pickup_queue[0]["Discord_ID"]
if str(user_id) in queue:
user = await bot.fetch_user(user_id)
channel = bot.get_channel(PICKUP_CHANNEL_ID)
initial_merged_state = MERGED
queue[str(user.id)]["QueueType"] = "Pickup"
embed = nextcord.Embed(title=f"Game Notification for {queue[str(user_id)]['QueueType']} Queue", description=f"{user.mention}, it's your turn!")
embed.set_thumbnail(url=user.display_avatar.url)
timeout_timestamp = int(time.time()) + TIMEOUT_TIMER
embed.add_field(name="Notes:", value=f"{queue[str(user_id)]['Notes']}", inline=False)
embed.add_field(name="Action Required", value=f"Please choose to start or leave the queue. Timeout at <t:{timeout_timestamp}:R>", inline=False)
view = nextcord.ui.View()
start_button = nextcord.ui.Button(label="Start", style=nextcord.ButtonStyle.green)
leave_button = nextcord.ui.Button(label="Leave", style=nextcord.ButtonStyle.red)
async def start_callback(interaction: nextcord.Interaction):
if interaction.user.id == user.id and str(user.id) in queue:
await start_user(interaction, user)
#await interaction.message.edit(view=None)
else:
await interaction.response.send_message("You are not authorized to use this button.", ephemeral=True)
async def leave_callback(interaction: nextcord.Interaction):
if interaction.user.id == user.id and str(user.id) in queue:
await leave_queue(interaction, user_id=user.id)
#await interaction.message.edit(view=None)
#await check_queue()
else:
await interaction.response.send_message("You are not authorized to use this button.", ephemeral=True)
start_button.callback = start_callback
leave_button.callback = leave_callback
view.add_item(start_button)
view.add_item(leave_button)
await channel.send(embed=embed, view=view)
await channel.send(f"{user.mention}, it's your turn!")
if pings[str(user.id)]['Next_in_Queue'] == "Yes":
await user.send("You are now the required ST on the unofficial, Please ensure you press the START Button to begin")
try:
next_user_id = sorted_pickup_queue[1]["Discord_ID"]
next_user = await bot.fetch_user(next_user_id)
await channel.send(f"{next_user.mention}, You are 2nd in the queue!")
if pings[str(next_user.id)]['2nd_in_Queue'] == "Yes":
await next_user.send("You are 2nd in the queue on the unofficial, please be ready for your turn")
except:
await channel.send("Queue is empty after you.")
for i in range(100):
if str(user.id) in queue and not is_active_storyteller(user.id):
await asyncio.sleep(TIMEOUT_TIMER/100) # Wait for 5 minutes
else:
return
# Check if the user is still first in queue and the merge state has not changed
if MERGED == initial_merged_state and str(user.id) in queue and not is_active_storyteller(user.id) and GAMES_RUNNING is True:
await channel.send(f"{user.mention}, You did not reply in time, your space has been skipped")
await remove_queue(user_id=user.id)
#await check_queue()
bot.load_extension("townsquare_spy.discord", extras=dict(db_path="townsquare.db"))
# Add other necessary commands and functionality as needed
bot.run(os.environ['DISCORD_TOKEN'])