【问题标题】:DiscordJS Canvas silently fails. Why?DiscordJS Canvas 静默失败。为什么?
【发布时间】:2020-08-17 05:38:25
【问题描述】:

我一直在学习创建 Discord 机器人的基础知识,并且一直在尝试将 Canvas 与 DiscordJS 结合使用。

我尝试关注this simple tutorial,但我似乎无法找到任何可能出错的线索。

作为参考,这是我在教程中得到的要点。

client.on('guildMemberAdd', async member => {
    const channel = member.guild.channels.cache.find(ch => ch.name === 'member-log');
    if (!channel) return;

    const canvas = Canvas.createCanvas(700, 250);
    const ctx = canvas.getContext('2d');

    // Since the image takes time to load, you should await it
    const background = await Canvas.loadImage('./wallpaper.jpg');
    // This uses the canvas dimensions to stretch the image onto the entire canvas
    ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
    // Use helpful Attachment class structure to process the file for you
    const attachment = new Discord.MessageAttachment(canvas.toBuffer(), 'welcome-image.png');

    channel.send(`Welcome to the server, ${member}!`, attachment);
});

当此函数触发时,它应该导致机器人向服务器发送“欢迎来到服务器,[此处的成员名称]”作为消息以及指定的附件。

但是,它并没有这样做,而是将消息发送到服务器,根本没有附件。

我在测试时也没有出错。

谁能告诉我这里可能出了什么问题?

编辑:经过进一步实验,我找到了解决方案。

client.on('guildMemberAdd', async member => {
    console.log("Here we go");
    console.log(member.guild.name);
    const channel = member.guild.channels.find(ch => ch.name === 'general');

    if (!channel) return;

    // Set a new canvas to the dimensions of 700x250 pixels
    const canvas = Canvas.createCanvas(2097, 2097); //Works correctly
    // ctx (context) will be used to modify a lot of the canvas

    const ctx = canvas.getContext('2d');

    // Since the image takes time to load, you should await it
    const background = await Canvas.loadImage('./sadman.jpg'); //Finds it
    // This uses the canvas dimensions to stretch the image onto the entire canvas
    ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
    // Use helpful Attachment class structure to process the file for you

    channel.send(`Welcome to the server, ${member}!`, { files: [{ attachment: canvas.toBuffer() }] });
});

【问题讨论】:

  • 一个没有图像的小画布如何在其中画一个矩形?这行得通吗?
  • 不,将 ctx.drawImage 行替换为 ctx.fillRect(0, 0, canvas.width, canvas.height); 会导致相同的结果。
  • 调试时canvas.toBuffer()的值是否正确?
  • ...他们确实有一个 github 存储库:github.com/discordjs/guide/tree/master/code-samples/… 你可以在那里提出问题以获得支持
  • 我刚刚用ctx.fillRect 尝试了你的代码,它成功了。您能否检查一下该机器人是否能够在该频道中发送图像?

标签: node.js canvas discord discord.js node-canvas


【解决方案1】:

这很可能是因为您没有在 Canvas.loadImage('./wallpaper.jpg'); 您的图片与该名称完全匹配吗?确保您的代码可以读取该目录中的该文件

【讨论】:

  • 不幸的是不是这个。当我将 Canvas.loadImage 中的路径替换为不存在的路径时,出现错误:UnhandledPromiseRejectionWarning: Error: ENOENT, No such file or directory './nonexistantFile.jpg' 当我使用有效的路径名时没有错误出现,但仍然无法生成图像。
猜你喜欢
  • 2011-07-26
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多