'Filter out bots from member count in client status
I want to make my bot activity say "Watching + Member Count (not include bots)".
I did some steps, here is my code:
client.once('ready', () => {
setInterval(() => {
targetGuild = client.guilds.cache.get('My Guild ID Here')
client.user.setPresence({
activities: [{ name: `${targetGuild.memberCount} Users`, type: 'WATCHING' }],
status: 'online'
});
}, 1000 * 60 * 5);
});
The thing that I need is to set a filter that it calculate members only, not bots.
Solution 1:[1]
Use GuildMemberManager#fetch() to fetch all members, then use Collection#partition() to split the member collection into bots
and humans
. Use humans.size
to display the user count as you intend. You can also Collection#filter() to filter the member collection to just the humans, however I use partition in this example to have access to both parties in one function call.
client.once('ready', async() => {
targetGuild = client.guilds.cache.get('My Guild ID Here');
try {
const [bots, humans] = (await targetGuild.members.fetch())
.partition(member => member.user.bot);
setInterval(() => {
client.user.setPresence({
activities: [
{
name: `${humans.size} Users`,
type: 'WATCHING'
}
],
status: 'online'
});
}, 1000 * 60 * 5);
} catch (err) {
console.error(err);
}
});
Solution 2:[2]
In discord.js v13 the member counting with bot filtering should look like this:
setInterval(() => {
const guild = client.guilds.cache.get('GUILD_ID');
let humanMembers = guild.members.cache.filter(
(user) => !user.user.bot
);
const channel = guild.channels.cache.get('CHANNEL_ID');
channel.setName(`?Member Count Test: ${humanMembers.size.toString()}`);
}, 60000);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Pooyan |