Discord: Assigning or Removing a Role by Button

40 Views Asked by At

I'm creating a discord bot in v14 and I'm having a problem in my code in the event when I click on a button with a certain ID

I have tried several options so far and nothing has worked. When the "Aluno" clicks on the button he receives the appropriate tag because he didn't have it, so far everything is perfect. My big problem is: If the "Aluno" already has the appropriate tag, how do I check if "Aluno" already has the tag and in that case remove it from the user? With the code below, whether or not the bot has the tag, it is executing the if, always giving the tag to the discord user. How do I resolve this issue?

if (interaction.customId === "ano1") {
      
      var guild = client.guilds.cache.get(`${config.servidor.id}`)
      const Aluno = await guild.members.fetch(interaction.user.id)
      const AlunoAno1 = await guild.roles.fetch(`${config["ID-role"]["ano.1"]}`)

      if (!Aluno.roles.cache.has(AlunoAno1)) {
        Aluno.roles.add(AlunoAno1)
        interaction.reply({ content: `**Olá ${interaction.user}, obtiveste o cargo ${AlunoAno1}.**\n*Visita <#${config["ID-chat"]["tags.ucs"]["ano.1"]}> para receberes as tags das Unidades Curriculares*`}).then((message) => {
          setTimeout(() => {
            message.delete();
          }, 15000);
        }).catch(console.error);

        let log_add_ano1 = new Discord.EmbedBuilder()
        .setColor("Green")
        .setFooter({ text: `${config.servidor.footer}`, iconURL: `${config.servidor.logo}`})
        .setDescription(`O Aluno ${interaction.user} \`${interaction.user.id}\` recebeu o cargo ${config["ID-role"]["ano.1"]}`)
        .setTimestamp()

        await interaction.guild.channels.cache.get(`${config["ID-chat"].logs["tags.ano"]}`).send({ embeds: [log_add_ano1] })
      
      } else {
        Aluno.roles.remove(AlunoAno1)
        interaction.reply({ content: `Olá **${interaction.user}**, removeste o cargo **${AlunoAno1}**.`}).then((message) => {
          setTimeout(() => {
            message.delete();
          }, 15000);
        }).catch(console.error);

        let log_remove_ano1 = new Discord.EmbedBuilder()
        .setColor("Red")
        .setFooter({ text: `${config.servidor.footer}`, iconURL: `${config.servidor.logo}`})
        .setDescription(`O Aluno ${interaction.user} \`${interaction.user.id}\` ficou sem o cargo ${config["ID-role"]["ano.1"]}`)
        .setTimestamp()

        await interaction.guild.channels.cache.get(`${config["ID-chat"].logs["tags.ano"]}`).send({ embeds: [log_remove_ano1] })
      }
0

There are 0 best solutions below