This code assigned specified role to a list of members. The problem when I try to get the member with userID from message.guild.members.
Code
// !roleAssign @role
const roleAssign = async function(message){
const Role = message.mentions.roles.first();
// split by new line
const users = message.content.slice(prefix.length).split(/\r?\n/).slice(1);
let members = await message.guild.members.fetch();
users.forEach(user => {
const u = client.users.cache.find(u => u.tag === user);
if(u){
const userId = u.id;
// member with the userID
let member = members.cache.get(userId);
// give role to the member
try{
member.roles.add(Role)
}
catch(e){console.error(e)};
});
}
I get this error. How do I use get function with fetched members?
let member = members.cache.get(userId);
^
TypeError: Cannot read properties of undefined (reading 'get')
It's because guild.members.fetch()
returns a collection, not a GuildMemberManager
that has a cache
property. It means, you can use Collection#get()
like this, without the cache
:
let member = members.get(userId);