How to code a discord bot!

Step 1: Creating the bot client

The first step is to make sure you have a server where you have the ability to add people to it, you’ll need this as you’ll need to be able to invite your bot.

Then go to http://discord.com/developers/applications | New Application

Once you’ve created your client application, go to Bot on the side panel and click Add Bot.

Brilliant now you have a bot within your application

Step 2: Giving the bot correct privileges

Whilst still in your application, go to OAuth2 (same side panel as Bot we clicked in step 1)

  1. Give it the SCOPES of Bot

2. Go down to the Bot permissions, in my example I just give the Bot all the permissions so I select admin, but you’ll potentially want to be a little more considerate in how much power you give your bot.

Step 3: Adding the bot to your Discord server

Scroll back up to where we just defined the scope as Bot (In the OAuth2 scope) and copy the URL it provides.

Paste the URL in to your favourite browser and choose the server you want to add it to:

There we go, the bot is now in your server đź‘Ź

Step 4: Writing the code

In this tutorial we are going to be creating a Node app, so go ahead and open up your favourite text editor, make sure you have npm installed.

  1. Initialise the node app, run:
npm init

Just hit enter until you get to the end of the terminal prompts, fill them in as you wish.

2. Create an index.js file (Entry point for the js code)

3. run this to add the dependency we will use to interact with our bot client

npm install discord.js

4. Write the code in index.js

const discord = require('discord.js');
const client = new discord.Client();


client.on('ready', () => {
    console.log('Connected to the bot');
});

client.on('message', msg => {
    if (msg.content === 'hi') {
        msg.reply('Hi to you too!');
    }
    
});


5. So this is a very simple example, if you write Hi in your server the bot will reply Hi to you too, however we are missing just one thing!

We need the token to allow us connect to the bot, so go back to https://discord.com/developers/applications/ back to your Bot and click copy token:

Then in your code add:

client.login('dsdasdasda.XxxLPQ.MdZwIzwEjD0xUYo-MbnLAlV1OP8');

Where the text is your token!

6. Next, run your app

node index.js

7. Write Hi in your discord server where you added the bot!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s