如何将canvas生成的附件添加到MessageEmbed嵌入式消息中
问题修复方案
现有代码问题列表
- 语法错误:
setDescription(Welcome!) 处字符串左侧缺少反引号,会直接导致代码编译报错 - 附件引用逻辑错误:Embed的
setImage方法不支持直接传入附件实例,必须通过特定协议关联附件 - 消息参数缺失:发送消息时没有将附件加入消息的
files字段,Discord服务端无法获取对应的图片资源 - 若使用discord.js v14及以上版本,还存在API命名过时问题:
MessageAttachment已更名为AttachmentBuilder、MessageEmbed已更名为EmbedBuilder
修正后代码
discord.js v13版本
const { MessageAttachment, MessageEmbed } = require('discord.js'); // 实例化附件时指定文件名,用于后续关联embed const attachment = new MessageAttachment(canvas.toBuffer(), 'welcome-card.png'); let embed = new MessageEmbed() .setTitle(`Hello`) .setDescription(`Welcome!`) // 补全反引号修复语法错误 .setImage(`attachment://welcome-card.png`) // 通过attachment协议关联附件 .setColor(embedColor) // 发送时同时传入embed数组和附件数组 message.channel.send({ embeds: [embed], files: [attachment] })
discord.js v14+版本
const { AttachmentBuilder, EmbedBuilder } = require('discord.js'); const attachment = new AttachmentBuilder(canvas.toBuffer(), { name: 'welcome-card.png' }); let embed = new EmbedBuilder() .setTitle(`Hello`) .setDescription(`Welcome!`) .setImage(`attachment://welcome-card.png`) .setColor(embedColor) message.channel.send({ embeds: [embed], files: [attachment] })
内容的提问来源于stack exchange,提问作者Jimboy
相关产品推荐
相关产品推荐

