Search code examples
javascriptnode.jsdiscorddiscord.js

Detecting when role is given to a member with my bot discord.js


I am trying to detect when a user is given a certain role on a server.

My code is:

// Require the necessary discord.js classes

const { token } = require('./config.json');

// Create a new client instance

const Discord = require('discord.js');
const settings = require('./config.json');

const { Client, GatewayIntentBits, Partials } = require('discord.js');
const client = new Client({
  intents: [
    GatewayIntentBits.DirectMessages,
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildBans,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
  ],
  partials: [Partials.Channel],
});

client.on('ready', () => {
   console.log("- Bot logged in -");
});
client.on('guildMemberUpdate', (oldMember, newMember) => {
    console.log("updated")
    const oldRoles = oldMember.roles.cache,
          newRoles = newMember.roles.cache;

    // Has Role?
    const oldHas = oldRoles.has('1093515437792305222'),
          newHas = newRoles.has('1093515437792305222');

    // Check if removed or added
    if (!oldHas && newHas) {
        console.log("got role")

    }
});
client.on('messageCreate', async (message) => {
  console.log("got message")
  if (message.content.includes('changeNick')) {
    message.member.setNickname(message.content.replace('changeNick ', ''));
}
});

client.login(settings.token);

Everything works, apart from the role update. I have tried adding intentions, but maybe didn't set the right ones?


Solution

  • The guildMemberUpdate event will need the Guilds, GuildMembers and GuildPresences intents to fire:

    const client = new Client({
      intents: [
        GatewayIntentBits.DirectMessages,
        GatewayIntentBits.GuildBans,
        GatewayIntentBits.GuildMembers,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.GuildPresences,
        GatewayIntentBits.Guilds,
        GatewayIntentBits.MessageContent,
      ],
      partials: [Partials.Channel],
    });