You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.js V13中如何在Embed的.setImage方法使用已下载的本地图片

discord.js V13 Embed插入本地图片实现方法

实现步骤

  • 将需要用到的本地图片存入你的机器人项目目录,推荐在根目录新建assets文件夹专门存放静态资源,例如本次要用到的饼干图片存为./assets/cookie.jpg
  • 引入Node.js内置path模块处理文件路径,避免相对路径引发的读取错误
  • 构造MessageAttachment实例关联本地图片
  • Embed的setImage传入attachment://[附件文件名]格式的地址,同时在发送消息时将附件加入files参数

修改后的完整代码

/** @format */
const path = require('path');
const Command = require("../Structures/Command.js");
const Discord = require("discord.js");

module.exports = new Command({
    name: "Cookie",
    description: "sends a image",
    permission: "SEND_MESSAGES", 
    async run(message, args, client) {
        // 构造本地图片附件,第二个参数为附件的自定义文件名
        const cookieImage = new Discord.MessageAttachment(
            // 此处路径根据你自己的项目结构调整,示例中代码位于./Commands/xxx/ 所以回溯两层到根目录
            path.resolve(__dirname, '../../assets/cookie.jpg'),
            'cookie.jpg'
        );
        const embed = new Discord.MessageEmbed();
        embed
            .setTitle("here is your cookie")
            .setDescription("photo discription")
            .setColor("BLURPLE")
            .setTimestamp()
            // 此处地址格式为 attachment:// + 上面设置的附件文件名,必须完全匹配
            .setImage("attachment://cookie.jpg")
        // 发送时添加files参数传入附件列表
        message.reply({ embeds: [embed], files: [cookieImage] });
    }
});

注意事项

  • 路径要根据你自己的项目文件结构调整,如果你不确定路径是否正确,可以先打印path.resolve的返回值校验
  • 附件的文件名和setImage中使用的文件名必须完全一致,包括大小写、后缀名,否则图片无法正常显示
  • Discord对Embed内的图片有大小限制,单张图片建议不超过8MB

内容的提问来源于stack exchange,提问作者user16052664

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 17:42:01