Home > Software design >  Discord.js | How to create a MessageEmbed with unknown amount of Fields?
Discord.js | How to create a MessageEmbed with unknown amount of Fields?

Time:04-07

I'm new to NodeJS and use it for my Discord bot. My goal is to reply to a command with an embed that has dynamic fields (depending on how many values I have). My approach was to pass an array that matches the Discord API's format to the MessageEmbed().addFields() function. This is what my JSON stringyfied array looks like:

[{"name":"eur","value":1176,"inline":false},{"name":"btc","value":0.0001,"inline":false}]

Which results in this error: TypeError: Cannot read properties of undefined (reading 'name')

That's because Discord doesn't want the Object's property names as strings. The output that I'd need would be: [{name:"eur",value:1176,inline:false},{name:"btc",value:0.0001,inline:false}]

Is there a way to pass the object's property names as 'non-strings'? Or should I approach it completely different?

Here is an example of a MessageEmbed:

interaction.reply({embeds: [
                    new MessageEmbed()
                    .setTitle("Server Info")
                    .addFields([
                            {
                                name: "Channels",
                                value: `${interaction.guild.channels.cache.size}`
                            },
                            {
                                name: "Members",
                                value: `${interaction.guild.members.cache.size}`
                            },
                            {
                                name: "Created",
                                value: `<t:${Math.round(interaction.guild.createdTimestamp / 1000)}>`,
                                inline: true
                            }
                        ])
                    ]}) 

In my case I don't know how many fields there are gonna be. Thats why i need some solution that works for an unknown amount of fields.

CodePudding user response:

Each MessageEmbed can have up to 25 fields, so you can either slice your array to that value, or send multiple embeds.

CodePudding user response:

It's very simple. Just, instead of using the quotes to make strings, remove them.

Important: Only 25 fields or less are allowed per embed.

const fields = [
   {
      name: "Channels",
      value: `${interaction.guild.channels.cache.size}`
   },
   {
      name: "Members",
      value: `${interaction.guild.members.cache.size}`
   },
   {
      name: "Created",
      value: `<t:${Math.round(interaction.guild.createdTimestamp / 1000)}>`,
      inline: true
   }
]

 interaction.reply({embeds: [
      new MessageEmbed()
          .setTitle("Server Info")
          .setDescription("Here is the server info:")
          .addFields(fields)
  })
  • Related