Detecting direct messages and responding to them using discord.js bot

I’m trying to create a Discord bot that can detect when someone sends it a private message and respond accordingly. I want the bot to recognize when a user DMs it directly and then send back an appropriate response.

I’ve been experimenting with different approaches but I’m having trouble with the condition that checks for direct messages. Some parts of my code work fine like sending messages and logging to console, but I can’t get the DM detection to work properly.

Here’s what I’ve tried so far:

// Command to handle user requests via DM
client.on('message', (msg) => {
  if(msg.channel.type === 'dm') {
    // Look for specific keyword
    if(msg.content.toLowerCase() === 'support') {
      console.log('Player ' + msg.author.username + ' needs help. Notifying moderators!');
      client.channels.cache.get("123456789012345678").send('**' + msg.author.username + '** needs moderator assistance!');
      msg.reply('Request submitted! A moderator will contact you shortly.');
    } else {
      msg.reply('For assistance, please send "support" via direct message.');
    }
  }
});

Can someone point me in the right direction? What’s the correct way to check for DMs in discord.js?

This might be simpler than fixing Discord intents and gateway issues. Your DM detection looks good, but Discord bots get messy fast when you need reliable message handling.

I’ve been there - dropped messages, weird partial data, constantly restarting bots just to tweak response logic. The real issue isn’t your code, it’s cramming everything into the bot.

What saved me was moving the heavy work outside Discord. Bot gets the DM, shoots it to an automation workflow that handles the processing. Way more reliable than praying Discord’s gateway behaves.

The workflow parses messages, picks responses, tracks conversations, and fires replies back through Discord’s API. Bot crashes don’t kill your support system anymore.

You can add smart routing - different keywords hit different workflows. Scales much better than a pile of if statements.

Latenode nails Discord integration for this. Your bot just forwards messages while the real logic runs in solid automation workflows.

You’re probably handling this manually when you could just automate it. I’ve built similar bots - hardcoding responses gets messy fast.

Your DM detection works fine, but what about different support requests? Different teams? Response tracking?

I fixed this by connecting my Discord bot to an automation platform that handles the logic. Someone sends a DM, triggers a workflow that parses the message, categorizes it, notifies the right people, and follows up automatically.

Someone says “billing”? Routes to finance. “Bug”? Goes to developers. You can set up auto-responses based on keywords or sentiment.

Best part - no bot restarts when you change logic. Update the workflow and it’s live.

Latenode works great for Discord automation. Connects directly to Discord’s API and handles routing/responses without touching your bot code.

could be a partialApplication issue. enable partials for USER and CHANNEL when you create your client. discord sometimes sends partial data for DMs, which breaks the channel.type check. try logging msg.channel right before your if statement to see what you’re actually getting.

Check for gateway connection issues with DMs. I hit this weird edge case where my bot got server messages fine but DM events would randomly drop or show up late. Discord’s gateway gets finicky with DM routing, especially if you’re in multiple servers. Drop a console.log right at the start of your message handler - see if DM events even reach your code. Also double-check your bot token permissions. Some bots created certain ways don’t get full DM access by default. If logging shows zero DM events, just recreate the whole bot application. Sounds extreme but I’ve seen corrupted configs that only broke private messages while everything else worked fine.

The Problem: Your Discord bot isn’t receiving direct messages (DMs), even though other parts of your code, such as sending messages and logging, are working correctly. Your current DM detection logic using msg.channel.type === 'dm' isn’t functioning as expected.

:thinking: Understanding the “Why” (The Root Cause):

The issue likely stems from a combination of factors related to Discord.js versions and the necessary gateway intents. Older versions of discord.js handled events differently, and more recent versions require explicit intent declarations to receive certain event types, including direct messages. Without the correct intents enabled, your bot won’t receive DM events, regardless of your code’s logic. Additionally, there might be issues with how your bot was created or invited to servers which could affect DM access.

:gear: Step-by-Step Guide:

Step 1: Update discord.js and Verify Your Version:

First, make sure you are using a recent version of discord.js (v14 or higher is recommended). You can check your current version and update using npm:

npm list discord.js  // Check current version
npm update discord.js // Update to latest version

After updating, verify the version again using npm list discord.js. Ensure it reflects the latest version.

Step 2: Enable Necessary Intents:

Discord requires you to explicitly enable intents for your bot to receive specific events. For direct messages, you need both GatewayIntentBits.DirectMessages and GatewayIntentBits.MessageContent. (The latter is required to access the content of the DM.)

  1. In the Discord Developer Portal: Navigate to your application, go to the “Bot” section, and enable the “Message Content Intent” and “Direct Messages Intent” under “Privileged Gateway Intents”.
  2. In your code: When you create your Discord client, specify these intents:
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.DirectMessages, GatewayIntentBits.MessageContent] }); //Add other intents as needed

// ... rest of your bot code ...

Step 3: Review Your DM Handling Code:

Ensure that your DM handling logic is correctly placed within the client.on('messageCreate', ...) event listener. (Note that the event name is messageCreate, not simply message, in recent versions of discord.js). Your existing code should work correctly if the intents are properly set up:

client.on('messageCreate', (msg) => {
  if (msg.channel.type === 'DM') {
    // Your DM handling logic here
    if(msg.content.toLowerCase() === 'support') {
      console.log('Player ' + msg.author.username + ' needs help. Notifying moderators!');
      client.channels.cache.get("123456789012345678").send('**' + msg.author.username + '** needs moderator assistance!');
      msg.reply('Request submitted! A moderator will contact you shortly.');
    } else {
      msg.reply('For assistance, please send "support" via direct message.');
    }
  }
});

Step 4: Check Bot Permissions:

Make sure your bot has the necessary permissions to receive and read direct messages within your Discord server. If it’s added to the server, it should automatically have these, but it’s best to verify this in the server’s role settings.

:mag: Common Pitfalls & What to Check Next:

  • Incorrect Intent Configuration: Double-check that both GatewayIntentBits.DirectMessages and GatewayIntentBits.MessageContent are enabled in both the Discord Developer Portal and your bot’s code.
  • Outdated discord.js: Using an outdated version can cause unexpected behavior. Always update to the latest stable release.
  • Missing Dependencies: Make sure you’ve installed all the necessary packages (npm install discord.js).
  • Typographical Errors: Review your code carefully for any typos or syntax errors.
  • Bot Token: Ensure your bot token is correct and hasn’t been revoked or regenerated.
  • Rate Limits: If you are sending many messages or making many requests to the Discord API, your bot might be subject to rate limiting, impacting its ability to receive messages (check Discord Developer Portal for rate limit info).

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

Your bot probably isn’t getting DM events at all. Had this exact problem last month building a support bot. Your code looks right for older discord.js versions, but you’re missing a crucial step - enable GatewayIntentBits.DirectMessages when you initialize your client. Without it, your bot won’t see private messages at all. Also check you’re not accidentally filtering out bot messages somewhere else in your code. I wasted hours debugging similar logic only to find a global bot filter catching everything. Log every message event first to see if DMs even reach your handler, then add the channel type check.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.