当成员加入语音频道时授予角色。不和谐.js

时间:2021-04-23 22:30:48

标签: discord.js

我正在尝试编写 discord.js 代码。当成员加入语音频道时,我希望机器人给他们一个角色,当成员离开时,我希望删除该角色。感谢您的帮助。

  const newChannelID = newState.channelID;
  const oldChannelID = oldState.channelID;

  if (oldChannelID === "835280102764838942"){
    member.send('role given');
    let role = message.guild.roles.cache.find(r => r.id === "835279162293747774");
    member.roles.add(835279162293747774);

  } else if(newChannelID === "835280102764838942"){
    member.send('role removed');
    member.roles.remove(835279162293747774);

  }
})

1 个答案:

答案 0 :(得分:0)

您需要在代码中清理几件事情。我假设您正在使用 voiceStateUpdate 事件来触发您的命令。

最重要的是,(逻辑上)您实际上需要翻转添加和删除角色的方式。目前,通用代码规定,如果用户离开语音通道(因此 oldChannelID = 实际 vc ID),那么它实际上会给用户一个角色。这似乎与您的意图相反,因此您只需更换每个 if/else if 语句中的代码。

其次,您分配和添加角色的方式不正确。我建议this resource了解更多信息。

第三,如果您确实使用 message 作为事件,则无法访问 voiceStateUpdate,因为它只发出 oldStatenewState

最后,您需要指定一个文本通道来发送消息。在我的代码中,我手动抓取了我想要的频道的 ID 并将其插入代码中。您必须通过用您自己的特定字符串替换我拥有的数字字符串来执行相同的操作。

话虽如此,以下是正确的修改代码:

client.on('voiceStateUpdate', (oldState, newState) => {
    const txtChannel = client.channels.cache.get('803359668054786118'); //manually input your own channel
    const newChannelID = newState.channelID;
    const oldChannelID = oldState.channelID;

    if (oldChannelID === "800743802074824747") { //manually put the voice channel ID
        txtChannel.send('role removed');
        let role = newState.guild.roles.cache.get("827306356842954762"); //added this
        newState.member.roles.remove(role).catch(console.error);
    } else if (newChannelID === "800743802074824747") {
        txtChannel.send('role given');
        let role = oldState.guild.roles.cache.get("827306356842954762"); //change this somewhat
        oldState.member.roles.add(role).catch(console.error); //adding a catch method is always good practice
    }
})