如何修复:未定义角色 (Discord.js)

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

我正在尝试在成员加入我的服务器时为其添加角色,这是我的代码:

我遇到的问题是"ReferenceError: roles is not defined"有人可以帮我解决这个问题吗?

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);
});

问题是 roles 变量从未在您的代码段中定义。


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}`));
});