'DiscordJS (Node) Sending PM to user and await reply

I'm trying to get my bot to send a user a private message when a user types a command, and then wait for a reply to the private message.

Expected flow:

  • Jim types: !auth
  • bot sends Jim a private message
  • Jim replies to the message with blablabla
  • Bot sees the blablabla reply and outputs to terminal => console.log( replyResponse );

I have tried numerous examples I have found from here and in the docs but none of them works.

message.author.send('test').then(function () {
  message.channel
    .awaitMessages((response) => message.content, {
      max: 1,
      time: 300000000,
      errors: ['time'],
    })
    .then((collected) => {
      message.author.send(`you replied: ${collected.first().content}`);
    })
    .catch(function () {
      return;
    });
});


Solution 1:[1]

message.author.send('test') returns the sent message so you should use that returned message to set up a message collector. At the moment, you're using message.channel.awaitMessages and that waits for messages in the channel where the user sent the !auth message, not the one where the bot sent a response.

Check out the working code below. It uses async-await, so make sure that the parent function is an async function. I used createMessageCollector instead of awaitMessages as I think it's more readable.

try {
  // wait for the message to be sent
  let sent = await message.author.send('test');
  // set up a collector in the DM channel
  let collector = sent.channel.createMessageCollector({
    max: 1,
    time: 30 * 1000,
  });

  // fires when a message is collected
  collector.on('collect', (collected) => {
    collected.reply(`? You replied: _"${collected.content}"_`);
  });

  // fires when we stopped collecting messages
  collector.on('end', (collected, reason) => {
    sent.reply(`I'm no longer collecting messages. Reason: ${reason}`);
  });
} catch {
  // send a message when the user doesn't accept DMs
  message.reply(`? It seems I can't send you a private message...`);
}

enter image description here

Make sure, you don't forget to enable the DIRECT_MESSAGES intents. For example:

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

const client = new Client({
  intents: [
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES,
    Intents.FLAGS.DIRECT_MESSAGES,
  ],
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zsolt Meszaros