Muhammad Mohsin Ajmal
Muhammad Mohsin Ajmal

Reputation: 147

Discord js direct message await not working

So my discord bot asks a user in DM for an API secret. I want to await the user's response so that I can do further things with my key.

From client.on('messageCreate') after a user requests to add key I call this function

async function takeApiSecret(msg) {

    const botMsg = await msg.author.send("Please provide your api secret");
    const filter = collected => collected.author.id === msg.author.id;

    const collected = await botMsg.channel.awaitMessages(filter, {
      max: 1,
      time: 50000,
  }).catch(() => {
    msg.author.send('Timeout');
  });

However I am not able to await the user's response and collect it. Instead when I reply I get another message on my client.on('messageCreate'). Any leads what I could be doing wrong?

Upvotes: 0

Views: 958

Answers (1)

Cannicide
Cannicide

Reputation: 4520

In discord.js v13.x, the parameters of awaitMessages() changed a little bit. There are no longer separate parameters for filter and options; filter is now contained within options. This should fix your problem:

const filter = collected => collected.author.id === msg.author.id;

const collected = await botMsg.channel.awaitMessages({
    filter,
    max: 1,
    time: 50000,
}).catch(() => {
    msg.author.send('Timeout');
});

You can find the documentation here. For some reason, the options do not appear to be fully documented, but you can view the example on that page to see the new format.


Additionally, if this code is called whenever a message is sent via DM, you may need to prevent collected messages from triggering the rest of your messageCreate event listener code. Here's one way you could do that:

Outside messageCreate handler:

const respondingUsers = new Set();

Right before awaitMessages()

respondingUsers.add(msg.author.id);

Inside your .then() and .catch() on your awaitMessages():

respondingUsers.delete(msg.author.id);

Near the top of your messageCreate handler, right after your other checks (e.g. checking if the message is a DM):

if (respondingUsers.has(msg.author.id)) return;

If we put all of this together, it may look something like this (obviously, modify this to work with your code):

const respondingUsers = new Set();

client.on('messageCreate', msg => {

    if (msg.channel.type != "DM") return;
    if (respondingUsers.has(msg.author.id)) return;

    respondingUsers.add(msg.author.id);
    
    const filter = collected => collected.author.id === msg.author.id;

    const collected = botMsg.channel.awaitMessages({
        filter,
        max: 1,
        time: 50000,
    })
    .then(messages => {
        msg.author.send("Received messages");
        respondingUsers.delete(msg.author.id);
    })
    .catch(() => {
        msg.author.send('Timeout');
        respondingUsers.delete(msg.author.id);
    });

})

Upvotes: 1

Related Questions