如何解决Discord.js机器人的‘Attachment is not a constructor’错误?
解决Discord.js中“Attachment is not a constructor”错误
这个问题我之前也碰到过,核心原因是Discord.js版本迭代带来的API变更——从v13版本开始,官方废弃了旧的Attachment构造函数,改用AttachmentBuilder来创建附件对象,同时发送消息的方式也需要调整,不能直接把附件拼接到字符串里。
步骤1:先确认你的Discord.js版本
先检查项目里的Discord.js版本,在终端运行:
npm list discord.js
如果版本是v13或更高,就按下面的v13+方案修改;如果是v12及更低,那是导入方式的问题,看后面的低版本适配方案。
步骤2:v13+版本的修复方案
2.1 正确导入AttachmentBuilder
在你的机器人主文件顶部,先导入需要的类:
const { AttachmentBuilder } = require('discord.js');
2.2 修改发送附件的代码
你原来直接把附件和字符串拼接的方式是错误的,Discord.js要求通过消息配置对象的files字段传递附件。修改后的代码如下:
case 'about': // 创建附件实例,第二个参数可以指定显示的文件名(可选) const attachment = new AttachmentBuilder('./DidYouThinkIAmTheRealFace.png', { name: 'BotFace.png' }); // 一次性发送文本和附件,用配置对象传递内容和文件 message.channel.send({ content: 'I am Damabot, developed by Damadion!', files: [attachment] }) .then(() => console.log('Bot successfully replied with attachment')) .catch(err => console.error('Error sending message:', err)); break;
为什么原来的代码不行?
- v13+不再支持
new Attachment()的声明方式,必须用AttachmentBuilder替代 - 不能直接把附件对象和字符串拼接,Discord.js的
send方法需要接收配置对象,通过files数组传递附件 - 分开调用两次
message.channel.send不是最优解,一次性发送更高效也符合API规范
如果你用的是v12及更低版本
如果你的Discord.js版本还停留在v12,只需要确保正确导入Attachment,然后调整发送逻辑:
// 顶部导入Attachment const { Attachment } = require('discord.js'); // 然后修改case里的代码 case 'about': const attachment = new Attachment('./DidYouThinkIAmTheRealFace.png'); // 用配置对象传递文本和附件 message.channel.send('I am Damabot, developed by Damadion!', { files: [attachment] }); console.log('Bot successfully replied'); break;
最后提醒下:一定要检查文件路径是否正确——确保DidYouThinkIAmTheRealFace.png确实在你的项目根目录(或者用绝对路径更稳妥),否则可能会出现找不到文件的新错误。
内容的提问来源于stack exchange,提问作者user11620803




