【问题标题】:Discord.js bot only detects last command in separate filesDiscord.js 机器人仅检测单独文件中的最后一个命令
【发布时间】:2021-03-02 16:05:14
【问题描述】:

我正在尝试使用 Javascript 对这个 discord 机器人进行编码,我目前正在逐步遵循 discordjs 指南,并且我正在执行与指南完全相同的步骤。现在我正在学习动态命令,似乎我在这个大洞里被困了 4 天。问题是命令处理程序确实检测到命令文件夹中的命令文件,但它只检测到该顺序中的最后一个命令。这是我的主文件夹中的 bot.js 文件中的代码:

const fs = require('fs');
const {prefix, token} = require('./config.json');
const Discord = require('discord.js');
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);
}

client.once('ready', () =>{
    console.log('Imperial Bot is online!');
});

client.on('message', message => {
    console.log(message.content);

    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const commandName = args.shift().toLowerCase();
    
    if (!client.commands.has(commandName)) return;

    const command = client.commands.get(commandName);
    try {
        command.execute(message, args);
    } catch (error) {
        console.error(error);
        message.reply('there was an error trying to execute that command!');
    }

})

client.login(token);

这是命令文件夹中文件 fun.js 中的代码:

module.exports = {
    name: 'avatar',
    description: '...',
    execute(message, args){
        if(!message.mentions.users.size){
            message.channel.send(`Poza ta de profil: <${message.author.displayAvatarURL({ format: "png", dynamic: true })}>`)
        }

        // the array of avatars of the tagged users get put in a constant and shown in the chat.
        const avatarList = message.mentions.users.map(user => { //for every user tagged in the message, an avatar of theirs will get shown
            return `Avatarul lui ${user.username}: <${user.displayAvatarURL({ format: "png", dynamic: true })}>`;
        });
        message.channel.send(avatarList);
    },
}

module.exports = {
    name: 'gaymeter',
    description: '...',
    execute(message, args){
        let gen = Math.floor(Math.random()*100 + 1);
        let tagged = message.mentions.users.first();
        if(!args[0]){
            message.channel.send(`Esti ${gen}% gay!`);
        } else {
            message.channel.send(`${tagged.username} este ${gen}% gay!  :gay_pride_flag: `);
        }
    }
}

module.exports = {
    name: 'delete',
    description: '...',
    execute(message, args){
        let checkINT = parseInt(args[0]);
        let amount = args[0];
        
        if(isNaN(checkINT) || !args[0]){
            message.channel.send("Trebuie precizat un numar.");
        } else if(amount < 2 || amount > 99){
            message.channel.send("Limita de mesaje care pot fii sterse este intre 2 si 99.");
        } else {
            message.channel.bulkDelete(amount, true);
            message.reply(`sterse ${amount} mesaje!`).catch(err => {
                console.error(err);
                message.channel.send('Eroare! Nu au putut fii sterse mesajele.');
            });
        }
    },
}

如果我运行机器人,它检测到的唯一命令是删除命令,它是该文件中的最后一个命令。我的问题是如何安排或修复代码,以便所有 module.exports 在那个 fun.js 文件中工作,而不仅仅是那个 delete 命令?我必须在一个模块导出中只放一个命令并为每个命令制作单独的文件吗?

【问题讨论】:

    标签: javascript discord.js dom-events


    【解决方案1】:

    我假设您希望通过将所有命令放入一个文件来实现的是创建一个类别。这是一种更有效地做到这一点的方法。是的,您需要为所有命令创建单独的文件。

    我们在您的命令文件夹中创建另一个文件夹并将命令放在那里。

    注意:因为这是一种创建类别的动态方式,您只需添加额外的文件夹,一个新的类别就会诞生。

    你的文件夹结构应该是这样的

    -- Your bot folder
        - index.js
        - package.json
        - package-lock.json
        -- commands
            -- fun
                - kick.js
                - ban.js
            -- some other category
    

    现在我们需要在你的命令阅读器中加入一些小东西。

    // create a new collection called catergories
    client.categories = new Discord.Collection();
    client.aliases = new Discord.Collection(); // only if you want aliases
    // Read every commands subfolder
    fs.readdirSync("./commands/").forEach(dir => {
        // Read all files in the commands folder and that ends in .js
        const commands = fs.readdirSync(`./commands/${dir}/`).filter(file => file.endsWith(".js"));
        // Loop over the commands, and add all of them to a collection
        // If there's no name found, prevent it from returning an error
        for (let file of commands) {
            const command = require(`../commands/${dir}/${file}`);
            // Check if the command has a name, a category and a description
            // add or remove things here as you need
            if (command.name && command.category && command.description) {
                client.commands.set(command.name, command);
            } else {
                console.log("A file is missing something");
                continue;
            }
            // use this if you wish to include an alias array in your commands
            // check if there is an alias and if that alias is an array
            if (command.aliases && Array.isArray(command.aliases))
                command.aliases.forEach(alias => client.aliases.set(alias, command.name));
        };
    })
    

    注意:如果你想使用别名,你需要在你的命令处理程序中检查它们之后没有找到命令。

    // you only need this if you want to use aliases
    if (!command) command = client.commands.get(client.aliases.get(commandName));
    

    现在您应该在命令文件中包含类别。

    module.exports = {
        name: 'avatar',
        description: '...',
        category: "fun",
        aliases: ["all", "your", "aliases"], // this is optional
        execute(message, args) {
            // your code
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-21
      • 2021-04-18
      • 2021-09-09
      • 2021-08-30
      • 2021-06-02
      • 2020-11-09
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      相关资源
      最近更新 更多