githubEdit

Responding to messages

Now that you've created your bot and successfully started it for the first time, let's move on to having your bot respond to your messages!

Starting off, we have to listen to the messageCreated arrow-up-rightevent, which emits a Message arrow-up-rightobject.

// index.js
// add this to your index.js file, preferably above the ready event listener

client.on("messageCreated", async message => {
     if(!message.content.startsWith("!")) return;
     // type 0 is for bots
     if(message.author.type === 0) return;
     
     if(message.content === "!hi") return message.reply("hi there!");
});

Now, let's explain what this code does. Inside the event listener, we have an asynchronous arrow-up-rightarrow functionarrow-up-right. This allows us to resolve any promisesarrow-up-right returned by some of our method calls later on. Inside this function, the first thing we do is check whether the message starts with our prefix (we chose ! for example). If it doesn't, then we ignore the message.

Finally, we do a simple string comparison to see whether the contents of the message match !hi exactly. If it does, the bot will reply to the author with the words hi there!. Congratulations, you have now created a bot that responds to messages!

Some practice concepts for you

To help better your skills and prepare you for what's to come next, it's advised that you try the following out:

Last updated

Was this helpful?