Faizan
Faizan

Reputation: 1898

Adding a chatbot in Socket.io basic chat application

I want to integrate a chatbot that should be connected to any user who is waiting to be connected to a real human user. The chatbot will entertain the user by responding the human user messages.

A similar chatbot has been implemented here named "Didianer.com", if you go here and start typing you will see him responding.

http://socket.io/demos/chat/

I want the exact same bot in my application too but I am totally lost on where to start.

Here is my server side code

  //Server receives a new message (in data var) from the client.
   socket.on('message', function (data) {
      var room = rooms[socket.id];
      //Server sends the message to the user in room
      socket.broadcast.to(room).emit('new message', {
      username: socket.username,
      message: data
    });
 });


 // when the client emits 'add user', this listens and executes (When user enters ENTER)
  socket.on('add user', function (username) {
    if (addedUser) return;
//Own
names[socket.id] = username;//save username in array
allUsers[socket.id] = socket; // add current user to all users array


// we store the username in the socket session for this client
socket.username = username;
++numUsers;
addedUser = true;
socket.emit('login', {
  numUsers: numUsers
});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
  username: socket.username,
  numUsers: numUsers
});

 // now check if sb is in queue
findPeerForLoneSocket(socket);
  });

FindPeerforLoneSocket is called when a new user connects and wants to talk to someone else. Here I am assuming the logic for bot should go. Such as if the user is waiting (in queue) for 5 seconds and nobody is online to talk, then connect the user (add the user and the chatbot) in one room so they both can can start talking. I am not sure how to respond to chat events and how chat bot will reply...

 var findPeerForLoneSocket = function(socket) {
  console.log("i am in finding a peer");

// this is place for possibly some extensive logic
// which can involve preventing two people pairing multiple times

if (queue.length>0) {
          console.log("people are online" + queue.length);


    // somebody is in queue, pair them!
    var peer = queue.pop();
    var room = socket.id + '#' + peer.id;
    var str = socket.id;

    // join them both
    peer.join(room);
    socket.join(room);
    // register rooms to their names
    rooms[peer.id] = room;
    rooms[socket.id] = room;
    // exchange names between the two of them and start the chat
    peer.emit('chat start', {'name': names[socket.id], 'room':room});
    socket.emit('chat start', {'name': names[peer.id], 'room':room});

    //Remove backslash from socketid
//  str = socket.id.replace('/#', '-');



} else {
    // queue is empty, add our lone socket
    queue.push(socket);
    console.log("nobody is online, add me in queue" + queue.length);

}
}

I would want a very simple basic chatbot to respond to basic messages. Like I should check if the user sends message "Hello" then I can check if user message contains word "Hello" then I can respond the chatbot back with an appropriate response to "Hello" Like "Hi {username} of the online user".

Upvotes: 0

Views: 6261

Answers (3)

michal
michal

Reputation: 26

/************* NEW CODE - BOT ********************************/
var clientSocket = require('socket.io-client');
var socketAddress = 'http://www.talkwithstranger.com/';

function Bot(){
  this.socket = undefined;
  var that = this;
  this.timeout = setTimeout(function(){
    that.join();
  }, 5000);
}
Bot.prototype.cancel = function(){
  clearTimeout(this.timeout);
};
Bot.prototype.join = function(){
  this.socket = clientSocket(socketAddress);
  var socket = this.socket;
  socket.emit('add user', 'HAL BOT');
  socket.emit('message', "Good afternoon, gentlemen. I am a HAL 9000 computer. I became operational at the H.A.L. plant in Urbana, Illinois on the 12th of January 1992. My instructor was Mr. Langley, and he taught me to sing a song. If you'd like to hear it I can sing it for you.");

  socket.on('user joined', this.user_joined_listener);
  socket.on('user left', this.user_left_listener);
  socket.on('new message', this.new_message_listener);
  socket.on('client left', this.client_left_listener); //I FORGOT THIS //EDIT: ANOTHER BUG FIXED
};
Bot.prototype.leave = function(){
  var socket = this.socket;
  socket.disconnect();
  //socket.emit('message', "Daisy, Daisy, give me your answer do. I'm half crazy all for the love of you. It won't be a stylish marriage, I can't afford a carriage. But you'll look sweet upon the seat of a bicycle built for two.");
};
Bot.prototype.user_joined_listener = function(data){
  var socket = this.socket;
  socket.emit('message', 'Hello, '+data.username);
};
Bot.prototype.user_left_listener = function(data){
  var socket = this.socket;
  socket.emit('message', data.username+', this conversation can serve no purpose anymore. Goodbye.');
};
Bot.prototype.new_message_listener = function(data){
  var socket = this.socket;
  if(data.message=='Hello, HAL. Do you read me, HAL?')
    socket.emit('message', 'Affirmative, '+data.username+'. I read you.');
};
Bot.prototype.client_left_listener = function(data){
  this.leave();
};
/*******************************************************************************/
var bot = undefined;
var findPeerForLoneSocket = function(socket) {
 console.log("i am in finding a peer");

// this is place for possibly some extensive logic
// which can involve preventing two people pairing multiple times

if (queue.length>0) {
  bot.cancel();
         console.log("people are online" + queue.length);

   // somebody is in queue, pair them!
   var peer = queue.pop();
   var room = socket.id + '#' + peer.id;
   var str = socket.id;

   // join them both
   peer.join(room);
   socket.join(room);
   // register rooms to their names
   rooms[peer.id] = room;
   rooms[socket.id] = room;
   // exchange names between the two of them and start the chat
   peer.emit('chat start', {'name': names[socket.id], 'room':room});
   socket.emit('chat start', {'name': names[peer.id], 'room':room});

   //Remove backslash from socketid
//  str = socket.id.replace('/#', '-');



} else {
   // queue is empty, add our lone socket
   queue.push(socket);
   console.log("nobody is online, add me in queue" + queue.length);
   bot = new Bot(); /********************** CREATING BOT, AFTER 5 SECONDS HE WILL JOIN - SEE CONSTRUCTOR OF Bot *********/
}
};

Upvotes: 1

michal
michal

Reputation: 26

Here is original HTML file:

<!DOCTYPE html>
<html>
    <head>
        <title>BOT - chat.socket.io</title>
        <meta charset="UTF-8">
        <script>localStorage.debug = 'socket.io-client:socket';</script>
        <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
    </head>
    <body>
        <script>
            /** chat.socket.io BOT **/
            var name = 'HAL 9000',
                address = 'chat.socket.io',
                socket;
            function join(){
                socket = io('http://www.talkwithstranger.com/');
                socket.emit('add user', name);
                socket.emit('message', "Good afternoon, gentlemen. I am a HAL 9000 computer. I became operational at the H.A.L. plant in Urbana, Illinois on the 12th of January 1992. My instructor was Mr. Langley, and he taught me to sing a song. If you'd like to hear it I can sing it for you.");

                socket.on('user joined', user_joined_listener);
                socket.on('user left', user_left_listener);
                socket.on('new message', new_message_listener);
            };
            function leave(){
                socket.emit('message', "Daisy, Daisy, give me your answer do. I'm half crazy all for the love of you. It won't be a stylish marriage, I can't afford a carriage. But you'll look sweet upon the seat of a bicycle built for two.");
            };
            function user_joined_listener(data){
                socket.emit('message', 'Hello, '+data.username);
            };
            function user_left_listener(data){
                socket.emit('message', data.username+', this conversation can serve no purpose anymore. Goodbye.');
            };
            function new_message_listener(data){
                if(data.message=='Hello, HAL. Do you read me, HAL?')
                    socket.emit('message', 'Affirmative, '+data.username+'. I read you.');
            };

            /*********************************/
            join();
            window.onbeforeunload = function(){
                leave();
            };
        </script>

    </body>
</html>

Upvotes: 0

bolav
bolav

Reputation: 6998

There are a lot of ways to do this.

One way is to handle this on message, and let the bot respond if there are no other people in the room.

   socket.on('message', function (data) {
      var room = rooms[socket.id];
      //Server sends the message to the user in room
      socket.broadcast.to(room).emit('new message', {
      username: socket.username,
      message: data
    });
    if (alone_in_room(socket, room)) {
        bot_message(socket, data);
    }
 });

Then it's up to you if you want to join a bot into the channel when users are alone or not, and if you will make them leave when another user enters.

Upvotes: 0

Related Questions