Search code examples
javascriptnode.jsdiscord.js

How to send image using Discord.MessageAttachment


I'm retrieving image data from the google maps API and trying to send it as an image through 'Discord.MessageAttachment', however it is throwing the error:

TypeError: Discord.MessageAttachment is not a constructor at C:\Users\dario\OneDrive\dev\JavaScript\DscBot\src\index.js:35:30 at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Here is the releveant code

      const latitude = Math.random() * 180 - 90;
      const longitude = Math.random() * 360 - 180;
      const apiUrl = `https://maps.googleapis.com/maps/api/streetview?size=400x400&location=${latitude},${longitude}&key=*MyAPIKey`;
  
      axios
        .get(apiUrl, { responseType: 'arraybuffer' })
        .then(response => {
          const attachment = new Discord.MessageAttachment(response.data, 'image.jpg');
          message.channel.send(attachment);
        })
        .catch(error => {
          console.error(error);
          message.channel.send('Failed to get a street view image.');
        });

Note that I am on the latest version of Discord.js, and this 'Discord is imported (I think) correctly:

const Discord = require('discord.js');

I expected an image to be sent to the server which I am testing it on, however 'Failed to get a street view image.' was returned alongside a terminal error.


Solution

  • In the newest version of Discord.js "MessageAttachment" was renamed to "AttachmentBuilder". (More Info in the documentation)

    So your code would have to look like this:

    const latitude = Math.random() * 180 - 90;
    const longitude = Math.random() * 360 - 180;
    const apiUrl = `https://maps.googleapis.com/maps/api/streetview?size=400x400&location=${latitude},${longitude}&key=*MyAPIKey`;
      
    axios
      .get(apiUrl, { responseType: 'arraybuffer' })
      .then(response => {
        const attachment = new Discord.AttachmentBuilder(response.data, { name: 'image.jpg' });
        message.channel.send(attachment);
      })
      .catch(error => {
        console.error(error);
        message.channel.send('Failed to get a street view image.');
      });