如何使用我的机器人修复此“附件不是构造函数”错误?

Posted

技术标签:

【中文标题】如何使用我的机器人修复此“附件不是构造函数”错误?【英文标题】:How to fix this 'Attachment is not a constructor' error with my bot? 【发布时间】:2019-10-24 01:12:05 【问题描述】:

当我为 Discord 制作我的机器人并尝试附加图片时,由于这个错误,我不能这样做

这是一个在 Discord.js 上运行的 Discord 机器人 我一开始就尝试了 const Attachment ,但是没用,代码中去掉 new 和 const 也没有用

        case 'about':
            message.channel.send('I am Damabot, developed by Damadion!')
            const attachment = new Attachment('./DidYouThinkIAmTheRealFace.png')
            message.channel.send('I am Damabot, developed by Damadion!' + attachment)
            console.log('Bot successfully replied')
            break;

我希望它发送附件,但它没有发送此错误

【问题讨论】:

嗨,您是否尝试过使用 MessageAttachment 而不是 Attachment? 嗨,现在它说 MessageAttachment 不是构造函数 【参考方案1】:

你可以这样做:

message.channel.send('I am Damabot, developed by Damadion!',  files: ['./DidYouThinkIAmTheRealFace.png'] );

它将文件直接添加到消息中,因此您不必创建附件。我用这个我的 BOT,它工作得很好。

【讨论】:

欢迎来到 Stack Overflow。你能edit你的答案为代码添加一些解释吗?【参考方案2】:

Attachment 是 Discord.js 中的一个类。除非您对 require 语句 (const Attachment = require('discord.js')) 使用解构赋值,否则 Node.js 会尝试基于代码中的类构造 Attachment 对象。当它发现没有时,它会抛出你的错误。

如果你想坚持构造 Attachment 对象,你可以使用:

const attachment = new Discord.Attachment('./path/to/file.png', 'name'); // name is optional

message.channel.send('Hey there', attachment)
  .catch(console.error);

否则,您可以像这样使用消息的files 属性:

message.channel.send('Hey there', 
  files: ['./path/to/file.png']
)
.catch(console.error);

后者还允许您发送嵌入(并且可能使用嵌入中的附件)。

Discord.js Docs

【讨论】:

【参考方案3】:

对我来说,以下代码有效:

const attachment = new Discord.MessageAttachment("url");
channel.send(attachment);

Discord.Attachment 被替换为 Discord.MessageAttachement

【讨论】:

【参考方案4】:

我遇到了同样的问题。我运行npm install 来更新我的软件包并检查我的不和谐版本是否已过时并因此导致任何问题。 之后,我决定浏览文档并在这里找到这个 sn-p:

const attachment=new Discord.MessageAttachment("enter the URL u wanna enter here")
const generalChannel=client.channels.cache.get("enter ur channel id here")
$generalChannel.send(attachment);

至少,它对我有用。请让我知道它是否也适合您。

【讨论】:

以上是关于如何使用我的机器人修复此“附件不是构造函数”错误?的主要内容,如果未能解决你的问题,请参考以下文章

如何修复此错误调用google位置来解决服务“目标机器主动拒绝它”

如何在 Wamp_Server 中修复此错误? [关闭]

我的不和谐机器人出现错误,请告诉我如何修复

使用lampp托管时如何修复“Slim Application Error”错误

如何在我的查询中修复此语法错误?

如何在我的 Django 应用程序的“评论”视图中修复此错误?