Californium
Californium

Reputation: 591

DiscordJS Canvas attachments not being fully sent?

I'm currently using Discord.js and Node for my bot that sends attachments in a set interval. I'm faced with an issue where sometimes the attachments don't fully load (they load indefinitely and only when I click "open original" can I see the top few px of the image). Why is this? Is it because the attachment file isn't complete when the attachment is sent?

Adding Image to the File

async function makeCanvas(img, code, channel) {
  const canvas = createCanvas(900, 1375);
  const ctx = canvas.getContext("2d");
  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 1255, 900, 120);
  let image = await loadImage(img);
  ctx.drawImage(image, 0, -40);
  ctx.font = "bold 100px sans-serif'";
  ctx.textAlign = "center";
  ctx.fillStyle = "#FFFFFF";
  ctx.fillText(`${code}`, 435, 1350);
  const writeable = fs.createWriteStream(`./temp/${channel.id}.png`);
  const readable = canvas.createPNGStream();
  const connection = readable.pipe(writeable);
  return connection.path;
}

Sending the attachment

const imgCode = await applyCodeToImg(url, code, message.channel);
await message.channel.send("A new attachment has appeared!", new Discord.MessageAttachment(imgCode));

I'm still very new to JavaScript and Node, please bear with me!

Upvotes: 5

Views: 1162

Answers (2)

Glitchy Brick
Glitchy Brick

Reputation: 126

const attachment = new Discord.MessageAttachment(canvas.toBuffer(), 'image.png');

message.channel.send("A new attachment has appeared!", attachment);

Upvotes: 0

Crist
Crist

Reputation: 358

You can use

message.channel.send("message", { files: [canvas.toBuffer()] });

or

const attachment = new Discord.MessageAttachment(canvas.toBuffer(), 'image.png');

message.channel.send("message", attachment);

to send the attachment directly, without saving it using fs, make sure to check out Canvas#toBuffer() for any futher info on the API and discordjs.guide on basic image loading.

Upvotes: 1

Related Questions