Search code examples
javascriptbotsdiscorddiscord.jsreplit

.hasPermissions not working? Type Error: Cannot read property of undefined client?


My friends an I are trying to make a Discord Bot. We are currently trying to make a kick command. However, when we try to kick a member with no roles, and only ever basic perms, It doesn't work and this error appears on Repl.it console:

if(member.hasPermission("ADMINISTRATOR"))
                  ^

TypeError: Cannot read property 'hasPermission' of undefined
at Client.client.on.msg

And then a whole error paragraph.

Here is our code:

I have tried looking for solutions, but couldn't find any. Most websites I've found all use has.Permission() and on post on GitHub says to use perm.has but apparently "perm" is not defined. Here is the Github post: https://github.com/AnIdiotsGuide/discordjs-bot-guide/blob/master/understanding/roles.md

const Discord = require('discord.js');
const client = new Discord.Client();
const token = process.env.DISCORD_BOT_SECRET;

client.on('ready', () => {
  console.log("I'm in.  My prefix is &.");
  console.log(client.user.username);
});

client.on('message', msg => {
    if (msg.author.id != client.user.id)
    {
      if(msg == "&help")
      {
        msg.channel.send("Here are some commands you can do! (prefix is &):");
      }    
      if (msg.content.startsWith("&kick")) 
      {
        if(member.hasPermission("ADMINISTRATOR"))
        {
          // Easy way to get member object though mentions.
          var member = msg.mentions.members.first();
          // Kick
          member.kick().then((member) => {
            // Successmessage
            message.channel.send(member.displayName + " has been successfully kicked!");
          }).catch(() => {
             // Failmessage
            msg.channel.send("Access Denied");
          });
        }
      }
    }
});


client.login(token);

Solution

  • It looks like you're not setting your member variable, or you're using the incorrect variable to reference the user running the command.

    You can either set the member variable to the member calling the command, but since you're only using it once, it's better to simply use it directly.

    ...
    if (msg.content.startsWith("&kick")) 
          {
            // Get the member calling the command.
            if(msg.member.hasPermission("ADMINISTRATOR"))
    ...
    

    Note that the given solution will cause problems if this command was run inside of Direct Messages.