🚀
API Docs
  • 📚Introduction
  • Setting up a Guilded bot
  • Create a basic bot
  • Responding to messages
Powered by GitBook
On this page

Was this helpful?

Edit on GitHub

Responding to messages

PreviousCreate a basic bot

Last updated 2 years ago

Was this helpful?

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 event, which emits a object.

// 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!");
});
// index.ts
// add this to your index.ts 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 . This allows us to resolve any 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.

  • for a cleaner string comparison experience

messageCreated
Message
asynchronous
arrow function
promises
Extracting the command name from the message