如何使某些角色运行discord.js命令?

时间:2020-07-28 13:54:25

标签: javascript bots discord.js

我的discord.js机器人中有一个命令,我只希望使用某些角色。但是,运行代码后,我立即收到错误消息。

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);

这是错误。

ReferenceError: member is not defined

如果有人可以给我解决方案,那就太好了!

1 个答案:

答案 0 :(得分:1)

如果要访问GuildMember,则需要通过 message 变量进行访问,该变量只能在事件回调函数内部访问。
您还应该检查message.member不为null(可能是通过DM不在公会通道上通过DM发送消息时),并且message.member.user不是机器人(只是为了确保您的机器人不会对消息做出反应)来自其他机器人及其本身) 像这样:

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);
        }
    }
});

如果您想了解更多信息: (https://discord.js.org/#/docs/main/stable/class/Message?scrollTo=member