首页 > 解决方案 > 如果频道中没有人超过 5 分钟,如何让我的机器人离开语音频道

问题描述

所以最近我一直在为不和谐制作一个音乐机器人,但如果没有人在语音频道中超过 5 分钟,我想让我的机器人离开频道。现在我的机器人仅通过停止命令断开连接

    
    if (!queue) return message.reply("There is nothing playing.").catch(console.error);
    if (!canModifyQueue(message.member)) return;

    queue.songs = [];
    queue.connection.dispatcher.end();
    queue.textChannel.send(`${message.author} ⏹ stopped the music!`).catch(console.error);
  }
};

有人可以帮我弄这个吗?我将不胜感激。

标签: discorddiscord.js

解决方案


您可以使用该voiceStateUpdate事件,该事件在有人加入或离开语音频道(除其他外)时发出。

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

  // if nobody left the channel in question, return.
  if (oldState.channelID !==  oldState.guild.me.voice.channelID || newState.channel)
    return;

  // otherwise, check how many people are in the channel now
  if (!oldState.channel.members.size - 1) 
    setTimeout(() => { // if 1 (you), wait five minutes
      if (!oldState.channel.members.size - 1) // if there's still 1 member, 
         oldState.channel.leave(); // leave
     }, 300000); // (5 min in ms)
});

推荐阅读