Home > database >  Convert Discord Attachment to Binary
Convert Discord Attachment to Binary

Time:10-26

So I have a discord.js bot. And I want moderators to be able to run a slash command and upload an image to the bot's directory (folder on my Raspberry Pi, where my bot is hosted). So I made a command,

const fs = require("fs");
const path = require("path");
const Discord = require("discord.js");

module.exports = {
  data: new SlashCommandBuilder()
    .setName("addimg")
    .setDescription("Allows Moderators to add needed images.")
    .addAttachmentOption((option) =>
      option
        .setName('image')
        .setDescription('The image you want to add.')
        .setRequired(true)
    ),
  async execute(interaction, client) {
    var image = interaction.options.getAttachment("image");
    console.log(image)
    if(path.parse(image.name).ext == ".png" || path.parse(image.name).ext == ".jpg"){
      await fs.writeFileSync(`../../../imgs/${image.name}`, /*Data*/)
      const embed = new Discord.EmbedBuilder()
        .setTitle(`Image Added!`)
        .setColor("000000")
        .setDescription(`Check it out by using the /img command and choosing ${image}`)

      interaction.reply({ embeds: [embed] });
    }
    else{
      return interaction.reply({ embeds: [new Discord.EmbedBuilder()
        .setTitle(`Failed to Add Image.`)
        .setColor("000000")
        .setDescription(`This format of image is not allowed. Try again with a .png or .jpg image.`)] })
    }
  }
}

But I don't know how/where to start with converting the Discord Attachment to binary (raw image data). And I know that the Discord Attachments have a .url which maybe should be used? But still I don't know how I would do that.

CodePudding user response:

I researched on the topic a bit, and I hope this works.

I think using something like this might work:

const imageUrl = image.url

var request = require('request').defaults({ encoding: null });

request.get(imageUrl, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        data = "data:"   response.headers["content-type"]   ";base64,"   Buffer.from(body).toString('base64');
        console.log(data);
    }
});

Sources:

  1. Source 1
  2. Source 2

CodePudding user response:

So I found an answer. Here it is.

var request = require("request").dafaults({ })
await request(image.url).pipe(fs.createWriteStream(`./imgs/${image.name}`))

you would replace ./imgs/${image.name} with whatever the path you want to write to.

  • Related