Search code examples
javascriptnode.jsdiscordpermissionsdiscord.js

TypeError: Cannot read properties of undefined (reading 'has') Discord.JS V14


I'm trying to check permissions for a user, if the user is admin it won't do anything else it'll return "No links allowed". I'm having issue with the permission check.

My code is:

client.on("messageCreate", (message) => {
  let regexp =
    /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
  if (regexp.test(message.content)) {
    if (
      message.author.permissions.has(PermissionFlagsBits.Administrator)
    ) {
      return;
    } else {
      message.delete().then(() => {
        message.channel.send(`**<@${message.author.id}> No links allowed!**`);
      });
    }
  }
});

And I get the error:

TypeError: Cannot read properties of undefined (reading 'has')
    at Client.<anonymous> (/home/runner/sancturopolis-city-assistant/index.js:65:34)

I also tried:

client.on("messageCreate", (message) => {
  let regexp =
    /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
  if (regexp.test(message.content)) {
    if (
      message.author.id.permissions.has(PermissionFlagsBits.Administrator)
    ) {
      return;
    } else {
      message.delete().then(() => {
        message.channel.send(`**<@${message.author.id}> No links allowed!**`);
      });
    }
  }
});

But still the same error.

I was expecting if the user is admin it won't do anything else it'll return "No links allowed".


Solution

  • message.author is a User and only GuildMembers have permissions. To get the message author as a GuildMember, you can use message.member instead:

    message.member.permissions.has(PermissionFlagsBits.Administrator)