DEV Community

Cover image for Easiest way to create a ChatBOT from Level 0 by SilvenLEAF
SilvenLEAF
SilvenLEAF

Posted on • Updated on

Easiest way to create a ChatBOT from Level 0 by SilvenLEAF

Wondering how to create a freakin' livin' alive an' kickin' Chatbot with XP 0? Then fear not my Brave Dev, here we go onto conquering the kingdom of chatbots! Yay! Who's excited?

Step 0: Begin the project

Well, as all amazing stories init from the village of "npm init". Let's init our adventure.

Create a folder, open it in your beloved editor, (mine VS Code). Then type the following command on your terminal

npm init -y
Enter fullscreen mode Exit fullscreen mode

(It'll create package.json file to track all the packages you'd download and so on)

Now create an app.ts file, let the adventure begin!!

Step 1: Create the Server and API

Let's create the API where the bot will live. You can use anything, restify, hapi, loopback, express or anything. I'm goin' with express. Why? Because it's express-y haha!

For those who are a bit lost on how to create an express server with typescript, check this one out
How to Create a TypeScript Project with ExpressJS the Simplest Way!!

In short (for details, checkout above link),
0. install packages

npm i typescript ts-node express @types/node @types/express
Enter fullscreen mode Exit fullscreen mode

1. init tsconfig (make sure you already have typescript globally installed, if not type npm i -g typescript. And don't get it confused with the previous normal npm i typescript etc etc)

tsc --init
Enter fullscreen mode Exit fullscreen mode

create server on our app.ts file

import express, { Request, Response } from 'express';





// -------------------firing express app
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended:false}));




// -------------------routes
app.get('/api/messages', (request: Request, response: Response)=>{
  // this is where our bot will live after her birth
  console.log(request.url)
  response.json({ message: `Welcome to the home of the bot!` })
});



// --------------------Listen
const PORT = process.env.PORT || 5000;
app.listen(PORT, ()=>{
  console.log(`Server running on PORT ${ PORT }`);
})
Enter fullscreen mode Exit fullscreen mode

To test out our server, run ts-node app.ts and go to localhost:5000/api/messages

Step 2: Let's create our BOT

Let's create our bot now. First create a file named bot.ts. Here is where we will build our sweet little bot.

But first of all we need the packages and tools to build our bot. So let's get them from our inventory with npm.
Type the following command to install the core SDK packages.

npm i botbuilder
Enter fullscreen mode Exit fullscreen mode

Now the fun stuff, finally let's create the bot (in the bot.ts file)

import { TurnContext } from "botbuilder";






// __________________THE BOT
export default class SillyBot {

  constructor() { }


  /* 
  onTurn() method is the CORE method that starts the bot, 
  all root bot logics go inside it, 
  anything you want your bot to do mainly go inside it.
  It will be fired on that API endpoint
  */
  async onTurn(context: TurnContext) {
    if (context.activity.type === 'message') { 
    /*
     users can do many things to our sweet bot, 
     here we are only interested if the user sent a message to it
    */

      await context.sendActivity(`You said : ${context.activity.text}`);
      /*
     what message user sent to the bot is inside this "context.activity.text" property.
     for those sweetest mates who are curious, console.log(context) to explore wonders!
      */
    }
  }

}
Enter fullscreen mode Exit fullscreen mode

Holy cheese and crackers!! Yippie!! We just made our very first bot!! Well, not yet pretty boy (or girl)! Yes we created it, but it's not in its rightful home right? I mean, it's not living on that api endpoint where it was supposed to be. Let's go place her to her rightful home (or api I mean)! Well anyway

Open app.ts, and let's create a bot instance, remember the bot we created was a class. And we all know about our classical classes!

const mySillyBot = new SillyBot()
Enter fullscreen mode Exit fullscreen mode

Haha, now a bot was created from that bot creator machine! Now let's create an adapter. What an adapter you ask? It's the Personal Assistant (PA) for our silly little bot, who (this PA) will pass her (our bot) request and response objects from that api so that she (our bot) can do whatever she does. Also one more thing, why do we need a PA for our bot? Well, pretty simple answer, firstly, our bot is silly, and being a father (or a mother), we don't want her to be alone, feeling sad in that lonely apartment. So, let her older sister, Miss "adapter" accompany her and help her with her tasks.

Creating an adapter and placing our bot on that API


import { BotFrameworkAdapter, TurnContext } from 'botbuilder';
// _________creating an adapter
const adapter = new BotFrameworkAdapter({
  appId: "",
  appPassword: "",
});



// __________the bot
const mySillyBot: SillyBot = new SillyBot()


// -------------------routes
app.post('/api/messages', (request: Request, response: Response)=>{
  // this is where our bot will live after her birth
  console.log(request.url)

  adapter.processActivity(request, response, async (context: TurnContext) => {
    await mySillyBot.onTurn(context); //__________our bot is now listening on this API endpoint
  })
});
Enter fullscreen mode Exit fullscreen mode

IMPORTANT NOTE: We replaced GET ["app.get()"] with POST ["app.post()"] for securing our bot api

After all those changes, our app.ts looks like this now

import express, { Request, Response } from 'express';

import { BotFrameworkAdapter, TurnContext } from 'botbuilder';
import SillyBot from './bot';




// -------------------firing express app
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended:false}));



// _________creating an adapter
const adapter = new BotFrameworkAdapter({
  appId: "",
  appPassword: "",
});



// __________the bot
const mySillyBot: SillyBot = new SillyBot()



// -------------------routes
app.post('/api/messages', (request: Request, response: Response)=>{
  // this is where our bot will live after her birth
  console.log(request.url)

  adapter.processActivity(request, response, async (context: TurnContext) => {
    await mySillyBot.onTurn(context); //__________our bot is now listening on this API endpoint
  })
});



// --------------------Listen
const PORT = process.env.PORT || 5000;
app.listen(PORT, ()=>{
  console.log(`Server running on PORT ${ PORT }`);
})
Enter fullscreen mode Exit fullscreen mode

Yippie, pretty happy to see your bot happily settled in that api apartment? But being a father (or mother) how do you know that she is ok, livin' happily ever after?

So let's chat with her. But how? we can't use our phone to chat with her because we didn't deploy her and she is still local to your pc where you are running the server now.

Don't worry, let's use "Botframework Emulator", it's an emulator that emulates your chatting environment (the interface where you chat). For now let's settle with this, but if you had your bot deployed. Then you could chat with her from any chat app, from Telegram, Teams, Whatsapp, Twitter to any freakin app with chat interface out there. But for now, let's use emulator since she is not deployed yet.

Download the emulator from this link if you don't have it yet (or from google or any place you like)
https://github.com/Microsoft/BotFramework-Emulator/releases/tag/v4.14.0

After downloading and installing, open it, it'll show you something like this
Botframework Emulator

Now, click "Open Bot" and it'll show up something like this
Open Bot

Type the url (api endpoint) where your bot is living, for our case, it is http://localhost:5000/api/messages. Then hit connect (But before that, make sure your server is running. To run that server, you type ts-node app.ts on your project terminal).

Now congrats, the messaging place is ready!! Now feel free to chat with your beloved little bot all day all night long!
Chat Now

Now, for all those worrying fathers and mothers who are worried that our bot is silly and can only repeat what we say,

Stay tuned, I might drop by another lovely weekend to make our bot SUPER SMART using AI and our silly bot will become SOO INSANELY SMART than you can pretty much ask her any freakin' thing out there, and she'll reply/explain to you in the most amazing way. Then you can make her a teacher, restaurant call/order receiver, flight booker, story teller, or a housewife, or a sweet friend to casually talk to you to drive off boredom. So are you feeling excited or not? Because I sure am!

We'll be using LUIS, QnA Maker and other cool AI and machine learning stuff!!

What's NEXT?

1. Improved AI BOT that can do anything

2. Other kool stuff regarding bots, web dev, and MORE

3. Insane stuff with JavaScript/TypeScript and MORE

Got any doubt?

Drop a comment or Feel free to reach out to me @SilveLEAF on Twitter or Linkedin

Wanna know more about me? Come here!
SilvenLEAF.github.io

Top comments (4)

Collapse
 
arvndvv profile image
Aravind V V

Well done 🎉👏

Collapse
 
silvenleaf profile image
SilvenLEAF

Thanks Chief

Collapse
 
rfariaspoblete profile image
Rafael FarĂ­as

Great Job ! Thanks

Collapse
 
silvenleaf profile image
SilvenLEAF

Thank you for your sweet comment Dear Rafael! Wish you an amazing weekend