Reputation: 23
I am trying to assign a role to a user who direct messaging the bot. Although the user was being assigned the role but it throw the error below and shut down my program. I have been researching this issue for few hours but still no luck.
TypeError: Cannot read properties of undefined (reading 'id')
Error Stack
TypeError: Cannot read properties of undefined (reading 'id')
at GuildMemberRoleManager.get cache [as cache] (C:\Users\josh\Desktop\discord\node_modules\discord.js\src\managers\GuildMemberRoleManager.js:36:101)
at Client.<anonymous> (C:\Users\josh\Desktop\discord\discordBot.js:46:23)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
TypeError Cannot read properties of undefined (reading 'id')
UNHANDLED REJECTION! 💥 Shutting down...
[nodemon] app crashed - waiting for file changes before starting...
Here is my code.
const { Client, Intents } = require('discord.js');
const client = new Client({
partials: ['CHANNEL'],
intents: [Intents.FLAGS.DIRECT_MESSAGES, Intents.FLAGS.GUILD_MEMBERS],
});
client.once('ready', () => {
console.log(`Ready!`);
});
client.on('messageCreate', async (message) => {
if (message.author.bot) return;
if (message.content.startsWith('/test')) {
const member = await client.guilds.cache
.get(process.env.DISCORD_GUILD_ID)
.members.fetch(message.author.id);
await member.roles.add('123456789012345678');
}
});
client.login(process.env.DISCORD_TOKEN);
Upvotes: 2
Views: 620
Reputation: 9041
This is because of the lack of GUILDS
intent. If you look at the source code, here, it shows that it tries to get the @everyone role from cache, but can't find it since it's not cached (giving undefined
).
Provide GUILDS
intent to fix
const client = new Client({
partials: ['CHANNEL'],
intents: [Intents.FLAGS.DIRECT_MESSAGES, Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS],
})
Upvotes: 1