NewJs
NewJs

Reputation: 295

remove role automatically discord.js v13

i want to remove first role if user got second role. but dont why its not working. please help.

ex - suppose i got one role on joining. then if i manually give new role to user then first role that got from joining want to remove by automatically.

const { Client, Intents } = require('discord.js');
const client = new Client({
  intents: [
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES,
    Intents.FLAGS.GUILD_MEMBERS,
  ],
});

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('guildMemberAdd', (member) => {
  let MemberRole = member.guild.roles.cache.get('874556919354912768');
  member.roles.add(MemberRole);
});

// here im trying to remove role.
client.on('guildMemberUpdate', (member) => {
  let MemberRole = member.guild.roles.cache.get('874556919354912768');

  if (member.roles.cache.some((role) => role.name === 'bee')) {
    member.roles.remove(MemberRole);
  }
});

client.login('my_token');

Upvotes: 0

Views: 2618

Answers (1)

Skulaurun Mrusal
Skulaurun Mrusal

Reputation: 2847

The problem is that you are searching for the role on oldMember, which is an instance of GuildMember before the update. The guildMemberUpdate event's callback has two parameters.

client.on("guildMemberUpdate", (oldMember, newMember) => {
    if (newMember.roles.cache.some(role => role.name === "bee")) {
        newMember.roles.remove("874556919354912768");
    }
});

Also make sure that your bot's role is above the one you are trying to remove.

Note that the event won't get fired for GuildMembers that the client didn't cache. To fix that, you need to enable the partial GUILD_MEMBER.

const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES", "GUILD_MEMBERS"], partials: ["GUILD_MEMBER"] });

Tested using discord.js ^13.0.1.

Upvotes: 2

Related Questions