Discord.js中如何将Base64图片显示为Embed缩略图
解决Discord.js中Base64图片作为Embed缩略图无法显示的问题
我在Discord.js里尝试将Base64图片作为Embed消息的缩略图展示时遇到了显示问题,从API获取到的图片Base64内容为:iVBORw0KGgoAAAANS[...]N02ziqF8weBaAAAAAElFTkSuQmCC,原代码如下:
const response = await fetch(`https://api.mcsrvstat.us/2/${host}:${port}`); const json = await response.json(); console.log(json); if (json !='') { try { var imageStream = Buffer.from(json.icon.split(",")[1], "base64"); var img = new AttachmentBuilder(imageStream, {name : "favicon.png"}); console.log(typeof img); console.log(img); const embed = new EmbedBuilder() .setTitle(host) .setThumbnail("attachment://favicon.png") [...] await interaction.editReply({embeds: [embed]}); } catch (error) { await interaction.editReply({content: `Une erreur est survenue : ${error}`, ephemeral: true }); }
当前缩略图无法正常显示,尝试将图片作为文件返回时还会报错:TypeError [ReqResourceType]: The resource must be a string, Buffer or a valid file stream。
修复方案
核心问题是你没有将构建好的AttachmentBuilder实例添加到消息的files参数中,Embed引用的本地附件必须和消息一起发送,否则Discord无法找到对应的资源。
修复后的完整代码:
const response = await fetch(`https://api.mcsrvstat.us/2/${host}:${port}`); const json = await response.json(); console.log(json); // 替换原有的空对象判断逻辑,API返回的是对象而非字符串 if (Object.keys(json).length > 0) { try { // 处理Base64数据前先做合法性校验 const base64Data = json.icon?.split(",")[1]; if (!base64Data) throw new Error("获取到无效的图片Base64数据"); const imageBuffer = Buffer.from(base64Data, "base64"); const imgAttachment = new AttachmentBuilder(imageBuffer, { name: "favicon.png" }); const embed = new EmbedBuilder() .setTitle(host) .setThumbnail("attachment://favicon.png"); // 关键:将附件加入files参数,和Embed一起发送 await interaction.editReply({ embeds: [embed], files: [imgAttachment] }); } catch (error) { await interaction.editReply({ content: `发生错误:${error}`, ephemeral: true }); } }
额外优化说明
- 替换原有的
json != ''判断:API返回的是JSON对象,和空字符串比较逻辑错误,改用Object.keys(json).length > 0判断是否获取到有效数据。 - 增加Base64数据校验:通过可选链
json.icon?.split(",")[1]避免API未返回icon字段时的报错,同时判断数据有效性,提前抛出明确错误。 - 规范变量命名:将
var替换为const,提升代码可读性和稳定性。
内容的提问来源于stack exchange,提问作者Eloi DOLLE Overlord
相关产品推荐
相关产品推荐

