Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

517
Views
Discord.js get Roles of a user by id: cannot read properties

I want to make a Discord.js bot that just checks if a member with the given ID has a role (by id). I know this is a duplicate, but .cache doesn't work for me, so I used the guild.members.fetch function:

const { Client, Intents, GuildMemberManager } = require('discord.js');
const { token, server_id } = require('./config.json');

// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

// When the client is ready, run this code (only once)
client.once('ready', () => {
    console.log('Ready!');
});

function validateUser(user_id) {
  const guild = server_id;
  guild.members.fetch(user_id)
  .then(console.log)
  .catch(console.error);
}

validateUser(491553591434412057)

// Login to Discord with your client's token
client.login(token);

However, I run into an error:

TypeError: Cannot read properties of undefined (reading ‘fetch‘).

Does anyone know a better way to get the roles without a written message etc. or how to fix this?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The problem is that your guild is not a guild but a string (server_id). You'll need to get the guild by this id:

const guild = client.guilds.cache.get(server_id);
if (!guild)
  return console.log(`Can't find the guild with ID ${server_id}`);

guild.members.fetch(user_id)
  .then(member => {
    // member.roles.cache is a collection of roles the member has
    console.log(member.roles.cache)

    if (member.roles.cache.has('ROLE ID'))
      console.log('member has the role')
  })
  .catch(console.error);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!