Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Discordjs V13: Add Role from Direct Message

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);

>Solution :

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],
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading