-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
2842 lines (2534 loc) · 128 KB
/
index.js
File metadata and controls
2842 lines (2534 loc) · 128 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
import 'dotenv/config';
import {
Client, EmbedBuilder, ChannelType, GatewayIntentBits, MessageMentions, ModalBuilder, TextInputBuilder,
TextInputStyle, ActionRowBuilder, ButtonStyle, PermissionsBitField, AttachmentBuilder,
MessageFlags, StringSelectMenuBuilder, ButtonBuilder, ComponentType
} from 'discord.js';
import fs from 'fs';
import { getHelpEmbed } from './embed.js';
import {
BOT_PREFIX, TEST_USER_ID, DEFAULT_LIT_CANDLE_EMOJI, DEFAULT_UNLIT_CANDLE_EMOJI, finalRecordingsMessage
} from './config.js';
import {
loadGameData, saveGameData, printActiveGames, getGameData, sendCandleStatus, getLitCandleEmoji,
gameData, playAudioFromUrl, playRandomConflictSound, handleEditGearModal, getUnlitCandleEmoji,
speakInChannel, requestConsent, loadBlockUserList, isWhitelisted, handleAddGearModal,
handleAddGearModalSubmit, isBlockedUser, loadChannelWhitelist, saveChannelWhitelist, getRandomTheme,
channelWhitelist, respondViaDM, findGameByUserId, normalizeBrink, getRandomBrink, sanitizeString,
getRandomMoment, getRandomVice, getRandomVirtue, getRandomName, getRandomLook, getRandomConcept,
handleDoneButton, handleDeleteGearModal, handleDeleteGearModalSubmit, handleEditGearModalSubmit,
displayInventory, markPlayerDead, askPlayerToGiftHope, sendDM, clearReminderTimers, getVirtualTableOrder
} from './utils.js';
import { prevStep, sendCharacterGenStep } from './steps.js';
import { startGame } from './commands/startgame.js';
import { conflict, extinguishCandle } from './commands/conflict.js';
import { gameStatus, gmGameStatus, generatePlayerStatusEmbed, generateGameStatusEmbed } from './commands/gamestatus.js';
import { removePlayer } from './commands/removeplayer.js';
import { leaveGame } from './commands/leavegame.js';
import { cancelGame } from './commands/cancelgame.js';
import { died } from './commands/died.js';
import { getVoiceConnection, joinVoiceChannel } from '@discordjs/voice';
export const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers, GatewayIntentBits.DirectMessages, GatewayIntentBits.GuildMessageReactions, GatewayIntentBits.GuildVoiceStates] });
const version = '0.9.962a';
const botName = 'Ten Candles Bot';
export const isTesting = false;
let botRestarted = false;
client.once('ready', async () => {
const startupTimestamp = new Date().toLocaleString();
console.log(`${botName} (v${version}) is ready @ ${startupTimestamp}`);
console.log(`Logged in as ${client.user.tag} (${client.user.id})`);
const serverIds = client.guilds.cache.map(guild => guild.id).join(', ');
console.log(`${botName} is in ${client.guilds.cache.size} server${client.guilds.cache.size === 1 ? '' : 's'} (${serverIds}).`)
console.log(`Command prefix is ${BOT_PREFIX}`);
console.log(`Use ${BOT_PREFIX}help for a list of commands.`);
if (!fs.existsSync('config.js')) {
console.error('Configuration file not found. Please create a config.js file or copy one from https://github.com/Gavi616/CandleBot');
return;
}
loadBlockUserList();
loadChannelWhitelist();
loadGameData();
if (isTesting) {
console.log('-- Testing Mode Engaged! --');
await sendTestDM(client, 'Listening for test commands.');
return;
} else { // not in testing mode
if (Object.keys(gameData).length > 0) {
botRestarted = true;
for (const channelId in gameData) {
const game = gameData[channelId];
if (game.pendingMartyrdom) {
console.log(`Clearing pending martyrdom state for game ${channelId} on restart.`);
// Clear associated timeouts if IDs were stored (though they are likely invalid after restart)
if (game.pendingMartyrdom.gmTimeoutId) clearTimeout(game.pendingMartyrdom.gmTimeoutId);
if (game.pendingMartyrdom.playerTimeoutId) clearTimeout(game.pendingMartyrdom.playerTimeoutId);
delete game.pendingMartyrdom;
saveGameData(); // Save the cleared state
}
const channel = client.channels.cache.get(channelId);
if (channel) {
await channel.send(`**${botName}** has restarted and found one or more games in-progress.`);
if (game.characterGenStep < 9) {
await channel.send(`Character generation was in progress.\nRestarting character generation from last successful step.\n*If this occurrs repeatedly, contact the developer and/or consider using \`${BOT_PREFIX}cancelgame\`*`);
await sendCharacterGenStep(channel, game);
} else if (game.inLastStand) {
if (Object.values(game.players).every(player => player.isDead)) {
if (game.endGame) {
await channel.send("The game has ended. Restarting **Session Data Management** processes.");
await cancelGame(channel);
} else {
await channel.send("All characters are dead. Restarting the **Final Recordings**.");
await playRecordings(channel);
}
}
} else if (game.inLastStand) {
if (Object.values(game.players).every(player => player.isDead)) {
if (game.endGame) {
await channel.send("The game has ended. Restarting **Session Data Management** processes.");
await cancelGame(channel);
} else {
await channel.send("All characters are dead. Restarting the **Final Recordings**.");
await playRecordings(channel);
}
} else {
await gameStatus(channel);
await channel.send(`We are in **The Last Stand**. GM continues narration until all characters have \`${BOT_PREFIX}died @PlayerId [cause]\``);
}
} else { // scene play continues
await gameStatus(channel);
await sendCandleStatus(channel, 11 - game.scene);
await channel.send(`GM continues narration until a Player uses \`${BOT_PREFIX}conflict\` to move the story forward.`);
}
}
}
botRestarted = false;
}
printActiveGames();
}
});
client.on('interactionCreate', async interaction => {
// --- Skip Chat Input Commands ---
if (interaction.isChatInputCommand()) return;
// --- Button, Modal, Select Menu Handling ---
if (interaction.isButton() || interaction.isModalSubmit() || interaction.isStringSelectMenu()) {
const interactorId = interaction.user.id;
let game = null; // Initialize game to null
let gameChannelId = null; // Initialize gameChannelId
// --- Game Finding Logic ---
// Try extracting channel ID from customId first (most reliable for interactions tied to a game)
const customIdParts = interaction.customId.split('_');
const potentialChannelId = customIdParts[customIdParts.length - 1]; // Often the last part
if (/^\d+$/.test(potentialChannelId)) {
gameChannelId = potentialChannelId;
game = getGameData(gameChannelId);
}
// If no game found via channel ID in customId, try finding by user ID (for DM commands like .me, .gear)
if (!game && (interaction.isButton() || interaction.isModalSubmit() || interaction.isStringSelectMenu())) {
const userGame = await findGameByUserId(interactorId);
if (userGame) {
game = userGame;
gameChannelId = game.textChannelId; // Get channel ID from the found game
console.log(`DEBUG Game Finding: Assigned userGame to game. Current game.gmId = ${game?.gmId}, game.textChannelId = ${game?.textChannelId}`);
} else {
console.log(`DEBUG Game Finding: findGameByUserId returned undefined, 'game' remains null.`);
}
}
// --- Logging for askForTraits Interactions ---
if (interaction.isButton() && interaction.customId.startsWith('ask_traits_start_')) {
console.log(`Interaction LOG: Received 'ask_traits_start' button click. ID: ${interaction.customId}, User: ${interaction.user.tag}`);
// Ensure game context is found for this button
const parts = interaction.customId.split('_');
const channelIdFromButton = parts[parts.length - 1];
const traitGame = getGameData(channelIdFromButton);
if (!traitGame) {
console.error(`Interaction ERROR: Could not find game for ask_traits_start button: ${interaction.customId}`);
try { await interaction.reply({ content: 'Error: Could not find game context for this action.' }); } catch { /* ignore */ }
return; // Stop if no game found
}
// Add permission check if needed (e.g., ensure it's the correct player)
const targetPlayerId = parts[3];
if (interaction.user.id !== targetPlayerId) {
console.warn(`Interaction WARN: User ${interaction.user.tag} clicked ask_traits_start button for player ${targetPlayerId}`);
try { await interaction.reply({ content: 'You cannot start this process for another player.' }); } catch { /* ignore */ }
return;
}
console.log(`Interaction LOG: Proceeding to show modal for ${interaction.customId}`);
return;
}
if (interaction.isModalSubmit() && interaction.customId.startsWith('traits_modal_')) {
console.log(`Interaction LOG: Received 'traits_modal' submission. ID: ${interaction.customId}, User: ${interaction.user.tag}`);
// Add game/permission checks if needed
const parts = interaction.customId.split('_');
const channelIdFromModal = parts[parts.length - 1];
const traitGame = getGameData(channelIdFromModal);
if (!traitGame) {
console.error(`Interaction ERROR: Could not find game for traits_modal submission: ${interaction.customId}`);
try { await interaction.reply({ content: 'Error: Could not find game context for this submission.' }); } catch { /* ignore */ }
return; // Stop if no game found
}
const targetPlayerId = parts[2];
if (interaction.user.id !== targetPlayerId) {
console.warn(`Interaction WARN: User ${interaction.user.tag} submitted traits_modal for player ${targetPlayerId}`);
try { await interaction.reply({ content: 'You cannot submit this form for another player.' }); } catch { /* ignore */ }
return;
}
console.log(`Interaction LOG: Proceeding to process modal and show confirmation for ${interaction.customId}`);
return;
}
if (interaction.isButton() && interaction.customId.startsWith('traits_confirm_')) {
console.log(`Interaction LOG: Received 'traits_confirm' button click. ID: ${interaction.customId}, User: ${interaction.user.tag}`);
// Add game/permission checks if needed
const parts = interaction.customId.split('_');
const channelIdFromButton = parts[parts.length - 1];
const traitGame = getGameData(channelIdFromButton);
if (!traitGame) {
console.error(`Interaction ERROR: Could not find game for traits_confirm button: ${interaction.customId}`);
try { await interaction.reply({ content: 'Error: Could not find game context for this action.' }); } catch { /* ignore */ }
return; // Stop if no game found
}
const targetPlayerId = parts[3];
if (interaction.user.id !== targetPlayerId) {
console.warn(`Interaction WARN: User ${interaction.user.tag} clicked traits_confirm button for player ${targetPlayerId}`);
try { await interaction.reply({ content: 'You cannot confirm traits for another player.' }); } catch { /* ignore */ }
return;
}
console.log(`Interaction LOG: Proceeding to handle confirmation for ${interaction.customId}`);
return;
}
// --- End Logging for askForTraits ---
// --- NEW: Handle "Set Theme" Button ---
if (interaction.isButton() && interaction.customId.startsWith('set_theme_button_')) {
const channelIdFromButton = customIdParts[customIdParts.length - 1];
const themeGame = getGameData(channelIdFromButton); // Get game data using ID from button
if (!themeGame) {
try { await interaction.reply({ content: 'Could not find the game associated with this button. It might have been cancelled.' }); } catch { /* ignore */ }
return;
}
if (interaction.user.id !== themeGame.gmId) {
try { await interaction.reply({ content: 'Only the GM can set the theme.' }); } catch { /* ignore */ }
return;
}
if (themeGame.characterGenStep !== 2) {
try { await interaction.reply({ content: `Theme can only be set during Step 2. Current step: ${themeGame.characterGenStep}.` }); } catch { /* ignore */ }
return;
}
// Build the modal first
const themeModal = new ModalBuilder()
.setCustomId(`theme_modal_${channelIdFromButton}`)
.setTitle('Set Game Theme');
const titleInput = new TextInputBuilder()
.setCustomId('themeTitle')
.setLabel("Title")
.setStyle(TextInputStyle.Short)
.setPlaceholder("Enter theme title (or '?' for random).")
.setRequired(true);
const descriptionInput = new TextInputBuilder()
.setCustomId('themeDescription')
.setLabel("Description")
.setStyle(TextInputStyle.Paragraph)
.setPlaceholder("Enter theme description (auto-filled if title is '?').") // Updated placeholder
.setRequired(false)
.setMaxLength(1024);
themeModal.addComponents(
new ActionRowBuilder().addComponents(titleInput),
new ActionRowBuilder().addComponents(descriptionInput)
);
// --- Action 1: Show the modal (This is the primary interaction response) ---
try {
await interaction.showModal(themeModal); // <<< PRIMARY RESPONSE
console.log(`Theme Modal shown to GM ${interaction.user.tag} for game ${channelIdFromButton}`);
} catch (modalError) {
console.error(`Error showing theme modal:`, modalError);
// Use followUp here because showModal might have failed *after* acknowledging
try {
// Check if already replied/deferred before attempting followUp
if (!interaction.replied && !interaction.deferred) {
await interaction.reply({ content: 'Could not display the theme input form. Please try again or contact support.' });
} else {
await interaction.followUp({ content: 'Could not display the theme input form. Please try again or contact support.' });
}
} catch (followUpError) {
console.error(`Error sending followUp after modal error:`, followUpError);
}
return; // Stop if modal failed to show
}
// --- Action 2: Disable the button on the original message (Secondary effect) ---
try {
// Fetch the original message the button was on
const originalMessage = interaction.message;
if (originalMessage && originalMessage.components.length > 0) {
// Rebuild the row with the clicked button disabled
const disabledRow = new ActionRowBuilder().addComponents(
originalMessage.components[0].components.map(comp => {
const button = ButtonBuilder.from(comp);
if (comp.customId === interaction.customId) {
button.setDisabled(true);
}
return button;
})
);
// Edit the *message*, not the interaction
await originalMessage.edit({ components: [disabledRow] }); // <<< USE message.edit()
}
} catch (e) {
// Ignore errors if message was deleted (10008) or interaction expired (10062)
// These errors are okay because the primary action (modal) likely succeeded.
if (e.code !== 10008 && e.code !== 10062) {
console.error("Error disabling 'Set Theme' button after showing modal:", e);
}
}
return; // Handled button
}
// --- NEW: Handle Theme Modal Submission ---
if (interaction.isModalSubmit() && interaction.customId.startsWith('theme_modal_')) {
const channelIdFromModal = customIdParts[customIdParts.length - 1];
const themeGame = getGameData(channelIdFromModal); // Get game data
if (!themeGame) {
await interaction.reply({ content: 'Could not find the game associated with this submission.' });
return;
}
if (interaction.user.id !== themeGame.gmId) {
await interaction.reply({ content: 'Only the GM can submit the theme.' });
return;
}
if (themeGame.characterGenStep !== 2) {
await interaction.reply({ content: `Theme can only be set during Step 2. Current step: ${themeGame.characterGenStep}.` });
return;
}
let title = interaction.fields.getTextInputValue('themeTitle').trim();
let description = interaction.fields.getTextInputValue('themeDescription').trim();
let chosenTheme = { title: "", description: "" };
if (title === '?') {
chosenTheme = getRandomTheme(); // Gets { title, description }
console.log(`Theme Modal: GM requested random theme. Got: "${chosenTheme.title}"`);
} else {
chosenTheme.title = sanitizeString(title);
// Use provided description, or use title as description if description is empty
chosenTheme.description = sanitizeString(description) || chosenTheme.title;
console.log(`Theme Modal: GM submitted custom theme. Title: "${chosenTheme.title}"`);
}
// Store temporarily in game object (will be cleared or finalized)
themeGame.pendingTheme = chosenTheme;
// saveGameData(); // Save pending theme temporarily
// Build confirmation embed
const confirmEmbed = new EmbedBuilder()
.setColor(0xFFA500) // Orange for confirmation
.setTitle('Confirm Theme')
.setDescription(`Please review the theme details below for the game in <#${channelIdFromModal}>.`)
.addFields(
{ name: 'Title', value: chosenTheme.title },
{ name: 'Description', value: chosenTheme.description.substring(0, 1020) + (chosenTheme.description.length > 1020 ? '...' : '') } // Limit description length in embed field
);
const confirmRow = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId(`theme_confirm_yes_${channelIdFromModal}`)
.setLabel('Confirm & Start Step 3')
.setStyle(ButtonStyle.Success),
new ButtonBuilder()
.setCustomId(`theme_confirm_no_${channelIdFromModal}`)
.setLabel('Edit')
.setStyle(ButtonStyle.Danger)
);
try {
// Reply to the modal submission with the confirmation
await interaction.reply({ embeds: [confirmEmbed], components: [confirmRow] });
console.log(`Theme Modal: Sent confirmation to GM ${interaction.user.tag}`);
} catch (replyError) {
console.error(`Theme Modal: Error sending confirmation reply:`, replyError);
// Attempt follow-up if reply failed
try {
await interaction.followUp({ content: 'Error displaying confirmation. Please try setting the theme again.' });
} catch { /* Ignore follow-up error */ }
// Clear pending theme on error
delete themeGame.pendingTheme;
// saveGameData();
}
return; // Handled modal submit
}
// --- NEW: Handle Theme Confirmation Buttons ---
if (interaction.isButton() && interaction.customId.startsWith('theme_confirm_')) {
const parts = interaction.customId.split('_');
const confirmationType = parts[2]; // 'yes' or 'no'
const channelIdFromConfirm = parts[parts.length - 1];
const themeGame = getGameData(channelIdFromConfirm); // Get game data
if (!themeGame) {
try { await interaction.reply({ content: 'Could not find the game associated with this confirmation.' }); } catch { /* ignore */ }
return;
}
if (interaction.user.id !== themeGame.gmId) {
try { await interaction.reply({ content: 'Only the GM can confirm or edit the theme.' }); } catch { /* ignore */ }
return;
}
if (!themeGame.pendingTheme) {
try { await interaction.reply({ content: 'Could not find the theme data to confirm or edit. Please try setting it again.' }); } catch { /* ignore */ }
return;
}
// --- Logic Split: YES vs EDIT ---
if (confirmationType === 'yes') {
// --- Confirm YES ---
console.log(`Theme Confirm: GM ${interaction.user.id} confirmed theme for game ${channelIdFromConfirm}`);
// Disable buttons on the confirmation message first
try {
const disabledRows = interaction.message.components.map(row => {
const newRow = ActionRowBuilder.from(row);
newRow.components.forEach(component => component.setDisabled(true));
return newRow;
});
await interaction.update({ components: disabledRows }); // Use update here for the 'Yes' path
} catch (e) {
if (e.code !== 10062 && e.code !== 10008) console.error("Error disabling theme confirm buttons (Yes):", e);
// Proceed even if disabling fails
}
// Finalize theme
themeGame.theme = themeGame.pendingTheme;
delete themeGame.pendingTheme; // Clean up temporary storage
themeGame.characterGenStep++; // Advance to Step 3
clearReminderTimers(themeGame); // Stop reminder timers for Step 2
saveGameData(); // Save the finalized theme and step
// Fetch channel and start Step 3
const gameChannel = client.channels.cache.get(channelIdFromConfirm);
if (gameChannel) {
// Use followUp because we already used interaction.update
await interaction.followUp({ content: `Theme confirmed! Starting Step 3 in <#${channelIdFromConfirm}>.` }).catch(console.error);
sendCharacterGenStep(gameChannel, themeGame); // Trigger handleStepThree
} else {
console.error(`Theme Confirm: Could not find game channel ${channelIdFromConfirm} to start Step 3.`);
await interaction.followUp({ content: `Theme confirmed, but could not find the game channel <#${channelIdFromConfirm}> to start Step 3 automatically.` }).catch(console.error);
}
} else { // confirmationType === 'no' (Edit)
// --- Confirm Edit ---
console.log(`Theme Confirm: GM ${interaction.user.id} chose to edit theme for game ${channelIdFromConfirm}`);
// Build the modal first
const themeModal = new ModalBuilder()
.setCustomId(`theme_modal_${channelIdFromConfirm}`) // Same modal ID
.setTitle('Edit Game Theme');
const titleInput = new TextInputBuilder()
.setCustomId('themeTitle')
.setLabel("Theme Title (or '?' for random)")
.setStyle(TextInputStyle.Short)
.setValue(themeGame.pendingTheme.title || '') // Pre-fill
.setRequired(true);
const descriptionInput = new TextInputBuilder()
.setCustomId('themeDescription')
.setLabel("Theme Description")
.setStyle(TextInputStyle.Paragraph)
.setPlaceholder("Enter the theme description here.")
.setValue(themeGame.pendingTheme.description || '') // Pre-fill
.setRequired(false)
.setMaxLength(1024); // Ensure max length is set
themeModal.addComponents(
new ActionRowBuilder().addComponents(titleInput),
new ActionRowBuilder().addComponents(descriptionInput)
);
// --- Action 1: Show the modal (Primary response for 'Edit') ---
try {
await interaction.showModal(themeModal); // <<< PRIMARY RESPONSE
console.log(`Theme Edit: Re-showing modal to GM ${interaction.user.tag}`);
} catch (modalError) {
console.error(`Theme Edit: Error re-showing theme modal:`, modalError);
// Use followUp because showModal might fail *after* acknowledging
try {
if (!interaction.replied && !interaction.deferred) {
await interaction.reply({ content: 'Could not display the theme edit form. Please try again.' });
} else {
await interaction.followUp({ content: 'Could not display the theme edit form. Please try again.' });
}
} catch (followUpError) {
console.error(`Error sending followUp after modal error (Edit):`, followUpError);
}
// Keep pendingTheme for next attempt
return; // Stop if modal failed
}
// --- Action 2: Disable buttons on the *previous* confirmation message (Secondary effect) ---
try {
const originalMessage = interaction.message; // The message the 'Edit' button was on
if (originalMessage && originalMessage.components.length > 0) {
const disabledRows = originalMessage.components.map(row => {
const newRow = ActionRowBuilder.from(row);
newRow.components.forEach(component => component.setDisabled(true));
return newRow;
});
// Edit the *message*, not the interaction
await originalMessage.edit({ components: disabledRows }); // <<< USE message.edit()
}
} catch (e) {
// Ignore errors if message was deleted (10008) or interaction expired (10062)
if (e.code !== 10008 && e.code !== 10062) {
console.error("Error disabling theme confirm buttons (Edit):", e);
}
}
} // End Edit logic
return; // Handled confirmation button
}
// --- NEW: Sacrifice Button Handling (Player) ---
if (interaction.isButton() && interaction.customId.startsWith('sacrifice_')) {
// customId format: sacrifice_yes/no_<playerId>_<channelId>
const parts = interaction.customId.split('_');
const type = parts[1]; // 'yes' or 'no'
const playerId = parts[2];
const channelIdFromButton = parts[3];
// Permission Check: Must be the player the prompt was for
if (interaction.user.id !== playerId) {
await interaction.reply({ content: 'You cannot respond to another player\'s sacrifice prompt.' });
return;
}
// Context Check
if (game.textChannelId !== channelIdFromButton) {
await interaction.reply({ content: 'Game context mismatch.' });
return;
}
// Ensure player exists and is alive (might be redundant if prompt was recent, but safe)
const player = game.players[playerId];
if (!player || player.isDead) {
await interaction.reply({ content: 'Cannot process sacrifice: Player not found or already dead.' });
return;
}
// Disable buttons on the original DM
try {
const disabledRows = interaction.message.components.map(row => {
const newRow = ActionRowBuilder.from(row);
newRow.components.forEach(component => component.setDisabled(true));
return newRow;
});
await interaction.update({ components: disabledRows }); // Update original interaction first
} catch (e) {
if (e.code !== 10062 && e.code !== 10008) { // Ignore interaction/message already gone
console.error("Sacrifice Button: Error disabling buttons:", e);
}
// Don't return yet, try to proceed if possible
}
if (type === 'yes') {
// --- Player chose YES to Sacrifice ---
console.log(`Sacrifice Button: Player ${playerId} chose YES in game ${channelIdFromButton}. Showing reason modal.`);
// Build and show the modal
const reasonModal = new ModalBuilder()
.setCustomId(`sacrifice_reason_${playerId}_${channelIdFromButton}`) // Include player/channel ID
.setTitle('Describe Your Sacrifice');
const reasonInput = new TextInputBuilder()
.setCustomId('sacrificeReasonInput')
.setLabel("Reason/Final Action (Optional)")
.setStyle(TextInputStyle.Paragraph)
.setPlaceholder("Briefly describe your character's final moments...")
.setRequired(false);
const actionRow = new ActionRowBuilder().addComponents(reasonInput);
reasonModal.addComponents(actionRow);
try {
await interaction.showModal(reasonModal);
// The rest of the logic (martyrdom, death, scene change) happens in the modal submit handler below
} catch (modalError) {
console.error(`Sacrifice Button: Error showing modal to ${playerId}:`, modalError);
// Fallback: If modal fails, proceed with default reason and scene change
await interaction.followUp({ content: "Error showing reason input form. Proceeding with default reason." }).catch(console.error);
markPlayerDead(game, playerId, "Sacrificed for narrative control (Modal Error)", null); // Mark dead (no channel needed here)
const gameChannel = client.channels.cache.get(channelIdFromButton);
if (gameChannel) {
await gameChannel.send(`:skull: <@${playerId}> chooses to make the ultimate sacrifice! (Modal Error)`);
await extinguishCandle({ channel: gameChannel }, channelIdFromButton); // Trigger scene change
} else {
saveGameData(); // Save death at least
}
}
} else { // type === 'no'
// --- Player chose NO to Sacrifice ---
console.log(`Sacrifice Button: Player ${playerId} chose NO in game ${channelIdFromButton}. Triggering scene change.`);
// Announce choice in channel
const gameChannel = client.channels.cache.get(channelIdFromButton);
if (gameChannel) {
// Simply trigger a scene change
await extinguishCandle({ channel: gameChannel }, channelIdFromButton); // Pass a mock message object
} else {
console.error(`Sacrifice Button: Could not find game channel ${channelIdFromButton} to announce 'no' or change scene.`);
saveGameData(); // Save anyway? Maybe not needed if nothing changed.
}
}
return; // Handled sacrifice button
}
// Sacrifice Reason Modal Submit Handling
if (interaction.isModalSubmit() && interaction.customId.startsWith('sacrifice_reason_')) {
// customId format: sacrifice_reason_<playerId>_<channelId>
const parts = interaction.customId.split('_');
const playerId = parts[2];
const channelIdFromModal = parts[3];
// Permission Check: Must be the player who submitted
if (interaction.user.id !== playerId) {
await interaction.reply({ content: 'Invalid user for this modal submission.' });
return;
}
// Context Check
if (game.textChannelId !== channelIdFromModal) {
await interaction.reply({ content: 'Game context mismatch.' });
return;
}
const player = game.players[playerId];
if (!player || player.isDead) {
await interaction.reply({ content: 'Cannot process sacrifice reason: Player not found or already dead.' });
return;
}
// Get the reason from the modal
const reasonInput = interaction.fields.getTextInputValue('sacrificeReasonInput');
const sacrificeReason = sanitizeString(reasonInput.trim()) || "Sacrificed for narrative control"; // Use default if empty
console.log(`Sacrifice Modal: Received reason "${sacrificeReason}" from ${playerId} for game in ${channelIdFromModal}.`);
// Acknowledge modal submission quickly
await interaction.reply({ content: `Sacrifice reason received. Processing...` });
// --- Now continue with Martyrdom Check ---
let martyrdomGranted = false; // Flag
if (player.hopeDice > 0) {
const gmMember = await client.guilds.cache.get(game.guildId)?.members.fetch(game.gmId).catch(() => null);
if (gmMember) {
const gmConfirm = await requestConsent(
gmMember.user,
`<@${playerId}> (${player.name || player.playerUsername}) failed a conflict and chose to sacrifice.\nReason: ${sacrificeReason}\n\nDoes this act of sacrifice count as Martyrdom...?`,
`martyr_confirm_yes_${playerId}_${channelIdFromModal}`, // Use correct IDs
`martyr_confirm_no_${playerId}_${channelIdFromModal}`,
MARTYRDOM_TIMEOUT,
`Confirm Martyrdom...?`
);
// Store the reason in the pendingMartyrdom state (if it exists)
if (game.pendingMartyrdom && game.pendingMartyrdom.dyingPlayerId === playerId) {
game.pendingMartyrdom.reason = sacrificeReason;
saveGameData(); // Save the reason
console.log(`Sacrifice Modal: Stored reason "${sacrificeReason}" in pendingMartyrdom for ${playerId}. Waiting for GM confirmation.`);
// Inform player we're waiting for GM
await interaction.followUp({ content: "Reason recorded. Waiting for GM confirmation on Martyrdom before proceeding." }).catch(console.error);
} else {
// This case shouldn't happen if flow is correct, but handle it.
// GM confirmation might have timed out already, or state is weird.
console.warn(`Sacrifice Modal: pendingMartyrdom state missing or mismatched for ${playerId}. Proceeding with death using submitted reason.`);
await interaction.followUp({ content: "Reason recorded, but couldn't find pending Martyrdom state. Proceeding with death." }).catch(console.error);
const gameChannel = client.channels.cache.get(channelIdFromModal);
if (gameChannel) {
await gameChannel.send(`:skull: <@${playerId}> makes the ultimate sacrifice!`); // Announce
markPlayerDead(game, playerId, sacrificeReason, gameChannel); // Mark dead (saves)
await extinguishCandle({ channel: gameChannel }, channelIdFromModal); // Trigger scene change
} else {
markPlayerDead(game, playerId, sacrificeReason, null); // Mark dead (saves)
}
}
} else { // Couldn't find GM
await interaction.followUp({ content: "Reason recorded, but could not contact GM for Martyrdom confirmation. Proceeding with death." }).catch(console.error);
const gameChannel = client.channels.cache.get(channelIdFromModal);
if (gameChannel) {
await gameChannel.send(`:skull: <@${playerId}> makes the ultimate sacrifice! (Could not reach GM for Martyrdom check)`); // Announce
markPlayerDead(game, playerId, sacrificeReason, gameChannel); // Mark dead (saves)
await extinguishCandle({ channel: gameChannel }, channelIdFromModal); // Trigger scene change
} else {
markPlayerDead(game, playerId, sacrificeReason, null); // Mark dead (saves)
}
}
} else { // Player had no hope dice
await interaction.followUp({ content: "Reason recorded. Proceeding with death (no Martyrdom possible)." }).catch(console.error);
const gameChannel = client.channels.cache.get(channelIdFromModal);
if (gameChannel) {
await gameChannel.send(`:skull: <@${playerId}> makes the ultimate sacrifice!`); // Announce
markPlayerDead(game, playerId, sacrificeReason, gameChannel); // Mark dead (saves)
await extinguishCandle({ channel: gameChannel }, channelIdFromModal); // Trigger scene change
} else {
markPlayerDead(game, playerId, sacrificeReason, null); // Mark dead (saves)
}
}
return; // Handled modal submit
}
// --- GM Status Button Handling (Switching Views) ---
// This part handles clicking the Game or Player buttons to change the embed
if (interaction.isButton() && interaction.customId.startsWith('gmstatus_') && !interaction.customId.startsWith('gmstatus_toggle_ghosts_')) {
// customId format: gmstatus_<type>_<targetId>_<channelId> OR gmstatus_game_<channelId>
const parts = interaction.customId.split('_');
const type = parts[1]; // 'game' or 'player'
const channelIdFromButton = parts[parts.length - 1]; // Always last part
const statusGame = getGameData(channelIdFromButton);
if (!statusGame) {
await interaction.reply({ content: `The interaction chain for this button was broken, please use \`${BOT_PREFIX}gamestatus\` again.` });
return;
}
// Permission Check: Must be the GM
if (interaction.user.id !== statusGame.gmId) {
await interaction.reply({ content: 'Only the GM can view this status information.' });
return;
}
let newEmbed;
let targetId = null;
if (type === 'player') {
targetId = parts[2]; // Player ID is the third part
newEmbed = generatePlayerStatusEmbed(statusGame, targetId);
} else { // type === 'game'
let gameChannelName = `Channel ${channelIdFromButton}`;
try {
const channel = await client.channels.fetch(channelIdFromButton);
if (channel) gameChannelName = `#${channel.name}`;
} catch { /* Ignore error, use fallback */ }
newEmbed = generateGameStatusEmbed(statusGame, gameChannelName);
}
// Update button states (disable the clicked one, enable others)
const updatedComponents = interaction.message.components.map(row => {
const newRow = ActionRowBuilder.from(row);
newRow.components.forEach(component => {
if (component.data.type === ComponentType.Button) {
// Disable the button if its customId matches the interaction's customId
// Enable if it doesn't match
// Crucially, the toggle button should always be enabled
if (component.data.custom_id.startsWith('gmstatus_toggle_ghosts_')) {
component.setDisabled(false);
} else {
component.setDisabled(component.data.custom_id === interaction.customId);
}
}
});
return newRow;
});
try {
await interaction.update({ embeds: [newEmbed], components: updatedComponents });
} catch (error) {
console.error(`Error updating GM status interaction: ${error}`);
// Attempt a follow-up if update fails (e.g., interaction expired)
try {
await interaction.followUp({ content: 'Failed to update the status view.' });
} catch (followUpError) {
console.error(`Error sending follow-up for failed GM status update: ${followUpError}`);
}
}
return; // Handled GM status button, stop further processing
}
// --- Handle Ghosts Speak Toggle ---
if (interaction.isButton() && interaction.customId.startsWith('gmstatus_toggle_ghosts_')) {
const channelIdFromButton = interaction.customId.split('_')[3];
const statusGame = getGameData(channelIdFromButton);
if (!statusGame) {
await interaction.reply({ content: `The interaction chain for this button was broken, please use \`${BOT_PREFIX}gamestatus\` again.` });
return;
}
if (interaction.user.id !== statusGame.gmId) {
await interaction.reply({ content: 'Only the GM can change this setting.' });
return;
}
// Toggle the value (treat undefined as true, so toggling makes it false)
statusGame.ghostsSpeakTruths = !(statusGame.ghostsSpeakTruths !== false);
saveGameData();
console.log(`gmstatus_toggle_ghosts: Toggled ghostsSpeakTruths to ${statusGame.ghostsSpeakTruths} for game ${channelIdFromButton}`);
// --- Regenerate Embed and Buttons ---
let gameChannelName = `Channel ${channelIdFromButton}`;
try {
const channel = await client.channels.fetch(channelIdFromButton);
if (channel) gameChannelName = `#${channel.name}`;
} catch { /* Ignore */ }
// The embed remains the game status embed
const updatedEmbed = generateGameStatusEmbed(statusGame, gameChannelName);
const updatedComponents = [];
const updatedButtons = [];
// Game button: Should be DISABLED because the game embed is being shown
updatedButtons.push(
new ButtonBuilder()
.setCustomId(`gmstatus_game_${channelIdFromButton}`)
.setLabel(gameChannelName.substring(0, 80))
.setStyle(ButtonStyle.Primary)
.setDisabled(true) // <--- FIX: Disable the game button
);
// Updated Ghosts Speak button: Should be ENABLED
const ghostsSpeak = statusGame.ghostsSpeakTruths; // Get the new value
updatedButtons.push(
new ButtonBuilder()
.setCustomId(`gmstatus_toggle_ghosts_${channelIdFromButton}`)
.setLabel(`Ghosts Speak: ${ghostsSpeak ? 'ON' : 'OFF'}`) // Update label
.setStyle(ghostsSpeak ? ButtonStyle.Success : ButtonStyle.Danger) // Update style
.setDisabled(false) // <--- FIX: Keep enabled
);
// Player buttons: Should be ENABLED
for (const playerId of statusGame.playerOrder) {
const player = statusGame.players[playerId];
if (player) {
const playerName = player.name || player.playerUsername;
updatedButtons.push(
new ButtonBuilder()
.setCustomId(`gmstatus_player_${playerId}_${channelIdFromButton}`)
.setLabel(playerName.substring(0, 80))
.setStyle(ButtonStyle.Secondary)
.setDisabled(false) // <--- FIX: Ensure player buttons are enabled
);
}
}
// Arrange buttons into rows
for (let i = 0; i < updatedButtons.length; i += 5) {
const row = new ActionRowBuilder().addComponents(updatedButtons.slice(i, i + 5));
updatedComponents.push(row);
}
try {
// Update the interaction with the *same* embed but *new* buttons reflecting the toggle
await interaction.update({ embeds: [updatedEmbed], components: updatedComponents });
} catch (error) {
console.error(`Error updating GM status interaction after toggle: ${error}`);
// Attempt follow-up if update fails
try {
await interaction.followUp({ content: 'Failed to update the status view after toggle.' });
} catch { /* Ignore follow-up error */ }
}
return; // Handled toggle button
}
}
// Martyrdom Confirmation Button Handling (GM) ---
if (interaction.isButton() && interaction.customId.startsWith('martyr_confirm_')) {
// customId format: martyr_confirm_yes/no_<playerIdToKill>_<channelId>
const parts = interaction.customId.split('_');
const confirmationType = parts[2]; // 'yes' or 'no'
const playerIdToKill = parts[3];
const channelIdFromButton = parts[4];
const martyrGame = getGameData(channelIdFromButton);
if (!martyrGame) {
await interaction.reply({ content: `The interaction chain associated with this martyrdom confirmation was broken.` });
return;
}
// Permission Check: Must be the GM
if (interaction.user.id !== martyrGame.gmId) {
await interaction.reply({ content: 'Only the GM can respond to this confirmation.' });
return;
}
// State Check: Ensure this confirmation is still pending and matches the interaction
if (!martyrGame.pendingMartyrdom || martyrGame.pendingMartyrdom.dyingPlayerId !== playerIdToKill || martyrGame.pendingMartyrdom.gmMessageId !== interaction.message.id) {
await interaction.reply({ content: 'This martyrdom confirmation is no longer valid or has already been processed.' });
// Disable buttons on the potentially old message
try {
const disabledRow = new ActionRowBuilder().addComponents(
interaction.message.components[0].components.map(button => ButtonBuilder.from(button).setDisabled(true))
);
await interaction.update({ components: [disabledRow] });
} catch (e) {
if (e.code !== 10008 && e.code !== 10062) { // Ignore if message/interaction gone
console.error("martyr_confirm: Error disabling old buttons:", e);
}
}
return;
}
// Clear the GM timeout
if (martyrGame.pendingMartyrdom.gmTimeoutId) {
clearTimeout(martyrGame.pendingMartyrdom.gmTimeoutId);
martyrGame.pendingMartyrdom.gmTimeoutId = null; // Clear the stored ID
}
// Retrieve the reason before potentially deleting the pending state
const reason = martyrGame.pendingMartyrdom.reason;
const dyingPlayer = martyrGame.players[playerIdToKill];
const characterName = dyingPlayer?.name || dyingPlayer?.playerUsername || `<@${playerIdToKill}>`;
// Disable buttons on the GM's DM
try {
const disabledRow = new ActionRowBuilder().addComponents(
interaction.message.components[0].components.map(button => ButtonBuilder.from(button).setDisabled(true))
);
// Update the message content based on the choice
const updateContent = confirmationType === 'yes'
? `You confirmed martyrdom for ${characterName}. They will be prompted.`
: `You denied martyrdom for ${characterName}.`;
await interaction.update({ content: updateContent, components: [disabledRow] });
} catch (editError) {
// Ignore if interaction already acknowledged or message deleted
if (editError.code !== 10062 && editError.code !== 10008) {
console.error("martyr_confirm: Error disabling buttons:", editError);
}
}
const gameChannel = client.channels.cache.get(channelIdFromButton);
if (!gameChannel) {
console.error(`martyr_confirm: Could not find game channel ${channelIdFromButton}`);
await interaction.followUp({ content: `Error: Could not find the game channel <#${channelIdFromButton}>.` });
// Clean up pending state even on error
delete martyrGame.pendingMartyrdom;
saveGameData();
return;
}
if (confirmationType === 'yes') {
// GM confirmed martyrdom
console.log(`martyr_confirm: GM ${interaction.user.id} confirmed martyrdom for player ${playerIdToKill} in game ${channelIdFromButton}. Reason: ${reason}`);
try {
const dyingPlayerUser = await client.users.fetch(playerIdToKill);
// Pass the game object which now contains the pendingMartyrdom info (including reason)
await askPlayerToGiftHope(dyingPlayerUser, martyrGame, playerIdToKill);
// No need for followUp here as the interaction.update already confirmed
// Save game data (includes updated pendingMartyrdom with playerTimeoutId if set by askPlayerToGiftHope)
saveGameData();
} catch (error) {
console.error(`martyr_confirm: Error fetching dying player or calling askPlayerToGiftHope for ${playerIdToKill}:`, error);
await interaction.followUp({ content: `An error occurred trying to prompt the player <@${playerIdToKill}>. Proceeding as normal death.` });
// Fallback to normal death
delete martyrGame.pendingMartyrdom; // Clean up
markPlayerDead(martyrGame, playerIdToKill, reason, gameChannel); // markPlayerDead saves
}
} else { // confirmationType === 'no'
// GM denied martyrdom
console.log(`martyr_confirm: GM ${interaction.user.id} denied martyrdom for player ${playerIdToKill} in game ${channelIdFromButton}.`);
// Clean up pending state *before* calling markPlayerDead
delete martyrGame.pendingMartyrdom;
saveGameData(); // Save the cleanup
// No need for followUp here as the interaction.update already confirmed
// Proceed with normal death
markPlayerDead(martyrGame, playerIdToKill, reason, gameChannel); // markPlayerDead saves
}
return; // Handled martyrdom confirmation
}
// Hope Gifting Select Menu Handling (Player) ---
if (interaction.isStringSelectMenu() && interaction.customId.startsWith('gift_hope_select_')) {
// customId format: gift_hope_select_<dyingPlayerId>_<channelId>
const parts = interaction.customId.split('_');
const dyingPlayerId = parts[3];
const channelIdFromMenu = parts[4];
const hopeGame = getGameData(channelIdFromMenu);
if (!hopeGame) {
await interaction.reply({ content: `The interaction chain associated with this Hope gifting was broken.` });
return;
}
// Permission Check: Must be the dying player
if (interaction.user.id !== dyingPlayerId) {
await interaction.reply({ content: 'Only the character who died can choose who receives their Hope Die.' });
return;
}
// State Check: Ensure martyrdom was confirmed and is still pending for this player
if (!hopeGame.pendingMartyrdom || hopeGame.pendingMartyrdom.dyingPlayerId !== dyingPlayerId) {
await interaction.reply({ content: 'This action is no longer valid or has already been completed.' });
// Optionally disable components if message still exists
try {
const disabledComponents = interaction.message.components.map(row => {
const newRow = ActionRowBuilder.from(row);
newRow.components.forEach(component => component.setDisabled(true));
return newRow;
});
await interaction.update({ components: disabledComponents });
} catch (e) {
if (e.code !== 10008 && e.code !== 10062) { // Ignore if message/interaction gone
console.error("Error disabling old hope gift menu:", e);
}
}
return;
}
// Clear the player timeout
if (hopeGame.pendingMartyrdom.playerTimeoutId) {
clearTimeout(hopeGame.pendingMartyrdom.playerTimeoutId);
hopeGame.pendingMartyrdom.playerTimeoutId = null;
}
const recipientId = interaction.values[0];