Uncaught TypeError: MessageAttachment不是构造函数 如何修复?
解决Discord.js中"Uncaught TypeError: MessageAttachment is not a constructor"错误
这个错误的核心原因是:你当前使用的Discord.js版本是v14及以上,该版本已经移除了MessageAttachment类,改用AttachmentBuilder来创建附件对象。
解决方案一:使用AttachmentBuilder替换MessageAttachment
- 修改导入语句,把
MessageAttachment换成AttachmentBuilder - 调整附件创建的代码,v14中
AttachmentBuilder的参数格式略有不同
修改后的代码片段:
// Import required packages and modules const { Client, AttachmentBuilder } = require('discord.js'); // 替换MessageAttachment为AttachmentBuilder const { GatewayIntentBits, IntentsBitField } = require('discord.js'); const fetch = require('node-fetch'); const dotenv = require('dotenv'); //... // Send the image to the Discord channel if (imageUrl) { const attachment = new AttachmentBuilder(imageUrl, { name: 'selfie.png' }); // 参数改为配置对象 message.channel.send({ content: 'Here is your selfie!', files: [attachment] }); } else { message.channel.send('Error: Unable to generate the selfie. Please try again later.'); }
解决方案二:直接传入URL到files数组(更简洁)
如果不需要额外配置附件,也可以跳过创建附件对象,直接把URL和文件名以对象形式传入files数组:
//... // Send the image to the Discord channel if (imageUrl) { message.channel.send({ content: 'Here is your selfie!', files: [{ attachment: imageUrl, name: 'selfie.png' }] }); } else { message.channel.send('Error: Unable to generate the selfie. Please try again later.'); }
补充说明
如果你的项目仍在使用Discord.js v13或更低版本,MessageAttachment是可以正常使用的,但出于兼容性和功能更新考虑,建议升级到最新版本并适配新的API规范。
内容的提问来源于stack exchange,提问作者ohgoditdoesntwork
相关产品推荐
相关产品推荐

