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

DiscordJS配合JIMP使用时首次命令正常发图第二次仅返回下载文件求助

问题根因
  • Jimp 提供的write()方法为异步IO操作,你的代码未添加await关键字等待写入完成。首次调用时磁盘写入速度刚好匹配回复逻辑,可正常发送图片;第二次调用时未等新图片写入完成就读取了本地旧文件/未完成写入的损坏文件,导致Discord无法识别为图片格式,仅展示为可下载附件。
  • 反复写入同一路径的本地文件容易出现IO占用冲突,并发调用时故障概率会大幅提升。
修复方案

优先推荐直接生成内存Buffer发送,无需写入本地磁盘,修正后代码如下:

const Discord = require('discord.js')
const Jimp = require('jimp');

module.exports = (client) => {
    client.on('interactionCreate', async interaction => {
        if (!interaction.isCommand()) return;
        if (interaction.commandName === 'evil') {
            if (interaction.options.getSubcommand() === 'user') {
                const user = interaction.options.getUser('mention');
                const toptext = interaction.options.getString('toptext')
                const bottext = interaction.options.getString('bottomtext')

                const font = await Jimp.loadFont(Jimp.FONT_SANS_32_WHITE);
                const image = await Jimp.read(user.displayAvatarURL({ format: 'png',size: 256 }));
                image.invert()
                .print(font, 0, 5, {
                    text: `${toptext}`,
                    alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER
                }, 256, 256)
                .print(font, 0, 220, {
                    text: `${bottext}`,
                    alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER
                }, 256, 256)
                // 直接生成PNG Buffer,不写入本地磁盘
                const imageBuffer = await image.getBufferAsync(Jimp.MIME_PNG)
                await interaction.reply({
                    files: [{
                      attachment: imageBuffer,
                      name: 'file.png'
                }]});
            }
        }
    })
}

如果需要保留写入本地文件的逻辑,仅需给write方法添加await关键字即可:
await image.write('invert.png')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 09:57:00