Search code examples
javascriptdiscord.jsembed

Send multiple embeds if there are more than 25 fields (Discord.js)


I'd like to know how to send multiple embeds if there are more than 25 fields in an embed constructor. I need it to include the remaining fields(where there may be 75 or more at any given time), while retaining the Title, Description, Color, etc.

My Embed is constructed as such, sourcing each .addField() from a for...in loop

const shop = new MessageEmbed()
    .setTitle(`My Title`)
    .setDescription(`My Description`)
    .setThumbnail('My Thumbnail')
    .setFooter(`My Footer`)

    let listItems = ITEMS;
    for(key in listItems) {
        if (listItems.hasOwnProperty(key)) {
            shop.addField(`${listItems[key].name}`, `${commafy(listItems[key].price)}`, true)
        }
    }
message.channel.send(shop);

There are more than 25 keys in listItems, and as such, sending the embed vanilla only sends the embed including the first 25 fields.

I know I will need to loop around shop.fields.length somewhere, but I cant for the life of me figure out how to get this done.

Can anyone point me in the right direction, here? Thanks!


Solution

  • You can achieve your goal in few simple steps!:

    • Initialize an array of embeds ( which we will send together after adding fields to them at last )
    • Initialize an index variable i which would hold how many fields we need.
    • Now start by looping through listItems, using a for...in loop for value of listItems assigning it to a key. we would add them to a singular embed ( 25 per embed ) and then incremenate i.
    • Further send our array of embeds through the TextChannel#send method which accepts BaseMessageOptions which further accepts an embeds parameter which accepts a Type as an Array of MessageEmbed objects.
    
        const all_embeds = [];
        let i = 0;
        for(key in listItems) {
                    if (!all_embeds[Math.floor(i / 25)]) { //checks if the embed with the required fields already exists in our array
                        all_embeds.push(new Discord.MessageEmbed().setTitle(`My Title`).setDescription(`My Description`).setThumbnail('My Thumbnail').setFooter(`My Footer`)); // add required amount of embeds to our array
                    }
                    all_embeds[Math.floor(i / 25)].addField(`${listItems[key].name}`, `${(listItems[key].price)}`, true);
                    i++;
                }
                message.channel.send({
                    embeds: [all_embeds]
                });