Making A Robo Response Using Socket IO

Using nodejs and socket io, we can build an app that responds to human questions and do the needful. Lets create a simple app that gives simple answers to questions.

Install Socket Io

Lets not go in depth of how to install nodejs, as there could be number of tutorials doing this.

Create a nodejs App
Create a folder for the project and create your nodejs app like this


npm init

Install Express & Socket


npm install --save express
npm install --save socket.io

Simple HTML App client using Socket.io

Explainations
1. On form submit, add the user message to the messages list.
2. On response from the server through socket, add response to the messages list.



<!DOCTYPE html>
<html>
<head>
 <title>Chat Bot</title>
 <style>

 * { margin: 0; padding: 0; box-sizing: border-box; }
 body { font: 13px Helvetica, Arial; }
 #bot-wrapper {
 margin-top: 30px;
 margin-left: auto;
 margin-right: auto;
 width: 400px;
 height: 500px;
 position: relative;
 
 box-shadow: 2px 2px 20px #333;
 }
 form { border-top:1px solid #ddd; position: absolute; bottom: 0; width: 100%; }
 form input { border: 0; padding: 10px; width: 85%; }
 form button { width: 15%; background: rgb(130, 224, 255); border: none; padding: 10px; }
 #messages { list-style-type: none; margin: 0; padding: 0; }
 #messages li { padding: 5px 10px; }
 #messages li:nth-child(odd) { background: #eee; }
 </style>


<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
 var socket = io();
 $('#botHelp').submit(function(){
 var userMessage = $('#m').val();
 socket.emit('message', userMessage);
 $("#messages").append("<li>"+userMessage+"</li>");
 $('#m').val('');
 return false;
 });

 socket.on('reply', function(body){
 //console.log(body);
 $("#messages").append("<li>"+body+"</li>");
 })
 });
</script>

</head>
<body>
<div id="bot-wrapper">
 <ul id="messages"></ul>
 <form action="" id="botHelp">
 <input id="m" autocomplete="off" /><button>Send</button>
 </form>
 </div>
</body>
</html>

Building Server App using Socket.io

Save the below code in the node app as bot.js



var app = require('express')();
var http = require('http').Server(app);

var io = require('socket.io')(http);

app.get('/', function(req, res){
 res.sendFile(__dirname + '/chat.html');
});

var users = [1, 2];
var userSockets = []

var botResponse = function(response, socket) {
 setTimeout(function(){
 socket.emit("reply", response);
 }, 1000)
}

io.on('connection', function(socket){

 console.log('User Connected');

 socket.on('message', function(msg){
 if(msg == "hello") {
 botResponse("hi..how are you doing ", socket);
 }
 else if(msg == "good") {
 botResponse("Thats great, what can I do for you today..!", socket);
 }
 else if(msg == "movie tickets") {
 botResponse("Available Movies: <b>Iron Man</b>, <b>Bat Man</b>, <b>Super Man</b>", socket);
 }
 else {
 botResponse("eeee :-( I am clueless", socket);
 }
 });

 socket.on('disconnect', function(){
 console.log('user disconnected');
 });

});

http.listen(3000, function(){
 console.log('listening on *:3000');
});

Running Node Bot

In the cmd prompt run your app using node command node bot.js.
App will now run.

Open your browser visit http://localhost:3000. The sample result will look like something below.

UPDATE: 23-May-2017

Getting Real Movie List From Themoviedb.org

We can replace the list of the latest movies string with actual result from themoviedb.org.

1. Get an API key from themoviedb.org developers site.
2. Use axios package to get the latest from the movie db API.


var currentDate = new Date();
 currentDate = currentDate.toISOString();
 currentDate = currentDate.substr(currentDate, currentDate.indexOf("T"));
 
 var weekOldDate = new Date();
 weekOldDate.setDate(weekOldDate.getDate() - 7);

 weekOldDate = weekOldDate.toISOString();
 weekOldDate = weekOldDate.substr(weekOldDate, weekOldDate.indexOf("T"));
 
 var url = "https://api.themoviedb.org/3/discover/movie?"
 +"api_key={API_KEY}&"
 +"sort_by=popularity.desc&include_adult=false"
 +"&include_video=false&page=1&primary_release_date.gte="+ weekOldDate +"&primary_release_date.lte=" + currentDate;
 moviesString = "<ul>";
 axios.get(url).then(function(response){
 var movieResults = response.data.results;
 movieResults.forEach(function(movie, index){
 moviesString = moviesString + "<li>" + movie.title + "</li>";
 })
 moviesString = moviesString + "</ul>";
 // console.log(moviesString);
 botResponse(moviesString, socket);
 }).catch(function(error){
 console.log(error);
 })

Sources:
https://socket.io/get-started/chat/
https://developers.themoviedb.org/3/discover