Search code examples
javascriptnode.jsmongodbdiscord.jscommando

Discord.js Commando need to havehasPermisison() needs to make it async or wait for database query


So I am working on a discord bot using discord.js and its commando framework.

I store some information in a mongodb database like server prefix or roles for certain commands to run.

The commando framework has a function called

hasPermission(message) {
   ...
}

This expects a value to return true or false and if true, command runs, if false command does not run and spits an error in discord.

Well I need to check that the user has a specific role or roles for them to use a certain command (moderation)

Here is the code

async hasPermission(message) {
   const perm = await roleList.find({Guild_id: message.guild.id})
   console.log(perm[0].Roles)
   return (message.member.roles.cache.some(role => perm[0].Roles.includes(role.name)))
}

Now, making it async just breaks its functionality and will always return true.

So I tried using promises like so

hasPermission(message){
   roleList.find({Guild_id: message.guild.id}).then(roles => {
      console.log(roles[0].Roles)
      const b= (message.member.roles.cache.some(role => roles[0].Roles.includes(role.name)))
      console.log("Has permission?", b)
      return b
   })
}

This returned true within the .then() but it did not go through and returned false (which is the default value)

The Database call works correctly, the comparison returns true when it should and false when it should, just the function hasPermission() does not run.

I need to check their roles from the database before they can run the command and there is not a built in "Role" check and I have had no luck with their discord support server. Any suggestions.


Solution

  • You were definitely on the right track! Instead of just using then, try returning a promise.

    hasPermission(message) {
      return new Promise((resolve, reject) => {
        roleList.find({
            Guild_id: message.guild.id
        }).then(perm => {
            console.log(perm[0].Roles);
    
            return resolve((message.member.roles.cache.some(role => perm[0].Roles.includes(role.name))));
        });
      });
    };
    

    This will return a promise that will resolve itself when the resolve function is called. Now you can simply await the hasPermission function when you call it, and it should return what you want it to. This also lets you use .then() on the hasPermission function as well if needed.