当Discord.js机器人断开连接时清除队列

时间:2020-10-11 11:50:30

标签: javascript node.js discord discord.js

我是discord.js的新手,我按照教程创建了一个简单的音乐机器人。
我唯一的问题是,当该机器人被用户从语音通道断开连接时,队列不会停止,并且当我尝试播放歌曲时,它不会重新连接并且join命令有效,但它不会播放任何内容。
当机器人断开连接时,如何清除队列。

disconnect picture

我的代码:

script-src 'self' 'unsafe-eval' 'unsafe-inline' https://hcaptcha.com https://*.hcaptcha.com;
frame-src 'self' https://hcaptcha.com https://*.hcaptcha.com;
style-src 'self' 'unsafe-inline' https://hcaptcha.com https://*.hcaptcha.com

1 个答案:

答案 0 :(得分:1)

好的,要完成这项工作,您需要做两件事。

  • 使用正确的侦听器
  • 如果漫游器断开连接,则删除队列

所以让我们这么做

您需要使用的听众是voiceStateUpdate,它可以跟踪语音通道参与者的所有更改,例如“静音”,“聋哑”,并且(也是重要的部分)连接和断开。它带有两个参数oldStatenewState。我们需要同时使用它们。

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

现在我们已经设置了侦听器,我们可以填充它。

首先,我们需要检查oldState的channelID是undefined还是null。两者都表明用户正在加入连接,并且由于我们只想在有人断开连接时采取行动,因此如果他们没有连接,我们需要返回。

if (oldState.channelID === null || typeof oldState.channelID == 'undefined') return;

接下来,我们需要检查触发此侦听器的用户是否是漫游器。如果每次有人断开任何语音通道的连接时我们都没有这样做,请清除队列。

if (newState.id !== client.user.id) return;

最后,我们可以使用公会的ID清除队列。

return queue.delete(oldState.guild.id);

现在,您的voiceStateUpdate侦听器应该看起来像这样:

client.on('voiceStateUpdate', (oldState, newState) => {
    // check if someone connects or disconnects
    if (oldState.channelID === null || typeof oldState.channelID == 'undefined') return;
    // check if the bot is disconnecting
    if (newState.id !== client.user.id) return;
    // clear the queue
    return queue.delete(oldState.guild.id);
    
});

https://discord.js.org/#/docs/main/stable/class/VoiceState