-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.js
More file actions
731 lines (606 loc) · 30 KB
/
bot.js
File metadata and controls
731 lines (606 loc) · 30 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
const { Client, GatewayIntentBits, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, PermissionFlagsBits } = require('discord.js');
require('dotenv').config();
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.MessageContent
]
});
// Store active Secret Santa sessions
// Structure: { channelId: { organizer: userId, participants: Set, assignments: Map, messageId: string, receivedGifts: Set } }
const secretSantaSessions = new Map();
client.once('ready', () => {
console.log(`✅ Logged in as ${client.user.tag}`);
console.log(`Bot is ready and listening for commands!`);
});
// Helper function to shuffle array
function shuffleArray(array) {
const shuffled = [...array];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
// Helper function to create assignments (circular)
function createAssignments(participants) {
const shuffled = shuffleArray(participants);
const assignments = new Map();
for (let i = 0; i < shuffled.length; i++) {
const giver = shuffled[i];
const receiver = shuffled[(i + 1) % shuffled.length];
assignments.set(giver, receiver);
}
return assignments;
}
client.on('messageCreate', async (message) => {
// Ignore bot messages
if (message.author.bot) return;
// /secretsanta command
if (message.content.toLowerCase() === '/secretsanta') {
const channelId = message.channel.id;
// Check if there's already an active session
if (secretSantaSessions.has(channelId)) {
return message.reply('⚠️ There is already an active Secret Santa in this channel! Use `/assign` to close signups or wait for it to complete.');
}
// Create embed message
const embed = new EmbedBuilder()
.setColor('#FF0000')
.setTitle('🎅 Secret Santa Sign-Up! 🎄')
.setDescription('React with 🎁 to join the Secret Santa!\n\n**How it works:**\n• React to this message to participate\n• The organizer will use `/assign` to close signups and assign Secret Santas\n• You\'ll receive a DM with your assignment\n• Use `/ordered` when you order your gift\n• Use `/delivered` when your gift is delivered')
.addFields(
{ name: 'Organizer', value: `<@${message.author.id}>`, inline: true },
{ name: 'Participants', value: '0', inline: true }
)
.setFooter({ text: 'React with 🎁 to join!' })
.setTimestamp();
const sentMessage = await message.channel.send({ embeds: [embed] });
await sentMessage.react('🎁');
// Initialize session
secretSantaSessions.set(channelId, {
organizer: message.author.id,
participants: new Set(),
assignments: new Map(),
receivedGifts: new Set(),
messageId: sentMessage.id,
guildId: message.guild.id
});
console.log(`Secret Santa started in channel ${channelId} by ${message.author.tag}`);
}
// /assign command
if (message.content.toLowerCase() === '/assign') {
const channelId = message.channel.id;
const session = secretSantaSessions.get(channelId);
if (!session) {
return message.reply('⚠️ There is no active Secret Santa in this channel. Start one with `/secretsanta`');
}
if (session.organizer !== message.author.id) {
return message.reply('⚠️ Only the organizer can assign Secret Santas!');
}
if (session.participants.size < 2) {
return message.reply('⚠️ Need at least 2 participants to assign Secret Santas!');
}
// Create assignments
const participantArray = Array.from(session.participants);
session.assignments = createAssignments(participantArray);
// Send announcement in channel
const participantMentions = participantArray.map(id => `<@${id}>`).join(', ');
const announceEmbed = new EmbedBuilder()
.setColor('#00FF00')
.setTitle('🎁 Secret Santa Assignments Complete!')
.setDescription(`**Participants:** ${participantMentions}\n\nCheck your DMs for your Secret Santa assignment! 🎅`)
.setTimestamp();
await message.channel.send({ embeds: [announceEmbed] });
// Send DMs to each participant
let successCount = 0;
let failCount = 0;
const failedUsers = [];
for (const [giverId, receiverId] of session.assignments.entries()) {
try {
const giver = await client.users.fetch(giverId);
const receiver = await client.users.fetch(receiverId);
const channel = await client.channels.fetch(channelId);
const guild = await client.guilds.fetch(session.guildId);
const dmEmbed = new EmbedBuilder()
.setColor('#FF0000')
.setTitle('🎅 Your Secret Santa Assignment!')
.setDescription(`**Server:** ${guild.name}\n**Channel:** #${channel.name}\n\nYou are the Secret Santa for: **${receiver.username}**`)
.addFields(
{ name: '📝 What to do:', value: '• Get them a gift!\n• Use `/ordered` when you order the gift (in channel or DM me)\n• Use `/delivered` when the gift is delivered (in channel or DM me)\n• They can use `/received` to confirm receipt!' }
)
.setFooter({ text: 'Keep it secret! 🤫' })
.setTimestamp();
await giver.send({ embeds: [dmEmbed] });
successCount++;
console.log(`✅ Sent assignment to ${giver.tag}: ${receiver.tag}`);
} catch (error) {
console.error(`❌ Failed to DM user ${giverId}:`, error.message);
failCount++;
failedUsers.push(giverId);
}
}
// Report results
let resultMessage = `✅ Sent ${successCount} assignment(s)!`;
if (failCount > 0) {
const failedMentions = failedUsers.map(id => `<@${id}>`).join(', ');
resultMessage += `\n\n⚠️ **${failCount} user(s) failed to receive DMs:**\n${failedMentions}\n\n**Please enable DMs from server members in your Privacy Settings!**`;
}
await message.channel.send(resultMessage);
console.log(`Assignments completed for channel ${channelId}`);
}
// /finish command
if (message.content.toLowerCase() === '/finish') {
const channelId = message.channel.id;
const session = secretSantaSessions.get(channelId);
if (!session) {
return message.reply('⚠️ There is no active Secret Santa in this channel.');
}
if (session.organizer !== message.author.id) {
return message.reply('⚠️ Only the organizer can finish the Secret Santa!');
}
// Remove the session
secretSantaSessions.delete(channelId);
const finishEmbed = new EmbedBuilder()
.setColor('#00FF00')
.setTitle('🎄 Secret Santa Finished!')
.setDescription('The Secret Santa has been closed. Happy holidays! 🎅')
.setFooter({ text: 'Start a new one anytime with /secretsanta' })
.setTimestamp();
await message.channel.send({ embeds: [finishEmbed] });
console.log(`Secret Santa finished in channel ${channelId} by ${message.author.tag}`);
}
// /santastatus command
if (message.content.toLowerCase() === '/santastatus') {
const channelId = message.channel.id;
const session = secretSantaSessions.get(channelId);
if (!session) {
return message.reply('⚠️ There is no active Secret Santa in this channel.');
}
const totalParticipants = session.assignments.size; // Use assignments size, not participants
const assignmentsComplete = session.assignments.size > 0;
const receivedCount = session.receivedGifts.size;
const progressPercent = totalParticipants > 0 ? Math.round((receivedCount / totalParticipants) * 100) : 0;
// Create progress bar
const barLength = 10;
const filledBars = Math.round((receivedCount / totalParticipants) * barLength);
const progressBar = '🟩'.repeat(filledBars) + '⬜'.repeat(barLength - filledBars);
const statusEmbed = new EmbedBuilder()
.setColor('#3498DB')
.setTitle('📊 Secret Santa Status')
.addFields(
{ name: '👥 Total Participants', value: `${totalParticipants}`, inline: true },
{ name: '✅ Assignments Sent', value: assignmentsComplete ? 'Yes' : 'No', inline: true },
{ name: '🎁 Gifts Received', value: `${receivedCount}/${totalParticipants}`, inline: true },
{ name: '📈 Progress', value: `${progressBar}\n${progressPercent}% complete` }
)
.setFooter({ text: `Organizer: ${message.guild.members.cache.get(session.organizer)?.user.username || 'Unknown'}` })
.setTimestamp();
await message.channel.send({ embeds: [statusEmbed] });
}
// /participants command
if (message.content.toLowerCase() === '/participants') {
const channelId = message.channel.id;
const session = secretSantaSessions.get(channelId);
if (!session) {
return message.reply('⚠️ There is no active Secret Santa in this channel.');
}
// Get the list of participants
let participantList;
if (session.assignments.size > 0) {
// If assignments have been made, use those participants (frozen list)
const participantIds = Array.from(session.assignments.keys());
const participants = await Promise.all(
participantIds.map(async (id) => {
try {
const user = await client.users.fetch(id);
return user.username;
} catch (error) {
return `Unknown User (${id})`;
}
})
);
participantList = participants.map((name, index) => `${index + 1}. ${name}`).join('\n');
} else {
// If no assignments yet, show current sign-ups
const participantIds = Array.from(session.participants);
if (participantIds.length === 0) {
participantList = 'No participants yet';
} else {
const participants = await Promise.all(
participantIds.map(async (id) => {
try {
const user = await client.users.fetch(id);
return user.username;
} catch (error) {
return `Unknown User (${id})`;
}
})
);
participantList = participants.map((name, index) => `${index + 1}. ${name}`).join('\n');
}
}
const participantsEmbed = new EmbedBuilder()
.setColor('#E74C3C')
.setTitle('🎅 Secret Santa Participants')
.setDescription(participantList)
.addFields(
{ name: 'Status', value: session.assignments.size > 0 ? '✅ Assignments sent' : '⏳ Waiting for assignments' }
)
.setTimestamp();
await message.channel.send({ embeds: [participantsEmbed] });
}
// /ordered command - can be used in DM or channel
if (message.content.toLowerCase().startsWith('/ordered')) {
const userId = message.author.id;
// If in DM, find the user's Secret Santa session(s)
if (message.channel.type === 1) { // DM channel
const userSessions = [];
// Find all sessions where this user is a participant with assignments
for (const [channelId, session] of secretSantaSessions.entries()) {
if (session.assignments.has(userId)) {
userSessions.push({ channelId, session });
}
}
if (userSessions.length === 0) {
return message.reply('⚠️ You are not participating in any active Secret Santa with assignments.');
}
if (userSessions.length === 1) {
// Auto-infer the session
const { session } = userSessions[0];
await sendOrderedNotification(message, session, userId);
} else {
// Multiple sessions - ask user to specify
const sessionList = await Promise.all(userSessions.map(async ({ channelId, session }, index) => {
try {
const channel = await client.channels.fetch(channelId);
const guild = await client.guilds.fetch(session.guildId);
return `${index + 1}. **${guild.name}** - #${channel.name}`;
} catch (error) {
return `${index + 1}. Channel ID: ${channelId}`;
}
}));
const listEmbed = new EmbedBuilder()
.setColor('#FFA500')
.setTitle('🎁 Multiple Secret Santas Found')
.setDescription('You are participating in multiple Secret Santas. Please specify which one:\n\n' + sessionList.join('\n') + '\n\nUse: `/ordered <number>`')
.setTimestamp();
return message.reply({ embeds: [listEmbed] });
}
} else {
// In channel - use that channel's session
const channelId = message.channel.id;
const session = secretSantaSessions.get(channelId);
if (!session || session.assignments.size === 0) {
return message.reply('⚠️ There is no active Secret Santa with assignments in this channel.');
}
if (!session.assignments.has(userId)) {
return message.reply('⚠️ You are not participating in this Secret Santa!');
}
// Delete the command message for privacy
try {
await message.delete();
} catch (error) {
console.log('Could not delete message');
}
await sendOrderedNotification(message, session, userId);
}
}
// /delivered command - can be used in DM or channel
if (message.content.toLowerCase().startsWith('/delivered')) {
const userId = message.author.id;
// If in DM, find the user's Secret Santa session(s)
if (message.channel.type === 1) { // DM channel
const userSessions = [];
// Find all sessions where this user is a participant with assignments
for (const [channelId, session] of secretSantaSessions.entries()) {
if (session.assignments.has(userId)) {
userSessions.push({ channelId, session });
}
}
if (userSessions.length === 0) {
return message.reply('⚠️ You are not participating in any active Secret Santa with assignments.');
}
if (userSessions.length === 1) {
// Auto-infer the session
const { session } = userSessions[0];
await sendDeliveredNotification(message, session, userId);
} else {
// Multiple sessions - ask user to specify
const sessionList = await Promise.all(userSessions.map(async ({ channelId, session }, index) => {
try {
const channel = await client.channels.fetch(channelId);
const guild = await client.guilds.fetch(session.guildId);
return `${index + 1}. **${guild.name}** - #${channel.name}`;
} catch (error) {
return `${index + 1}. Channel ID: ${channelId}`;
}
}));
const listEmbed = new EmbedBuilder()
.setColor('#00FF00')
.setTitle('🎁 Multiple Secret Santas Found')
.setDescription('You are participating in multiple Secret Santas. Please specify which one:\n\n' + sessionList.join('\n') + '\n\nUse: `/delivered <number>`')
.setTimestamp();
return message.reply({ embeds: [listEmbed] });
}
} else {
// In channel - use that channel's session
const channelId = message.channel.id;
const session = secretSantaSessions.get(channelId);
if (!session || session.assignments.size === 0) {
return message.reply('⚠️ There is no active Secret Santa with assignments in this channel.');
}
if (!session.assignments.has(userId)) {
return message.reply('⚠️ You are not participating in this Secret Santa!');
}
// Delete the command message for privacy
try {
await message.delete();
} catch (error) {
console.log('Could not delete message');
}
await sendDeliveredNotification(message, session, userId);
}
}
// /received command - can be used in DM or channel
if (message.content.toLowerCase().startsWith('/received')) {
const userId = message.author.id;
// If in DM, find the user's Secret Santa session(s)
if (message.channel.type === 1) { // DM channel
const userSessions = [];
// Find all sessions where this user is a participant (as a receiver in assignments)
for (const [channelId, session] of secretSantaSessions.entries()) {
// Check if user is either a giver or receiver in assignments
const isParticipant = session.assignments.has(userId) ||
Array.from(session.assignments.values()).includes(userId);
if (isParticipant && session.assignments.size > 0) {
userSessions.push({ channelId, session });
}
}
if (userSessions.length === 0) {
return message.reply('⚠️ You are not participating in any active Secret Santa with assignments.');
}
if (userSessions.length === 1) {
// Auto-infer the session
const { session } = userSessions[0];
await sendReceivedNotification(message, session, userId);
} else {
// Multiple sessions - ask user to specify
const sessionList = await Promise.all(userSessions.map(async ({ channelId, session }, index) => {
try {
const channel = await client.channels.fetch(channelId);
const guild = await client.guilds.fetch(session.guildId);
return `${index + 1}. **${guild.name}** - #${channel.name}`;
} catch (error) {
return `${index + 1}. Channel ID: ${channelId}`;
}
}));
const listEmbed = new EmbedBuilder()
.setColor('#9B59B6')
.setTitle('🎁 Multiple Secret Santas Found')
.setDescription('You are participating in multiple Secret Santas. Please specify which one:\n\n' + sessionList.join('\n') + '\n\nUse: `/received <number>`')
.setTimestamp();
return message.reply({ embeds: [listEmbed] });
}
} else {
// In channel - use that channel's session
const channelId = message.channel.id;
const session = secretSantaSessions.get(channelId);
if (!session || session.assignments.size === 0) {
return message.reply('⚠️ There is no active Secret Santa with assignments in this channel.');
}
// Check if user is in the assignments (either as giver or receiver)
const isParticipant = session.assignments.has(userId) ||
Array.from(session.assignments.values()).includes(userId);
if (!isParticipant) {
return message.reply('⚠️ You are not participating in this Secret Santa!');
}
// Delete the command message for privacy
try {
await message.delete();
} catch (error) {
console.log('Could not delete message');
}
await sendReceivedNotification(message, session, userId);
}
}
});
// Helper function to send ordered notification
async function sendOrderedNotification(message, session, userId) {
const receiverId = session.assignments.get(userId);
if (!receiverId) {
return message.reply('⚠️ Could not find your assignment. Please contact the organizer.');
}
try {
const receiver = await client.users.fetch(receiverId);
// Send anonymous notification to receiver
const notifyEmbed = new EmbedBuilder()
.setColor('#FFA500')
.setTitle('🎁 Gift Update!')
.setDescription('Good news! Your Secret Santa has ordered your gift! 🛍️')
.setFooter({ text: 'Stay tuned for delivery!' })
.setTimestamp();
await receiver.send({ embeds: [notifyEmbed] });
// Confirm to sender
const confirmEmbed = new EmbedBuilder()
.setColor('#00FF00')
.setTitle('✅ Notification Sent!')
.setDescription(`Your recipient has been notified that their gift has been ordered!`)
.setTimestamp();
await message.reply({ embeds: [confirmEmbed] });
console.log(`${message.author.tag} marked gift as ordered for ${receiver.tag}`);
} catch (error) {
console.error('Error sending ordered notification:', error);
await message.reply('⚠️ Could not send notification. Please try again.');
}
}
// Helper function to send delivered notification
async function sendDeliveredNotification(message, session, userId) {
const receiverId = session.assignments.get(userId);
if (!receiverId) {
return message.reply('⚠️ Could not find your assignment. Please contact the organizer.');
}
try {
const receiver = await client.users.fetch(receiverId);
// Send anonymous notification to receiver
const notifyEmbed = new EmbedBuilder()
.setColor('#00FF00')
.setTitle('🎁 Gift Delivered!')
.setDescription('Your Secret Santa gift has been delivered! 🎉\n\nCheck your mailbox or doorstep! 📦')
.setFooter({ text: 'Happy Holidays!' })
.setTimestamp();
await receiver.send({ embeds: [notifyEmbed] });
// Confirm to sender
const confirmEmbed = new EmbedBuilder()
.setColor('#00FF00')
.setTitle('✅ Notification Sent!')
.setDescription(`Your recipient has been notified that their gift has been delivered!`)
.setTimestamp();
await message.reply({ embeds: [confirmEmbed] });
console.log(`${message.author.tag} marked gift as delivered for ${receiver.tag}`);
} catch (error) {
console.error('Error sending delivered notification:', error);
await message.reply('⚠️ Could not send notification. Please try again.');
}
}
// Helper function to send received notification
async function sendReceivedNotification(message, session, userId) {
// Check if already marked as received
if (session.receivedGifts.has(userId)) {
return message.reply('⚠️ You have already confirmed receipt of your gift!');
}
// Find who gave this user a gift (reverse lookup)
let giverId = null;
for (const [gId, rId] of session.assignments.entries()) {
if (rId === userId) {
giverId = gId;
break;
}
}
if (!giverId) {
return message.reply('⚠️ Could not find your Secret Santa. Please contact the organizer.');
}
try {
const giver = await client.users.fetch(giverId);
// Mark as received
session.receivedGifts.add(userId);
// Calculate progress using frozen assignments count
const totalParticipants = session.assignments.size;
const receivedCount = session.receivedGifts.size;
const progressPercent = Math.round((receivedCount / totalParticipants) * 100);
// Send notification to giver
const notifyEmbed = new EmbedBuilder()
.setColor('#9B59B6')
.setTitle('🎉 Gift Received!')
.setDescription('Great news! Your Secret Santa recipient has confirmed they received their gift! 🎁\n\nThank you for participating! 🎅')
.addFields(
{ name: '📊 Overall Progress', value: `${receivedCount}/${totalParticipants} participants received their gifts (${progressPercent}%)` }
)
.setFooter({ text: 'Mission accomplished!' })
.setTimestamp();
await giver.send({ embeds: [notifyEmbed] });
// Confirm to receiver
const confirmEmbed = new EmbedBuilder()
.setColor('#00FF00')
.setTitle('✅ Notification Sent!')
.setDescription(`Your Secret Santa has been notified that you received your gift!\n\n**Progress:** ${receivedCount}/${totalParticipants} gifts received (${progressPercent}%)`)
.setTimestamp();
await message.reply({ embeds: [confirmEmbed] });
console.log(`${message.author.tag} confirmed receipt, notified ${giver.tag} (Progress: ${receivedCount}/${totalParticipants})`);
// If all gifts received, send celebration message
if (receivedCount === totalParticipants) {
// Find the channel
for (const [channelId, sess] of secretSantaSessions.entries()) {
if (sess === session) {
try {
const channel = await client.channels.fetch(channelId);
const celebrationEmbed = new EmbedBuilder()
.setColor('#FFD700')
.setTitle('🎄 Secret Santa Complete! 🎄')
.setDescription('🎉 **All participants have received their gifts!** 🎉\n\nThank you everyone for participating! Happy holidays! 🎅🎁')
.setFooter({ text: 'Use /finish to close this Secret Santa' })
.setTimestamp();
await channel.send({ embeds: [celebrationEmbed] });
} catch (error) {
console.error('Could not send celebration message:', error);
}
break;
}
}
}
} catch (error) {
console.error('Error sending received notification:', error);
await message.reply('⚠️ Could not send notification. Please try again.');
}
}
// Handle reactions for sign-up
client.on('messageReactionAdd', async (reaction, user) => {
// Ignore bot reactions
if (user.bot) return;
// Handle partial reactions
if (reaction.partial) {
try {
await reaction.fetch();
} catch (error) {
console.error('Error fetching reaction:', error);
return;
}
}
const channelId = reaction.message.channel.id;
const session = secretSantaSessions.get(channelId);
// Check if this is a Secret Santa sign-up message
if (!session || session.messageId !== reaction.message.id) return;
if (reaction.emoji.name !== '🎁') return;
// Add participant
session.participants.add(user.id);
// Update the embed
try {
const message = await reaction.message.fetch();
const embed = message.embeds[0];
const updatedEmbed = EmbedBuilder.from(embed)
.setFields(
{ name: 'Organizer', value: `<@${session.organizer}>`, inline: true },
{ name: 'Participants', value: `${session.participants.size}`, inline: true }
);
await message.edit({ embeds: [updatedEmbed] });
console.log(`${user.tag} joined Secret Santa in channel ${channelId}`);
} catch (error) {
console.error('Error updating embed:', error);
}
});
// Handle reaction removal
client.on('messageReactionRemove', async (reaction, user) => {
if (user.bot) return;
if (reaction.partial) {
try {
await reaction.fetch();
} catch (error) {
console.error('Error fetching reaction:', error);
return;
}
}
const channelId = reaction.message.channel.id;
const session = secretSantaSessions.get(channelId);
if (!session || session.messageId !== reaction.message.id) return;
if (reaction.emoji.name !== '🎁') return;
// Remove participant
session.participants.delete(user.id);
// Update the embed
try {
const message = await reaction.message.fetch();
const embed = message.embeds[0];
const updatedEmbed = EmbedBuilder.from(embed)
.setFields(
{ name: 'Organizer', value: `<@${session.organizer}>`, inline: true },
{ name: 'Participants', value: `${session.participants.size}`, inline: true }
);
await message.edit({ embeds: [updatedEmbed] });
console.log(`${user.tag} left Secret Santa in channel ${channelId}`);
} catch (error) {
console.error('Error updating embed:', error);
}
});
// Login
client.login(process.env.DISCORD_BOT_TOKEN);