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

求助:使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 06:21:37