Using discord.js to detect image and respond

落爺英雄遲暮 提交于 2021-02-05 07:42:23

问题


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 >.>");
  }
})

回答1:


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.



来源:https://stackoverflow.com/questions/50710598/using-discord-js-to-detect-image-and-respond

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!