-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
421 lines (366 loc) · 14.4 KB
/
index.js
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
require('dotenv').config();
const { Client, GatewayIntentBits, REST, Routes, SlashCommandBuilder } = require('discord.js');
const { createClient } = require('@supabase/supabase-js');
// Initialize Discord client
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
],
});
// Initialize Supabase client
const supabase = createClient(
process.env.SUPABASE_URL,
process.env.SUPABASE_SERVICE_ROLE_KEY
);
// Command registration
const commands = [
{
name: 'node',
description: 'Verify your node and get roles',
options: [{
name: 'nodeid',
description: 'Your Node ID',
type: 3, // STRING type
required: true
}],
default_member_permissions: null, // Allow everyone to use the command
dm_permission: false
},
{
name: 'checkroles',
description: 'Check if your node is still active',
default_member_permissions: null, // Allow everyone to use the command
dm_permission: false
}
];
// Register commands when bot starts
client.once('ready', async () => {
try {
console.log('Started refreshing application (/) commands.');
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN);
// Register commands for the first guild the bot is in
const guild = client.guilds.cache.first();
if (!guild) {
console.error('No guild found!');
return;
}
console.log(`Registering commands for guild: ${guild.name} (${guild.id})`);
try {
// Delete existing commands first
console.log('Deleting existing commands...');
// Delete guild commands
await rest.put(Routes.applicationGuildCommands(client.user.id, guild.id), { body: [] });
console.log('Successfully deleted existing commands.');
// Register new commands
console.log('Registering new commands...');
const data = await rest.put(
Routes.applicationGuildCommands(client.user.id, guild.id),
{ body: commands }
);
console.log(`Successfully registered ${data.length} commands!`);
// Start the role check interval
setInterval(() => checkInactiveNodes(guild), 24 * 60 * 60 * 1000);
} catch (error) {
console.error('Error managing commands:', error);
}
} catch (error) {
console.error('Error in ready event:', error);
}
});
// Function to check and remove roles from inactive nodes
async function checkInactiveNodes(guild, specificMember = null) {
try {
console.log('Checking for inactive nodes...');
// Get both roles
const activeRole = guild.roles.cache.find(r => r.name === 'Active Participant');
const inactiveRole = guild.roles.cache.find(r => r.name === 'Inactive Participant');
if (!activeRole) {
console.error('Active Participant role not found');
return false;
}
if (!inactiveRole) {
console.error('Inactive Participant role not found');
return false;
}
// If checking a specific member
if (specificMember) {
console.log(`Checking status for member: ${specificMember.user.tag} (${specificMember.user.id})`);
// Get the most recent node record for this specific Discord user
const { data: nodeRecords, error } = await supabase
.from('node_records')
.select('*')
.eq('discord_user_id', specificMember.user.id)
.order('timestamp', { ascending: false })
.limit(1);
if (error) {
console.error('Error checking node records:', error);
return false;
}
// Get one week ago timestamp
const oneWeekAgo = new Date();
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
// Check if node is inactive
const isInactive = !nodeRecords.length || new Date(nodeRecords[0].timestamp) < oneWeekAgo;
console.log(`Node status - Records exist: ${nodeRecords.length > 0}, Last timestamp: ${nodeRecords.length ? new Date(nodeRecords[0].timestamp).toISOString() : 'none'}, Is inactive: ${isInactive}`);
if (isInactive) {
// Remove Active role and add Inactive role
if (specificMember.roles.cache.has(activeRole.id)) {
await specificMember.roles.remove(activeRole);
await specificMember.roles.add(inactiveRole);
console.log(`Changed ${specificMember.user.tag} to inactive status`);
}
return false;
} else {
// Add Active role and remove Inactive role if needed
if (specificMember.roles.cache.has(inactiveRole.id)) {
await specificMember.roles.remove(inactiveRole);
await specificMember.roles.add(activeRole);
console.log(`Changed ${specificMember.user.tag} to active status`);
}
return true;
}
}
// If checking all members
const membersWithRole = guild.members.cache.filter(member =>
member.roles.cache.has(activeRole.id)
);
const oneWeekAgo = new Date();
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
for (const [_, member] of membersWithRole) {
const { data: nodeRecords, error } = await supabase
.from('node_records')
.select('*')
.eq('discord_user_id', member.user.id)
.order('timestamp', { ascending: false })
.limit(1);
if (error) {
console.error('Error checking node records:', error);
continue;
}
if (!nodeRecords.length || new Date(nodeRecords[0].timestamp) < oneWeekAgo) {
try {
await member.roles.remove(activeRole);
await member.roles.add(inactiveRole);
console.log(`Changed ${member.user.tag} to inactive status due to inactivity`);
} catch (error) {
console.error(`Error updating roles for ${member.user.tag}:`, error);
}
}
}
} catch (error) {
console.error('Error in checkInactiveNodes:', error);
return false;
}
}
// Handle slash commands
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === 'node') {
try {
await interaction.deferReply({ ephemeral: true });
// Check bot permissions first
if (!interaction.guild.members.me.permissions.has('ManageRoles')) {
await interaction.editReply({
content: '❌ Bot is missing permissions. Please give the bot "Manage Roles" permission and make sure its role is above the roles.',
ephemeral: true
});
return;
}
const nodeId = interaction.options.getString('nodeid');
console.log(`Processing verification for user: ${interaction.user.tag}`);
// First, check if this Discord user already has a node
const { data: existingUserNodes, error: userCheckError } = await supabase
.from('node_records')
.select('node_id')
.eq('discord_user_id', interaction.user.id)
.limit(1);
if (userCheckError) {
console.error('Error checking existing user nodes:', userCheckError);
await interaction.editReply({
content: '❌ Error checking user status.',
ephemeral: true
});
return;
}
if (existingUserNodes && existingUserNodes.length > 0) {
await interaction.editReply({
content: '❌ You already have a node associated with your Discord account. Please contact the moderators if you need to change your node association.',
ephemeral: true
});
return;
}
// Then, check if the node is already associated with another Discord user
const { data: existingNodeUser, error: nodeCheckError } = await supabase
.from('node_records')
.select('discord_user_id')
.eq('node_id', nodeId)
.not('discord_user_id', 'is', null)
.limit(1);
if (nodeCheckError) {
console.error('Error checking node association:', nodeCheckError);
await interaction.editReply({
content: '❌ Error checking node status.',
ephemeral: true
});
return;
}
if (existingNodeUser && existingNodeUser.length > 0) {
await interaction.editReply({
content: '❌ This node is already associated with another Discord user. Please contact the moderators if you believe this is an error.',
ephemeral: true
});
return;
}
// Now check if the node exists and is active (within last 24 hours)
const { data: existingNode, error: findError } = await supabase
.from('node_records')
.select('*')
.eq('node_id', nodeId)
.order('timestamp', { ascending: false })
.limit(1);
if (findError) {
console.error('Error finding node:', findError);
await interaction.editReply({
content: '❌ Error checking node status.',
ephemeral: true
});
return;
}
if (!existingNode || existingNode.length === 0) {
console.log('Node verification failed for user:', interaction.user.tag);
await interaction.editReply({
content: '❌ No node found with this ID. However, the bot only works for nodes setup using the [Codex CLI](https://github.com/codex-storage/cli) and does not work on manual installation of Codex as we do not log node information from the manual process.',
ephemeral: true
});
return;
}
// Check if node is active (last update within 24 hours)
const oneDayAgo = new Date();
oneDayAgo.setDate(oneDayAgo.getDate() - 1);
if (new Date(existingNode[0].timestamp) < oneDayAgo) {
await interaction.editReply({
content: '❌ This node has not been active in the last 24 hours. Please make sure your node is running and try again.',
ephemeral: true
});
return;
}
// Get all roles first
const altruisticRole = interaction.guild.roles.cache.find(r => r.name === 'Altruistic Mode');
const activeRole = interaction.guild.roles.cache.find(r => r.name === 'Active Participant');
const inactiveRole = interaction.guild.roles.cache.find(r => r.name === 'Inactive Participant');
if (!altruisticRole || !activeRole || !inactiveRole) {
await interaction.editReply({
content: '❌ Could not find one or more required roles.',
ephemeral: true
});
return;
}
// Check bot permissions
if (!interaction.guild.members.me.permissions.has('ManageRoles')) {
await interaction.editReply({
content: '❌ Bot is missing "Manage Roles" permission.',
ephemeral: true
});
return;
}
// Check if bot's role is higher than the roles it needs to assign
const botRole = interaction.guild.members.me.roles.highest;
if (botRole.position <= altruisticRole.position ||
botRole.position <= activeRole.position ||
botRole.position <= inactiveRole.position) {
await interaction.editReply({
content: '❌ Bot\'s role must be higher than the roles it needs to assign. Please move the bot\'s role up in the server settings.',
ephemeral: true
});
return;
}
// Now update the discord_user_id
console.log(`Attempting to update discord_user_id for node ${nodeId} to ${interaction.user.id}`);
const { error: updateError } = await supabase
.from('node_records')
.update({ discord_user_id: interaction.user.id })
.eq('node_id', nodeId)
.eq('timestamp', existingNode[0].timestamp);
if (updateError) {
console.error('Error updating node:', updateError);
await interaction.editReply({
content: '❌ Error updating node information.',
ephemeral: true
});
return;
}
console.log(`Successfully updated discord_user_id for node ${nodeId}`);
// Add Altruistic and Active roles, remove Inactive role
try {
await interaction.member.roles.add([altruisticRole, activeRole]);
if (interaction.member.roles.cache.has(inactiveRole.id)) {
await interaction.member.roles.remove(inactiveRole);
}
console.log('Roles updated successfully for user:', interaction.user.tag);
// Send private success message to user
await interaction.editReply({
content: '✅ Your node has been verified and roles have been granted!',
ephemeral: true
});
} catch (roleError) {
console.error('Role assignment error:', roleError);
await interaction.editReply({
content: '❌ Failed to update roles. The bot\'s role must be higher than the roles it needs to assign.',
ephemeral: true
});
}
} catch (error) {
console.error('Error:', error);
try {
if (!interaction.replied && !interaction.deferred) {
await interaction.reply({
content: '❌ An error occurred.',
ephemeral: true
});
} else {
await interaction.editReply({
content: '❌ An error occurred.',
ephemeral: true
});
}
} catch (replyError) {
console.error('Error sending error message:', replyError);
}
}
} else if (interaction.commandName === 'checkroles') {
try {
await interaction.deferReply({ ephemeral: true });
const isActive = await checkInactiveNodes(interaction.guild, interaction.member);
if (isActive) {
await interaction.editReply({
content: '✅ Your node is active and roles are up to date.',
ephemeral: true
});
} else {
await interaction.editReply({
content: '❌ No node found with this ID. However, the bot only works for nodes setup using the [Codex CLI](https://github.com/codex-storage/cli) and does not work on manual installation of Codex as we do not log node information from the manual process.',
ephemeral: true
});
}
} catch (error) {
console.error('Error in role check:', error);
try {
if (!interaction.replied && !interaction.deferred) {
await interaction.reply({
content: '❌ An error occurred.',
ephemeral: true
});
} else {
await interaction.editReply({
content: '❌ An error occurred.',
ephemeral: true
});
}
} catch (replyError) {
console.error('Error sending error message:', replyError);
}
}
}
});
client.login(process.env.DISCORD_BOT_TOKEN);