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?
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.