【问题标题】:Adding a chatbot in Socket.io basic chat application在 Socket.io 基本聊天应用程序中添加聊天机器人
【发布时间】:2020-02-01 19:49:04
【问题描述】:

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

这里已经实现了一个类似的聊天机器人,名为“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”的适当响应回复聊天机器人就像在线用户的“Hi {username}” .

【问题讨论】:

    标签: javascript node.js socket.io chat chatbot


    【解决方案1】:
    /************* 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 *********/
    }
    };
    

    【讨论】:

    • 顺便说一句,这段代码很糟糕,它只是给你概念概述
    【解决方案2】:

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

    一种方法是在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);
        }
     });
    

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

    【讨论】:

      【解决方案3】:

      这是原始的 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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-20
        相关资源
        最近更新 更多