Spectrum
Spectrum

Reputation: 21

DiscordJS Detecting when a User joins a guild

client.on('guildMemberAdd', guildMemberAdd => {
  console.log("Guild Member joined");
});

I know I have some noob error please help lmao, Just trying to simply detect when a user joins a guild/server and give them a certain role.

Upvotes: 1

Views: 8433

Answers (3)

jemiloii
jemiloii

Reputation: 25759

A couple ways of adding the roles. Either by id or by role. It's better to know the role ids as it will be faster, however you can look up the role by name as well.

client.on('guildMemberAdd', member => {
    // Set the member's roles by id
    member.setRoles([/* role id here */]);

    // Don't know the role id?
    const role = guild.roles.find(role => role.name === 'your role name');
    member.addRole(role);
});

Upvotes: 3

Blundering Philosopher
Blundering Philosopher

Reputation: 6805

From the docs on guildMemberAdd, you can see that the parameter returned in the function is actually a GuildMember (you put guildMemberAdd, probably because you didn't know what was passed into that callback).

From there, you can just use Guildmember.setRoles to give that member / user a specific role.

Try something like this:

// the parameter of the callback function is a `GuildMember` class, so name the variable
// something reasonable like 'guildMember', not 'guildMemberAdd'
client.on('guildMemberAdd', guildMember => {
    // Set the member's roles to a single role
    guildMember.setRoles(['<your role id>'])
        .then(console.log)
        .catch(console.error);
});

Upvotes: 0

Matt Pengelly
Matt Pengelly

Reputation: 1596

I just testing this code and it already works. Just have someone join your channel and you'll see that message in your console.

Upvotes: 0

Related Questions