求助:使用Discord.MessageAttachment发送谷歌地图API图片触发构造函数错误
问题解决:Discord.MessageAttachment 不是构造函数
错误原因
最新版Discord.js(v14及以上)已废弃MessageAttachment构造函数,改用AttachmentBuilder来创建附件。
修改步骤
- 替换附件构造类:将
Discord.MessageAttachment改为Discord.AttachmentBuilder - 转换数据格式:把axios返回的
arraybuffer转为Node.js的Buffer类型 - 调整发送方式:发送消息时需将附件放入
files数组参数中
修改后的完整代码
const latitude = Math.random() * 180 - 90; const longitude = Math.random() * 360 - 180; const apiUrl = `https://maps.googleapis.com/maps/api/streetview?size=400x400&location=${latitude},${longitude}&key=*MyAPIKey`; axios .get(apiUrl, { responseType: 'arraybuffer' }) .then(response => { // 转换arraybuffer为Buffer,并用AttachmentBuilder创建附件 const attachment = new Discord.AttachmentBuilder(Buffer.from(response.data), { name: 'image.jpg' }); // 通过files数组发送附件 message.channel.send({ files: [attachment] }); }) .catch(error => { console.error(error); message.channel.send('Failed to get a street view image.'); });
补充说明
如果你的Discord.js版本是v14+,导入方式可以保持const Discord = require('discord.js');,AttachmentBuilder已包含在导出的Discord对象中。若想更简洁,也可以解构导入:
const { AttachmentBuilder } = require('discord.js');
之后直接使用new AttachmentBuilder(...)即可。
内容的提问来源于stack exchange,提问作者Jäger
相关产品推荐
相关产品推荐

