image url showing as undefined discord.js

Issue

so I’m making a discord bot as a small project and when I try to get the url from an image attachment it shows up as undefined.
here’s my code:

var attachment = message.attachments
if (message.content.includes("is dropping 3 cards!")) {
    let image = attachment
    console.log(image.url)
}

when I use this code the image url shows up as undefined and I don’t know why. I’ve tried using image without .url and the url seems to show up but when I use .url it doesn’t seem to work.

Solution

Now now, message.attachments contains an array. The attachment can be image, video or file. There can be also multiple attachments in one message. Meaning that you need to define which one of the attachments you want to use. You should also check if there is any attachments in the message before going forward.

Below is little example for using the first file/image in the message:

if(message.attachments.size > 0) {
     var attachment = message.attachments.first();
     console.log(attachment.url)
}

Answered By – NotTrixxie

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published