What is the best way to list the members inside a voice channel ?

Hello I would like to know the best way to list all members inside a voice channel. Does the property "members" is fully reliable ? Right now I have this code but I wanted to be sure that's the correct way
const channel = await guild.channels.fetch("<id>")
.catch( err => {
if (err.status === 404) {
return null;
}

throw err;
});
if (channel?.type !== ChannelType.GuildVoice) {
throw new Error("Not a voice channel");
return;
} else if (channel.members.size > 0) {
throw new Error("Some users are still in voice channel");
return;
}
const channel = await guild.channels.fetch("<id>")
.catch( err => {
if (err.status === 404) {
return null;
}

throw err;
});
if (channel?.type !== ChannelType.GuildVoice) {
throw new Error("Not a voice channel");
return;
} else if (channel.members.size > 0) {
throw new Error("Some users are still in voice channel");
return;
}
Versions - discord.js : 14.15.3 - node.js : 20.14.0
6 Replies
d.js toolkit
d.js toolkit4mo ago
- What's your exact discord.js npm list discord.js and node node -v version? - Not a discord.js issue? Check out #other-js-ts. - Consider reading #how-to-get-help to improve your question! - Explain what exactly your issue is. - Post the full error stack trace, not just the top part! - Show your code! - Issue solved? Press the button! - Marked as resolved by OP
chewie
chewie4mo ago
You definitely need the GuildVoiceStates intent, then it could work also you dont need to fetch the channel, you can just grab it from cache (which is what fetch is doing too, but with a promise)
Apokalypt
ApokalyptOP4mo ago
Yeah I have it So the getter members will always be up to date even if all the members are not in the cache ?
chewie
chewie4mo ago
since the .members property on a voice channel points to VoiceStates and not members, it should but I'm not 100% sure
Apokalypt
ApokalyptOP4mo ago
Ok thanks, I'll consider it reliable. In my use case it shouldn't be a problem since it's a custom bot and I shouldn't reach the cache size limit so I should have everything in the cache 👍 For the channel, I used to call fetch all the time and let discord.js decide whether to take it into the cache or not 😂
chewie
chewie4mo ago
channels are cached by default, so all your fetch does is grab the channel from cache anyway, no api request but its an unnecessary promise
Want results from more Discord servers?
Add your server