简体   繁体   中英

How do I make certain roles run a discord.js command?

I have a command in my discord.js bot that I only want certain roles to use. However, I'm getting an error as soon as I run the code.

 const Discord = require('discord.js'); const keepAlive = require('./server'); const client = new Discord.Client(); checkRole = member.roles.cache.has('725812531637125120'); client.on('message', message => { if (message.toString().includes('[PING]')) { if (checkRole){ message.channel.send(`> <@&727633811709362187>:arrow_up:`); } else { const embed = new Discord.MessageEmbed().setTitle(`Invalid Command`).setColor('#0099ff').setDescription(`${message.author}, the command that you have used is invalid:\nThis command is only for managment.`) message.author.send(embed); } } }); keepAlive(); client.login(process.env.TOKEN);

Here is the error.

ReferenceError: member is not defined

If anyone can give me a solution, that would be great!

If you want to access GuildMember you need to access it through your message variable which you can only access inside event callback function.
You should also check is message.member is not null (which can be when message is sent via DM not on guild channel) and message.member.user is not a bot (just to make sure that your bot won't react to message from other bots and from itself) Something like this:

client.on('message', message => {
    if (message.author !== null && message.author.bot) return;
    if (message.toString().includes('[PING]')) {
        if (message.member !== null && message.member.roles.cache.has('725812531637125120');){
            message.channel.send(`> <@&727633811709362187> :arrow_up:`);
        }
        else {
            const embed = new Discord.MessageEmbed()
            .setTitle(`Invalid Command`)
            .setColor('#0099ff')
            .setDescription(`${message.author}, the command that you have used is invalid:\nThis command is only for managment.`)
        message.author.send(embed);
        }
    }
});

If you want to read more: ( https://discord.js.org/#/docs/main/stable/class/Message?scrollTo=member )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM