Wait for messages - NodeJS Discord Bot Development
h
static2020 (20)

Hey there! Today I will be teaching you how to 'wait for messages' in discord.js. Also known as awaitMessages. This tutorial is written in Nodejs and uses the dependancy Discord.js

What is awaitMessages! What does it do?

Image not loading? Click Here

As we can see in the above image, awaitMessages basically does is that it allows for a user to input information after a certain condition, say, a command being ran. Here I used my slowmode command without the number and the bot allowed me to enter the number for the command.

Creating a filter

Alright, so you want the bot to wait for a message from the original message author. We do this buy making sure the id of the user who enters data is the same of the person who started the command. Do this buy:

// in your message event, and a command
const filter = m => m.author.id ===  message.author.id;

Now we call the awaitMessages function

The function takes 2 params, max and time

const filter = m => m.author.id ===  message.author.id;
message.channel.awaitMessages(filter, {
max: 1, // leave this the same
time: 10000, // time in MS. there are 1000 MS in a second
   })

Great! How do I use what is collected?

So, all we do now is attach a .then() block to the end of this.

NIOTE: The collected is a collection, hence we use collected.first().content.

const filter = m => m.author.id ===  message.author.id;
message.channel.awaitMessages(filter, {
max: 1. // leave this the same
time: 10000, // time in MS. there are 1000 MS in a second
   }).then(async(collected) => {
    if(collected.first().content == 'cancel'){
    message.reply('Command cancelled.')
} 
console.log('collected :' + collected.first().content)
}

I do apologise for any weird indentations

What to do if they take tooo long?

Simple! We add a .catch() block at the end! Here's an example...

const filter = m => m.author.id ===  message.author.id;
message.channel.awaitMessages(filter, {
max: 1. // leave this the same
time: 10000, // time in MS. there are 1000 MS in a second
   }).then(async(collected) => {
    if(collected.first().content == 'cancel'){
    message.reply('Command cancelled.')
} 
console.log('collecred :' + collected.first().content)
}).catch(() => {
    // what to do if a user takes too long goes here 

message.reply('You took too long! Goodbye!') 
});

And there you have it!

Any questions please feel free to ask me in the comments section. I have also included a repl with an awaitMessages command inside it.

PLEASE NOTE: You may need to adapt the above examples to suit your bot.

Thank you for reading, upvote if you thought this was helpful.

You are viewing a single comment. View All
CodeABC123 (212)

I don’t know what you mean. @static2020