How to remove a role from someone who leaves a voice channel?

Viewed 212

I am currently making a Discord bot that assigns a role when you enter a specific voice channel and removes it when you leave. Here is the code:

client.on('voiceStateUpdate', (oldState, newState) => {

const testChannel = newState.guild.channels.cache.find(c => c.name === ' 1h de travail');
const role = newState.guild.roles.cache.find(r => r.name === 'test');

if (newState.channelID === testChannel.id) {
  // Triggered when the user joined the channel we tested for
  if (!newState.member.roles.cache.has(role))
    newState.member.roles.add(role); 
    // Add the role to the user if they don't already have it
  }
  else {
    console.log('detected');

    if (oldState.voiceChannel !== undefined && newState.voiceChannel === undefined)
      oldState.member.roles.remove(role);
  }
});

My issue is that it doesn't actually remove the role. How can I make it do so?

1 Answers

VoiceState doesn't have a voiceChannel property, so both your oldState.voiceChannel and newState.voiceChannel will be undefined. As you're checking if one of them is undefined AND the other one is not undefined, the if statement will always be false and you will never remove the role.

The good news is that VoiceState does have a channel property which you can use in this case. It is the channel that the member is connected to and has a type of VoiceChannel.

The following code should work as expected. I also made it a bit simpler than the original.

client.on('voiceStateUpdate', (oldState, newState) => {
  const testChannel = newState.guild.channels.cache.find(
    (c) => c.name === ' 1h de travail',
  );
  const role = newState.guild.roles.cache.find((r) => r.name === 'test');

  // Triggered when the user joined the channel we tested for
  if (newState.channelID === testChannel.id) {
    // Add the role to the user if they don't already have it
    if (!newState.member.roles.cache.has(role)) {
      newState.member.roles.add(role);
    }
  }

  // Triggered when the user left the voice channel
  if (oldState.channel && !newState.channel) {
    oldState.member.roles.remove(role);
  }
});
Related