如何检查discord.js机器人是否与该成员在同一语音通道内



问题:
我无法检查我编程的dscord.js bot是否与试图命令它的成员在同一个语音通道中。我需要一个类似:if (client.member.voice.channel==true)的函数。然后如果";如果";声明是真的,机器人会执行命令,如果不是,机器人会道歉并说你需要和机器人在同一个频道。

我正在使用的代码:

const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => res.send('Music Bot'));

app.listen(port, () => console.log(`Web is ready!`));

const Discord = require('discord.js');

const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
const ffmpeg = require('ffmpeg-static');
const client = new Discord.Client()
//=========================================

client.once( 'ready', () => {

console.log('Bot is ready!')
client.user.setActivity(`Use +play or +leave!`, { type: "LISTENING" }).catch(console.error)
});

client.on('message', async msg => {

const args = msg.content.trim().split(/ +/g);

if(msg.content.startsWith('+play'))
{
const voiceChannel = msg.member.voice.channel;
let videoName = msg.content.slice(5).trim()

if (!voiceChannel) return msg.channel.send('You need to be in a channel to play music!');
const permissions = voiceChannel.permissionsFor(msg.client.user);

if (!videoName) return msg.channel.send('You need to type the song name!');

const validURL = (str) =>{
var regex = /(http|https)://(w+:{0,1}w*)?(S+)(:[0-9]+)?(/|/([w#!:.?+=&%!-/]))?/;
if(!regex.test(str)){
return false;
} else {
return true;
}
}

if(validURL(args[0])){

const  connection = await voiceChannel.join();
const stream  = ytdl(args[0], {filter: 'audioonly'});

connection.play(stream, {seek: 0, volume: 1})
.on('finish', () =>{
voiceChannel.leave();
msg.channel.send('Leaving channe!');
});

await msg.reply(`Now Playing ***Your Link!***`)

return
}


const  connection = await voiceChannel.join();

const videoFinder = async (query) => {
const videoResult = await ytSearch(query);

return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;

}

const video = await videoFinder(args.join(' '));

if(video){
const stream  = ytdl(video.url, {filter: 'audioonly'});
connection.play(stream, {seek: 0, volume: 1})
.on('finish', () =>{
voiceChannel.leave();
});

await msg.reply(`Now Playing ***${video.title}***`)
} else {
msg.channel.send('No results found');
}
}
if(msg.content.startsWith('+leave'))
{
const voiceChannel = msg.member.voice.channel;

if(!voiceChannel) return msg.channel.send("You need to be in a voice channel to stop the music!");
await voiceChannel.leave();
await msg.channel.send(`Leaving **${voiceChannel.name}**!`)


}




});

client.login(process.env.Token)

我需要什么:

检查机器人是否已经在另一个语音通道中的功能与上面的代码类似;"问题";。

谢谢

client有一个返回ClientVoiceManagervoice属性。voice.connections返回VoiceConnection的集合,因此它具有size属性。

这意味着您可以检查client.voice.connections.size是否大于0。如果是,则机器人在语音通道中。

在discord.js v13和v14中,ClientVoiceManager不再具有connections属性,但可以使用client.voice.adapters。在这种情况下,您可以检查client.voice.adapters.size

最新更新