如何从离开语音频道的人中删除角色?

时间:2021-01-26 15:23:59

标签: javascript node.js discord.js bots

我目前正在制作一个 Discord 机器人,它会在您进入特定语音频道时分配角色,并在您离开时将其删除。代码如下:

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);
  }
});

我的问题是它实际上并没有删除角色。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

VoiceState 没有 voiceChannel 属性,因此您的 oldState.voiceChannelnewState.voiceChannel 都将是 undefined。当您检查其中一个是否为 undefined 而另一个不是 undefined 时,if 语句将始终为 false,并且您永远不会删除该角色。

好消息是 VoiceState 确实有一个 channel 属性,您可以在这种情况下使用它。它是成员连接到的频道,类型为 VoiceChannel

以下代码应该可以正常工作。我也让它比原来的简单一点。

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);
  }
});