Bot not responding when trying to give roles to mentioned users

I’m having trouble with my Discord bot. The bot logs in fine and shows the login message in console, but it won’t respond to commands at all. I want it to give a specific role to users when they get mentioned in a message.

client.once('ready', () => {
    console.log(`Bot is online as: ${client.user.tag}!`) 
})

client.on('messageCreate', (msg) => {
  if (msg.content.startsWith(COMMAND_PREFIX)) {
    const parameters = msg.content.slice(COMMAND_PREFIX.length).trim().split(/ +/);
    const cmd = parameters.shift().toLowerCase();

    if (cmd === 'giverole') {
      if (msg.mentions.users.size === 1) {
        const targetUser = msg.mentions.users.first();
        const targetRole = msg.guild.roles.cache.find((role) => role.name === 'Team A');

        if (targetRole) {
          const guildMember = msg.guild.members.cache.get(targetUser.id);
          guildMember.roles.add(targetRole)
            .then(() => {
              msg.reply(`Successfully gave ${targetRole.name} role to ${targetUser.tag}`);
            })
            .catch((err) => {
              console.error(err);
              msg.reply('Failed to assign the role.');
            });
        } else {
          msg.reply('Cannot find that role.');
        }
      } else {
        msg.reply('You need to mention exactly one user.');
      }
    }
  }
});

client.login(BOT_TOKEN);

The goal is to automatically assign the specified role to any user that gets mentioned in the command. What could be wrong with my setup?

I had the same problem - it’s probably your bot’s intents. Since you’re using messageCreate events, you need MESSAGE_CONTENT_INTENT enabled in the Discord Developer Portal. Without it, your bot sees messages but can’t read what’s inside them, so it won’t respond to commands. You also need to set the intents when creating your client: const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] }). This tripped me up too when Discord changed their intent requirements.

your code looks good but just check if COMMAND_PREFIX is set up properly. also, ensure ur bot has the right permissions and its role is above ‘Team A’ in the role hierarchy. that’s a common reason for issues like this.

Add some debug logging to your messageCreate event handler to see if your bot’s actually getting the messages. I had this exact problem and found out my COMMAND_PREFIX variable wasn’t set right - it was undefined, so the startsWith check just failed silently. Drop a console.log(‘Message received:’, msg.content) at the top of your messageCreate handler to check if the bot’s picking up messages. Also make sure COMMAND_PREFIX is actually set to ‘!’ or whatever you’re using. Your code looks fine, so it’s probably either the prefix variable or bot permissions in your server.