首页 > 解决方案 > Discord.js 命令处理对我不起作用

问题描述

我创建了一个 Discord.js 机器人,我想用fs分隔每个命令,例如 ./commands/ping.js。它起作用了,但不知道为什么,一个小时后它就崩溃了。我对机器人没有任何兴趣,而且没有人可以访问代码-当然-。该机器人可以工作,并且没有错误消息。事件,如准备就绪和消息也可以正常工作,但是直接在文件中的命令不起作用。例如,它会提示“BOT 已启动”,但 ping.js 无法正常工作。

这是 index.js,但如果您需要其他任何调试,请发表评论!

const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');

const client = new Discord.Client();
client.commands = new Discord.Collection();

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


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

fs.readdir('./events/', (err, files) => {
  files.forEach(file => {
    const eventHandler = require(`./events/${file}`)
    const eventName = file.split('.')[0]
    client.on(eventName, (...args) => eventHandler(client, ...args))
  })
})

client.login(token);

谢谢大家!~阿科斯

标签: node.jsdiscord.js

解决方案


健在这里,

这应该适合你:)。我试图留下一些评论,以便您可以理解代码,如果您对此代码有任何问题,请发表评论并编辑代码以使其正常工作

const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');

const client = new Discord.Client();
client.commands = new Discord.Collection();

fs.readdir("./commands/", (err, files) => {

    // check for errors
    if (err) console.log(err);

    // get name of file
    let jsfile = files.filter(f => f.split(".").pop() === "js");

    // if it cannot find any commands
    if (jsfile.length <= 0) {
        console.log("Couldn't find commands.");
        return;
    }

    // log the amount of files
    console.log(`Loading ${jsfile.length} commands!`);

    // load the command
    jsfile.forEach((f, i) => {
        // grab the module.exports from the file
        let props = require(`./commands/${f}`);
        console.log(`${i+1}: ${f} loaded!`);
        client.commands.set(props.name, props);
    });
});

// apparently this works so i'll leave it chief :)
fs.readdir('./events/', (err, files) => {
    files.forEach(file => {
        const eventHandler = require(`./events/${file}`)
        const eventName = file.split('.')[0]
        client.on(eventName, (...args) => eventHandler(client, ...args))
    })
})

client.login(token);

好好过~不知道


推荐阅读