-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.js
953 lines (896 loc) · 29.4 KB
/
bot.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
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
const fs = require('fs');
const csv = require('csv-parser');
const sqlite3 = require('better-sqlite3');
const dotenv = require('dotenv');
const express = require('express');
const app=express();
dotenv.config();
const port = process.env.PORT||3008;
const {
Client,
GatewayIntentBits,
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
ComponentType,
ChannelType,
PermissionsBitField,
AttachmentBuilder,
PermissionFlagsBits,
} = require('discord.js');
// Define intents using GatewayIntentBits
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.DirectMessageReactions,
GatewayIntentBits.MessageContent,
],
});
const db = new sqlite3('./database.db');
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
setupDatabase();
});
// Initialize database
const setupDatabase = () => {
db.prepare(
'CREATE TABLE IF NOT EXISTS users (ID INTEGER PRIMARY KEY AUTOINCREMENT, group_id TEXT, Name TEXT, Enrollment TEXT, Phone TEXT, Email TEXT, Discord TEXT)'
).run();
db.prepare(
'CREATE TABLE IF NOT EXISTS newUsers (ID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Enrollment TEXT, Phone TEXT, Email TEXT, Discord TEXT)'
).run();
db.prepare(
'CREATE TABLE IF NOT EXISTS groups (group_id TEXT PRIMARY KEY, number_of_members INTEGER)'
).run();
db.prepare(
'CREATE TABLE IF NOT EXISTS newMentees (ID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Enrollment TEXT, group_id TEXT, Phone TEXT, Email TEXT)'
).run();
preloadGroups();
preloadUserData();
};
// Preload groups from CSV into the database
const preloadGroups = () => {
const groups = {};
fs.createReadStream('./mentorship_data.csv')
.pipe(csv())
.on('data', (data) => {
if (!groups[data.Group]) {
groups[data.Group] = 1;
} else {
groups[data.Group]++;
}
})
.on('end', () => {
const batch = db.transaction((groupData) => {
for (const [Group, count] of Object.entries(groupData)) {
db.prepare(
'INSERT OR IGNORE INTO groups (group_id, number_of_members) VALUES (?, ?)'
).run(Group, count);
}
});
batch(groups);
console.log('Groups loaded into database');
});
};
const preloadUserData = () => {
const users = [];
fs.createReadStream('./mentorship_data.csv')
.pipe(csv())
.on('data', (data) => users.push(data))
.on('end', () => {
const checkUserExists = db.prepare(
'SELECT * FROM users WHERE Enrollment = ?'
);
const insert = db.prepare(
'INSERT INTO users (group_id, Name, Enrollment, Phone, Email, Discord) VALUES (?, ?, ?, ?, ?, ?)'
);
const batch = db.transaction((users) => {
for (const user of users) {
const existingUser = checkUserExists.get(
user.Enrollment.toUpperCase()
);
if (!existingUser) {
insert.run(
user.Group,
user.Name,
user.Enrollment.toUpperCase(),
user.Phone,
'',
''
);
}
}
});
batch(users);
console.log('User data loaded into database');
});
};
const activeUsers = new Set();
client.on('messageCreate', async (message) => {
if (message.author.bot || !message.guild) return;
const userId = message.author.id;
const commands = [
'!join_lwd',
'!list_new_reg',
'!assign_group',
'!new_mentees',
'!delete_mentees',
'!deassign_group',
'!delete_entry',
];
const command = message.content.trim().toLowerCase();
if (commands.includes(command)) {
if (activeUsers.has(userId)) {
message.channel.send(
"You're already running a command. Please wait until it's completed."
);
return;
}
activeUsers.add(userId);
}
try {
if (command === '!join_lwd' && message.channel.name === 'welcome-to-lwd') {
message.channel
.send('🚀 Check your DMs for verification steps! 🛡️')
.catch(console.error);
const dmChannel =
(await message.author.dmChannel) || (await message.author.createDM());
try {
await dmChannel.send(
`Hello! 👋 I'm Mr. DCC Bot! 🤖\nLet\'s get started with your verification process. Please check the instructions below carefully. 📝\n\n`
);
} catch (error) {
console.error('Error handling DM:', error);
message.channel.send(
`@${message.author.username}, I could not send you a DM 🥲. Please make sure your DMs are open and try again.`
);
}
const enrollmentRegex = /^[a-zA-Z0-9]+$/;
let valid = false;
let enrollment;
while (!valid) {
enrollment = await getUserInput(
message,
dmChannel,
enrollmentRegex,
'enrollment number'
);
if (!enrollment) {
await dmChannel.send('no input provided! Exiting...');
activeUsers.delete(userId);
return;
}
enrollment = enrollment.toUpperCase();
valid = await yesNoButton(
message,
dmChannel,
`You entered \`${enrollment}\`. Is this correct?`
);
if (!valid) {
await dmChannel.send('🔄 Starting over...');
}
}
if (!valid) {
activeUsers.delete(userId);
return;
}
// Fetch user data
const userData = db
.prepare('SELECT * FROM users WHERE Enrollment = ?')
.get(enrollment);
const newUserData = db
.prepare('SELECT * FROM newUsers WHERE Enrollment = ?')
.get(enrollment);
const newMenteeExist = db
.prepare('SELECT * FROM newMentees WHERE ENROLLMENT = ?')
.get(enrollment);
const userDiscord_id = JSON.stringify(userData?.Discord)?.id;
if (newUserData) {
dmChannel.send(
'You have already registered with us. Please wait for the admin to assign you to a group. 🕒\n our ADMINs are working tirelessly we hope you would understand'
);
} else if (userData && !userDiscord_id) {
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
let email = await getUserInput(message, dmChannel, emailRegex, 'email');
if (!email) {
await dmChannel.send('no input provided! Exiting...');
activeUsers.delete(userId);
return;
}
const discordUser = JSON.stringify(message.author);
db.prepare(
'UPDATE users SET Email = ?, Discord = ? WHERE Enrollment = ?'
).run(email, discordUser, enrollment);
handleRoleAndChannelAssignment(
dmChannel,
message.author,
userData.group_id
);
db.prepare(
'INSERT INTO newMentees (Name, Enrollment, group_id, Phone, Email) VALUES (?, ?, ?, ?, ?)'
).run(userData.Name, userData.Enrollment, userData.group_id, userData.Phone, userData.Email);
} else if (userData && userDiscord_id === message.author.id) {
dmChannel.send(
'You are already assigned to a group and your role is set. If you need any help, please reach out to the admins. 👨💼👩💼'
);
} else if (userData && userDiscord_id !== message.author.id) {
dmChannel.send(
'Oops! 🚨 It looks like this enrollment number is already linked to another Discord account. If this seems like a mistake, please contact our admin team. 🛠️'
);
} else {
dmChannel.send('It looks like you are not in our records!');
const wantToRegister = await yesNoButton(
message,
dmChannel,
'Do you want to register with 🧑🏫 Learn With DCC?'
);
if (wantToRegister) {
dmChannel.send(
`🧐 Let's get you registered! Please follow the next steps carefully.`
);
let name = await getUserInput(
message,
dmChannel,
/^[a-zA-Z ]+$/,
'full name 🧑🦰'
);
if (!name) {
await dmChannel.send('no input provided! Exiting...');
activeUsers.delete(userId);
return;
}
const phoneRegex = /^\d{10}$/;
let phone = await getUserInput(
message,
dmChannel,
phoneRegex,
'10-digit phone number 📱'
);
if (!phone) {
await dmChannel.send('no input provided! Exiting...');
activeUsers.delete(userId);
return;
}
const emailRegex =
/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; // Email validation regex
let email = await getUserInput(
message,
dmChannel,
emailRegex,
'email 📧'
);
if (!email) {
await dmChannel.send('no input provided! Exiting...');
activeUsers.delete(userId);
return;
}
const messageAuthor = JSON.stringify(message.author);
db.prepare(
'INSERT INTO newUsers (Name, Enrollment, Phone, Email, Discord) VALUES (?, ?, ?, ?, ?)'
).run(name, enrollment, phone, email, messageAuthor);
// handleRoleAndChannelAssignment(dmChannel, message.author, newGroup);
db.prepare(
'INSERT INTO newMentees (Name, Enrollment, group_id, Phone, Email) VALUES (?, ?, ?, ?, ?)'
).run(name, enrollment, '-', phone, email);
dmChannel.send(
`Thank you for registering! 🎉 Your details have been recorded. Please wait for the admin to assign you to a group. 🕒`
);
const guild = client.guilds.cache.get(process.env.GUILD_ID);
const logChannel = guild.channels.cache.find(
(channel) =>
channel.name === 'mr-dcc-logs' &&
channel.type === ChannelType.GuildText
);
if (logChannel) {
logChannel.send(
`🆕 New user registered: \`${name}\` with enrollment number \`${enrollment}\` and email \`${email}\`.`
);
}
} else {
dmChannel.send(
`👋 BYE ... If you change your mind, feel free to reach out to us anytime.`
);
}
}
} else if (
/*
* list new registered users
*/
command === '!list_new_reg' &&
message.channel.name === 'admin-mentorship'
) {
message.channel.send('the new users who are trying to join DCC are:');
const newUsers = db.prepare('SELECT * FROM newUsers').all();
// parse the whole newUsers into a table format and send it to the channel
let table = '```';
table += 'ID\tName\tEnrollment\tPhone\tEmail\n';
newUsers.forEach((user) => {
table += `${user.ID}\t${user.Name}\t${user.Enrollment}\t${user.Phone}\t${user.Email}\n`;
});
table += '```';
message.channel.send(table);
} else if (
/*
* assign group to the new users
* - get the list of IDs
* - get the group name
* - assign the group to the users
*/
command === '!assign_group' &&
message.channel.name === 'admin-mentorship'
) {
message.channel.send(
'Now we will proceed to assign the new users to the groups'
);
const idList = await getUserInput(
message,
message.channel,
/^[0-9,]+$/,
'ID list separated by commas'
);
if (!idList) {
message.channel.send('No IDs provided. Exiting...');
activeUsers.delete(userId);
return;
}
const group = await getUserInput(
message,
message.channel,
/^[a-zA-Z0-9]+$/,
'group'
);
if (!group) {
message.channel.send('No group provided. Exiting...');
activeUsers.delete(userId);
return;
}
const idArray = idList.split(',');
idArray.forEach((id, index) => {
setTimeout(() => {
const userData = db
.prepare('SELECT * FROM newUsers WHERE ID = ?')
.get(id);
if (userData) {
const discordUser = JSON.parse(userData.Discord);
handleRoleAndChannelAssignment(message.channel, discordUser, group);
db.prepare(
'INSERT INTO users (group_id, Name, Enrollment, Phone, Email, Discord) VALUES (?, ?, ?, ?, ?, ?)'
).run(
group,
userData.Name,
userData.Enrollment,
userData.Phone,
userData.Email,
userData.Discord
);
db.prepare(
'UPDATE newMentees SET group_id = ? WHERE Enrollment = ?'
).run(group, userData.Enrollment);
db.prepare('DELETE FROM newUsers WHERE ID = ?').run(id);
message.channel.send(
`User with ID \`${id}\` has been assigned to group \`${group}\``
);
} else {
if (id !== undefined)
message.channel.send(
`User with ID \`${id}\` not found in the database.`
);
}
}, index * 1000);
});
} else if (
command === '!deassign_group' &&
message.channel.name === 'admin-mentorship'
) {
message.channel.send(
'Now we will proceed with de-assigning the users from the groups'
);
const enrollment = await getUserInput(
message,
message.channel,
/^[a-zA-Z0-9]+$/,
'enrollment number'
);
if (!enrollment) {
message.channel.send('No enrollment number provided. Exiting...');
activeUsers.delete(userId);
return;
}
const userData = db
.prepare('SELECT * FROM users WHERE Enrollment = ?')
.get(enrollment);
if (userData) {
if (!userData.Discord) {
message.channel.send(
`User with Enrollment \`${enrollment}\` does not have a Discord account linked.`
);
activeUsers.delete(userId);
return;
}
const discordUser = JSON.parse(userData.Discord);
console.log(userData.group_id);
handleRoleAndChannelDeAssignment(
message.channel,
discordUser,
userData.group_id,
enrollment
);
message.channel.send(
`User with Enrollment \`${enrollment}\` has been deassigned from group \`${userData.group_id}\``
);
}
} else if (
command === '!delete_entry' &&
message.channel.name === 'admin-mentorship'
) {
const idList = await getUserInput(
message,
message.channel,
/^[0-9]+$/,
'ID list, separated by commas'
);
if (!idList) {
message.channel.send('No IDs provided. Exiting...');
activeUsers.delete(userId);
return;
}
const idArray = idList.split(',');
idArray.forEach((id, _) => {
const userData = db
.prepare('SELECT * FROM newUsers WHERE ID = ?')
.get(id);
if (userData) {
db.prepare('DELETE FROM newUsers WHERE ID = ?').run(id);
message.channel.send(
`User with Enrollment \`${userData.Enrollment}\` has been deleted from the new users list`
);
} else {
message.channel.send(
`User with Enrollment \`${userData.Enrollment}\` not found in the new users list. Make sure you de-assigned the user already. If not please de-assign the user first using \`!deassign_group\`.`
);
}
});
}else if (
command === '!new_mentees' &&
message.channel.name === 'admin-mentorship'
) {
message.channel.send('The new Mentees who are trying to join DCC LWD are:');
const newMentees = db.prepare('SELECT * FROM newMentees').all();
let table = '```';
table += 'ID\tName\tEnrollment\tGroup\tPhone\tEmail\n';
newMentees.forEach((mentee) => {
table += `${mentee.ID}\t${mentee.Name}\t${mentee.Enrollment}\t${mentee.group_id}\t${mentee.Phone}\t${mentee.Email}\n`;
});
table += '```';
message.channel.send(table);
} else if (
command === '!delete_mentees' &&
message.channel.name === 'admin-mentorship'
) {message.channel.send(
'Now we will proceed to deletion of the new mentees:'
);
const idList = await getUserInput(
message,
message.channel,
/^[0-9,]+$/,
'ID list separated by commas'
);
if (!idList) {
message.channel.send('No IDs provided. Exiting...');
activeUsers.delete(userId);
return;
}
const idArray = idList.split(',');
idArray.forEach((id, index) => {
setTimeout(() => {
const menteeData = db
.prepare('SELECT * FROM newMentees WHERE ID = ?')
.get(id);
if(menteeData){
db.prepare('DELETE FROM newMentees WHERE ID = ?').run(id);
message.channel.send(
`User with ID \`${id}\` is deleted from Mentee Table.`
);
} else {
if (id !== undefined)
message.channel.send(
`User with ID \`${id}\` not found in the database.`
);
}
},index*1000);
});
} else
if(command === '!member_list_lwd'){
const categoryId = process.env.LWD_CATEGORY_ID;
if (message.channel.parentId !== categoryId) {
return ;
}
let table = '```';
table += 'username\tName\n';
const members = await getMembersWithRolePermissionsInChannel(message.guild, message.channel.id);
members.forEach(member=>{
if(member.name!=null){
table += `${member.username}\t${member.name}\n`;
}
else{
table += `${member.username}\t - \n`;
}
})
table += '```';
if (table.length>375){
message.channel.send(`Everyone is present in this ${message.channel.name} channel.`);
return;
}
message.channel.send(`The List of Members in ${message.channel.name}:`);
message.channel.send(table);
} else {
return;
}
// Remove the user from the active set once the command is done
activeUsers.delete(userId);
} catch (error) {
console.error('Error handling command:', error);
message.channel.send('An error occurred while processing your command.');
activeUsers.delete(userId);
}
});
client.on('messageCreate', async (message) => {
if (message.author.bot) return;
if (message.content === 'ping') {
message.channel.send('pong');
}
// if (message.content.trim().toLowerCase() === 'cutie') {
// message.channel.send('A fresh cutie coming through! 🥰');
// message.channel.send('https://s9.gifyu.com/images/SZozs.gif');
// }
// if (message.content.trim().toLowerCase() === 'ok') {
// message.channel.send('OK 🫠');
// message.channel.send(
// 'https://cdn.discordapp.com/attachments/1231682621252042812/1232422515704336485/image0.jpg?ex=66296669&is=662814e9&hm=e313fb3dfdea82574267ad87cd72c4004bfaa04136e8a2ff17875ad0944ae571&'
// );
// }
if (message.content === '!help') {
message.channel.send(
'Commands:\n`!help` - Display this help message \n`!join_lwd` - Join the LWD Discord server\n`!list_new_reg` - List the new users who are trying to join DCC\n`!assign_group` - Assign the new users to the groups'
);
}
});
async function getMembersWithRolePermissionsInChannel(guild, channelId){
const channel = guild.channels.cache.get(channelId);
if (!channel) {
throw new Error(`Channel with ID ${channelId} not found`);
}
await guild.members.fetch();
const membersSet = new Set();
channel.guild.roles.cache.filter(role => {
const permissions = channel.permissionsFor(role);
return permissions && permissions.has(PermissionFlagsBits.ViewChannel);
}).forEach(role => {
console.log(role.name);
role.members.forEach(member => {
if(member.user.bot===false&&role.name!=='MOD')
membersSet.add(member);
});
});
const members = Array.from(membersSet).map(member => ({
id: member.id,
username: member.user.username,
name: member.user.globalName
}));
membersSet.clear();
return members;
}
async function getUserInput(message, channel, regex, fieldName) {
const filter = (m) => m.author.id === message.author.id;
let valid = false,
timeUp = false,
userInput;
while (!valid) {
try {
await channel.send(`Please enter your ${fieldName}:`);
const response = await channel.awaitMessages({
filter,
max: 1,
time: 60000,
errors: ['time'],
});
userInput = response.first().content.trim();
if (regex.test(userInput)) {
valid = true;
} else {
channel.send(
`🚫 Invalid input. Please ensure you enter a valid ${fieldName}.`
);
}
} catch {
if (timeUp) {
channel.send(
`⏰ Time's up! Due to No response! Please start the process again.`
);
break;
}
channel.send(
`⏰ Time's up! Please try again and respond within 1 minute.`
);
timeUp = true;
continue;
}
}
return userInput;
}
async function yesNoButton(message, channel, question) {
const row = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId('yes')
.setLabel('Yes ✔️')
.setStyle(ButtonStyle.Success),
new ButtonBuilder()
.setCustomId('no')
.setLabel('No ✖️')
.setStyle(ButtonStyle.Danger)
);
await channel.send({
content: question,
components: [row],
});
const buttonFilter = (i) => {
i.deferUpdate();
return i.user.id === message.author.id;
};
try {
const buttonResponse = await channel.awaitMessageComponent({
filter: buttonFilter,
componentType: ComponentType.Button,
time: 60000,
errors: ['time'],
});
if (buttonResponse.customId === 'yes') {
return true;
}
return false;
} catch (error) {
await channel.send(
'Failed to process your button click. 🚫 Please try again or contact support if the issue persists. 🆘'
);
}
}
async function handleRoleAndChannelAssignment(channel, user, groupName) {
const guild = client.guilds.cache.get(process.env.GUILD_ID);
const groupName2 = "LWD - GR "+groupName;
console.log("LWD - GR",groupName2);
let role = guild.roles.cache.find((role) => role.name === groupName2);
if (!role) {
console.log('Mentee role does not exist, creating one...');
role = await guild.roles.create({
name: groupName2,
color: '#FF5733',
permissions: [],
});
}
// Find or create the category
// let category = guild.channels.cache.find(
// (c) =>
// c.name === `Group ${groupName}` && c.type === ChannelType.GuildCategory
// );
// if (!category) {
// console.log(`Creating new category and channels for group ${groupName}`);
// category = await guild.channels.create({
// name: `Group ${groupName}`,
// type: ChannelType.GuildCategory,
// permissionOverwrites: [
// {
// id: guild.id,
// deny: [PermissionsBitField.Flags.ViewChannel],
// },
// {
// id: role.id,
// deny: [PermissionsBitField.Flags.ViewChannel],
// },
// ],
// });
// Create channels for category
// await createOrUpdateChannel(
// guild,
// category,
// 'announcements',
// 'Group announcements and important info'
// );
// await createOrUpdateChannel(
// guild,
// category,
// 'general-chat',
// 'General discussion for the group'
// );
// await createOrUpdateChannel(
// guild,
// category,
// 'voice-chat',
// '',
// ChannelType.GuildVoice
// );
// }
//
// Ensure the user has the Mentee role
const member = await guild.members.fetch(user.id);
// Update existing channels
// await ensureUserAccess(guild, category, user);
// console.log("role:",role);
await member.roles.add(role);
channel.send(
`Verification successful! ✅ Now you have access to exclusive channels in \`#Group ${groupName}\`. Enjoy your journey with us! 🌟`
);
console.log(
`Assigned '${groupName2}' role and access to 'Group ${groupName}' channel for user ${user.username}`
);
const logChannel = guild.channels.cache.find(
(channel) =>
channel.name === 'mr-dcc-logs' && channel.type === ChannelType.GuildText
);
if (logChannel) {
logChannel.send(
`✅ Assigned \`'${groupName2}'\` role and access to \`#Group ${groupName}\` channel for user \`@${user.username}\``
);
} else {
console.log("Couldn't find the #mentorship-logs channel.");
}
}
async function handleRoleAndChannelDeAssignment(
channel,
user,
groupName,
enrollment
) {
const guild = client.guilds.cache.get(process.env.GUILD_ID);
try {
const member = await guild.members.fetch(user.id);
let role = guild.roles.cache.find((role) => role.name === 'Mentee');
if (member.roles.cache.has(role.id)) {
await member.roles.remove(role);
}
channel.send(`Mentee role has been removed from the user <@${user.id}>`);
} catch (error) {
channel.send(`Unable to remove role Mentee form <@${user.id}>`);
}
try {
let category = guild.channels.cache.find(
(c) =>
c.name === `Group ${groupName}` && c.type === ChannelType.GuildCategory
);
if (category) {
await removeUserAccess(guild, category, user);
} else {
channel.send(`Unable to remove user <@${user.id}> from the group`);
}
channel.send(
`User <@${user.id}> has been removed from the group ${groupName}`
);
} catch (error) {
channel.send(
`Unable to remove user <@${user.id}> from the group ${groupName}`
);
}
try {
// remove user form the user table and insert into the newUser table
const userData = db
.prepare('SELECT * FROM users WHERE Enrollment = ?')
.get(enrollment);
db.prepare(
'INSERT INTO newUsers (Name, Enrollment, Phone, Email, Discord) VALUES (?, ?, ?, ?, ?)'
).run(
userData.Name,
userData.Enrollment,
userData.Phone,
userData.Email,
userData.Discord
);
db.prepare('DELETE FROM users WHERE Enrollment = ?').run(enrollment);
} catch (error) {
channel.send(
`there has been some error in database update please fix it ASAP!!!`
);
console.log(error);
}
const logChannel = guild.channels.cache.find(
(channel) =>
channel.name === 'mr-dcc-logs' && channel.type === ChannelType.GuildText
);
if (logChannel) {
logChannel.send(
`User has been removed from the group ${groupName} and the role Mentee has been removed`
);
}
}
async function createOrUpdateChannel(
guild,
category,
channelName,
topic,
type = ChannelType.GuildText
) {
let channel = guild.channels.cache.find(
(c) => c.name === channelName && c.parentId === category.id
);
if (!channel) {
console.log(`Creating new channel: ${channelName}`);
channel = await guild.channels.create({
name: channelName,
type: type,
parent: category.id,
topic: topic,
});
}
}
async function ensureUserAccess(guild, category, user) {
const channels = guild.channels.cache.filter(
(c) => c.parentId === category.id
);
channels.forEach(async (channel) => {
const permission = channel.permissionOverwrites.cache.get(user.id);
if (!permission) {
await channel.permissionOverwrites.create(user.id, {
ViewChannel: true,
});
console.log(`Added permissions for ${channel.name}`);
}
});
}
async function removeUserAccess(guild, catagory, user) {
const channels = guild.channels.cache.filter(
(c) => c.parentId === catagory.id
);
channels.forEach(async (channel) => {
const permission = channel.permissionOverwrites.cache.get(user.id);
if (permission) {
await channel.permissionOverwrites.create(user.id, {
ViewChannel: false,
});
console.log(`Removing permission for ${channel.name}`);
}
});
}
/*
* function to generate new group id with some sexy logic
* @returns {String} new group id
*/
// const getNewUserGroup = () => {
// try {
// const lastGroup = db
// .prepare('SELECT * FROM groups ORDER BY group_id DESC LIMIT 1')
// .get();
// if (lastGroup) {
// if (lastGroup.number_of_members < 10) {
// db.prepare(
// 'UPDATE groups SET number_of_members = number_of_members + 1 WHERE group_id = ?'
// ).run(lastGroup.group_id);
// return lastGroup.group_id;
// } else {
// const prefix = lastGroup.group_id.charAt(0);
// const number = parseInt(lastGroup.group_id.substring(1));
// let newGroupId;
// if (number < 5) {
// newGroupId = `${prefix}${number + 1}`;
// } else {
// newGroupId = String.fromCharCode(prefix.charCodeAt(0) + 1) + '1';
// }
// db.prepare(
// 'INSERT INTO groups (group_id, number_of_members) VALUES (?, 1)'
// ).run(newGroupId);
// return newGroupId;
// }
// }
// } catch (error) {
// console.error('Error fetching group data:', error);
// return 'TEMP';
// }
// };
client.login(process.env.DISCORD_TOKEN);
app.get('/', (req, res) => {
res.status(200).send('Bot is running');
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});