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
event, which emits a Message
object.
Now, let's explain what this code does. Inside the event listener, we have an asynchronous arrow function. This allows us to resolve any promises 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:
Chaining your if statement with some else-if statements to have multiple commands.
Using a switch-case statement to explore alternatives to else-if chaining.
Extracting the command name from the message for a cleaner string comparison experience
Last updated