LifesGood
LifesGood

Reputation: 25

"mute" command gives random output

if(command === "mute"){
    const target = message.mentions.users.first();
    if (target) {

        if (!message.member.hasPermission("ADMINISTRATOR")) {
            return message.reply("Unauthorized");
        }
        let muted = client.settings.get(message.guild.id, 'mute')
        
        let muteRole = message.guild.roles.cache.find(role => role.name === muted);
        
        let memberTarget = message.guild.members.cache.get(target.id);

        let rolelist = memberTarget.roles.cache
            .map(r => r)

        if (!args[1]) {
          
            memberTarget.roles.remove(rolelist);
            memberTarget.roles.add(muteRole);
            message.channel.send(`<@${memberTarget.user.id}> has been muted`);
            return
        }
        memberTarget.roles.remove(rolelist);
        memberTarget.roles.add(muteRole);
        message.channel.send(`<@${memberTarget.user.id}> will be muted for ${ms(ms(args[1]))}`);

        setTimeout(function () {
            memberTarget.roles.add(rolelist);
            memberTarget.roles.remove(muteRole);
        }, ms(args[1]));
        
    } else {
        message.channel.send('User not found!');
    }

So I have this mute command which removes all your roles, gives you the muteRole, when time is up, it gives back your previous roles and removes the muteRole. The problem I'm having is that it sometimes removes all your roles and doesn't give you the muteRole, other times it doesn't remove the muteRole when the time is up. Sometimes it removes all your roles and doesn't give you the muteRole and when the times up it doesn't give your roles back...

Basically the outcome is always random. So my question is how do I make it consistent?

Upvotes: 0

Views: 53

Answers (1)

Toasty
Toasty

Reputation: 1880

The methods .add() and .remove() return a Promise so you should try using await / .then().

If you do it with this, the next function or .then() will not be executed until the promise is completely processed.

Example:

memberTarget.roles.remove(rolelist)
   .then(() => memberTarget.roles.add(muteRole))
   .then(() => message.channel.send('some message'));

Now you're nearly finished. The last thing you need is the .catch() block, because if the code above fails / throws an error you should catch that:

.catch(err => console.log(`An error occured: ${err}`))

Final result:

memberTarget.roles.remove(rolelist)
   .then(() => memberTarget.roles.add(muteRole))
   .then(() => message.channel.send('some message'))
   .catch(err => console.log(`An error occured: ${err}`));

References

Upvotes: 1

Related Questions