How to Build a Real-Time Chat Bot
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.
This post was originally featured in January 2017 on the ScaleGrid blog and quickly became a popular post. In this article, we will show you how to build a real-time chat application using Redis, Node.js + Express.js, Socket.IO, and Heroku.
If you have any other points to share, please do so in the comments section below.
In this article, we will show you how to build a real-time chat application using the following technologies:
- Node.js + Express.js
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.
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.
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.
Initialize a package.json file by running
Install the following dependencies:
…and some other utility methods:
by running the following command:
Create a public folder for storing our CSS and JS files
Create a views folder for storing our main HTML file
creds.json file that will contain the credentials for connecting to our Redis Cluster. It should follow the following format:
index.js file that will host our Node.js code and will serve as a starting point for Heroku.
.gitignore file so the node_modules folder is not checked in to Heroku.
After the end of Step 7, you should have the following structure:
Now that everything is setup, we can start writing our backend code. First of all, we need to bring all our modules in. So, open up the index.js file and paste the following:
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.
Once the cluster creation is complete, make note of the above information and add it to the relevant fields of the
Now that we have our credentials setup, we are ready to create our Redis client in Node that will connect to our cluster and start storing key-value pairs.
Add the following code to the index.js file:
The above code does two things:
- Reads the credentials from
creds.jsonand creates a Redis client that is used to perform key-value operations
- Once the client is ready, we populate the
chat_messagesso 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.
Here we have the API for leaving the chat room:
Sending and storing the message:
Get all messages in room:
Get all members:
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
These events are then picked up on the front-end by the socket.IO library which in turn updates the UI.
Now, we need to build our UI that will allow users to sign in and chat.
Open up the
index.html file and add the following code:
The following code gets the number of chatters so we can update the UI about the total number of people in the room:
This code allows users to join the chat room. Usernames are unique and cannot be duplicated.
Here is the code for allowing users to leave the chat room:
Here is the code that runs every time someone sends a message:
The following is the socket.IO code that listens for events from the backend and updates the UI. For example, adding new messages to the messages area, updating the chatter count etc.
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/
For deploying this application on Heroku, check out their docs: https://devcenter.heroku.com/categories/deployment
The entire source code is also 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.