More on Discord.js

So this guide will tell you to do some more awesome things with your bot.

Adding Bot Owners

Now first I will tell about how to add Bot Owners (you can make some commands that only the bot owner can use)

You can add more than 1 field in a JSON file, so make your json file like this,

{
"prefix": "prefix",
"ownerID": "id"}

If you want more than 1 then,

{
"prefix": "prefix",
"ownerID": ["id1", "id2"]}

You can add unlimited owner ids, but how you will know if user is bot owner, so I will tell how.

if (message.author.id !== config.ownerID) return;

this line will check if user is bot owner or not, I will give an sample code.

if (message.content === "botowneronly"){
if(message.author.id !== config.ownerID) return;
message.channel.send('You are my bot owner!');
}

How to add more types of commands?

Now I will tell how you can add more commands, you already know one way but there are more,

As you know about a simple command,
— if line {
— message sending
— }

What we can do in IF?

So you can do this too,

if (message.content.startsWith(prefix + "hi")){

This will check if message starts with prefix and hi, means !hi and !hiii both will work, you can also use toLowerCase and toUpperCase at the place of startsWith also thier name says what they will do. You can also use includes to check if the message sent includes that word.

Now what about second line?

You can also use diffrent types here. Here are some examples,

message.channel.send
Just like you know, sends message to current channel.

message.author.send
DMs the user of command.

message.guild.defaultChannel.send
Sends message in server’s default Channel(mainly #general)

message.reply
Replies to user, message will start with @mention, Not Works in DM

Using a command handler

Q. What is Command Handler?
A. It lets you store your commands in files to make index.js short and clean.

So to make it you need this somewhere in message event.

const args = message.content.split(" "); 
const command = args.shift().slice(config.prefix.length); 

if (message.content.startsWith(prefix)){
try {
       let commandFile = require(`./commands/${command}.js`); 
       commandFile.run(client, message, args);  
 } catch (err) {
       console.error(err);
}
});

And now create a folder named commands(in same folder in which your index.js is) and add files there be sure to end file name with .js the code in that file is little diffrent.

Example of ping.jsexports.run = (client, message, args) => {

message.channel.send(“pong!”)
} don’t change first line, it will stay same forever. You can also check the message after command name like this,

exports.run = (client, message, args) => {
if(args[0] === "pong"){
message.reply("why you said pong, it's my line.");
}
}

That’s it for now. Hope you learned something.

Advertisements