Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

424
Vistas
Why do I get "Invalid Form Body" when trying to embed a local image in a message?

Right now I'm working on making a bot that will post a random image from a local folder on my VSC. However, posting an embed message with the image results in an error:

DiscordAPIError: Invalid Form Body embeds[0].image.url: Could not interpret "{'attachment': ['1.jpg', '2mkjR-3__400x400.jpg', '8921036_sa.jpg', '91Vk1mS1x3L.png'], 'name': None}" as string.

This can be reproduced with the sample code:

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

const config = require('config');
const authToken = config.get('authToken');

const myIntents = new Intents([
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES
]);
const client = new Discord.Client({ intents: myIntents });

client.on("ready", (client) => {
    console.log(`Logged in as ${client.user.tag}.`);
});

client.on("messageCreate", (message) => {
    if ('.pic' === message.content) {
        let files = fs.readdirSync('./assets/images/');
        let chosenFile = files[Math.floor(Math.random() * files.length)];
        const image = new Discord.MessageAttachment(files);
        const embed = new Discord.MessageEmbed()
              .setTitle('yeet')
              .setImage(image)
              .setFooter('By K4STOR','');
        message.channel.send({embeds: [embed]});
    }
});

client.login(authToken);

In addition to the above script, you'll need to:

  • create an 'assets/images' directory and
  • add at least one image;
  • create a configuration file (e.g. 'config/local.json') and
  • add an appropriate 'authToken' entry

How can the above code be fixed to send the image?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Try this:

var fs = require('fs');

client.on("ready", () => {
    
    console.log("Why did I make this...")

    command(client, 'pic', (message) => {
        //choose one file from folder "./images" randomly
        var files = fs.readdirSync("./images/")
        let chosenFile = files[Math.floor(Math.random() * files.length)]
 
        //create embed and use image from messageAttachments
        const embed = new Discord.MessageEmbed()
            .setTitle('yeet')
            .setImage(`attachment://${chosenFile}`)
            .setFooter('By K4STOR','')

        //discord.js V13 variant of sending embeds
        //necessary to set files, otherwise #setImage with localfile does not work
        message.channel.send({
          embeds: [embed], 
          files: [`./images/${chosenFile}`]
        });
    })
})

about 4 years ago · Juan Pablo Isaza Denunciar

0

Main Issue

MessageEmbed.setImage() takes a URL, not a MessageAttachment. For attachments, you must pass them via the files option TextChannel.send(). Note the guide on attaching images to an embed message shows this.

Additionally, the path to the image directory must be combined with the chosen file name when the attachment object is created.

Minor issue

Note that all images appear in the error message. This is due to a minor issue: the attachment is set to files, rather than chosenFile. Note this sort of issue is considered on SO.

Changes

Just these changes would look like:

const path = require('path');
...
const imgDir = './assets/images/';
...
        const image = new Discord.MessageAttachment(
            path.join(imgDir, chosenFile),
            chosenFile,
            {url: 'attachment://' + chosenFile});
        const embed = new Discord.MessageEmbed()
              .setImage(image.url)
              ...
        
        message.channel.send({embeds: [embed], files: [image]});

Full Sample

The sample with the above changes applied would be:

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

const config = require('config');
const authToken = config.get('authToken');

const myIntents = new Intents([
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES
]);
const client = new Discord.Client({ intents: myIntents });

client.on("ready", (client) => {
    console.log(`Logged in as ${client.user.tag}.`);
});

const imgDir = './assets/images/';
client.on("messageCreate", (message) => {
    if ('.pic' === message.content) {
        let files = fs.readdirSync(imgDir);
        let chosenFile = files[Math.floor(Math.random() * files.length)];
        const image = new Discord.MessageAttachment(
            path.join(imgDir, chosenFile),
            chosenFile,
            {url: 'attachment://' + chosenFile});
        const embed = new Discord.MessageEmbed()
              .setTitle('yeet')
              .setImage(image.url)
              .setFooter('By K4STOR','');
        console.log(`Sending ${chosenFile}.`);
        message.channel.send({embeds: [embed], files: [image]});
    }
});

client.login(authToken);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda