How to only allow certian roles ot use this command

I’m trying to only allow people with the Staff role to run this command. Basically what the command does, is allowing a bot to DM users the command is <prefix>send @RandomUserName <message>

I am trying to prevent random users from abusing this command to flood other players DMs.

client.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();
    if (message.member.roles.cache.some(role => role.name === 'Staff')) return;
    if (command === 'send'){
        function getUserFromMention(mention) {
            if (!mention) return;
            if (mention.startsWith('<@') && mention.endsWith('>')) {
                mention = mention.slice(2, -1);
                if (mention.startsWith('!')) {
                    mention = mention.slice(1);
                }
                return mention;
            }
        }
        const user = getUserFromMention(args[0])
        let MessageDM = args[1]
        client.users.cache.get(user).send(MessageDM);
    }
    // ...
});

Answer

You’re missing a negation (!) in your role-check. Your current if only evaluates to true, when the role is present. But you want to return if the role is not present.

Change your line

if (message.member.roles.cache.some(role => role.name === 'Staff')) return;

to

if (!message.member.roles.cache.some(role => role.name === 'Staff')) return;

Also, as I mentioned in my comment, putting a function inside an if is never a good idea. I’d just put it into the upper scope:

function getUserFromMention(mention) {
    if (!mention) return;
    if (mention.startsWith('<@') && mention.endsWith('>')) {
        mention = mention.slice(2, -1);
        if (mention.startsWith('!')) {
            mention = mention.slice(1);
        }
        return mention;
    }
}

client.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();
    if (!message.member.roles.cache.some(role => role.name === 'Staff')) return;
    if (command === 'send'){
        const user = getUserFromMention(args[0]);
        let MessageDM = args[1];
        client.users.cache.get(user).send(MessageDM);
    }
    // ...
});

Leave a Reply

Your email address will not be published. Required fields are marked *