Sentiment Analysis examines the problem of studying texts, uploaded by users on microblogging platforms or electronic businesses. It is based on the opinions they have about a product, service or idea. Using sentiment analysis, we can suggest emojis to be used as replies to messages based on the context of the received message.
Using Ionic, you can create a mobile application using web technologies and use a wide array of existing components. Using Pusher Channels, we can enable realtime messaging in the chat using the Pusher pub/sub pattern.
We’ll be building a realtime chat application using Pusher Channels, Ionic and the Sentiment library for emoji suggestions based on the context of messages received.
Here’s a demo of the final product:
To follow this tutorial a basic understanding of Angular, Ionic and Node.js is required. Please ensure that you have Node and npm installed before you begin.
We’ll be using these tools to build out our application:
We’ll be sending messages to the server and using Pusher Channels pub/sub pattern, we’ll listen to and receive messages in realtime.
Once you sign up, go to the dashboard and click Create new Channels app, fill out the details, click Create my app, and make a note of the details on the App Keys tab.
Let’s build!
We’ll initialize our project using the Ionic CLI (command line interface). First, install the CLI by running npm install -g ionic
in your terminal. NPM is a package manager used for installing packages. It will be available on your PC if you have Node installed.
To create a new Ionic project called chat-app
using the CLI, open a terminal and run:
ionic start chat-app blank
The command is simply telling the CLI to create a new project called chat-app
without a template.
Follow the prompt and integrate your app with Cordova to target IOS and Android.
Type Y to integrate Cordova into the application. The next prompt will ask if you want to integrate Ionic pro into the application. If you have a pro account type Y and N if you don’t.
The Ionic team provides three ready made starter templates. You can check out the rest of the templates here
Open the newly created folder, your folder structure should look something like this:
1chat-app/ 2 resources/ 3 node_modules/ 4 src/ 5 app/ 6 app.component.html 7 app.module.ts 8 app.scss 9 ...
Open a terminal inside the project folder and start the application by running ionic serve
. A browser window should pop up and you should see a page like this.
Next, run the following commands in the root folder of the project to install dependencies.
1// install depencies required to build the server 2 npm install express body-parser dotenv pusher sentiment uuid 3 4 // front-end dependencies 5 npm install pusher-js @types/pusher-js
Now that we have our application running, let’s build out our server.
To do this we’ll make user of Express. Express is a fast, unopinionated, minimalist web framework for Node.js. We’ll use this to receive requests from our Angular application.
Create a file called server.js
in the root of the project and update it with the code snippet below:
1// server.js 2 3 require('dotenv').config(); 4 const express = require('express'); 5 const bodyParser = require('body-parser'); 6 const Pusher = require('pusher'); 7 8 const pusher = new Pusher({ 9 appId: process.env.PUSHER_APP_ID, 10 key: process.env.PUSHER_KEY, 11 secret: process.env.PUSHER_SECRET, 12 cluster: process.env.PUSHER_CLUSTER, 13 encrypted: true, 14 }); 15 const app = express(); 16 const port = process.env.PORT || 4000; 17 18 app.use(bodyParser.json()); 19 app.use(bodyParser.urlencoded({ extended: false })); 20 app.use((req, res, next) => { 21 res.header('Access-Control-Allow-Origin', '*'); 22 res.header( 23 'Access-Control-Allow-Headers', 24 'Origin, X-Requested-With, Content-Type, Accept' 25 ); 26 next(); 27 }); 28 29 app.listen(port, () => { 30 console.log(`Server started on port ${port}`); 31 });
We referenced three packages in the snippet above, body-parser
, pusher
and dotenv
. Let’s get into what each one does.
req.body
property..env
file into [process.env](https://nodejs.org/docs/latest/api/process.html#process_process_env)
. This package is used so sensitive information like the appId
and secret
aren’t added to our codebase directly..env
file into our environment.The dotenv
package should always be initialized very early in the application at the top of the file. This is because we need the environment variables available throughout the application.
The calls to our endpoint will be coming in from a different origin, therefore we need to make sure we include the CORS headers (Access-Control-Allow-Origin
). If you are unfamiliar with the concept of CORS headers, you can find more information here.
Also, you’ll notice that we installed Pusher library as a dependency. Visit the Pusher website to create a Pusher account if you haven’t done so already
Create a .env
file to load the variables we’ll be needing into the Node environment. The file should be in the root folder of your project. Open the file and update it with the code below.
1// .env 2 3 PUSHER_APP_ID=<APP_ID> 4 PUSHER_KEY=<PUSHER_KEY> 5 PUSHER_SECRET=<PUSHER_SECRET> 6 PUSHER_CLUSTER=<PUSHER_CLUSTER>
P.S: Please ensure you replace the placeholder values above with your Pusher
appId
,key
,secret
andcluster
.
This is a standard Node application configuration, nothing specific to our app.
To enable users send and receive messages, we’ll create a route to handle incoming requests. Update your server.js
file with the code below.
1// server.js 2 3 require('dotenv').config(); 4 const express = require('express'); 5 const bodyParser = require('body-parser'); 6 7 ... 8 9 app.use((req, res, next) => { 10 res.header('Access-Control-Allow-Origin', '*'); 11 res.header( 12 'Access-Control-Allow-Headers', 13 'Origin, X-Requested-With, Content-Type, Accept' 14 ); 15 next(); 16 }); 17 18 app.post('/messages', (req, res) => { 19 const { body } = req; 20 const { text, id } = body; 21 const data = { 22 text, 23 id, 24 timeStamp: new Date(), 25 }; 26 27 pusher.trigger('chat', 'message', data); 28 res.json(data); 29 }); 30 ...
POST /messages
route which, when hit, triggers a Pusher event.text
and id
in the request body sent by the user.data
object will contain the text
and id
sent by the user accompanied by a timestamp.trigger
method which takes the trigger identifier(chat
), an event name (message
), and a payload(data
).data
object.Sentiment analysis refers to the use of natural language processing, text analysis, computational linguistics, and biometrics to systematically identify, extract, quantify, and study effective states and subjective information. - Wikipedia
You can read up a bit about sentiment analysis using the following links below:
Using sentiment analysis, we’ll analyse the messages sent to determine the attitude of the sender. With the data gotten from the analysis, we’ll determine the emojis to suggest to the user.
We’ll use the Sentiment JavaScript library for analysis. The next step is to update our POST /messages
route to include analysis of the messages being sent in. Update your server.js
with the code below.
1// server.js 2 require('dotenv').config(); 3 const express = require('express'); 4 const bodyParser = require('body-parser'); 5 const Pusher = require('pusher'); 6 7 const Sentiment = require('sentiment'); 8 const sentiment = new Sentiment(); 9 10 ... 11 12 app.post('/messages', (req, res) => { 13 const { body } = req; 14 const { text, id } = body; 15 const result = sentiment.analyze(text); 16 const comparative = result.comparative; 17 const tone = 18 comparative >= 0 ? (comparative >= 1 ? 'positive' : 'neutral') : 'negative'; 19 const data = { 20 text, 21 id, 22 timeStamp: new Date(), 23 sentiment: { 24 tone, 25 score: result.score, 26 }, 27 }; 28 pusher.trigger('chat', 'message', data); 29 res.json(data); 30 }); 31 32 ...
result
: analyze the message sent in by the user to determine the context of the message.comparative
: this is the comparative score gotten after analyzing the message. This score is used to determine if a message is positive
, negative
or neutral
.tone
: this variable is the context of the message gotten after analysis. This will be negative
if the comparative score is below 0
, neutral
if the score is above 0
but below 1
. The tone is positive
if the comparative score is 1
and above.sentiment
) property is added to the response data containing the message’s tone and score.You can now start the server by running node server.js
in a terminal in the root folder of the project.
Let’s build out our chat interface. We’ll create a chat
component to hold the chat interface. Create a folder called components
in the src/
directory. This folder will hold all our components.
In the components
folder, create a folder named chat
, then proceed to create three files in the chat folder. chat.ts
, chat.scss
and chat.html
.
Now let’s go ahead and update the newly created chat component files. Open the chat.html
file and update it with the code snippet below:
1// src/components/chat/chat.html 2 3 <div class="main"> 4 <div class="chat-box"> 5 <div class="message-area"> 6 <div class="message" *ngFor="let message of messages" [ngClass]="getClasses(message.type)"> 7 <p>{{message.text}}</p> 8 </div> 9 </div> 10 <div class="emo-area"> 11 <!-- emoji-panel component comes here --> 12 </div> 13 <div class="input-area"> 14 <form (submit)="sendMessage()" name="messageForm" #messageForm="ngForm"> 15 <ion-input type="text" name="message" id="message" [(ngModel)]="message" placeholder="Say something nice..."></ion-input> 16 <button> 17 <ion-icon name="send"></ion-icon> 18 </button> 19 </form> 20 </div> 21 </div> 22 </div>
In the code snippet above:
messages
in the .message-area
.ion-input
element and a submit button.Open the chat.ts
file and update with the code below:
1// src/components/chat/chat.ts 2 3 import { Component, OnInit } from '@angular/core'; 4 import { HttpClient } from '@angular/common/http'; 5 import { v4 } from 'uuid'; 6 7 interface Message { 8 id: string; 9 text: string; 10 timeStamp: Date; 11 type: string; 12 } 13 14 @Component({ 15 selector: 'chat', 16 templateUrl: 'chat.html', 17 }) 18 19 export class ChatComponent implements OnInit { 20 constructor(private http: HttpClient) {} 21 22 messages: Array<Message> = []; 23 message: string = ''; 24 lastMessageId; 25 26 sendMessage() { 27 if (this.message !== '') { 28 // Assign an id to each outgoing message. It aids in the process of differentiating between outgoing and incoming messages 29 this.lastMessageId = v4(); 30 const data = { 31 id: this.lastMessageId, 32 text: this.message, 33 }; 34 35 this.http 36 .post(`http://localhost:4000/messages`, data) 37 .subscribe((res: Message) => { 38 const message = { 39 ...res, 40 // The message type is added to distinguish between incoming and outgoing messages. It also aids with styling of each message type 41 type: 'outgoing', 42 }; 43 this.messages = this.messages.concat(message); 44 this.message = ''; 45 }); 46 47 } 48 } 49 50 // This method adds classes to the element based on the message type 51 getClasses(messageType) { 52 return { 53 incoming: messageType === 'incoming', 54 outgoing: messageType === 'outgoing', 55 }; 56 } 57 58 ngOnInit() { 59 } 60 }
sendMessage
: this method uses the native HttpClient
to make requests to the server. The POST
method takes a URL and the request body
as parameters. We then append the data returned to the array of messages. We make use of a package called [uuid](https://www.npmjs.com/package/uuid)
to give each message a unique id
.
getClasses
: this method generates classes for a message element based on the messageType
.
To make use of the HttpClient
service, we’ll need to import the HttpClientModule
and HttpClient
into the app.module.ts
file. Also, we’ll need to register our newly created component, we’ll add it to the declarations array.
1// src/app/app.module.ts 2 ... 3 import { ChatComponent } from '../components/chat/chat'; 4 import { HttpClientModule, HttpClient } from '@angular/common/http'; 5 6 @NgModule({ 7 declarations: [ 8 MyApp, 9 HomePage, 10 ChatComponent, 11 ], 12 imports: [BrowserModule, IonicModule.forRoot(MyApp), HttpClientModule], 13 ... 14 providers: [ 15 StatusBar, 16 SplashScreen, 17 { provide: ErrorHandler, useClass: IonicErrorHandler }, 18 HttpClient, 19 ], 20 }) 21 export class AppModule {} 22 23 ...
Open the chat.scss
file and update it with the styles below:
1// src/components/chat/chat.scss 2 3 .main { 4 display: flex; 5 justify-content: center; 6 align-items: center; 7 height: 100%; 8 .chat-box { 9 width: 100%; 10 height: 100%; 11 position: relative; 12 background: #f9fbfc; 13 .message-area { 14 max-height: 90%; 15 height: 90%; 16 overflow: auto; 17 padding: 15px 10px; 18 .message { 19 p { 20 color: #8a898b; 21 font-size: 13px; 22 font-weight: bold; 23 margin: 0px; 24 max-width: 95%; 25 min-width: 55%; 26 box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.1); 27 padding: 10px 15px 10px 7px; 28 margin: 5px 0; 29 background: white; 30 } 31 } 32 .message.incoming { 33 display: flex; 34 flex-direction: column; 35 justify-content: flex-start; 36 align-items: flex-start; 37 p { 38 color: white; 39 border-radius: 0 11px 11px 11px; 40 background: #B9C0E9; 41 } 42 } 43 .message.outgoing { 44 display: flex; 45 flex-direction: column; 46 justify-content: flex-end; 47 align-items: flex-end; 48 p { 49 border-radius: 11px 11px 0 11px; 50 } 51 } 52 } 53 .emo-area { 54 position: absolute; 55 bottom: 50px; 56 left: 0; 57 width: 100%; 58 padding: 3px 10px; 59 } 60 } 61 }
This first SCSS snippet styles the .chat-area
, including how messages should look. The next snippet will style the input area and the send button. The styles below should be nested within the .main
style.
1// src/components/chat/chat.scss 2 3 .input-area { 4 position: absolute; 5 bottom: 1px; 6 left: 0; 7 width: 100%; 8 height: 50px; 9 background: white; 10 form { 11 display: flex; 12 height: 100%; 13 14 ion-input { 15 width: 82%; 16 border: none; 17 padding: 5px 10px; 18 color: #8a898b; 19 font-size: 14px; 20 font-weight: bold; 21 font-family: 'Titillium Web', sans-serif; 22 background: inherit; 23 &:focus { 24 outline: none; 25 } 26 } 27 button { 28 width: 18%; 29 border: none; 30 color: #8a898b; 31 opacity: 0.9; 32 display: flex; 33 justify-content: center; 34 align-items: center; 35 cursor: pointer; 36 background: inherit; 37 ion-icon { 38 font-size: 3rem; 39 } 40 } 41 } 42 }
Let’s include the chat
component in the home page. In the pages
directory, you’ll find the home
folder, open the home.html
file in the home folder and replace the content with the snippet below:
1// src/pages/home/home.html 2 3 <ion-header> 4 <ion-navbar color="light"> 5 <ion-title>Chat</ion-title> 6 </ion-navbar> 7 </ion-header> 8 9 <ion-content> 10 <chat></chat> 11 </ion-content>
Visit http://localhost:8100 in your browser to view the chat interface. It should be similar to the screenshot below:
So far we have an application that allows users send messages but the messages aren’t delivered in realtime. To solve this problem, we’ll include the Pusher library.
Let’s create a Pusher service to be used application wide. The Angular CLI can aid in the service creation. Open a terminal in your project’s root folder and run the following command.
ionic generate provider pusher
This command simply tells the CLI to generate a provider named pusher
. Now open the pusher.ts
file in the src/providers/pusher
directory and update it with the code snippet below:
1// src/providers/pusher/pusher.ts 2 3 import { Injectable } from '@angular/core'; 4 import Pusher from 'pusher-js'; 5 6 @Injectable() 7 export class PusherProvider { 8 constructor() { 9 var pusher = new Pusher('<PUSHER_KEY>', { 10 cluster: '<PUSHER_CLUSTER>', 11 encrypted: true, 12 }); 13 this.channel = pusher.subscribe('chat'); 14 } 15 channel; 16 17 public init() { 18 return this.channel; 19 } 20 }
init
method returns the Pusher property we created.Note: Ensure you replace the
PUSHER_KEY
andPUSHER_CLUSTER
string with your actual Pusher credentials.
We’ll make use of this service in our component, by binding to the message event and appending the returned message into the list of messages. This will be done in the ngOnInit
lifecycle.
1// src/components/chat/chat.ts 2 ... 3 import { v4 } from 'uuid'; 4 import { PusherProvider } from '../../providers/pusher/pusher'; 5 6 ... 7 // Include the PusherProvider in the component's constructor 8 constructor(private http: HttpClient, private pusher: PusherProvider){} 9 ... 10 11 ngOnInit() { 12 const channel = this.pusher.init(); 13 channel.bind('message', (data) => { 14 if (data.id !== this.lastMessageId) { 15 const message: Message = { 16 ...data, 17 type: 'incoming', 18 }; 19 this.messages = this.messages.concat(message); 20 } 21 }); 22 } 23 }
To display emoji suggestions during a chat session, we’ll make use of the sentiment
param being sent from the server as a response for each message request. The data being sent from the server should be similar to the snippet below.
1{ 2 id: '83d3dd57-6cf0-42dc-aa5b-2d997a562b7c', 3 text: 'i love pusher', 4 timeStamp: '2018-04-27T15:04:24.574Z' 5 sentiment: { 6 tone: 'positive', 7 score: 3 8 } 9 }
Create an emoji
component that will hold the emoji section. This component will handle the display of emojis based on the tone of each message received. Create a folder emoji-panel
in the components
directory and in that directory, create three files, emoji-panel.ts
, emoji-panel.scss
and emoji-panel.html
Replace the contents of the emoji-panel.html
in the src/components/emoji-panel
directory with the code snippet below.
1// src/components/emoji-panel/emoji-panel.html 2 3 <div class="emojis" [hidden]="!showEmojis" [attr.aria-hidden]="!showEmojis"> 4 <div class="emoji-list positive" *ngIf="result.tone === 'positive'"> 5 <span class="emoji" *ngFor="let emoji of emojiList.positive; let i = index;" (click)="onClick('positive', i)"> 6 {{codePoint(emoji)}} 7 </span> 8 </div> 9 10 <div class="emoji-list neutral" *ngIf="result.tone === 'neutral'"> 11 <span class="emoji" *ngFor="let emoji of emojiList.neutral; let j = index;" (click)="onClick('neutral', j)"> 12 {{codePoint(emoji)}} 13 </span> 14 </div> 15 16 <div class="emoji-list negative" *ngIf="result.tone === 'negative'"> 17 <span class="emoji" *ngFor="let emoji of emojiList.negative; let k = index;" (click)="onClick('negative', k)"> 18 {{codePoint(emoji)}} 19 </span> 20 </div> 21 </div>
attr.aria-hidden
: here we set the accessibility attribute of the element to either true
or false
based on the showEmojis
variable.
Update the emoji-panel.ts
with code below:
1// src/components/emoji-panel/emoji-panel.ts 2 import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; 3 4 @Component({ 5 selector: 'emoji-panel', 6 templateUrl: 'emoji-panel.html', 7 }) 8 9 export class EmojiPanelComponent implements OnInit { 10 constructor() {} 11 @Input() result = {}; 12 @Input() showEmojis: boolean = false; 13 @Output() onEmojiSelect: EventEmitter<string> = new EventEmitter(); 14 15 emojiList = { 16 positive: [128512, 128513, 128536, 128516], 17 neutral: [128528, 128529, 128566, 129300], 18 negative: [128543, 128577, 128546, 128542], 19 }; 20 codePoint(emojiCodePoint) { 21 return String.fromCodePoint(emojiCodePoint); 22 } 23 24 onClick(reaction, index) { 25 const emoji = this.emojiList[reaction][index]; 26 this.onEmojiSelect.emit(emoji); 27 } 28 29 ngOnInit() {} 30 }
emojiList
: this is an object containing a list of unicode characters for each emoji that’ll be used. There’s a list for each message tone.
codePoint
: this method returns an emoji from the codepoint passed in. It uses String.fromCodePoint introduced in ES2015.
showEmojis
: an input variable from the parent component(chat
) to determine the visibility of the emoji panel
onClick
: this method takes to parameters. The reaction
param is used to select the list of emojis to check for the provided index
. The selected emoji is then emitted to the parent component.
Add the following styles to the emoji-panel.scss
file.
1// /src/components/emoji-panel/emoji-panel.scss 2 3 .emojis { 4 &[aria-hidden='true'] { 5 animation: slideOutDown 0.7s; 6 } 7 &[aria-hidden='false'] { 8 animation: slideInUp 0.7s; 9 } 10 .emoji-list { 11 display: flex; 12 .emoji { 13 margin: 0 5px; 14 cursor: pointer; 15 } 16 } 17 } 18 @keyframes slideInUp { 19 from { 20 transform: translate3d(0, 100%, 0); 21 visibility: visible; 22 } 23 to { 24 transform: translate3d(0, 0, 0); 25 } 26 } 27 @keyframes slideOutDown { 28 from { 29 transform: translate3d(0, 0, 0); 30 } 31 to { 32 visibility: hidden; 33 transform: translate3d(0, 100%, 0); 34 } 35 }
After creating the emoji-panel
component, the next step is to register it in the app.module.ts
file and then add it to our chat
component. Update the app.module.ts
file and the chat component to include the emoji-panel
.
1// src/app/app.module.ts 2 3 ... 4 import { PusherProvider } from '../providers/pusher/pusher'; 5 import { EmojiPanelComponent } from '../components/emoji-panel/emoji-panel'; 6 7 @NgModule({ 8 declarations: [ 9 MyApp, 10 HomePage, 11 ChatComponent, 12 EmojiPanelComponent 13 ], 14 ... 15 }) 16 export class AppModule {}
Then include the emoji-panel
component in the chat.html
file.
1// chat.component.html 2 ... 3 <div class="main"> 4 ... 5 <div class="emo-area"> 6 <emoji-panel [showEmojis]="showEmojis" [result]="score" (onEmojiSelect)="selectEmoji($event)"></emoji-panel> 7 </div> 8 <div class="input-area"> 9 ... 10 </div> 11 </div>
Let’s update the chat.ts
to display or hide the emoji-panel based on the sentiment of each message.
Open the chat.ts
file and update it like so:
1// src/components/chat/chat.ts 2 3 ... 4 messages: Array<Message> = []; 5 message: string = ''; 6 lastMessageId; 7 showEmojis = false; 8 score = { 9 tone: '', 10 score: 0, 11 }; 12 13 sendMessage() { 14 if (this.message !== '') { 15 this.lastMessageId = v4(); 16 this.showEmojis = false; 17 ... 18 } 19 } 20 21 selectEmoji(e) { 22 const emoji = String.fromCodePoint(e); 23 this.message += ` ${emoji}`; 24 this.showEmojis = false; 25 } 26 ... 27 28 ngOnInit() { 29 const channel = this.pusher.init(); 30 channel.bind('message', (data) => { 31 if (data.id !== this.lastMessageId) { 32 const message: Message = { 33 ...data, 34 type: 'incoming', 35 }; 36 this.showEmojis = true; 37 this.score = data.sentiment; 38 this.messages = this.messages.concat(message); 39 } 40 }); 41 } 42 ...
selectEmoji
: this method gets the emoji from the codepoint passed as a parameter and then appends the selected emoji to the current message. Finally it hides the emoji panel by setting showEmojis
to false.
In the Pusher event callback, we set the showEmojis
property to true
. In the same callback, we assign the data's
sentiment property to the score
variable.
By now our application should provide emoji suggestions for received messages.
To test the application on your mobile device, download the IonicDevApp on your mobile device. Make sure your computer and your mobile device are connected to the same network. When you open the IonicDevApp, you should see Ionic apps running on your network listed.
Note: Both the server(
node server
), ngrok for proxying our server and the Ionic dev server(ionic serve
) must be running to get the application working. Run the commands in separate terminal sessions if you haven’t done so already.
To view the application, click on it and you should see a similar view to what was in the browser. Sending messages to the server might have worked in the browser but localhost doesn’t exist on your phone, so we’ll need to create a proxy to be able to send messages from mobile.
To create a proxy for our server, we’ll download Ngrok. Visit the download page on the Ngrok website. Download the client for your OS. Unzip it and run the following command in the folder where Ngrok can be found:
./ngrok http 4000
Copy the forwarding url with https
and place it in the chat.ts
file that previously had http://localhost:4000/message
. Please do not copy mine from the screenshot above.
1// src/components/chat/chat.ts 2 ... 3 export class ChatComponent implements OnInit { 4 ... 5 sendMessage() { 6 ... 7 this.http 8 .post('<NGROK_URL>/messages', data) 9 .subscribe((res: Message) => {}); 10 } 11 ... 12 } 13 ...
Ensure to include the forwarding URL you copied where the placeholder string is
Now you should be receiving messages sent from the phone on the browser. Or if you have more than one phone you can test it using two of them.
Note: Both the server(
node server
), ngrok for proxying our server and the Ionic dev server(ionic serve
) must be running to get the application working. Run the commands in separate terminal sessions if you haven’t done so already.
To build your application to deploy on either the AppStore or PlayStore, follow the instructions found here.
Using sentiment analysis library, we’ve been able to suggest emojis as replies for received messages and with the help of Pusher and Ionic we’ve built an application can send and receive messages in realtime. You can view the source code for the demo here.