在 Socket.io 基本聊天应用程序中添加聊天机器人

Adding a chatbot in Socket.io basic chat application

我想集成一个聊天机器人,它应该连接到任何等待连接到真实人类用户的用户。聊天机器人将通过响应人类用户消息来娱乐用户。

这里已经实现了一个名为 "Didianer.com" 的类似聊天机器人,如果你到这里开始打字,你会看到他的回应。

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

我也想在我的应用程序中使用完全相同的机器人,但我完全不知道从哪里开始。

这是我的服务器端代码

  //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 在新用户连接并想与其他人交谈时调用。在这里我假设机器人的逻辑应该去。例如,如果用户正在等待(排队)5 秒钟,但没有人在线聊天,则将用户(添加用户和聊天机器人)连接到一个房间,这样他们就可以开始聊天了。我不确定如何响应聊天事件以及聊天机器人将如何回复...

 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);

}
}

我想要一个非常简单的基本聊天机器人来响应基本消息。就像我应该检查用户是否发送消息 "Hello" 然后我可以检查用户消息是否包含单词 "Hello" 然后我可以用对 "Hello" 的适当响应回复聊天机器人 Like "Hi {username} of the online user".

有很多方法可以做到这一点。

一种方法是在 message 上处理这个问题,如果房间里没有其他人,让机器人响应。

   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);
    }
 });

然后由您决定是否要在用户单独或不在时将机器人加入频道,以及是否让他们在其他用户进入时离开。

/************* 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 *********/
}
};

这里是原始HTML文件:

<!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>