Advertisement
Guest User

ImageArgumentType - discord.js-commando

a guest
Feb 19th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const { ArgumentType } = require('discord.js-commando');
  2.  
  3. const fileType = require('file-type');
  4. const fetch = require('node-fetch');
  5.  
  6.  
  7. let buffer;
  8.  
  9. /**
  10.  * ImageArgumentType for discord.js-commando
  11.  * returns a buffer usable for MessageAttachment
  12.  */
  13. class ImageArgumentType extends ArgumentType {
  14.   constructor(client) {
  15.     super(client, 'image');
  16.   }
  17.  
  18.  
  19.   async validate(val, msg, arg) {
  20.     const matches = val ? val.match(/^(?:http(s)?:\/\/)\s?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/gi) : null;
  21.    const mime = ['image/jpeg', 'image/jpg', 'image/png'];
  22.  
  23.  
  24.    if (val && msg.attachments.size > 0) {
  25.      // const message = await msg.channel.messages.get(msg.author.lastMessageID);
  26.      const attachment = msg.attachments.first();
  27.  
  28.      buffer = await fetch(attachment.url).then(res => res.buffer())
  29.      const type = fileType(buffer)
  30.  
  31.      if (type === null) {
  32.        return "You provided an invalid image. Please try again."
  33.      }
  34.  
  35.      const check = mime.find(n => n === type.mime)
  36.      if (check) return true
  37.  
  38.    }
  39.  
  40.    const message = await msg.channel.messages.get(msg.author.lastMessageID);
  41.  
  42.    if (message.attachments.size > 0) {
  43.      const attachment = message.attachments.first();
  44.  
  45.      buffer = await fetch(attachment.url).then(res => res.buffer());
  46.      const type = fileType(buffer)
  47.  
  48.      if (type === null) {
  49.        return "You provided an invalid image. Please try again."
  50.      }
  51.  
  52.      const check = mime.find(n => n === type.mime)
  53.      if (check) return true
  54.  
  55.  
  56.    }
  57.  
  58.    if (matches) {
  59.      buffer = await fetch(val).then(res => res.buffer())
  60.      const type = fileType(buffer)
  61.  
  62.      if (type === null) {
  63.        return "You provided an invalid image url. Please try again."
  64.      }
  65.  
  66.      const check = mime.find(n => n === type.mime)
  67.      if (check) return true
  68.  
  69.    }
  70.  
  71.    return false;
  72.  
  73.  }
  74.  
  75.  async parse(val, msg) {
  76.  
  77.    return buffer;
  78.  
  79.  }
  80.  
  81.  isEmpty(val, msg, arg) {
  82.    if (msg.attachments.size) return false;
  83.    // if (!match) return !val
  84.  
  85.    if (Array.isArray(val)) return val.length === 0;
  86.    return !val;
  87.  }
  88.  
  89. };
  90.  
  91. module.exports = ImageArgumentType;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement