简体   繁体   中英

Discord Bot how to remove specific user roles

I have been trying to make a bot which is, if the user has 'role 1' then he typed in channel 'role 2' the bot should check if he has any of 'role 1 or role 3' remove them from the user then add 'role 2' to the user.

if (message == 'role 2') {
  var role = message.guild.roles.find("name", "2");

  if (message.member.roles.has('1')) {
    console.log('user has role 1');
    await message.member.removeRole("1");
    try {
      console.log('removed role 1');
    } catch(e){
      console.error(e)
    }
  }
  message.member.addRole(role);
}

But this isn't working, it's only adding roles not removing. console.log prints the following:

DeprecationWarning: Collection#find: pass a function insteadDeprecationWarning: Collection#find: pass a function instead

How I can check for user roles and remove them before adding a new one?


Edit: error fixed with this new code:

var role = message.guild.roles.find(role => role.name === "2")

But removing role command still not working.

  • It appears like message is a Message object. You should be comparing its content property rather than the object itself.
  • As Saksham Saraswat has also stated, you should pass a function into Collection.find() . Not doing so is deprecated.*
  • Map.has() searches by key. Collection s use Discord IDs as their keys, which are Snowflakes . The ID shown in your code is not an ID, so the block for that if statement isn't executed.
  • The way you've written await(...) is for executing a function. See the documentation here on the await keyword. Note that it can only be used inside of async functions .
  • You aren't catching any rejected Promises .*

* This is not affecting the current outcome of your code.

Implementing these solutions...

if (message.content === 'role 2') {
  try {
    // message.member will be null for a DM, so check that the message is not a DM.
    if (!message.guild) return await message.channel.send('You must be in a guild.');

    // Find Role 2.
    const role2 = message.guild.roles.find(role => role.name === '2');
    if (!role2) return console.log('Role 2 missing.');

    // If the user has Role 1, remove it from them.
    const role1 = message.member.roles.find(role => role.name === '1');
    if (role1) await message.member.removeRole(role1);

    // Add Role 2 to the user.
    await message.member.addRole(role2);
  } catch(err) {
    // Log any errors.
    console.error(err);
  }
}

I am guessing in message.guild.roles.find you have to pass in a function like message.guild.roles.find(function); also I think find is deprecated which means, out of date and substituted for a better solution/function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM