How do I get the user count of a voice by channel id? I'm using Discordjs v.13.
Here's my current code:
async function usercount(channelId) {
try {
let voiceChannel = Client.guilds.cache
.get('guildId')
.channels.cache.get(channelId);
let membersInChannel = voiceChannel.members.size;
console.log(membersInChannel);
} catch (error) {
logger.error('Error while performing usercount');
console.log(error);
}
}
You can get the number of members by fetching the voice channel by its ID and grabbing its members
property. You'll probably need to use the { force: true }
option to skip the cache check and request the API. This way, when someone leaves/joins the channel, the number will still be accurate.
Notice that you will either need a guild ID or a guild to which the voice channel belongs.
async function userCount(guildId, channelId) {
try {
let guild = client.guilds.cache.get(guildId);
let voiceChannel = await guild.channels.fetch(channelId, { force: true });
return voiceChannel.members?.size;
} catch (error) {
logger.error('Error while performing usercount');
console.log(error);
}
}
And here is an example how to use this. Here, I'm passing down the message.guild.id
as the guild ID, and the first argument as the channel ID.
const { Client, Intents } = require('discord.js');
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_VOICE_STATES,
],
});
client.on('messageCreate', async (message) => {
if (message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
const channelId = args[0];
message.reply(
`There are ${await userCount(
message.guild.id,
channelId,
)} members in the voice channel _"${
message.guild.channels.cache.get(channelId).name
}"_`,
);
});
Important: Don't forget that you'll need to enable the GUILD_VOICE_STATES
intents. Without that the number of connected members won't change.