Home > Net >  Discord.js Bot that Automatically Gives Roles
Discord.js Bot that Automatically Gives Roles

Time:10-27

I'm trying to find out how to give a person a role automatically once he joins a server on Discord. The tutorial I watched didn't explain this very well.

Here's a snippet of I have so far:

const fs = require('node:fs')
const path = require('node:path')
const { Client, Collection, GatewayIntentBits } = require('discord.js')
const { token } = require('./config.json')

const client = new Client({ intents: [GatewayIntentBits.Guilds], partials: ["MESSAGE", "CHANNEL", "REACTION"] })
client.commands = new Collection()

const commandsPath = path.join(__dirname, 'commands')
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'))
client.on('guildMemberAdd', guildMember => {
    guildMember.roles.add('ROLE ID')
    guildMember.guild.channels.cache.get('CHANNEL ID').send(`<@${guildMember.user.id}> joined as <@ROLE ID>!`)
})

Does anyone have any idea as to what I should do?

Thanks!

I expected an automatic Discord bot that gives someone a role on joining, but I got nothing. Nothing seems to respond.

CodePudding user response:

Discord has made it so that listening for member join events is now a privileged intent, so you must add it:

const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers], partials: ["MESSAGE", "CHANNEL", "REACTION"] });

See this page in the guide.

CodePudding user response:

I am attaching a code that works for sure to add a roll to every user who joins the server, (edit the role id)

client.on('guildMemberAdd', (member) => {
      let welcomeRole = member.guild.roles.cache.find(role => role.id == 'yourRoleId');
      if (!welcomeRole) return console.log('Couldn\'t find the member role.');
      member.roles.add(welcomeRole);
    });
  • Related