Reputation: 23
I'm pretty new to working on Discord bots, but I'm trying to create a bot for Discord that gets all the members in a guild, so they can be used later on. But everytime I try to get the guild with its ID it gives an undefined back, even though I know I put in the right ID.
const Discord = require("discord.js");
const client = new Discord.Client();
const members = client.guilds.cache.get("guildID");
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
console.log(members);
});
client.login('token');
Am I doing something wrong?
Upvotes: 2
Views: 2595
Reputation: 1
Put the const members = client.guilds.cache.get("guildID");
inside the ready event.
Upvotes: 0
Reputation:
You aren't being very clear. You stated you want your bot to get all members in a guild, but you proceed to get a guild ID instead.
Assuming you want to get all members in a guild. First thing you need is Privileged Gateway Intents enabled in your bot and implemented in your code.
Step 1: Enable Intents
Bot
section of your bot and scroll down till you see "Privileged Gateway Intents" and select both "PRESENCE INTENT" and "SERVER MEMBERS INTENT
"Example
Step 2: Implementing In Code
const Discord = require('discord.js');
const client = new Discord.Client({ ws: { intents: new Discord.Intents(Discord.Intents.ALL) }});
^^^^^^^
This is what is making you access all server members within a guild
Code for getting all server members:
// If prefix not set: do this: const prefix = "!"; whatever you want
const prefix = "!";
// Usernames
const members = message.guild.members.cache.map(member => member.user.tag);
// ID's
const members = message.guild.members.cache.map(member => member.user.id);
if(message.content.startsWith(prefix + "test")){ // Gets all members usernames within the guild this message was sent on.
console.log(members) // Logs all each members username
}
In depth but I hope it helps.
Upvotes: 3
Reputation: 952
Before client is ready, use client.guilds.fetch('<guild id>')
which returns a promise. Note that before the ready event is triggered many things on the client are uninitialized such as client.user
Upvotes: 0
Reputation: 1
Try:
const members = client.guilds.cache.get("guildID");
list.members.cache.forEach(member => console.log(member.user.username));
Upvotes: -2
Reputation: 348
Try using this instead:
client.guilds.fetch("guildID");
Also, I recommend you put that line in your ready event or somewhere where you are sure the client has fully logged in when ran to make sure that it is logged in when you run that.
Upvotes: 0
Reputation:
I believe it's just:
client.guilds.get("guildID");
and not:
client.guilds.cache.get("guildID");
Upvotes: 0