How to Build a Real-Time Chatbot

Published Mar 20, 2017
How to Build a Real-Time Chatbot

ScaleGrid is the only MongoDB and Redis hosting solution that lets you manage mongo and Redis instances on both public clouds and on premise from a single central console. Try us free for 30 days.

Originally, this post was featured this past January on the ScaleGrid blog under the title "Using Redis with Node.js and Socket.IO."

Since it quickly became a popular post and has been shared heavily by viewers on social media, we thought it would also be beneficial to share with this audience.

In this article, we will show you how to build a real-time chat application using the following technologies:

  • Redis
  • Node.js + Express.js
  • Socket.IO
  • Heroku

Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, and geospatial indexes with radius queries.

In this application, we will be connecting to one of the clusters hosted on ScaleGrid.

Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, and thus perfect for data-intensive real-time applications that run across distributed devices.

Express.js is a Node.js framework. Node.js is a platform that allows JavaScript to be used outside the web browsers, for creating web and network applications. This means that you can create the server and server-side code for an application like most of the other web languages but using JavaScript.

Socket.IO is a JavaScript library for real-time web applications. It enables real-time, bidirectional communication between web clients and servers. It has two parts: a client-side library that runs in the browser, and a server-side library for node.js. Both components have nearly identical APIs.

Heroku is a cloud platform that lets companies build, deliver, monitor, and scale apps — it is the fastest way to go from idea to URL, bypassing all those infrastructure headaches.

This article assumes that you already have Redis, Node.js, and the Heroku Toolbelt installed on your machine.

Setup

Create a folder and give it a name. You can create it anywhere on your machine since Node.js does not need a special server like Apache/nginx.

Step 1:

Initialize a package.json file by running npm init.
Screen Shot 2017-03-13 at 7.11.42 PM.png

Step 2:

Install the following dependencies:

  • expressjs
  • socketio
  • redis

…and one other utility method:

  • body-parser

by running the following command:

Screen Shot 2017-03-13 at 7.13.04 PM.png

Step 3:

Create a public folder for storing our CSS and JS files.

Screen Shot 2017-03-13 at 7.13.40 PM.png

Step 4:

Create a views folder for storing our main HTML file.

Screen Shot 2017-03-13 at 7.13.52 PM.png

Step 5:

Create a creds.json file that will contain the credentials for connecting to our Redis Cluster. It should follow this format:

Screen Shot 2017-03-13 at 7.14.52 PM.png

Step 6:

Create the index.js file that will host our Node.js code and will serve as a starting point for Heroku.

Step 7:

Add a .gitignore file so the node_modules folder is not checked in to Heroku.

Screen Shot 2017-03-13 at 7.15.41 PM.png

After the end of Step 7, you should have the following structure:

Screen Shot 2017-03-13 at 7.16.25 PM.png

Step 8:

Now that everything is set up, we can start writing our back-end code. First of all, we need to bring all our modules in, so open up the index.js file and paste the following:

Screen Shot 2017-03-13 at 7.17.02 PM.png

Before we can start writing any code, we need a cluster running Redis. Fortunately, Redis on ScaleGrid provides a high performance, one click, and fully managed Redis-as-a-service solution.

If you’re not already a member, you can sign up for a free 30-day trial here.

Otherwise, log in to your dashboard and create a new Redis cluster under the Redis section.

Screen Shot 2017-03-13 at 7.18.14 PM.png

Once the cluster creation is complete, make note of the above information and add it to the relevant fields of the creds.json file.

Now that we have our credentials setup, we are ready to create our Redis client in Node, which will connect to our cluster and start storing key-value pairs.

Add the following code to the index.js file:

Screen Shot 2017-03-13 at 7.18.51 PM.png

The above code does two things:

  1. Reads the credentials from creds.json and creates a Redis client that is used to perform key-value operations.
  2. Once the client is ready, we populate the chatters and the chat_messages, so any new members that join will be able to see the chat history.

We are now going to write a couple of APIs to handle the chat application. We need the following APIs:

  • Join Room [POST]
  • Leave Room [POST]
  • Send Message [POST]
  • Get Messages [GET]
  • Get Members [GET]

Let’s start with the Join Room API. This is called when any new user first starts the application and tries to join the chat room.

Screen Shot 2017-03-13 at 7.19.23 PM.png

Here we have the API for leaving the chat room:

Screen Shot 2017-03-13 at 7.20.35 PM.png

Sending and storing the message:

Screen Shot 2017-03-13 at 7.20.59 PM.png

Get all messages in room:

Screen Shot 2017-03-13 at 7.21.28 PM.png

Get all members:

Screen Shot 2017-03-13 at 7.21.53 PM.png

Once we have all the APIs set up, we need to write socket.io code to emit events when certain properties such as the following get updated:

  • Room Count
  • Messages

Screen Shot 2017-03-13 at 7.22.24 PM.png

These events are then picked up on the front-end by the socket.IO library which in turn updates the UI.

Step 9:

Now, we need to build our UI which will allow users to sign in and chat.

Open up the index.html file and add the following code:

Screen Shot 2017-03-13 at 7.23.05 PM.png

Step 10:

To make our HTML work, we need to add some JavaScript AJAX events that will handle the various operations like joining a room, leaving, sending a message, etc.

The following code gets the number of chatters so we can update the UI about the total number of people in the room:

Screen Shot 2017-03-13 at 7.23.39 PM.png

This code allows users to join the chat room. Usernames are unique and cannot be duplicated.

Screen Shot 2017-03-13 at 7.24.12 PM.png

Here is the code for allowing users to leave the chat room:

Screen Shot 2017-03-13 at 7.25.37 PM.png

Here is the code that runs every time someone sends a message:

Screen Shot 2017-03-13 at 7.26.13 PM.png

The following is the socket.IO code that listens for events from the back-end and updates the UI. For example, adding new messages to the messages area, updating the chatter count etc.

Screen Shot 2017-03-13 at 7.26.39 PM.png

And you’re done! Fire up the server using npm start and open multiple browser windows to simulate multiple users.

A demo of the application is available here: https://node-socket-redis-chat.herokuapp.com/

Other Resources

For deploying this application on Heroku, check out their docs: https://devcenter.heroku.com/categories/deployment

The entire source code is available on GitHub for you to fork and work on: https://github.com/Scalegrid/code-samples/tree/sg-redis-node-socket-chat/redis-node-socket-chat

As always, if you build something awesome, do tweet us about it @scalegridio

If you need help with Redis hosting and management, let us simplify things for you with our professional services.

Discover and read more posts from ScaleGrid.io
get started