#Using @napi-rs/canvas library with @discordjs/core library (Discord.js v14.x)

2 messages · Page 1 of 1 (latest)

rapid depot

Hi,
I had some issues finding this s*** so I put it here if some ppls need it.

When you are using the napi-rs canvas library, it may be horrible to use it and send some image through an interaction reply or a message.
I looked at the REST api, discord-api-types api and others for you to debug my thing.

Here's the code (a simple example thing):

const data = new SlashCommandBuilder()
    .setName("draw")
    .setDescription("Draw a blue square to show that it works")

/**
 * @param {import("discord.js").APIInteraction} interaction
 * @param {API} api
 */
async function execute(interaction, api) {
        
        // Create a new canvas of 200x200 pixels in 2d
    const canvas = createCanvas(200, 200);
    const ctx = canvas.getContext("2d");
        
        // We fill his belly in blue (dabudee dabudaa)
    ctx.fillStyle = "blue";
    ctx.fillRect(0,0, canvas.width, canvas.height);

        // We reply to our slash command
    await api.interactions.reply(interaction.id, interaction.token, {
                // We want to send an image, so we're providing a file
                // Structure:
                // https://discord.js.org/docs/packages/rest/2.3.0/RawFile:Interface
        files: [
            {
                // MIME format (In my case, a png)
                contentType: "image/png",
                // File name (Captain obvious here!)
                name: "test.png",
                // Data /!\ Accept a lot of things, but in our case we send an image buffer
                data: canvas.toBuffer("image/png")
            }
        ]
    });
}

export default { data, execute };
remote sandalBOT
  • Consider reading #how-to-get-help to improve your question!
  • Explain what exactly your issue is.
  • Post the full error stack trace, not just the top part!
  • Show your code!
  • Issue solved? Press the button!
  • Marked as resolved by OP