Search code examples
automationdiscord.jsbots

How to send a message to a Discord user using a Discord Bot


I know there are some similar questions but methods have recently been updated and the documentation I've found to be unusual.

So I'm wondering what intents do I need to send a message to a Discord user through a discord bot and only relying on internal triggers to run the code so function call and not events on the discord server.

This is a rough idea of what I have so far:

  const { Client, GatewayIntentBits } = require('discord.js');

  const client = new Client({ intents: [GatewayIntentBits.DIRECT_MESSAGES] });
  
  // Cut the code out starting from here 
  async function sendMessage(page, messageURL){
  
    const userID = '644643045622415366'; 
    
    await client.login('asdfafasddfq234123421235sdgergafaesfsa');
    
    const user = await client.users.fetch (userID);
    

    await user.send (messageURL);
      

  
  
  }

Most of these methods are abstracted into separate functions with try catch blocks just an example

I've tried different combinations and methods of sending messages but nothing seems to work.

Any patience would be much appreciated since I'm new to this and I'm just trying to piece things together from different articles


Solution

  • When you're trying to send a message to a user privately, you do need to use the DirectMessages intent. Here's how the whole code for sending a message might look

    const { Client, GatewayIntentBits } = require('discord.js');
    
    const client = new Client({ 
        intents: [GatewayIntentBits.DirectMessages /* Add other intents here */],
    });
    
    // Function for sending the message
    async function sendMessage() {
        const userID = '123456789';
        const user = await client.users.fetch(userID);
        await user.send('hello world').catch(() => console.log("User does not accept DM's")); // Add the catch to check whether or not the bot can send DM's to the user
    }