简体   繁体   中英

Image Manipulation Discord.js: No Such file or dictionary

I am trying to make a Discord Bot with discord.js but every time I try to run the command, it returns with an error saying:

UnhandledPromiseRejectionWarning: Error: ENOENT, No such file or directory './background.jpg'

This is my code:

const Discord = require('discord.js');
const Canvas = require('canvas')

module.exports = {
    name: 'level',
    description: 'Level command.',
    execute: async (message, client) => {
        const canvas = Canvas.createCanvas(700, 250);

        const ctx = canvas.getContext('2d')
        const background = await Canvas.loadImage('./background.jpg')
        ctx.drawImage(background, 0, 0, canvas.width, canvas.height)

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

        message.channel.send(attachment)
    }
}

Image of my files and folders:

在此处输入图像描述

It seems your image file is in the same folder. Maybe try using absolute paths instead. You could use the path module's resolve() method to resolve the __dirname and the filename into an absolute path. Using it like this will work:

const Discord = require('discord.js');
const Canvas = require('canvas');
const path = require('path');

module.exports = {
  name: 'level',
  description: 'Level command.',
  execute: async (message, client) => {
    const canvas = Canvas.createCanvas(700, 250);

    const ctx = canvas.getContext('2d');
    const background = await Canvas.loadImage(
      path.resolve(__dirname, './background.jpg'),
    );
    ctx.drawImage(background, 0, 0, canvas.width, canvas.height);

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

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

The answer of your problem is there in your Error.
The ./background.jpg dosen't exist.

This is what you can do:

  • Make sure you copied the image file in the same directory
  • Make sure it has the correct extension ( .jpg , .jpeg or .png )

If this doesn't solve your problem then try hosting the image somewhere else and putting the link in Canvas.loadImage()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM