Discord.js 命令处理程序机器人没有响应

时间:2021-04-29 17:50:37

标签: javascript node.js discord.js

您好,我在命令处理程序方面遇到了一个非常大的问题,我为此苦苦挣扎了很长时间,问题是我的机器人在添加命令后在我键入时没有响应,我尝试了 youtube 上的几种方法,但没有一个它们有效,非常感谢您的帮助 代码如下!


const Discord = require('discord.js');
const client = new Discord.Client();
const config = require('./config.json')
const prefix = '$';
const fs = require('fs');


client.commands = new Discord.Collection();
client.events = new Discord.Collection();

const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));

client.once('ready', () => {
    console.log('Ready!')
});

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    client.commands.set(command.name, command);
}

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

const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
    console.log(message.content);

    if (command === `${prefix}ping`) {
        client.commands.get('ping').execute(message, args);
    }

}); 

client.login(config.token);

ping.js FILE!

module.exports = {
    name: 'ping',
    description: 'komenda ping',
    execute(message, args) {
        message.channel.send('Pong!');
    },
};

1 个答案:

答案 0 :(得分:1)

问题是 command 永远不会是 ${prefix}ping,因为您已经使用 .slice(prefix.length) 从消息中删除了前缀。检查并运行下面的代码片段:

const prefix = '!'
const message = {
  content: '!ping it now'
}

const args = message.content.slice(prefix.length).trim().split(' ')
const command = args.shift().toLowerCase()

console.log({'message.content': message.content, command, args})

要修复它,您需要检查命令是否为字符串 "ping":

if (command === 'ping') {
  client.commands.get('ping').execute(message, args)
}