This repository was archived by the owner on Sep 28, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
210 lines (179 loc) · 7.62 KB
/
Copy pathindex.js
File metadata and controls
210 lines (179 loc) · 7.62 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
const { Client, GatewayIntentBits, Partials, Collection, ChannelType } = require('discord.js');
const fs = require('fs');
const path = require('path');
require('dotenv').config();
const { ARCHIVE_CATEGORY_IDS, STAFF_ROLE_ID } = require('./utils/constants');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.DirectMessages
],
partials: [Partials.Channel] // Needed to DM users!
});
// Export client globally for all handlers to use (for DMs)
module.exports.client = client;
global.client = client; // Also attach to global for old handler logic
// --- Command loader ---
client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(path.join(commandsPath, file));
if (command.data && command.execute) {
client.commands.set(command.data.name, command);
}
}
// --- Interaction handlers ---
const handleButton = require('./interactions/buttons.js');
const handleModal = require('./interactions/modals.js');
client.on('interactionCreate', async interaction => {
try {
// Slash commands
if (interaction.isChatInputCommand()) {
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
if (!interaction.replied && !interaction.deferred) {
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
}
return;
}
// Buttons
if (interaction.isButton()) {
await handleButton(interaction);
return;
}
// Modals
if (interaction.isModalSubmit()) {
await handleModal(interaction);
return;
}
// Add select menu, etc as needed
} catch (err) {
console.error('Interaction Handler Error:', err);
if (!interaction.replied && !interaction.deferred) {
try {
await interaction.reply({ content: '❌ An error occurred.', ephemeral: true });
} catch {}
}
}
});
// --- Forward user DMs to their open ticket channel ---
const USER_MAP_PATH = path.join(__dirname, 'utils/ticketUserMap.json');
client.on('messageCreate', async (msg) => {
// Only handle user DMs, ignore bots and guild messages
if (msg.author.bot || msg.channel.type !== ChannelType.DM) return;
// Load map
let userMap = {};
try {
userMap = JSON.parse(fs.readFileSync(USER_MAP_PATH, 'utf8'));
} catch {
userMap = {};
}
// Find the user's ticket entry, if any
const entry = Object.entries(userMap).find(([, data]) => data.userId === msg.author.id);
if (!entry) {
await msg.reply("❌ You don't have any active tickets. Please open one in the server to continue.");
return;
}
const [ticketId, data] = entry;
// If already marked closed, stop forwarding
if (data.isClosed) {
await msg.reply('Your ticket has been closed. Please open a new ticket in the server to continue.');
return;
}
// Try to fetch the ticket channel
const ch = await client.channels.fetch(data.channelId).catch(() => null);
const archivedIds = Object.values(ARCHIVE_CATEGORY_IDS);
// If channel is missing, archived (by parent), or renamed to archived-*, mark closed and stop
if (!ch || archivedIds.includes(ch.parentId) || (ch.name && ch.name.startsWith('archived-'))) {
userMap[ticketId] = { ...(userMap[ticketId] || {}), isClosed: true, closedAt: Date.now() };
fs.writeFileSync(USER_MAP_PATH, JSON.stringify(userMap, null, 2));
await msg.reply('Your ticket has been closed. Please open a new ticket in the server to continue.');
return;
}
// Still open → forward DM into the ticket channel
await ch.send({
content: `**${msg.author.tag}:** ${msg.content || ''}`,
files: msg.attachments.size ? [...msg.attachments.values()] : [],
});
});
client.once('ready', () => {
console.log(`✅ Logged in as ${client.user.tag}`);
});
// --- Auto Reminder System for Tickets ---
const REMINDER_INTERVAL_MS = 60 * 1000; // check every 1 min
const REM_THRESHOLDS_MS = [5 * 60 * 1000, 30 * 60 * 1000, 60 * 60 * 1000]; // 5m, 30m, 1h
// Helpers: store reminder stage in channel topic as "[rem:N]"
function getReminderStageFromTopic(topic) {
if (!topic) return 0;
const m = topic.match(/\[rem:(\d)\]/);
const n = m ? parseInt(m[1], 10) : 0;
return Number.isFinite(n) ? n : 0;
}
async function setReminderStageInTopic(channel, stage) {
try {
const current = channel.topic || '';
const next = current.includes('[rem:')
? current.replace(/\[rem:\d\]/, `[rem:${stage}]`)
: (current ? `${current} [rem:${stage}]` : `[rem:${stage}]`);
if (next !== current) await channel.setTopic(next);
} catch (e) {
console.warn('[Reminders] Unable to set topic for channel', channel.id, e?.message || e);
}
}
setInterval(async () => {
let userMap = {};
if (fs.existsSync(USER_MAP_PATH)) {
try { userMap = JSON.parse(fs.readFileSync(USER_MAP_PATH, 'utf8')); } catch { userMap = {}; }
}
const now = Date.now();
for (const [ticketId, data] of Object.entries(userMap)) {
const channel = await client.channels.fetch(data.channelId).catch(() => null);
if (!channel) continue;
const archivedIds = Object.values(ARCHIVE_CATEGORY_IDS);
// Skip archived channels
if (archivedIds.includes(channel.parentId) || (channel.name && channel.name.startsWith('archived-'))) continue;
// Determine status: Pending via name; Unclaimed via embed text
const isPending = channel.name.startsWith('pending-');
// Fetch a handful of recent messages to find the staff embed
const msgs = await channel.messages.fetch({ limit: 20 }).catch(() => null);
const botMsg = msgs ? Array.from(msgs.values()).find(m => m.author?.id === client.user.id && m.embeds?.length) : null;
const embed = botMsg?.embeds?.[0];
const desc = embed?.description || '';
const isUnclaimed = /\*\*Assigned to:\*\*\s*Unclaimed/i.test(desc);
// If neither pending nor unclaimed, no reminders needed
if (!isPending && !isUnclaimed) continue;
// Elapsed since channel creation
const createdAt = channel.createdTimestamp || (Date.parse(channel.createdAt) || now);
const elapsed = now - createdAt;
// Compute which threshold we're at: 0 (none), 1 (5m), 2 (30m), 3 (1h)
let targetStage = 0;
if (elapsed >= REM_THRESHOLDS_MS[0]) targetStage = 1;
if (elapsed >= REM_THRESHOLDS_MS[1]) targetStage = 2;
if (elapsed >= REM_THRESHOLDS_MS[2]) targetStage = 3;
const currentStage = getReminderStageFromTopic(channel.topic);
if (targetStage > currentStage) {
// Send the appropriate reminder once per stage
try {
if (targetStage === 1) {
await channel.send(`<@&${STAFF_ROLE_ID}> ⚠️ This ticket has not been handled for **5 minutes** (${isPending ? 'pending approval' : 'unclaimed'}).`);
} else if (targetStage === 2) {
await channel.send(`<@&${STAFF_ROLE_ID}> ⏰ **30 minutes** elapsed and this ticket is still ${isPending ? 'pending' : 'unclaimed'}. Please take action.`);
} else if (targetStage === 3) {
await channel.send(`<@&${STAFF_ROLE_ID}> ⛳ **1 hour** elapsed — ticket remains ${isPending ? 'pending approval' : 'unclaimed'}. Prioritize this.`);
}
} catch (e) {
console.warn('[Reminders] Failed to send reminder in', channel.id, e?.message || e);
}
await setReminderStageInTopic(channel, targetStage);
}
}
}, REMINDER_INTERVAL_MS);
client.login(process.env.TOKEN);