试图检测用户何时离开,以便discord机器人可以离开



所以这里我希望我的音乐机器人在没有人在vc时离开vc。它确实有效,但对某些人来说,它会重复两次离职过程。我试过修补它,但找不到为什么它会离开两次的问题!这是我的代码:

const ytdl = require("ytdl-core-discord");
exports.run = async (client, message, args, ops) => {
const voiceChannel = message.member.voice.channel;
if (!message.member.voice.channel) return message.channel.send("Hm... I don't see you in a Voice Channel! Please connect to a voice channel before executing this command!");
if (message.guild.me.voice.channel) return message.channel.send("Smh! I am already playing in another vc!");
let validate = await ytdl.validateURL("Some Link");
if(!validate) return message.channel.send("This stream seems to be unaivalable, please try again later!");
let connection = await message.member.voice.channel.join();
let dispatcher = await connection.play(await ytdl("Some Link"), { type: 'opus' });
message.channel.send('Now Playing Some **Some Stream** by Some Person');
client.on('voiceStateUpdate', (oldMember, newMember) => {
let newUserChannel = newMember.voiceChannel
let oldUserChannel = oldMember.voiceChannel

if(oldUserChannel === undefined && newUserChannel !== undefined) {
// User Joins a voice channel
console.log("Staying in VC");
} else if(newUserChannel === undefined){
try{
if (voiceChannel) {
setTimeout(function() {
console.log("Leaving a VC!")
message.guild.me.voice.channel.leave();
}, 3000)
}
} catch(e) {
console.log(e);
}
}
})
}

您的代码有一些问题,对于newUserChanneloldUserChannel,您应该将其更改为.

let newUserChannel = newMember.channel
let oldUserChannel = oldMember.channel

当你检查oldUserChannelnewUserChannel的状态时,而不是对照undefined检查,而是对照null检查:

if(oldUserChannel === null && newUserChannel !== null) { ... }

在你的尝试中。。。catch您应该将健全性检查更改为newUserChannel

try {
if (newUserChannel) {

全代码

bot.on('voiceStateUpdate', (oldMember, newMember) => {
let newUserChannel = newMember.channel
let oldUserChannel = oldMember.channel
if(oldUserChannel === null && newUserChannel !== null) {
console.log("Staying in VC");
} else if(newUserChannel === null){
try{
if (newUserChannel) {
setTimeout(function() {
console.log("Leaving a VC!")
message.guild.me.voice.channel.leave();
}, 3000)
}
} catch(e) {
console.log(e);
}
}
});

最新更新