client.on('ready', () => {
arrayID = ['DISCORD_ID'];
guild.members.fetch(arrayID[0]).then(member => {
return guild.roles.fetch('ROLE_ID');
}).then(role => {
return member.roles.add(role);
}).catch((err) => {
});
});
With that code I am receiving the error: guild is not defined because of that I tried it with
client.guild.members.fetch(arrayID[0]).then(member => {
But then I am receiving the error: Cannot read properties of undefined (reading 'members')
CodePudding user response:
The problem is you haven't defined your guild
variable, that's why you received the error "guild is not defined". The other one is because client
doesn't have a guild
property.
Don't forget that your bot can be in different guild
s. You can get these guilds using client.guilds
. It returns a GuildManager
and its cache
returns a collection.
If you know your guild ID, you can get the guild like this:
let guild = client.guilds.cache.get('YOUR_GUILD_ID')
If your bot is only in a single guild, you could grab the first()
one in this collection:
let guild = client.guilds.cache.first()
Once guild
is defined, the rest of your code should work, although you should log the error in your catch
block. Oh, and member
won't be available in your second then
, so you should fix that too.
You could use async/await to make it more readable:
client.on('ready', async () => {
let arrayID = ['DISCORD_ID'];
let roleID = '928938568624263178';
let guild = client.guilds.cache.get('GUILD_ID');
try {
let member = await guild.members.fetch(arrayID[0]);
let role = await guild.roles.fetch(roleID);
if (!member) return console.log(`Can't find member with ID "${arrayID[0]}"`);
if (!role) return console.log(`Can't find role with ID "${roleID}"`);
member.roles.add(role);
} catch (err) {
console.log(err);
}
});