How to count all online members using v13? - javascript

So I'm currently trying to get all online members in a specific guild and count them. I already tried these methods:
let onlineMembers = (await interaction.guild.members.fetch()).filter(
(member) => !member.user.bot && member.user.presence.status !== "offline"
);
and
let onlineMembers = interaction.guild.members.cache.filter(member => member.presence.status !== "offline").size
I also tried fetching all members first and filter the result like this:
const allMembers = await interaction.guild.members.fetch();
const onlineMembers = allMembers.filter(member => !member.user.bot && member.presence.status !== "offline");
But I'm always getting this exception:
TypeError: Cannot read property 'status' of undefined
So I went looking for a solution and I noticed that I manually have to activate all intents I want my bot to use. I "activated" the needed intents in my index.js like this:
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_PRESENCES
],
});
But this didn't fix my problem either.
In the Discord Developer Portal I also enabled both privileged gateway intents:
And who could have guessed...it still doesn't work. It's weird, because for some members it's working but I need it to work for every member.
Does somebody know how to fix this?

Fetching this information changed in V13
This code will generate an Object with the properties online, idle and dnd:
let GUILD_MEMBERS = await client.guilds.cache.get(config.ids.serverID).members.fetch({ withPresences: true })
var onlineMembers = {
online: await GUILD_MEMBERS.filter((online) => online.presence?.status === "online").size,
idle: await GUILD_MEMBERS.filter((online) => online.presence?.status === "idle").size,
dnd: await GUILD_MEMBERS.filter((online) => online.presence?.status === "dnd").size
}
Let me know, if this works for you

Related

Discord channel category name not found even though it exists

Im using the lastest Discord.js 14 and trying to create a new channel in the support category.
I manually created the category so I know it exists.
There are no channels in this category at present and this new channel the bot is trying to create will be the first one.
When I run this code console.log(supportCategory) the terminal shows undefined
Why?
// Require the necessary discord.js classes
const { Client, Events, GatewayIntentBits, ChannelTypes } = require('discord.js');
const { token } = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// When the client is ready, run this code (only once)
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
client.once(Events.ClientReady, c => {
console.log(`Ready! Logged in as ${c.user.tag}`);
});
client.on('ready', async () => {
console.log(`Logged in as ${client.user.tag}!`);
const guild = client.guilds.cache.first();
const supportCategory = guild.channels.cache.find(channel => channel.type === 'GUILD_CATEGORY' && channel.name === 'Support');
console.log(supportCategory) //this produces undefined
try {
const channel = await guild.channels.create('new-channel-name', {
type: 'GUILD_TEXT',
parent: supportCategory.id,
permissionOverwrites: [
{
id: guild.roles.everyone.id,
deny: ['VIEW_CHANNEL'],
},
],
});
console.log(`Channel created: ${channel.name}`);
} catch (error) {
console.error(error);
}
});
// Log in to Discord with your client's token
client.login(token);
You need to use the ChannelType enum to check a channel's category.
const supportCategory = guild.channels.cache.find(channel => channel.type === ChannelType.GuildCategory && channel.name === 'Support');

Cannot read properties of undefined (reading 'join') Discord.js

im trying to create my discord music bot, but when i run it. It cannot join my voiceChannel, returning this error: channel_info.channelId.join is not a function. Below, my code:
const Discord = require('discord.js');
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const ytdl = require('ytdl-core');
const streamOptions = { seek: 0, volume: 1 };
const botToken = 'mytoken';
bot.login(botToken);
bot.on('ready', () => {
console.log('to olain');
});
bot.on('message', msg => {
if (msg.author.bot) {
return;
}
if (msg.content.toLowerCase().startsWith(';p')) {
const channel_info = msg.member.guild.voiceStates.cache.find(user => user.id == msg.author.id);
if (channel_info.channelId == null) {
return console.log('Canal não encontrado!');
}
console.log('Canal encontrado');
channel_info.channelId.join().then(connection => {
const stream = ytdl('https://www.youtube.com/watch?v=BxmMGnvvDCo', { filter: 'audioonly' });
const DJ = connection.playStream(stream, streamOptions);
DJ.on('end', end => {
channel_info.channelId.leave();
});
})
.catch(console.error);
}
});
There are several issues in this code. Even if we fix some of these issues, this code will still not work due to differences between discord.js v12 and v13. Let's get started.
Issue #1
This is not one of the core issues causing your code to not work, but it's something useful to consider. You are doing this to get the voice state of the message author:
msg.member.guild.voiceStates.cache.find(user => user.id == msg.author.id);
When you could easily do the exact same thing in a much shorter, less-likely-to-produce-errors way:
msg.member.voice;
Issue #2
Now this is a core issue causing your code to not work. In fact, it is causing the error in your question. You are trying to do:
channel_info.channelId.join();
That does not make sense. You are trying to join a channel ID? channelId is just a String of numbers like so: "719051328038633544". You can't "join" that String of numbers. You want to join the actual channel that the member is in, like so:
channel_info.channel.join();
Issue #3
Based on how you are using a channelId property instead of channelID, I assume you are on discord.js v13. Voice channels do not have a .join() method on v13; in fact, discord.js v13 has no support for joining or playing audio in voice channels. You must install the discord.js/voice package in order to join a voice channel in discord.js v13. This is critical. Even if you fix the above two issues, you must solve this third issue or your code will not work (unless you downgrade to discord.js v12).

TypeError: Cannot read property 'roles' of undefined in discord.js

I am trying to get the bot to add roles in one discord and also add a role in another discord. but I keep getting the "roles" is not defined error. I have little to no coding knowledge and most of my code is a combination of things I find on google or friends teach me, so please excuse me if it is a dumb problem with a simple solution.
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.GUILD_ROLES] });
module.exports = {
name: 'accept',
description: 'Adds A Player To The Whitelist',
permissions: `ADMINISTRATOR`,
execute(message, args, add, roles, addRole, guild) {
message.delete()
let rMember = guild.roles.cache
message.mentions.members.first() || // `.first()` is a function.
message.guild.members.cache.find((m) => m.user.tag === args[0]) ||
message.guild.members;
let role1 =
message.guild.roles.cache.find((r) => r.id == roleID)
let role2 =
message.guild.roles.cache.find((r) => r.id == roleID)
let server = client.guilds.cache.get('guild ID')
let memberRole = server.guild.roles.get("role ID");
rMember.roles.add(role1).catch((e) => console.log(e));
rMember.roles.add(role2).catch((e) => console.log(e));
rMember.roles.add(memberRole).catch((e) => console.log(e));
rMember.send(`message content`);
message.channel.send('message content')
}};
The error occurs in this line:
let memberRole = server.guild.roles.get("872432775330955264");
let server = client.guilds.cache.get('guild ID')
let memberRole = server.guild.roles.get("role ID");
These particular lines justify your error, in the first case you are assigning the property of a guild object to server by getting the guild from the cache, now you see a guild object does not have a property further named guild to it so your error actually rests in the next line, where you are trying to get from server.guild it's same as saying guild.guild which makes no actual sense.
Only correction you would want to make with your code would be something of this sort:
let server = client.guilds.cache.get('guild ID')
let memberRole = server.roles.cache.get("role ID");

Member online counter

My member counter didn't work
Why always my channel have name "online 0" 0 errors, console log working I don't know why
This is my code
const guild = client.guilds.cache.get('693805106906398722');
setInterval(() =>{
const memberCount = guild.memberCount;
const channel = guild.channels.cache.get('824050164376666182');
channel.setName(`Użytkownicy ${memberCount.toLocaleString()}`);
console.log('Member Status: Updating...');
}, 1200000);
setInterval(() =>{
const memberCollection = guild.members.cache;
const online = memberCollection.filter(member => {
member.presence.status === 'online'
}).size;
const channel1 = guild.channels.cache.get('824050194177720391');
channel1.setName(`Online ${online}`);
console.log('Member online Status: Updating...');
}, 1200);
} ```
Do you have Intents Enabled in your bot? If you do not: Then please do it in the Discord Developers Portal for your Application. You need to enable Guild Members intent. Also please do not forget to update your stuff in the Client Constructor (aka const client = new Discord.Client()) so that you can access the guild Member information!
There's a mistake in the code
const online = memberCollection.filter(member => {
member.presence.status === 'online'
}).size;
Please make it
const online = memberCollection.filter(member => {
return member.presence.status === 'online'
}).size;
Since for the filter to work, you need to have a function which returns a boolean and you're not returning anything from your filter function, it is getting a bit messed up.

Discord.js GuildMember#roles appears to sometimes be undefined

I have a function that accepts a user ID, and should return an array of all role IDs the user has, from all guilds that the bot is a part of.
To achieve this I wrote the following code
async getRoleList(userId) {
const guilds = this.client.guilds.cache.array();
const guildRoles = [];
const proms = guilds.map(async (guild) => {
const member = await guild.members.fetch(userId).catch(() => {});
if (!member) return;
const roleCollection = member.roles.cache;
guildRoles.push(roleCollection.array().map((role) => role.id));
});
await Promise.all(proms);
const res = guildRoles.flat();
res.push(userId);
return res;
}
However, I have noticed that on occasion I get the following error: TypeError: Cannot read property 'cache' of undefined
I am not able to replicate this bug reliably, it just seemingly randomly is thrown in production. From what I can tell of the discord.js docs the roles property of GuildMember always be there, and so I do not understand how the GuildMember exists but has no role manager.
Try updating your discord.js version with npm. This might have been fixed.
https://github.com/discordjs/discord.js/issues/1870

Categories

Resources