首页 > 解决方案 > Discord.js 帮助命令编译命令列表并嵌入缩略图

问题描述

我有一个非常简单的 Discord 机器人,它通过链接 Imgur/Tenor html 在命令上发布图像/gif。

命令存储在单独的.js文件中./commands/

我想创建一个帮助命令,它收集文件夹中的所有当前命令,并嵌入命令名称,并在其下方执行命令,以便创建图像/gif 的缩略图,但我主要是设法遵循Discord.js 指南,所以我对此非常陌生。谁能建议一些代码来帮助我入门?如何根据现有命令数组填充嵌入字段?

下面的机器人示例:

命令通过以下方式导入index.js

    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.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;
    
        const args = message.content.slice(prefix.length).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('Something bad happened!');
            }
    });

一个命令的例子./commands/test.js是:

module.exports = {
    name: 'test',
    description: 'A test',
    execute(message, args) {
        message.channel.send('This is a test.');
    }
}

标签: javascriptdiscord.js

解决方案


您可以使用.forEach()循环。
例如:

module.exports = {
    name: 'help',
    description: 'View a full list of commands',
    execute(message, client) {
        const Discord = require('discord.js');
        const embed = Discord.MessageEmbed();

        client.commands.forEach(command => {
            embed.addField(`${command.name}`, `${command.description}`, false);
        }
        message.channel.send(embed);
    }
}

推荐阅读