Search code examples
discord.js

Discord.js TypeError: Cannot read properties of undefined (reading 'add')


What is wrong with what I'm doing? I'm trying to make some code that detects when someone is trying to scam people. That's not the part that I'm have an error with. The error comes when I try to give the author of the message my muted role. Someone please help!

Here's the code:

// mute for 3 hours if anyone is scamming
client.on("messageCreate", async message => {
  if (message.author.bot) return;
  if (message.content.includes("free robux" || "free v-bucks" || ...)) {
    const target = message.author.username;
    const mutedRole = message.guild.roles.cache.get("1004037957902147676");

    message.delete();
    message.channel.send("@" + message.author.username + ", scamming is...");
    message.member.roles.add("1004037957902147676");

    setTimeout(() => {
      target.roles.cache.remove(mutedRole);
    }, 5000);
  }
}, {});

Here's the error: Cannot read properties of undefined (reading 'add')

Thanks!


Solution

  • Your code doesn't work for multiple reasons.

    • Your "pattern" inside the includes will only every check for the first item. (in your case "free robux", see MDN Logical Or (||)). To check for all the strings you'd either have to use a regex pattern or individually test every string you're searching for.

    • target is a string (the username of the message author). If you want to manage the user's roles, you'd have to change target to be message.member.

    Also you declared your callback as async, but didn't use any awaits.

    Your code should look something like this.

    const scamRegex = /pattern 1|second pattern|third pattern/;
    
    client.on('messageCreate', async (message) => {
      if (message.author.bot || !message.member) return;
      if (!scamRegex.test(message.content)) return;
    
      const userRoles = message.member.roles;
    
      await message.delete();
      await message.channel.send('...some warning...');
    
      await userRoles.add('<ROLE_ID>');
    
      setTimeout(() => userRoles.remove('<ROLE_ID>'), <MUTE_TIME_IN_MS>);
    });