我正在制作一个音乐机器人,当成员写“〜play”时,机器人在文件夹中搜索随机文件(.mp3),并加入用户当前所在的语音通道。我希望机器人离开所有用户都离开语音通道时进入语音通道。
const fs = require('fs');
module.exports.run = async (bot, message, args) => {
let channel = message.member.voice.channel;
if(!channel) return message.reply("You're not connected to a voice channel!");
if (channel) {
channel.join()
.then(connection => {
const commandFiles = fs.readdirSync('./commands/Workout/').filter(file => file.endsWith('.mp3'));
let randomfile = commandFiles[Math.floor(Math.random() * commandFiles.length)]
const dispatcher = connection.play(`./commands/Workout/${randomfile}`);
dispatcher.on('start', () => {
dispatcher.setVolume(0.70);
message.reply(" started this song: " + ` ${randomfile}`)
}).catch(err => console.error(err))
//console.log("Playing music");
})
dispatcher.on('error', (err) => console.log(err));
if(channel.members == 1){ //this is the problem
channel.leave()
}
dispatcher.on('finish', finish => {
message.reply(" Song ended! - " + ` ${randomfile}`)
//console.log("Playing ended");
channel.leave()
})
}).catch(err => console.error(err))
}
答案 0 :(得分:0)
嗯,我不知道它是否已经是not的数组,如果是的话
channel.members.length == 1
答案 1 :(得分:0)
我找到了答案。这是我的代码:
const fs = require('fs');
module.exports.run = async (bot, message, args) => {
let found = 0;
let channel = message.member.voice.channel;
if (channel) {
channel.join()
.then(connection => {
const commandFiles = fs.readdirSync('./commands/Workout/').filter(file => file.endsWith('.mp3'));
let randomfile = commandFiles[Math.floor(Math.random() * commandFiles.length)]
const dispatcher = connection.play(`./commands/Workout/${randomfile}`);
dispatcher.on('start', () => {
dispatcher.setVolume(0.70);
message.reply(" has started this song: " + ` ${randomfile}`).then(sent => {
sentmessage = sent;
//console.log(id);
}).catch(err => console.error(err))
//console.log("Playing music");
})
dispatcher.on('error', (err) => console.log(err));
const voicechannel = message.member.voice.channel; //saving the voicechannel to an array
for (const [memberID, member] of voicechannel.members) { //look for member in the voicechannel array
if(member.user) found++; //member gives giuld.user, when found, found++
if(found < 1) return channel.leave();
//console.log("when bot joins:" + found);
}
bot.on("voiceStateUpdate", (oldState, newState) => {
let oldVoice = oldState.channelID;
let newVoice = newState.channelID;
if (oldVoice != newVoice) {
if (oldVoice == null) {
//console.log("before join:" + found);
found++;
//console.log("after join:" + found);
//console.log("User joined!");
}
if (newVoice == null) {
//console.log("before leaving:" + found);
found--;
//console.log("after leaving:" + found);
if(found == 1) return channel.leave();
}
}
})
dispatcher.on('finish', finish => {
message.reply(" song ended! - " + ` ${randomfile}`)
//console.log("Playing end");
channel.leave()
})
}).catch(err => console.error(err))
}
};
module.exports.help = {
name: "play"
};