Home > database >  List all bot commands from specific category
List all bot commands from specific category

Time:10-10

I have a few commands from specific categories and I want to list them when user execute a command! For example one of my commands:

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

module.exports = {
    name: "ping",
    description: "Bot websocket ping",
    category: "general",
    run: async (Raphy, message, args) => {
      message.channel.send(`${Raphy.ws.ping} ws ping`);
    }
}

I want to list commands in General category if user execute !commands General, how can I do this?

CodePudding user response:

To list all commands from specific category in variable you can use this code:

v12

if(args[0]) {
let list = ` `;
let commands = message.client.commands.array();
commands.forEach((cmd) => {
if(cmd.category == args[0].toLowerCase()) {
list = list.toString()   " **|** "   cmd.name.toString()
}
})
if (list == ` `) {
message.reply("Any commands in category or category does not exist!")
} else {
list = list.toString()   " **|**"
message.channel.send(`${args[0].toLowerCase()} category commands list: ${list}`)
}
}

v13

if(args[0]) {
let list = ` `;
message.client.commands.each((cmd) => {
if(cmd.category == args[0].toLowerCase()) {
list = list.toString()   " **|** "   cmd.name.toString()
}
})
if (list == ` `) {
message.reply("Any commands in category or category does not exist!")
} else {
list = list.toString()   " **|**"
message.channel.send(`${args[0].toLowerCase()} category commands list: ${list}`)
}
}

CodePudding user response:

A simple filter will work:

let categoryCmds = message.client.commands.filter(c => c.category === args[0].toLowerCase())
message.reply(categoryCmds.map(c => c.name).join(" **|** "))

This is very short syntax and is easy to modify to your liking.

CodePudding user response:

To make things cleaner, use Collection#filter() with Collection#map(), This will work with both v12 & v13. However, make sure you're running Node version 14 or higher.

const category = args[0].toLowerCase?.() || 'unspecified';
const commandList = message.client.commands
   .filter(cmd => cmd.category == category)
   ?.map(cmd => cmd.name)
   ?.join(', ');
if (!commandList) {
   message.reply(`Commands with category ${category} not found`);
} else {  
   message.channel.send(`${category} command list: ${commandList}`);
}

Array-Like Methods for Collections

  • Related