Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const {
- SlashCommandBuilder,
- Client,
- Interaction,
- EmbedBuilder,
- } = require("discord.js");
- const DB = require("../../schemas/rankTime");
- const ranks = require("../../constants/rank");
- module.exports = {
- data: new SlashCommandBuilder()
- .setName("rank")
- .setDescription("[Rank] Configurações do Rank Time")
- .addSubcommand((subcommand) =>
- subcommand
- .setName("configurar")
- .setDescription("[Rank] Configuração inicial para o sistema de rank")
- .addRoleOption((option) =>
- option
- .setName("rank")
- .setDescription("Selecione o cargo inicial para o sistema de rank")
- .setRequired(true)
- )
- )
- .addSubcommand((subcommand) =>
- subcommand
- .setName("iniciar")
- .setDescription(
- "[Rank] Inicia o sistema de rank para todos os membros do servidor"
- )
- )
- .addSubcommand((subcommand) =>
- subcommand
- .setName("atualizar")
- .setDescription(
- "[Rank] Força a atualização dos rank de todos os membros do servidor"
- )
- ),
- /**
- * @param {Interaction} interaction
- * @param {Client} client
- */
- async execute(interaction, client) {
- const { options, guild } = interaction;
- const subCommand = options.getSubcommand([
- "configurar",
- "iniciar",
- "atualizar",
- ]);
- const successEmbed = new EmbedBuilder().setColor("Green");
- const warningEmbed = new EmbedBuilder().setColor("Yellow");
- const errorEmbed = new EmbedBuilder().setColor("Red");
- function meetsRequirement(joinDate, requirement) {
- const currentDate = new Date();
- const elapsedMilliseconds = currentDate - joinDate;
- const elapsedDays = elapsedMilliseconds / (1000 * 60 * 60 * 24);
- return elapsedDays >= requirement;
- }
- if (subCommand === "configurar") {
- return await interaction.reply({
- embeds: [
- errorEmbed.setDescription(
- "❌ No momento este comando não está funcionando..."
- ),
- ],
- ephemeral: true,
- });
- } else if (subCommand === "iniciar") {
- await interaction.reply({
- embeds: [
- warningEmbed.setDescription(
- `⏳ Iniciando sistema de rank para todos os membros do servidor, isso pode demorar um pouco...`
- ),
- ],
- });
- const members = await guild.members.fetch();
- const processingDelay = 100; // 1000ms (1 segundo) de atraso entre mensagens
- let num = 0;
- async function processMember(member) {
- try {
- const existingRankInfo = await DB.findOne({
- memberId: member.id,
- guildId: guild.id,
- });
- if (!existingRankInfo) {
- const newRankInfo = new DB({
- guildId: guild.id,
- memberId: member.id,
- joinTime: member.joinedAt,
- currentRankId: ranks.ranksTest.plebeu.roleId,
- });
- await newRankInfo.save();
- await member.roles
- .add(newRankInfo.currentRankId)
- .catch((err) => console.log(err));
- }
- } catch (error) {
- console.error(`Error processing member ${member.user.tag}: ${error}`);
- }
- num++;
- if (num === members.size) {
- await interaction.editReply({
- embeds: [
- successEmbed.setDescription(
- `✅ Sistema de rank iniciado para todos os membros do servidor.`
- ),
- ],
- ephemeral: true,
- });
- } else {
- await interaction.editReply({
- embeds: [
- warningEmbed.setDescription(
- `⏳ ${num}/${members.size} membros foram processados!`
- ),
- ],
- });
- }
- }
- for (const member of members.values()) {
- await processMember(member);
- await new Promise((resolve) => setTimeout(resolve, processingDelay));
- }
- }else if (subCommand === "atualizar") {
- // Início do comando
- await interaction.reply({
- embeds: [
- warningEmbed.setDescription(
- `⏳ Atualizando sistema de rank para todos os membros do servidor, isso pode demorar um pouco...`
- ),
- ],
- });
- try {
- const membersToUpdate = await DB.find({
- guildId: guild.id,
- });
- console.log(
- `\nFound ${membersToUpdate.length} members to update on guild ${interaction.guild.name}.\n`
- );
- let updatedMembersCount = 0;
- for (const memberInfo of membersToUpdate) {
- const member = await guild.members.fetch(memberInfo.memberId);
- if (!member) continue;
- for (const rankName of Object.keys(ranks.ranksTest).sort((a, b) => {
- // Ordene os ranks com base na hierarquia de cargos
- const roleA = guild.roles.cache.get(ranks.ranksTest[a].roleId);
- const roleB = guild.roles.cache.get(ranks.ranksTest[b].roleId);
- return roleA.comparePositionTo(roleB);
- })) {
- const rank = ranks.ranksTest[rankName];
- console.log(
- `Verifying user:${member.user.tag}\n${rankName}: ${
- rank.requirement
- } - Meet requirement: -> ${meetsRequirement(
- memberInfo.joinTime,
- rank.requirement
- )}`
- );
- // Verifique se o membro atende aos requisitos para o próximo rank
- if (
- meetsRequirement(memberInfo.joinTime, rank.requirement)
- ) {
- const nextRankName = Object.keys(ranks.ranksTest).find(
- (r) => ranks.ranksTest[r].roleId === rank.roleId
- );
- // Verifique o próximo cargo de rank
- const nextRank = guild.roles.cache.get(
- ranks.ranksTest[nextRankName].roleId
- );
- // Verifique se o membro já possui o próximo cargo de rank
- if (nextRank && !member.roles.cache.has(nextRank.id)) {
- // Remova o cargo do rank anterior se o membro já tiver um rank
- const currentRank = guild.roles.cache.get(
- memberInfo.currentRankId
- );
- console.log(
- `Verificando atual rank: ${currentRank.name} - ${member.user.tag}`
- );
- console.log(
- `Verificando próximo rank: ${nextRank.name} - ${member.user.tag}`
- );
- console.log(
- `Comparando rank ${
- currentRank.comparePositionTo(nextRank) < 0
- } - ${member.user.tag}`
- );
- // Verifique se o membro tem um cargo atual e se o próximo cargo é superior
- if (
- currentRank &&
- currentRank.comparePositionTo(nextRank) < 0
- ) {
- await member.roles.remove(currentRank);
- // Adicione o novo cargo e atualize a informação no banco de dados
- await member.roles.add(nextRank);
- memberInfo.currentRankId = nextRank.id; // Atualize no banco de dados
- await memberInfo.save();
- // Envie uma embed de confirmação para o membro promovido
- await interaction.channel.send({
- embeds: [
- successEmbed.setDescription(
- `✅ <@${member.id}> foi promovido a <@&${nextRank.id}>`
- ),
- ],
- });
- updatedMembersCount++;
- }
- }
- }
- }
- }
- if (updatedMembersCount === 0) {
- return await interaction.editReply({
- embeds: [
- warningEmbed.setDescription(
- `⚠️ Nenhum membro foi atualizado.`
- ),
- ],
- });
- }
- await interaction.followUp({
- embeds: [
- successEmbed.setDescription(
- `✅ **${updatedMembersCount}** membros tiveram seus ranks atualizados`
- ),
- ],
- });
- } catch (error) {
- console.error(`Error updating ranks: ${error}`);
- await interaction.followUp({
- embeds: [
- errorEmbed.setDescription(
- "❌ Ocorreu um erro ao atualizar os ranks dos membros."
- ),
- ],
- });
- // Final do comando
- }
- }
- },
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement