-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
435 lines (372 loc) · 14.2 KB
/
index.js
File metadata and controls
435 lines (372 loc) · 14.2 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
import express from "express";
const app = express();
app.get("/", (_, res) => res.send("✅ Poll Bot is alive and running!"));
app.listen(process.env.PORT || 3000, () => {
console.log(`🌐 Keep-alive web server running on port ${process.env.PORT || 3000}`);
});
import pkg from "discord.js";
const {
Client,
GatewayIntentBits,
SlashCommandBuilder,
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
StringSelectMenuBuilder,
EmbedBuilder,
} = pkg;
import dotenv from "dotenv";
dotenv.config();
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
import fs from "fs";
const DATA_FILE = "./retreats.json";
const activities = new Map();
function saveState() {
fs.writeFileSync(DATA_FILE, JSON.stringify(Object.fromEntries(activities), null, 2));
}
let saveTimeout;
function queueSave() {
clearTimeout(saveTimeout);
saveTimeout = setTimeout(saveState, 2000);
}
function loadState() {
if (fs.existsSync(DATA_FILE)) {
const data = JSON.parse(fs.readFileSync(DATA_FILE));
for (const [id, state] of Object.entries(data)) activities.set(id, state);
}
}
loadState();
console.log(`🗂 Loaded ${activities.size} retreats from ${DATA_FILE}`);
// ----------------- WAITLIST PROMOTION -----------------
async function promoteWaitlist(state, activityName, interaction) {
const activity = state.data[activityName];
if (!activity) return;
if (activity.waitlist.length > 0 && activity.claimed.length < activity.capacity) {
const promotedUserId = activity.waitlist.shift();
activity.claimed.push(promotedUserId);
const user = await client.users.fetch(promotedUserId);
const dmMessage = `🎉 You’ve been **promoted** from the waitlist to **${activityName}** for **${state.title}**!`;
try {
await user.send(dmMessage);
} catch {
console.warn(`⚠️ Could not DM ${user.tag}`);
}
try {
await interaction.followUp({
content: `🎉 <@${promotedUserId}> has been promoted from waitlist to **${activityName}**!`,
ephemeral: true,
});
} catch {
console.warn("⚠️ Could not send ephemeral promotion follow-up.");
}
console.log(`🎯 Promoted ${promotedUserId} from waitlist to ${activityName}`);
queueSave(); // ✅ Save after promotion
}
}
// ----------------- READY -----------------
client.once("clientReady", async () => {
console.log(`✅ Logged in as ${client.user.tag}`);
const commands = [
new SlashCommandBuilder()
.setName("retreat")
.setDescription("Create a claimable activity signup (first come, first served).")
.addStringOption(o =>
o.setName("title").setDescription("Title of the signup post").setRequired(true)
)
.addStringOption(o =>
o
.setName("activities")
.setDescription("Activities as 'Name:Capacity, Name:Capacity'")
.setRequired(true)
),
new SlashCommandBuilder()
.setName("retreat_close")
.setDescription("Close an active retreat signup (disable buttons).")
.addStringOption(o =>
o
.setName("message_id")
.setDescription("Message ID of the signup post (optional if you want to select)")
.setRequired(false)
),
new SlashCommandBuilder()
.setName("retreat_results")
.setDescription("Show results for a retreat signup.")
.addStringOption(o =>
o
.setName("message_id")
.setDescription("Message ID of the signup post (optional if you want to select)")
.setRequired(false)
),
];
try {
await client.application.commands.set(commands);
console.log("🌍 Registered global slash commands!");
} catch (err) {
console.error("❌ Failed to register global commands:", err);
}
});
// ----------------- MAIN INTERACTION HANDLER -----------------
client.on("interactionCreate", async interaction => {
try {
// ----- /retreat -----
if (interaction.isChatInputCommand() && interaction.commandName === "retreat") {
const title = interaction.options.getString("title");
const list = interaction.options.getString("activities");
const parsed = {};
for (const part of list.split(",")) {
const [name, capStr] = part.split(":").map(s => s.trim());
const cap = parseInt(capStr);
if (!name || isNaN(cap)) {
return interaction.reply({
content: "❌ Invalid format. Use 'Name:Capacity, Name:Capacity'",
ephemeral: true,
});
}
parsed[name] = cap;
}
const embed = new EmbedBuilder()
.setTitle(title)
.setDescription(
"Click a button to choose your activity! You can only choose one activity at a time.\nUse **View Participants** to see all sign-ups."
)
.setColor(0x57f287);
for (const [name, cap] of Object.entries(parsed)) {
embed.addFields({ name: `${name} — 0/${cap}`, value: "_No one yet_", inline: false });
}
const claimRow = new ActionRowBuilder();
for (const [name] of Object.entries(parsed)) {
claimRow.addComponents(
new ButtonBuilder()
.setCustomId(`claim_${name}`)
.setLabel(name)
.setStyle(ButtonStyle.Primary)
);
}
const viewRow = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId("view_participants")
.setLabel("🔍 View Participants")
.setStyle(ButtonStyle.Secondary)
);
await interaction.reply({
embeds: [embed],
components: [claimRow, viewRow],
});
const msg = await interaction.fetchReply();
activities.set(msg.id, {
title,
data: Object.fromEntries(
Object.keys(parsed).map(k => [k, { capacity: parsed[k], claimed: [], waitlist: [] }])
),
closed: false,
});
queueSave(); // ✅ Save new retreat
return;
}
// ----- /retreat_close -----
if (interaction.isChatInputCommand() && interaction.commandName === "retreat_close") {
const messageId = interaction.options.getString("message_id");
if (!messageId) {
const openPolls = Array.from(activities.entries()).filter(([_, v]) => !v.closed);
if (openPolls.length === 0) {
return interaction.reply({
content: "✅ There are no open retreats to close!",
ephemeral: true,
});
}
const selectMenu = new StringSelectMenuBuilder()
.setCustomId("close_select")
.setPlaceholder("Select a retreat to close")
.addOptions(
openPolls.map(([id, v]) => ({
label: v.title,
description: `ID: ${id}`,
value: id,
}))
);
const row = new ActionRowBuilder().addComponents(selectMenu);
return interaction.reply({
content: "Select a retreat to close:",
components: [row],
ephemeral: true,
});
}
const state = activities.get(messageId);
if (!state)
return interaction.reply({
content: "❌ Could not find that retreat post (bot must still be running).",
ephemeral: true,
});
const channel = await interaction.channel.fetch();
const msg = await channel.messages.fetch(messageId);
const disabledRows = msg.components.map(componentRow => {
const newRow = new ActionRowBuilder();
for (const btn of componentRow.components) {
newRow.addComponents(ButtonBuilder.from(btn).setDisabled(true));
}
return newRow;
});
await msg.edit({ components: disabledRows });
state.closed = true;
queueSave(); // ✅ Save closure
return interaction.reply({
content: `🔒 **${state.title}** has been closed.`,
ephemeral: true,
});
}
// ----- CLOSE SELECTION -----
if (interaction.isStringSelectMenu() && interaction.customId === "close_select") {
const messageId = interaction.values[0];
const state = activities.get(messageId);
if (!state)
return interaction.reply({
content: "❌ That retreat could not be found.",
ephemeral: true,
});
const channel = await interaction.channel.fetch();
const msg = await channel.messages.fetch(messageId);
const disabledRows = msg.components.map(componentRow => {
const newRow = new ActionRowBuilder();
for (const btn of componentRow.components) {
newRow.addComponents(ButtonBuilder.from(btn).setDisabled(true));
}
return newRow;
});
await msg.edit({ components: disabledRows });
state.closed = true;
queueSave(); // ✅ Save closure
return interaction.reply({
content: `🔒 **${state.title}** has been closed.`,
ephemeral: true,
});
}
// ----- /retreat_results -----
if (interaction.isChatInputCommand() && interaction.commandName === "retreat_results") {
const messageId = interaction.options.getString("message_id");
if (!messageId) {
const openPolls = Array.from(activities.entries());
if (openPolls.length === 0) {
return interaction.reply({
content: "📭 No retreats found to show results for.",
ephemeral: true,
});
}
const selectMenu = new StringSelectMenuBuilder()
.setCustomId("results_select")
.setPlaceholder("Select a retreat to view results")
.addOptions(
openPolls.map(([id, v]) => ({
label: v.title,
description: `ID: ${id}`,
value: id,
}))
);
const row = new ActionRowBuilder().addComponents(selectMenu);
return interaction.reply({
content: "Select a retreat to view results:",
components: [row],
ephemeral: true,
});
}
const state = activities.get(messageId);
if (!state)
return interaction.reply({
content: "❌ Could not find that signup post (bot may have been restarted).",
ephemeral: true,
});
let report = `📊 **Results for ${state.title}:**\n\n`;
for (const [name, info] of Object.entries(state.data)) {
report += `**${name}** — ${info.claimed.length}/${info.capacity}\n`;
if (info.claimed.length > 0)
report += `• ${info.claimed.map(id => `<@${id}>`).join(", ")}\n`;
if (info.waitlist.length > 0)
report += `• Waitlist: ${info.waitlist.map(id => `<@${id}>`).join(", ")}\n`;
report += "\n";
}
return interaction.reply({ content: report, ephemeral: true });
}
// ----- RESULTS SELECTION -----
if (interaction.isStringSelectMenu() && interaction.customId === "results_select") {
const messageId = interaction.values[0];
const state = activities.get(messageId);
if (!state)
return interaction.reply({
content: "❌ That retreat could not be found.",
ephemeral: true,
});
let report = `📊 **Results for ${state.title}:**\n\n`;
for (const [name, info] of Object.entries(state.data)) {
report += `**${name}** — ${info.claimed.length}/${info.capacity}\n`;
if (info.claimed.length > 0)
report += `• ${info.claimed.map(id => `<@${id}>`).join(", ")}\n`;
if (info.waitlist.length > 0)
report += `• Waitlist: ${info.waitlist.map(id => `<@${id}>`).join(", ")}\n`;
report += "\n";
}
return interaction.reply({ content: report, ephemeral: true });
}
// ----- BUTTONS -----
if (interaction.isButton()) {
const state = activities.get(interaction.message.id);
if (!state)
return interaction.reply({
content: "⚠️ This signup expired.",
ephemeral: true,
});
await interaction.deferReply({ ephemeral: true });
// 🔍 View participants
if (interaction.customId === "view_participants") {
let report = `📋 **Participants for ${state.title}:**\n\n`;
for (const [name, info] of Object.entries(state.data)) {
report += `**${name}** — ${info.claimed.length}/${info.capacity}\n`;
if (info.claimed.length > 0)
report += `• Claimed: ${info.claimed.map(id => `<@${id}>`).join(", ")}\n`;
if (info.waitlist.length > 0)
report += `• Waitlist: ${info.waitlist.map(id => `<@${id}>`).join(", ")}\n`;
report += "\n";
}
return interaction.editReply({ content: report });
}
const [_, activityName] = interaction.customId.split("_");
if (state.closed)
return interaction.editReply({ content: "🔒 This signup is closed." });
const userId = interaction.user.id;
for (const info of Object.values(state.data)) {
info.claimed = info.claimed.filter(id => id !== userId);
info.waitlist = info.waitlist.filter(id => id !== userId);
}
const act = state.data[activityName];
if (!act) return interaction.editReply({ content: "Invalid activity." });
let msg;
if (act.claimed.length < act.capacity) {
act.claimed.push(userId);
msg = `✅ You chose **${activityName}** (slot ${act.claimed.length}/${act.capacity}).`;
} else {
act.waitlist.push(userId);
msg = `⚠️ **${activityName}** is full. You're on the waitlist (${act.waitlist.length}).`;
}
// Promote if space opens
for (const [name] of Object.entries(state.data)) {
await promoteWaitlist(state, name, interaction);
}
const embed = EmbedBuilder.from(interaction.message.embeds[0]);
const fields = Object.entries(state.data).map(([name, info]) => ({
name: `${name} — ${info.claimed.length}/${info.capacity}${
info.claimed.length >= info.capacity ? " (FULL)" : ""
}`,
value:
info.claimed.length === 0 && info.waitlist.length === 0
? "_No one yet_"
: "Use **View Participants**",
inline: false,
}));
embed.setFields(fields);
await interaction.message.edit({ embeds: [embed] });
await interaction.editReply({ content: msg });
queueSave(); // ✅ Save signup changes
}
} catch (err) {
console.error("❌ Interaction error:", err);
}
});
client.login(process.env.DISCORD_TOKEN);