图像处理 Discord.js: 没有这样的文件或字典

Image Manipulation Discord.js: No Such file or dictionary

我正在尝试使用 discord.js 制作一个 Discord Bot,但每次我尝试 运行 命令时,它 returns 都会出现错误提示:

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

这是我的代码:

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)
    }
}

我的文件和文件夹的图像:

您的图像文件似乎在同一文件夹中。也许尝试使用绝对路径。您可以使用 path module's resolve() 方法将 __dirname 和文件名解析为绝对路径。像这样使用它会起作用:

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);
  },
};