Using a prefix

You might have noticed that a lot of bots respond to commands that have a prefix. This might be an exclamation mark (!), a dot (.), a question mark(?), or another character. This is useful for two things.

First, if you don’t use a unique prefix and have more than one bot on a server, both will respond to the same commands. On developer servers, typing !help leads to a flood of replies and private messages which is something to avoid.

Second, in the example in previous chapter. We used Hello as a command so it will also excute when you don’t want it to.

To work around this, we’ll be using prefix, which we will store in a variable. This way we get the prefix as well as the ability to change it for all commands in one place.

So now we will store all information like this in JSON file(JavaScript Object Notation) which is commonly used for storing data.

First, create a file named config.json(in same location as your index.js)

Now insert this in that file,

  • {
    "prefix": "!"}
    

    Yes you can have anything at the place of !

    And now time to change your main code,

    client.on("message", (message)=> {
      
    // Set the prefix
    let prefix = config.prefix  
    // Exit and stop if it's not there
    if (!message.content.startsWith(prefix)) return;
    if (message.content === prefix + "ping") {
        message.channel.send("pong!");
    }
    

    Stopping if not starts with prefix will speed up your bot, and will make it faster.

    So now your bot is with a prefix and it should be helpful.