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 -

Messaging is the new browser and bots are the new apps.

Prerequisites

Setting Up Dialogflow

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

Now, store the client access token in environment.ts file.

  1. export const environment = {
  2. production: false,
  3. dialogflow: {
  4. angularBot: 'your-key'
  5. }
  6. ;

Now, let us create the service using the following command.

  1. ng g s chat

Inside the chat service, we will first import the following packages.

  1. import { environment } from '../../environments/environment';
  2. import { ApiAiClient } from 'api-ai-javascript';
  3. import { Observable } from 'rxjs/Observable';
  4. 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’).

  1. export class Message {
  2. constructor(public msg: string, public from: string) { }
  3. }

  1. readonly token = environment.dialogflow.angularBot;
  2. 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.

  1. talk(msg: string) {
  2. const userMessage = new Message(msg, 'user');
  3. this.update(userMessage);
  4. return this._client.textRequest(msg)
  5. .then(res => {
  6. const speech = res.result.fulfillment.speech;
  7. const botMessage = new Message(speech, 'bot');
  8. this.update(botMessage);
  9. });
  10. }

The full chat.service.ts will look like below.

  1. import { Injectable } from '@angular/core';
  2. import { environment } from '../../environments/environment';
  3. import { ApiAiClient } from 'api-ai-javascript';
  4. import { Observable } from 'rxjs/Observable';
  5. import { BehaviorSubject } from 'rxjs/BehaviorSubject';
  6. export class Message {
  7. constructor(public msg: string, public from: string) { }
  8. }
  9. @Injectable()
  10. export class ChatService {
  11. readonly token = environment.dialogflow.angularBot;
  12. readonly _client = new ApiAiClient({ accessToken: this.token });
  13. conversation = new BehaviorSubject<Message[]>([]);
  14. constructor() { }
  15. // Sends and receives messages via DialogFlow
  16. talk(msg: string) {
  17. const userMessage = new Message(msg, 'user');
  18. this.update(userMessage);
  19. return this._client.textRequest(msg)
  20. .then(res => {
  21. const speech = res.result.fulfillment.speech;
  22. const botMessage = new Message(speech, 'bot');
  23. this.update(botMessage);
  24. });
  25. }
  26. // Adds message to source
  27. update(msg: Message) {
  28. this.conversation.next([msg]);
  29. }
  30. }

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.

  1. ng g c chatcompoent

Your chat.component.ts file look like following.

  1. import { Component, OnInit, ViewEncapsulation } from '@angular/core';
  2. import { ChatService, Message } from '../chat.service';
  3. import { Observable } from 'rxjs/Observable';
  4. import 'rxjs/add/operator/scan';
  5. @Component({
  6. selector: 'chat-component',
  7. templateUrl: './ 'chat-component.component.html',
  8. styleUrls: ['./ 'chat-component.component.css'],
  9. encapsulation: ViewEncapsulation.None
  10. })
  11. export class Chat-ComponentComponent implements OnInit {
  12. messages: Observable<Message[]>;
  13. strMsg: string;
  14. constructor(private chat: ChatService) { }
  15. ngOnInit() {
  16. this.messages = this.chat.conversation.asObservable()
  17. .scan((acc, val) => acc.concat(val));
  18. }
  19. sendMessage() {
  20. this.chat.talk(this.strMsg);
  21. this.strMsg = '';
  22. }
  23. }

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.

  1. <h1>My First ChatBot using Angular and Dialogflow</h1>
  2. <ng-container *ngFor="let m of messages | async">
  3. <div class="message" [ngClass]="{ 'from': m.from === 'bot',
  4. 'to': m.from === 'user' }">
  5. {{ m.msg }}
  6. </div>
  7. </ng-container>
  8. <label for="nameField">Your Message</label>
  9. <input [(ngModel)]="strMsg" (keyup.enter)="sendMessage()" type="text">
  10. <br>
  11. <button (click)="sendMessage()">Send</button>

Output

chatBots