Search code examples
javascriptnode.jsdiscorddiscord.js

How do I reply to a message only if it was from a DM in discord.js v14?


I want my bot to reply only if the message was sent via DM, not on any of the channel's server.

These are my intents and partials

const client = new Client({
  intents: [
    IntentsBitField.Flags.Guilds,
    IntentsBitField.Flags.GuildMembers,
    IntentsBitField.Flags.GuildMessages,
    IntentsBitField.Flags.MessageContent,
    IntentsBitField.Flags.DirectMessages
  ],partials:[
    Partials.Channel,
    Partials.Message
  ]
});

And this is the code im trying to use to read DMs. I got it from a tutorial but I cant find the channel object when I log the message.

client.on('messageCreate', async (message) => {
    
    // Check if the message is a direct message (DM)
    if (message.channel.type === 'DM') {
      message.author.send('Message Received');
    }
  });  

Any ideas?

I dont get the "Message Received" message when I send a dm but if i remove the dm verification i get the reply.


Solution

  • message.guild will be null inside a DM; this is one way to check if the message is from a DM.

    if (message.guild === null) return;