Jacob Clark
Jacob Clark

Reputation: 97

How to find a role by name and add a user to it (discord.js)

So I'm trying to create a bot that is more universal and can be added to more than one server. I've managed to reformat commands like announce or join messages etc. by using .find("name", "announcements").

My problem is that the same does not work for roles.

I've tried what little I could find on the internet, such as member.guild.roles.find("name", "Member") or member.guild.roles.find(role => role.name === "Member") but none of these work. A variety of different ways return different errors, but they usually say something along the lines of it not being an integer (I think) or snowflake.

This is the function that I am currently wrestling with:

client.on('guildMemberAdd', (member) => {
    var joinResponse = ("Hello **" + member.displayName + "**, welcome to **" + member.guild.name + "**!")
    let role = member.guild.roles.find("name", "Member");
    member.addRole(role).catch(console.error);
    member.guild.channels.find('name', 'general').send(joinResponse);

In short summary, what I'm looking for is the ability to get a role by name and add a user to it.

(I'm nearly certain it's possible, since popular bots like Dyno are capable of using commands to add roles to users.)

Upvotes: 0

Views: 13984

Answers (1)

user12042113
user12042113

Reputation:

client.on('guildMemberAdd', (member) => {
    const joinResponse = `Hello **${member.user.username}**, welcome to: **${member.guild.name}**!`
    let role = member.guild.roles.get('Member');
    if(!role) return console.log("Role doesen't exist.");
    member.addRole(role);
    const ch = member.guild.channels.get('general');
    if(!ch) return console.log("Channel doesen't exist.");
    ch.send(joinResponse);
});//You didn't have closing brackets (Could've been a problem)

First of all your string joinResponse was a function and you completely messed up merging it, I recommend using Template literal.

I used get function since it's a lot easier to use and cleaner, you only pass ID or name as a string.

To check if channel exists I used if statements and exclamation mark which means doesen't exist/false.

Upvotes: 1

Related Questions