discord.js

Discord.js: MessageAttachment is not defined


I'm having trouble making my bot filter messages and respond with a local file from my computer. Here is the code:

      client.on("message", msg => {
      console.log(msg.content);
      let wordArray = msg.content.split(" ")
      console.log(wordArray)

      let filterWords = ['test']

      for(var i = 0; i < filterWords.length; i++) {
        if(wordArray.includes(filterWords[i])) {
          msg.delete()
          // Create the attachment using MessageAttachment
          const attachment = new MessageAttachment('cbcfilter.png');
          msg.channel.send(attachment)  
        }
      }
    });

It gives me this error message:

    ReferenceError: MessageAttachment is not defined
        at Client.<anonymous> (/Users/DShirriff/cbcbot/bot.js:108:26)
        at Client.emit (events.js:323:22)
        at MessageCreateAction.handle (/Users/DShirriff/cbcbot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
        at Object.module.exports [as MESSAGE_CREATE] (/Users/DShirriff/cbcbot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
        at WebSocketManager.handlePacket (/Users/DShirriff/cbcbot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:386:31)
        at WebSocketShard.onPacket (/Users/DShirriff/cbcbot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:435:22)
        at WebSocketShard.onMessage (/Users/DShirriff/cbcbot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:293:10)
        at WebSocket.onMessage (/Users/DShirriff/cbcbot/node_modules/ws/lib/event-target.js:120:16)
        at WebSocket.emit (events.js:311:20)
        at Receiver.receiverOnMessage (/Users/DShirriff/cbcbot/node_modules/ws/lib/websocket.js:801:20)

Am I an idiot and missing a simple parentheses, or should I look for a different form of this line of code?


Solution

  • You need to import MessageAttachment.

    If you're using require to import discord.js then you can do:

    const Discord = require('discord.js')
    const attachment = new Discord.MessageAttachment('cbcfilter.png');
    

    If you're using import then you can do:

    import { MessageAttachment } from 'discord.js'
    const attachment = new MessageAttachment('cbcfilter.png');
    

    Side note: you don't have to construct a MessageAttachment you can just do

    msg.channel.send({files: ['cbcfilter.png']})
    

    OR

    msg.channel.send({
    files: [{
        attachment: 'entire/path/to/cbcfilter.png',
        name: 'cbcfilter.png'
      }]
    })