It seems you're using the setup available on the discordjs.guide site. It means, you already have a collection of commands available on client.commands
or bot.commands
. It holds all the data you'll need.
Collections have a map()
method that returns a new array. You can use it to iterate over the commands
and return a new field object (an object with a name
and value
prop). Once you have this array, you can use the .addFields
method that (unlike .addField
) accepts an array of fields.
The problem with this is that the maximum number of fields is 25. If you have more than 25 commands, you need to send them in different embeds. You've already imported discord.js-pagination
that allows you to provide an array of embeds and then it handles all the difficult work. But you still need to make sure that there are no more than 25 fields.
To solve this, you can chunk the original array to new ones with a maximum of 25 items. I've written a helper function for you that does this. It returns an array of arrays.
Now, you can iterate over the chunks and create a new embed object for each and set up pagination.
Check out the code below:
const Discord = require('discord.js');
const pagination = require('discord.js-pagination');
const { prefix } = require('../config.json').prefix;
module.exports = {
name: 'help', //.ping
description: 'Help command.',
use: `${prefix}help`,
async run(bot, message, args) {
const MAX_FIELDS = 25;
// iterate over the commands and create field objects
const fields = bot.commands.map((command) => ({
name: 'Command',
value: `${command.name}\n${command.description}\n${command.use}`,
}));
// if there is less than 25 fields, you can safely send the embed
// in a single message
if (fields.length <= MAX_FIELDS)
return message.channel.send(
new Discord.MessageEmbed()
.setTitle('Help')
.setDescription(`Prefix: ${prefix}`)
.addFields(fields),
);
// if there are more, you need to create chunks w/ max 25 fields
const chunks = chunkify(fields, MAX_FIELDS);
// an array of embeds used by `discord.js-pagination`
const pages = [];
chunks.forEach((chunk) => {
// create a new embed for each 25 fields
pages.push(
new Discord.MessageEmbed()
.setTitle('Help')
.setDescription(`Prefix: ${prefix}`)
.addFields(chunk),
);
});
pagination('some message', pages);
},
};
// helper function to slice arrays
function chunkify(arr, len) {
let chunks = [];
let i = 0;
let n = arr.length;
while (i < n) {
chunks.push(arr.slice(i, (i += len)));
}
return chunks;
}