How to add a role to a user in a specific guild

Viewed 157

So I have this current code:

const mutualGuilds = bot.guilds.cache.filter((guild) => {
  return guild.members.cache.has(message.author.id);
});

if (mutualGuilds.roles.cache.has("guildid")) {
  if (mutualGuilds.users.cache.has(user.id)) {
    let userInGuild = mutualGuilds.users.cache.find(user.id).roles.add("roleid");
  }
}

And when I try the command it outputs: Cannot read property 'cache' of undefined

If someone could help that would be amazing since my bot is on release today.

1 Answers

If you use the .filter method to get the mutualGuilds, it will return a collection. You can only access the .roles property on a single guild, so you need to grab the .first() one for example, like this:

const mutualGuilds = bot.guilds.cache.filter((guild) => {
  return guild.members.cache.has(message.author.id);
});

if (mutualGuilds.first().roles.cache.has("guildid")) {
  // ...

Or you can use the .each() method to execute the provided function once for each mutual guild:

const mutualGuilds = bot.guilds.cache.filter((guild) => {
  return guild.members.cache.has(message.author.id);
});

mutualGuilds.each((guild) => {
  if (guild.roles.cache.has("guildid")) {
  // ...
});
Related