【问题标题】:How to remove a role from someone who leaves a voice channel?如何从离开语音频道的人中删除角色?
【发布时间】:2021-04-30 09:38:01
【问题描述】:

我目前正在制作一个 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);
  }
});

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

【问题讨论】:

    标签: javascript node.js discord.js bots


    【解决方案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);
      }
    });
    

    【讨论】:

    • 非常感谢,它运行良好!只需将 AND 更改为 OR,以便在切换频道时正确删除角色,现在非常完美!
    猜你喜欢
    • 2018-06-16
    • 2021-07-06
    • 2021-04-24
    • 2019-04-08
    • 2020-07-17
    • 2020-10-24
    • 1970-01-01
    • 2019-07-08
    • 1970-01-01
    相关资源
    最近更新 更多