首页 文章

在Socket.io基本聊天应用程序中添加Chatbot

提问于
浏览 403
0

我做了一个基本的聊天应用程序,将两个随机对等连接在一起 .

您可以在此处看到实时运行示例:

http://talkwithstranger.com

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

这里有一个类似的聊天机器人名为“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 of online user” . 像这样的东西 .

任何帮助或源代码示例将非常感激 .

提前致谢

3 回答

  • 1

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

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

    然后,如果您想在用户独处时加入僵尸网站,并且如果您在其他用户进入时让他们离开,则由您决定 .

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

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

相关问题