Eric Wang
Eric Wang

Reputation: 436

Using discord.js to detect image and respond

I'm trying to make a prank Discord bot for my friend's Discord server, but the bot won't respond to anything; not even the elseif function passes. If anyone know why my code isn't working can you please specify it.

NOTE: Client variable is Discord.Client if you needed a reference.

client.on("message", message => {
  if (message.channel.id != 425328056777834506) return;
  if (Math.floor(Math.random() * Math.floor(4))== 3 && message.embeds.length > 0) {
    message.channel.send("https://cdn.discordapp.com/attachments/330441704073330688/453693702687162369/yeet.png");
  } else if (message.embeds.length < 0) {
    message.channel.send("send me photos of your win >.>");
  }
})

Upvotes: 4

Views: 30971

Answers (1)

WQYeo
WQYeo

Reputation: 4056

The Message have a attachments property which you can use to get a collection of attached file(s) to a message (if any)

You can do a if (message.attachments.size > 0) to check for any attached objects first.
Afterwards, you can loop through the collection and check if the attached file URL ends with a png or jpeg.

if (message.attachments.size > 0) {
    if (message.attachments.every(attachIsImage)){
        //something
    }
}
        
...
        
function attachIsImage(msgAttach) {
    var url = msgAttach.url;
    //True if this url is a png image.
    return url.indexOf("png", url.length - "png".length /*or 3*/) !== -1;
}

EDIT

For your bot not responding to anything. Make sure that you are testing the bot in the channel that has the same ID in the message.channel.id != 425328056777834506 statement.
(Or you can comment out that if statement first, then add that in when your bot is fully functional.)

Also, client.on("message", message => {... gets called when your bot sends a message too. You can do if (message.author.id == <YourBotID>) {return;} to let the bot ignore it's own messages.
Or you can do if (message.author.bot) {return;} if you want it to ignore messages sent by other bots.

Upvotes: 8

Related Questions