You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Discord.js机器人按指定类别列出命令

实现按类别列出Discord机器人命令的方法

嘿,我来帮你搞定这个按类别展示命令的需求!思路其实很直白:先确保机器人把所有命令都加载并存在一个集合里,然后新建一个commands命令,根据用户输入的类别筛选对应命令就行。

第一步:确保机器人已加载所有命令

首先,你的机器人启动文件里得有加载命令的逻辑,把所有命令存到Raphy.commands集合里(如果你的客户端变量名不是Raphy,换成你自己的就行)。示例代码如下:

const Discord = require('discord.js');
const fs = require('fs');
const path = require('path');

const Raphy = new Discord.Client({ intents: [/* 这里填入你的机器人需要的权限意图 */] });

// 初始化存储命令的集合
Raphy.commands = new Discord.Collection();

// 读取commands文件夹下的所有命令文件
const commandFiles = fs.readdirSync(path.join(__dirname, 'commands')).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const command = require(path.join(__dirname, 'commands', file));
    Raphy.commands.set(command.name, command);
}

// 登录机器人
Raphy.login('你的机器人Token');

第二步:创建commands命令文件

在你的命令文件夹里新建commands.js,这就是实现类别命令列表的核心文件:

const Discord = require('discord.js');
const { MessageEmbed } = require('discord.js');

module.exports = {
    name: "commands",
    description: "列出指定类别的所有命令",
    category: "general",
    run: async (Raphy, message, args) => {
        // 检查用户是否输入了类别参数
        if (!args[0]) {
            return message.channel.send('请指定要查看的命令类别哦,比如输入 `!commands General`');
        }

        // 统一转成小写,避免大小写不匹配的问题
        const targetCategory = args[0].toLowerCase();

        // 筛选出对应类别的命令
        const matchedCommands = Raphy.commands.filter(cmd => cmd.category === targetCategory);

        // 如果没找到对应类别的命令
        if (matchedCommands.size === 0) {
            return message.channel.send(`找不到类别为 \`${targetCategory}\` 的命令,请检查类别名称是否正确!`);
        }

        // 用Embed美化输出,看起来更整洁
        const commandEmbed = new MessageEmbed()
            .setColor('#2ECC71')
            .setTitle(`${targetCategory.charAt(0).toUpperCase() + targetCategory.slice(1)} 类命令列表`)
            .setDescription(matchedCommands.map(cmd => `\`${cmd.name}\` - ${cmd.description}`).join('\n'));

        message.channel.send({ embeds: [commandEmbed] });
    }
};

一些实用小细节

  • 转小写处理:因为你的ping命令里category是小写的"general",转小写后用户输入General、GENERAL都能匹配到,体验更友好。
  • 用MessageEmbed展示:比纯文本输出更整齐美观,符合Discord用户的使用习惯。
  • 可扩展功能:如果想在用户不输入类别时列出所有可用类别,只需要在!args[0]的分支里,提取所有命令的category去重后展示即可。

内容的提问来源于stack exchange,提问作者MegaMix_Craft

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 17:04:10