Guest User

Untitled

a guest
Sep 14th, 2024
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. async function handleCreateScrim(interaction) {
  2.     if (!interaction.member.permissions.has(PermissionsBitField.Flags.ManageGuild)) {
  3.         await interaction.reply({ content: 'You do not have MANAGE_GUILD permission to use this command.', ephemeral: true });
  4.         return;
  5.     }
  6.  
  7.     const registrationChannel = interaction.options.getChannel('registration_channel');
  8.     const slotListChannel = interaction.options.getChannel('slotlist_channel');
  9.     const successRole = interaction.options.getRole('success_role');
  10.     const requiredMentions = interaction.options.getInteger('required_mentions');
  11.     const totalSlots = interaction.options.getInteger('total_slots');
  12.     const openTime = interaction.options.getString('open_time');
  13.  
  14.     // Check if the channels are already in use
  15.     const existingScrim = Object.values(scrimSettings).find(settings =>
  16.         settings.registrationChannelId === registrationChannel.id ||
  17.         settings.slotListChannelId === slotListChannel.id
  18.     );
  19.  
  20.     if (existingScrim) {
  21.         await interaction.reply({
  22.             content: 'This channel is already set up for another scrim. Please delete the existing scrim before setting up a new one.',
  23.             ephemeral: true
  24.         });
  25.         return;
  26.     }
  27.  
  28.     if (!registrationChannel.isTextBased() || !slotListChannel.isTextBased()) {
  29.         await interaction.reply({ content: 'Both the registration and slotlist channels must be text channels.', ephemeral: true });
  30.         return;
  31.     }
  32.  
  33.     const botRole = interaction.guild.members.me.roles.highest;
  34.     if (successRole.position >= botRole.position) {
  35.         await interaction.reply({ content: 'The success role must be lower in position than the bot\'s highest role.', ephemeral: true });
  36.         return;
  37.     }
  38.  
  39.     if (requiredMentions < 1 || requiredMentions > 4 || totalSlots < 1 || totalSlots > 25) {
  40.         await interaction.reply({ content: 'Required mentions must be between 1 and 4, and total slots must be between 1 and 25.', ephemeral: true });
  41.         return;
  42.     }
  43.  
  44.     const timeParts = openTime.split(':');
  45.     if (timeParts.length !== 2 || isNaN(timeParts[0]) || isNaN(timeParts[1]) ||
  46.         timeParts[0] < 0 || timeParts[0] > 23 || timeParts[1] < 0 || timeParts[1] > 59) {
  47.         await interaction.reply({ content: 'Open time must be in 24-hour format (HH:MM).', ephemeral: true });
  48.         return;
  49.     }
  50.  
  51.     const now = new Date();
  52.     const openDateTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), timeParts[0], timeParts[1], 0);
  53.     if (openDateTime <= now) {
  54.         openDateTime.setDate(openDateTime.getDate() + 1); // Schedule for next day if time has already passed
  55.     }
  56.     const delay = openDateTime - now;
  57.  
  58.     scrimSettings[interaction.guildId] = {
  59.         registrationChannelId: registrationChannel.id,
  60.         slotListChannelId: slotListChannel.id,
  61.         successRoleId: successRole.id,
  62.         requiredMentions,
  63.         totalSlots,
  64.         filledSlots: 0,
  65.         confirmedUsers: []
  66.     };
  67.  
  68.     saveScrimSettings(scrimSettings); // Save scrim settings to file
  69.  
  70.     setTimeout(async () => {
  71.         const settings = scrimSettings[interaction.guildId];
  72.         if (!settings) return;
  73.  
  74.         const registrationChannel = interaction.guild.channels.cache.get(settings.registrationChannelId);
  75.         const slotListChannel = interaction.guild.channels.cache.get(settings.slotListChannelId);
  76.  
  77.         // Open registration channel
  78.         await registrationChannel.permissionOverwrites.edit(interaction.guild.roles.everyone, {
  79.             [PermissionsBitField.Flags.SendMessages]: true
  80.         });
  81.         const registrationStartTime = Date.now(); // Store the start time
  82.         const embed = new EmbedBuilder()
  83.             .setTitle('Registration is now open!')
  84.             .setDescription(`:mega: ${settings.requiredMentions} mentions required.\n:mega: Total slots: ${settings.totalSlots}`)
  85.             .setColor('#0099ff')
  86.             .setTimestamp();
  87.  
  88.         await registrationChannel.send({ embeds: [embed] });
  89.  
  90.         const collector = registrationChannel.createMessageCollector({ filter: (m) => !m.author.bot, time: 3600000 }); // 1 hour duration
  91.  
  92.         collector.on('collect', async (message) => {
  93.             if (message.author.bot) return; // Ignore messages from bots
  94.  
  95.             const mentions = message.mentions.users.filter(user => !user.bot).map(user => user.username); // Array of mentioned users
  96.  
  97.             // Check if enough users were mentioned
  98.             if (mentions.length < settings.requiredMentions) {
  99.                 await message.react('❌');
  100.             } else {
  101.                 await message.react('✅');
  102.                 await message.member.roles.add(settings.successRoleId);
  103.                 settings.confirmedUsers.push({
  104.                     username: message.author.username,
  105.                     userId: message.author.id, // Store user ID for mentioning
  106.                     mentions, // Store the actual mentioned users
  107.                     messageId: message.id // Store the message ID for redirect
  108.                 });
  109.                 settings.filledSlots++;
  110.  
  111.                 if (settings.filledSlots >= settings.totalSlots) {
  112.                     collector.stop();
  113.                 }
  114.             }
  115.         });
  116.  
  117.         collector.on('end', async () => {
  118.             const registrationDuration = Date.now() - registrationStartTime; // Duration in milliseconds
  119.             const durationInSeconds = Math.floor(registrationDuration / 1000); // Convert to seconds
  120.  
  121.             // Notify all slots filled in the registration channel
  122.             const filledEmbed = new EmbedBuilder()
  123.                 .setTitle('Registration is now closed.')
  124.                 .setColor('#0099ff');
  125.  
  126.             await registrationChannel.send({ embeds: [filledEmbed] });
  127.            
  128.             const numberedList = settings.confirmedUsers.map((user, index) => `Slot ${index + 1} -> ${user.username}'s Team`).join('\n');
  129.  
  130.            const embed = new EmbedBuilder()
  131.                .setTitle('Manager-Scrims Slotlist')
  132.                .setDescription(`\`\`\`\n${numberedList}\n\`\`\``)
  133.                .setColor('#0099ff')
  134.                .setFooter({
  135.                    text: `Registration took ${durationInSeconds} seconds`,
  136.                    iconURL: client.user.displayAvatarURL() // Add bot's avatar
  137.                 });
  138.  
  139.             // Send the embed and the Info button
  140.             const infoButton = new ButtonBuilder()
  141.                 .setCustomId('info_button')
  142.                 .setLabel('Info ❓') // Add the question mark emoji here
  143.                 .setStyle(ButtonStyle.Primary);
  144.  
  145.             const row = new ActionRowBuilder().addComponents(infoButton);
  146.  
  147.             await slotListChannel.send({
  148.                 embeds: [embed],
  149.                 components: [row] // Add the button
  150.             });
  151.  
  152.             // Button interaction listener
  153.             const buttonCollector = slotListChannel.createMessageComponentCollector({
  154.                 componentType: ComponentType.Button,
  155.                 time: 3600000, // 1 hour
  156.                 filter: (i) => i.customId === 'info_button'
  157.             });
  158.  
  159.             buttonCollector.on('collect', async (buttonInteraction) => {
  160.                 if (buttonInteraction.customId === 'info_button') {
  161.                     // Check if the user has the ManageGuild permission
  162.                     if (!buttonInteraction.member.permissions.has(PermissionsBitField.Flags.ManageGuild)) {
  163.                         await buttonInteraction.reply({
  164.                             content: 'You do not have MANAGE_GUILD permission to use this button.',
  165.                             ephemeral: true
  166.                         });
  167.                         return;
  168.                     }
  169.  
  170.                     // Generate the select menu options based on the filled slots
  171.                     const selectMenu = new SelectMenuBuilder()
  172.                         .setCustomId('slot_info_menu')
  173.                         .setPlaceholder('Choose a slot to view details')
  174.                         .addOptions(
  175.                             settings.confirmedUsers.map((user, index) => ({
  176.                                 label: `Slot ${index + 1}`,
  177.                                 value: `slot_${index + 1}`
  178.                             }))
  179.                         );
  180.  
  181.                     const menuRow = new ActionRowBuilder().addComponents(selectMenu);
  182.  
  183.                     await buttonInteraction.reply({
  184.                         content: 'Select a slot from the dropdown menu to view more information:',
  185.                         components: [menuRow],
  186.                         ephemeral: true
  187.                     });
  188.                 }
  189.             });
  190.  
  191.             // Create a select menu collector to handle slot selection
  192.             const menuCollector = slotListChannel.createMessageComponentCollector({
  193.                 componentType: ComponentType.SelectMenu,
  194.                 time: 3600000, // 1 hour
  195.                 filter: (i) => i.customId === 'slot_info_menu'
  196.             });
  197.  
  198.             menuCollector.on('collect', async (menuInteraction) => {
  199.                 const selectedValue = menuInteraction.values[0];
  200.                 const slotNumber = parseInt(selectedValue.split('_')[1], 10); // Extract slot number
  201.  
  202.                 // Get the details of the selected slot
  203.                 const slotDetails = settings.confirmedUsers[slotNumber - 1];
  204.                 const mentionedUsers = slotDetails.mentions.join(', '); // Join the mentions into a string
  205.                 const originalMessageLink = `https://discord.com/channels/${interaction.guild.id}/${settings.registrationChannelId}/${slotDetails.messageId}`;
  206.                 const registeredBy = `<@${slotDetails.userId}>`;
  207.                 // Build and send the info embed
  208.                 const infoEmbed = new EmbedBuilder()
  209.                     .setTitle(`Slot Info`)
  210.                     .setDescription(`**Slot No:** \`${slotNumber}\`\n**Name**: \`${slotDetails.username}'s Team\`\n**Captain:** ${slotDetails.username} (<@${slotDetails.userId}>)\n**Team:** ${mentionedUsers}\n**Registration Message**\n[Jump to Message](${originalMessageLink})`)
  211.                    .setColor('#0099ff');
  212.                await menuInteraction.reply({
  213.                    embeds: [infoEmbed],
  214.                    ephemeral: true
  215.                });
  216.            });
  217.  
  218.            await registrationChannel.permissionOverwrites.edit(interaction.guild.roles.everyone, {
  219.                [PermissionsBitField.Flags.SendMessages]: false
  220.            });
  221.  
  222.            delete scrimSettings[interaction.guildId];
  223.            saveScrimSettings(scrimSettings); // Save updated settings
  224.        });
  225.    }, delay);
  226.  
  227.    await interaction.reply({
  228.        content: `Scrim setup successful! Here are the details:
  229. Registration Channel: #${registrationChannel.name}
  230. Slot List Channel: #${slotListChannel.name}
  231. Success Role: @${successRole.name}
  232. Required Mentions: ${requiredMentions}
  233. Total Slots: ${totalSlots}
  234. Registration Opens At: ${openTime}`, ephemeral: true });
  235. }
Add Comment
Please, Sign In to add comment