First, let me tell you why you should require Chat Bots; is it really helpful; and who are building bots etc.
Anyone who has ever tried to contact a company through customer care center might know how slow and frustrating process it is. You remember that audio tape “press 1 for this, press 2 for this, press * to go back to the menu, and blah blah blah….“?
Say, for example, if you want to activate a simple caller tune to your phone number, you have to spend at least 10 minutes to know the code to activate that caller tune, by hearing that audio tape and pressing so many numbers. And finally, if you had a good luck, then only you are able to activate your caller tune.
However, there is a great solution to this kind of problem, which is faster than the customer care center - the Chat Bots. Nowadays, Chat Bots can be made using AI also, so it doesn’t limit them.
"A chatbot is a service, powered by rules and sometimes artificial intelligence that you interact with via a chat interface."
According to some people, Bots will completely kill the web and mobile apps. The main reasons for that are -
- Bots are faster than the website and mobile apps, they replied instantly.
- Mobile apps need to download and it occupies some memory of your phone whereas the bot doesn’t need to download it lives within your messenger only.
- It is easier to use Bots and many more.
Messaging is the new browser and bots are the new apps.
Prerequisites
- JavaScript
- Angular-CLI
- Dialogflow account (previously API.AI)
- Visual Studio Code (optional)
Setting Up Dialogflow
- Navigate to Dialogflow and log in to your account.
- Then, press "Create Agent" to create your first agent.
- After filling the required details, press "Create".
- Then, press the "Create Intent" button to create your first intent. Intents are usually user’s intention of asking questions. Dialogflow extracts the user intention from text using Natural Language Processing.
- Add you intent/question in “user says” field, as shown below.
- And, the answer should be in response field, as shown below.
- The entire page will look like the following.
- Now, you can also test your sentence in the console.
So far, we have created our Dialogflow Agent and Intent. Now, it’s time to create an Angular application to create a user interface and integrate our Dialogflow Agent to Angular.
Angular Application
- You can create an Angular project using Angular-CLI.
- Integrate Dialogflow JavaScript SDK in our Angular project using the following command.
- npm install api-ai-javascript - - save-dev
- Store the Client access token from Dialogflow to your app inside environment.ts file, as shown below.
Now, store the client access token in environment.ts file.
- export const environment = {
- production: false,
- dialogflow: {
- angularBot: 'your-key'
- }
- ;
Now, let us create the service using the following command.
Inside the chat service, we will first import the following packages.
- import { environment } from '../../environments/environment';
- import { ApiAiClient } from 'api-ai-javascript';
- import { Observable } from 'rxjs/Observable';
- import { BehaviorSubject } from 'rxjs/BehaviorSubject';
Then, we will create one message class inside the service, which has two members - msg (which will be used to store the content or message send by the user or bot) and from (which will be used to store the info of who sent that message, i.e., either ‘user’ or ‘Bot’).
- export class Message {
- constructor(public msg: string, public from: string) { }
- }
- Now, let us create the instance of API.AI client – the JavaScript SDK for Dialogflow, and then, pass the client access token to that instance of API.AI client.
- readonly token = environment.dialogflow.angularBot;
- readonly _client = new ApiAiClient({ accessToken: this.token });
Now, it’s time to create a method that will interact with our bot, i.e., send and receive messages, as shown below.
- talk(msg: string) {
- const userMessage = new Message(msg, 'user');
- this.update(userMessage);
- return this._client.textRequest(msg)
- .then(res => {
- const speech = res.result.fulfillment.speech;
- const botMessage = new Message(speech, 'bot');
- this.update(botMessage);
- });
- }
The full chat.service.ts will look like below.
- import { Injectable } from '@angular/core';
- import { environment } from '../../environments/environment';
- import { ApiAiClient } from 'api-ai-javascript';
- import { Observable } from 'rxjs/Observable';
- import { BehaviorSubject } from 'rxjs/BehaviorSubject';
-
- export class Message {
- constructor(public msg: string, public from: string) { }
- }
-
- @Injectable()
- export class ChatService {
- readonly token = environment.dialogflow.angularBot;
- readonly _client = new ApiAiClient({ accessToken: this.token });
- conversation = new BehaviorSubject<Message[]>([]);
- constructor() { }
-
- talk(msg: string) {
- const userMessage = new Message(msg, 'user');
- this.update(userMessage);
- return this._client.textRequest(msg)
- .then(res => {
- const speech = res.result.fulfillment.speech;
- const botMessage = new Message(speech, 'bot');
- this.update(botMessage);
- });
- }
-
- update(msg: Message) {
- this.conversation.next([msg]);
- }
-
- }
Now, finally, it’s time to create our user interface, i.e., chat-component and call talk method from chat.service.
Use this command to create a new component.
Your chat.component.ts file look like following.
- import { Component, OnInit, ViewEncapsulation } from '@angular/core';
- import { ChatService, Message } from '../chat.service';
- import { Observable } from 'rxjs/Observable';
- import 'rxjs/add/operator/scan';
-
- @Component({
- selector: 'chat-component',
- templateUrl: './ 'chat-component.component.html',
- styleUrls: ['./ 'chat-component.component.css'],
- encapsulation: ViewEncapsulation.None
- })
- export class Chat-ComponentComponent implements OnInit {
- messages: Observable<Message[]>;
- strMsg: string;
- constructor(private chat: ChatService) { }
- ngOnInit() {
- this.messages = this.chat.conversation.asObservable()
- .scan((acc, val) => acc.concat(val));
- }
- sendMessage() {
- this.chat.talk(this.strMsg);
- this.strMsg = '';
- }
- }
Here, I am injecting the chat-service inside the constructor. And calling my talk method when a user presses the Enter key or the Send button. I have used two-way binding to get the input from the input-box. For that, I have created the variable strMSg.
My chat-component.html will look like this.
- <h1>My First ChatBot using Angular and Dialogflow</h1>
- <ng-container *ngFor="let m of messages | async">
- <div class="message" [ngClass]="{ 'from': m.from === 'bot',
- 'to': m.from === 'user' }">
- {{ m.msg }}
- </div>
- </ng-container>
- <label for="nameField">Your Message</label>
- <input [(ngModel)]="strMsg" (keyup.enter)="sendMessage()" type="text">
- <br>
- <button (click)="sendMessage()">Send</button>
Output