Codementor Events

How To Build A Discord ChatBot Using IBM Watson Conversation API !

Published Feb 01, 2019
How To Build A Discord ChatBot Using IBM Watson Conversation API !

Donload Any Text Editor Or IDE You Want {I'm Using Vs Code}

First You Will need to go to IBM CLOUD SERVER and make a IBM Account. IBM offers a free tier and it include all the things you will need.

Then Follow These Steps To Make A Conversion API :
1. Go To Your DashBoard And Create An App
2. Select Watson Assistant For Type of Resources
3. Now Save All Your Credentials In A JSON File We Will Be Using It Later On..
4. Now Download Node JS { We Are Using JavaScript }
5. Make A Folder And Name It Anything You Want..
6. Open A Command Line In That Dir..
7. First Check If The Node Is Installed Properly By Typing
Node -v
8. Now If It Doesn't Show Any Errors Follow Along Or If Any Errors Restart Your Pc.
9. Now We Need To Install Watson SDK And Discord.js
10. Type npm install watson-developer-cloud To Install Watson SDK
11. After That Type npm install discord.js To Install Discord API
12. Go To Discord Developer Portal And Make An Discord Account Or Login If You Have It Already..
13. Create A New App Go To Bot Section And Turn On The Button That Says That "This App Is Going To Be A Bot"..
14. Now Fill In All The Details And It Going To Give You A Token Save It Somewhere Safe Don't Share It With Anyone...
15. Now Go To OAuth2 And From The Scope Section Select Bot And Then Select Bot Permission For This Tutorial Select Admin...
16. Now Go To The Link It Generated Above And Select A Server For Your Bot
17. Now Let's Start Coding...

Make A Main.js File In The Folder We Created Earlier

And Paste This Code In That File:
```
// Main Files Import
//This is The JSON File With The Bot Token In It..
const botConf = require("./botConfig.json"); 
//This is the Disocord.js API we download before..
const Discord = require("discord.js");

// Custom Files Import
//We will be making this file after this one
const Comm = require("./Commands");
// We will now using Watson SDK now but it's important to load it first
const Wat = require('./Watson API');

// Destructuring Modules And Classes

const {
    Client,
    ClientUser
} = Discord;

// Bot Initialiser
const Bot = new Client();


// Bot Starting Message

Bot.on("ready", () => {
    console.log("INITIALISING SKYNET SECURITY SYSTEMS PLEASE WAIT.........")
    setTimeout(() => {
        console.log("SKYNET ACTIVE");
    }, 1000);
});


/*

This Space is for Commands Customisations

*/

const Main = new Comm.Main();

Main.Com1();

const PoP = new Wat.Wat();

PoP.Bot();



// Logging in bot into the server
Bot.login(botConf.token); //Use the bot token here

```

Now Make A Commands.js File In The Same Dir

and paste this code in that file...
const botConf = require("./botConfig.json");
const Discord = require("discord.js");
const request = require('request');

const {
    Client,
    ClientUser,
    Role
  
} = Discord;


// Bot Initialiser
const Bot = new Client();

class Main {
    Main() {
        
    }
    Com1() {
        Bot.on("message", (mess) => {
            console.log(mess.content)
            let Mess = mess.content.split(" ");
            switch (Mess[0]) {
                case `${botConf.prefix}Hello`:
                    mess.channel.send(`Hello! ${mess.author} I'm SKYNET I'm new to human world and still observing every action for some amazing stuff I will controll everything in Year 3000 see you in future`);
                    setTimeout(() => {
                        mess.channel.send("Hope You're Having A Great Day ; )");
                    }, 2000);
                    break;
                case `${botConf.prefix}Who`:
                    mess.channel.send("Cyber Expert is a good person and a happy software developer as well. He likes people with some differnent kind of personalities");
                    mess.guild.members.first().sendMessage("Hope you enjoy your stay as we enjoy your welcome into our fold thanks for joining us");
                    break;
                case `${botConf.prefix}so`:
                    let userMess = Mess[1];
                    console.log(userMess);
                    mess.channel.send(`Hey guys a big fat shout out for ${userMess}`);
                    break;
                case `${botConf.prefix}addrole`:
                    if (mess.guild.members.first().hasPermissions("ADMINISTRATOR")) {
                        let addrole = mess.content.split(" ");
                        let Roll = mess.guild.roles.find(r => r.name === addrole[1]);
                        console.log(Roll.id);
                        mess.mentions.users.forEach((e) => {
                            mess.guild.members.find(r => r.id === e.id).addRole(Roll.id);
                        });
                    } else {
                        mess.guild.members.first().sendMessage("You Dont Have Permission Required To Use This Command { Contact Mod's To Do This }!")
                    }
                    break;
                case `${botConf.prefix}Commands`:
                    mess.channel.sendCode("", "1. !Who : Tell Us About Cyber Expert Who He Is And What He Likes \n2. !Hello : Say Hello To Cyber Expert \n3. !Commands : Tells All The Commands Can Be Used By Everyone");
                    break;
            }
            setInterval(() => {
                request('http://numbersapi.com/random', (error, response, body) => {
                    mess.channel.sendCode(`${response.body}`);
                });
            }, 1000 * 60 * 60);
            



        });
    }




}
Bot.login(botConf.token);


module.exports = {
    Main
};

    

Now Last Make A Watson API.js

and paste this code inside

// All Module Imports For Watson Conversation API
const Watson = require("watson-developer-cloud/assistant/v2");
const watson = require('watson-developer-cloud');
const Cred = require("./ibm-credentials.json");
const botConf = require("./botConfig.json");
const Discord = require("discord.js");


const {
  Client,
  ClientUser,
  Role

} = Discord;

// Global Variable For Seesion and Etc
var Sess_ID;
var Res;

// Initialising Watson Assisstant

const Ass = new Watson({
  version: '2018-11-08',
  username: 'Put Your Watson Login Username',
  password: 'Put Your Watson Login Password',
  url: Cred.URL
}, (err, res) => {
  console.log(err);
  console.log(res);
});

// Initialising Watson Services
const service = new watson.AssistantV2({
  iam_apikey: Cred.API, //Put Your API key from the credential JSON file we created earlier
  version: '2018-11-08',
  url: Cred.URL //Put your Url From that credentials JSON file we created earlier
});

// Section For Invoking All Watson API Services And Sending Messages To Conversational Bot And Receiving The Response Back

class Main {

  Start_Sessions() {
    // Session Starting
    service.createSession({
      assistant_id: Cred.Ass_ID, //Put your Assistant ID from the watson website
    }, function (err, response) {
      if (err) {
        console.error(err);
      } else {
        Sess_ID = response.session_id;
        console.log(Sess_ID);
      }
    });
  }

  Sending_Messages(mess, callback) {

    // Sending Messages With a Delay Of 5 Sec 
    setTimeout(() => {
      service.message({
        assistant_id: Cred.Ass_ID, //Put your Assistant ID from the watson website
        session_id: Sess_ID,
        input: {
          'message_type': 'text',
          'text': `${mess}`
        }
      }, function (err, response) {
          if (err)
            console.log('Error: Sorry For Some Trouble');
          else
            Res = response.output.generic[0].text.replace( /!/gi ,"");
          callback(Res);

      });
    }, 5000);


  }

  // Removing Sessions Explicitly Instead Of Session Time Out For API On A Delay Of 9 Sec
  Removing_Sessions() {
    setTimeout(() => {

      service.deleteSession({
        assistant_id: Cred.Ass_ID, //Put your Assistant ID from the watson website
        session_id: `${Sess_ID}`,
      }, function (err, response) {
        if (err) {
          console.error("Sorry Some Error's Need To Be Fixed");
        } else {
          console.log(JSON.stringify(response, null, 2));
        }
      });


    }, 9000);

  }
  Bot() {

    const Ses = new Main();
    

    const Bot = new Client();

    
    Bot.on("message", (mess) => {
      if (mess.content.includes("!")) {
        Ses.Start_Sessions();
        let mess1 = mess.content.replace("!", "");
        Ses.Sending_Messages(mess1, Bot_Call);
        //setTimeout(() => { Ses.Removing_Sessions(); }, 1000);
        }
        function Bot_Call(Result) {
          // Bot Initialiser
          
          mess.channel.send(Result);
        }

      });
    Bot.login(botConf.token);

  }



}



module.exports.Wat = Main;


Now Run Your Bot In NodeJS

1. Open a console inside your project dir
2. type ``` Node ./Main.js ```
3. And It Should Be Working Perfectly ; )
4. Using watson online tools you can make Dialogs and more { Need To Do Some Research YourSelf I don't waana spoil everything ; ) Good Luck This is just for Demo }
Discover and read more posts from Aamir Zaidi
get started
post commentsBe the first to share your opinion
☁️ Ronan Bourlier ☁️
5 years ago

The topic is interesting but some files are missing: “/ibm-credentials.json” and “./botConfig.json”. Is there any GitHub repository?

Aamir Zaidi
5 years ago

Of course those files are missing why would I share my API keys and everything else ? I have a gut repo but its private

☁️ Ronan Bourlier ☁️
5 years ago

I don’t need the API keys, just the file format, with the API keys not shown to know where to enter them. Could you add them in your post?

Ruben Colon
4 years ago

Does tutorial this still apply? I am trying to make a bot with this tutorial but watson assistant was renamed

Show more replies