我一直在学习创建 Discord 机器人的基础知识,并且一直在尝试将 Canvas 与 DiscordJS 一起使用。
我试图按照这个简单的教程进行操作,但我似乎无法找到任何可能出错的线索。
作为参考,这是我在教程中得到的要点。
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() }] });
});