How to fix: roles is not defined (Discord.js)

1.1k views Asked by At

I'm trying to add a role to a member when they join my server, here is the code I have:

The problem I'm getting is "ReferenceError: roles is not defined" can someone please help me solve this?

client.on("guildMemberAdd", (member) => {
    console.log("User " + member.user.username + " has joined the server!");
    var role = member.guild.roles.cache.find((role) => role.name === "Javjajjaj");
    roles.add(role);
});
1

There are 1 answers

0
Jakye On BEST ANSWER

The problem is that the roles variable is never defined within your piece of code.


client.on("guildMemberAdd", GuildMember => {
    // Logging when a GuildMember enters the Guild.
    console.log(`${GuildMember.user.tag} joined ${GuildMember.guild.name}!`);

    const Role = GuildMember.guild.roles.cache.find(role => role.name == "Javjajjaj"); // Finding the Role by name in the GuildMember's Guild.

    // Checking if the role exists.
    if (!Role) return console.error("Couldn't find the role!");
    // Trying to add the Role to the GuildMember and catching any error(s).
    GuildMember.roles.add(Role).catch(error => console.error(`Couldn't add the Role to the GuildMember. | ${error}`));
});