Advertisement
Uno2K

rankTime command

Sep 21st, 2023 (edited)
940
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const {
  2.   SlashCommandBuilder,
  3.   Client,
  4.   Interaction,
  5.   EmbedBuilder,
  6. } = require("discord.js");
  7. const DB = require("../../schemas/rankTime");
  8. const ranks = require("../../constants/rank");
  9.  
  10. module.exports = {
  11.   data: new SlashCommandBuilder()
  12.     .setName("rank")
  13.     .setDescription("[Rank] Configurações do Rank Time")
  14.     .addSubcommand((subcommand) =>
  15.       subcommand
  16.         .setName("configurar")
  17.         .setDescription("[Rank] Configuração inicial para o sistema de rank")
  18.         .addRoleOption((option) =>
  19.           option
  20.             .setName("rank")
  21.             .setDescription("Selecione o cargo inicial para o sistema de rank")
  22.             .setRequired(true)
  23.         )
  24.     )
  25.     .addSubcommand((subcommand) =>
  26.       subcommand
  27.         .setName("iniciar")
  28.         .setDescription(
  29.           "[Rank] Inicia o sistema de rank para todos os membros do servidor"
  30.         )
  31.     )
  32.     .addSubcommand((subcommand) =>
  33.       subcommand
  34.         .setName("atualizar")
  35.         .setDescription(
  36.           "[Rank] Força a atualização dos rank de todos os membros do servidor"
  37.         )
  38.     ),
  39.  
  40.   /**
  41.    * @param {Interaction} interaction
  42.    * @param {Client} client
  43.    */
  44.   async execute(interaction, client) {
  45.     const { options, guild } = interaction;
  46.  
  47.     const subCommand = options.getSubcommand([
  48.       "configurar",
  49.       "iniciar",
  50.       "atualizar",
  51.     ]);
  52.  
  53.     const successEmbed = new EmbedBuilder().setColor("Green");
  54.     const warningEmbed = new EmbedBuilder().setColor("Yellow");
  55.     const errorEmbed = new EmbedBuilder().setColor("Red");
  56.  
  57.     function meetsRequirement(joinDate, requirement) {
  58.       const currentDate = new Date();
  59.       const elapsedMilliseconds = currentDate - joinDate;
  60.       const elapsedDays = elapsedMilliseconds / (1000 * 60 * 60 * 24);
  61.  
  62.       return elapsedDays >= requirement;
  63.     }
  64.  
  65.     if (subCommand === "configurar") {
  66.       return await interaction.reply({
  67.         embeds: [
  68.           errorEmbed.setDescription(
  69.             "❌ No momento este comando não está funcionando..."
  70.           ),
  71.         ],
  72.         ephemeral: true,
  73.       });
  74.     } else if (subCommand === "iniciar") {
  75.       await interaction.reply({
  76.         embeds: [
  77.           warningEmbed.setDescription(
  78.             `⏳ Iniciando sistema de rank para todos os membros do servidor, isso pode demorar um pouco...`
  79.           ),
  80.         ],
  81.       });
  82.    
  83.       const members = await guild.members.fetch();
  84.       const processingDelay = 100; // 1000ms (1 segundo) de atraso entre mensagens
  85.       let num = 0;
  86.    
  87.       async function processMember(member) {
  88.         try {
  89.           const existingRankInfo = await DB.findOne({
  90.             memberId: member.id,
  91.             guildId: guild.id,
  92.           });
  93.    
  94.           if (!existingRankInfo) {
  95.             const newRankInfo = new DB({
  96.               guildId: guild.id,
  97.               memberId: member.id,
  98.               joinTime: member.joinedAt,
  99.               currentRankId: ranks.ranksTest.plebeu.roleId,
  100.             });
  101.             await newRankInfo.save();
  102.             await member.roles
  103.               .add(newRankInfo.currentRankId)
  104.               .catch((err) => console.log(err));
  105.           }
  106.         } catch (error) {
  107.           console.error(`Error processing member ${member.user.tag}: ${error}`);
  108.         }
  109.    
  110.         num++;
  111.    
  112.         if (num === members.size) {
  113.           await interaction.editReply({
  114.             embeds: [
  115.               successEmbed.setDescription(
  116.                 `✅ Sistema de rank iniciado para todos os membros do servidor.`
  117.               ),
  118.             ],
  119.             ephemeral: true,
  120.           });
  121.         } else {
  122.           await interaction.editReply({
  123.             embeds: [
  124.               warningEmbed.setDescription(
  125.                 `⏳ ${num}/${members.size} membros foram processados!`
  126.               ),
  127.             ],
  128.           });
  129.         }
  130.       }
  131.    
  132.       for (const member of members.values()) {
  133.         await processMember(member);
  134.         await new Promise((resolve) => setTimeout(resolve, processingDelay));
  135.       }
  136.     }else if (subCommand === "atualizar") {
  137.       // Início do comando
  138.       await interaction.reply({
  139.         embeds: [
  140.           warningEmbed.setDescription(
  141.             `⏳ Atualizando sistema de rank para todos os membros do servidor, isso pode demorar um pouco...`
  142.           ),
  143.         ],
  144.       });
  145.  
  146.       try {
  147.         const membersToUpdate = await DB.find({
  148.           guildId: guild.id,
  149.         });
  150.  
  151.         console.log(
  152.           `\nFound ${membersToUpdate.length} members to update on guild ${interaction.guild.name}.\n`
  153.         );
  154.  
  155.         let updatedMembersCount = 0;
  156.  
  157.         for (const memberInfo of membersToUpdate) {
  158.           const member = await guild.members.fetch(memberInfo.memberId);
  159.           if (!member) continue;
  160.  
  161.           for (const rankName of Object.keys(ranks.ranksTest).sort((a, b) => {
  162.             // Ordene os ranks com base na hierarquia de cargos
  163.             const roleA = guild.roles.cache.get(ranks.ranksTest[a].roleId);
  164.             const roleB = guild.roles.cache.get(ranks.ranksTest[b].roleId);
  165.             return roleA.comparePositionTo(roleB);
  166.           })) {
  167.             const rank = ranks.ranksTest[rankName];
  168.  
  169.             console.log(
  170.               `Verifying user:${member.user.tag}\n${rankName}: ${
  171.                 rank.requirement
  172.               } - Meet requirement:  -> ${meetsRequirement(
  173.                 memberInfo.joinTime,
  174.                 rank.requirement
  175.               )}`
  176.             );
  177.  
  178.             // Verifique se o membro atende aos requisitos para o próximo rank
  179.             if (
  180.               meetsRequirement(memberInfo.joinTime, rank.requirement)
  181.             ) {
  182.               const nextRankName = Object.keys(ranks.ranksTest).find(
  183.                 (r) => ranks.ranksTest[r].roleId === rank.roleId
  184.               );
  185.  
  186.               // Verifique o próximo cargo de rank
  187.               const nextRank = guild.roles.cache.get(
  188.                 ranks.ranksTest[nextRankName].roleId
  189.               );
  190.  
  191.               // Verifique se o membro já possui o próximo cargo de rank
  192.               if (nextRank && !member.roles.cache.has(nextRank.id)) {
  193.                 // Remova o cargo do rank anterior se o membro já tiver um rank
  194.                 const currentRank = guild.roles.cache.get(
  195.                   memberInfo.currentRankId
  196.                 );
  197.                 console.log(
  198.                   `Verificando atual rank: ${currentRank.name} - ${member.user.tag}`
  199.                 );
  200.                 console.log(
  201.                   `Verificando próximo rank: ${nextRank.name} - ${member.user.tag}`
  202.                 );
  203.                 console.log(
  204.                   `Comparando rank ${
  205.                     currentRank.comparePositionTo(nextRank) < 0
  206.                   } - ${member.user.tag}`
  207.                 );
  208.                 // Verifique se o membro tem um cargo atual e se o próximo cargo é superior
  209.                 if (
  210.                   currentRank &&
  211.                   currentRank.comparePositionTo(nextRank) < 0
  212.                 ) {
  213.                   await member.roles.remove(currentRank);
  214.  
  215.                   // Adicione o novo cargo e atualize a informação no banco de dados
  216.                   await member.roles.add(nextRank);
  217.                   memberInfo.currentRankId = nextRank.id; // Atualize no banco de dados
  218.                   await memberInfo.save();
  219.  
  220.                   // Envie uma embed de confirmação para o membro promovido
  221.                   await interaction.channel.send({
  222.                     embeds: [
  223.                       successEmbed.setDescription(
  224.                         `✅ <@${member.id}> foi promovido a <@&${nextRank.id}>`
  225.                       ),
  226.                     ],
  227.                   });
  228.                   updatedMembersCount++;
  229.                 }
  230.               }
  231.             }
  232.           }
  233.         }
  234.  
  235.         if (updatedMembersCount === 0) {
  236.           return await interaction.editReply({
  237.             embeds: [
  238.               warningEmbed.setDescription(
  239.                 `⚠️ Nenhum membro foi atualizado.`
  240.               ),
  241.             ],
  242.           });
  243.         }
  244.  
  245.         await interaction.followUp({
  246.           embeds: [
  247.             successEmbed.setDescription(
  248.               `✅ **${updatedMembersCount}** membros tiveram seus ranks atualizados`
  249.             ),
  250.           ],
  251.         });
  252.       } catch (error) {
  253.         console.error(`Error updating ranks: ${error}`);
  254.         await interaction.followUp({
  255.           embeds: [
  256.             errorEmbed.setDescription(
  257.               "❌ Ocorreu um erro ao atualizar os ranks dos membros."
  258.             ),
  259.           ],
  260.         });
  261.         // Final do comando
  262.       }
  263.     }
  264.   },
  265. };
  266.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement