• 聊天机器人遇到的难题


    webscoket:

    'use strict';
    
    /**
     * @ngdoc function
     * @name hrchatbotAdminApp.factory:myWebsocket
     * @description
     * # MainCtrl
     * Controller of the hrchatbotAdminApp
     */
    
    
    angular.module('hrchatbotAdminApp')
      .factory('myWebsocket', function ($websocket, storage, $http, $state) {
        
    
        function mywebscoket(){
            this.mywebsocket = null;
            this.manRecords = {};//
          this.robotRecords = {};//机器
            var self = this;
            this.openWebSocket = function(){
                var dataStream = $websocket('ws://10.202.10.89:8070/app/echo');
                dataStream.socket.onopen = function (evnt) {  
                    console.log("Webscoket opened.");  
                };  
                dataStream.socket.onmessage  = function (evnt) {  
                    self.onMessage(evnt)  
                };  
                dataStream.socket.onclose = function (evnt) {
                  // storage.remove('user');
                  // storage.remove('token');
                  // storage.remove('manRecords');
                  // storage.remove('robotRecords');
                  // $http.defaults.headers.common["Authorization"] = undefined;
                    console.log("Webscoket closed.");
                    //$state.go('login');
                };  
                dataStream.socket.onerror = function (evnt) {  
                    console.log("Webscoket Error.");  
                };  
                this.mywebsocket =  dataStream;
            }
            
            this.closeWebSocket = function(){
                if(this.mywebsocket != null){
                    this.mywebsocket.close();
                }
            }
            
            this.onMessage = function(evnt) {
              var message = JSON.parse(evnt.data);
              //机器人
              var storeRobotRecords = storage.getObject('robotRecords');
              if(storeRobotRecords != null && storeRobotRecords != undefined && !jQuery.isEmptyObject(storeRobotRecords)){
                var conversations_robot_new = {}  
                angular.forEach(message.conversations_robot,function(item,index){
                   item.readMsgs = [];
                   conversations_robot_new[item.name] = item;
                   if(storeRobotRecords[item.name] != null && storeRobotRecords[item.name] != undefined){
                      item.readMsgs = storeRobotRecords[item.name].readMsgs;
                      self.robotRecords[item.name] = item;
                   }else{
                     self.robotRecords[item.name] = item;
                   }
                 });
                 
                 angular.forEach(self.robotRecords,function(value,index){
                    var conversation = conversations_robot_new[index];
                    if(conversation == null || conversation == undefined){
                      delete self.robotRecords[index];
                    }
                 });
                 storage.setObject('robotRecords', this.robotRecords);
    
              }else{
                 angular.forEach(message.conversations_robot,function(item,index){
                   item.readMsgs = [];
                   self.robotRecords[item.name] = item;
                 })
              }
              console.log(message);
              storage.setObject('robotRecords', this.robotRecords);
         
              //人工
              var storeManRecords = storage.getObject('manRecords');
              if(storeManRecords != null && storeManRecords != undefined && !jQuery.isEmptyObject(storeManRecords)){
                 angular.forEach(message.conversations_hr,function(item,index){
                   item.readMsgs = [];
                   if(storeManRecords[item.name] != null && storeManRecords[item.name] != undefined){
                      item.readMsgs = storeManRecords[item.name].readMsgs;
                      self.manRecords[item.name] = item;
                   }else{
                    self.manRecords[item.name] = item;
                   }
                 })
              }else{
                 angular.forEach(message.conversations_hr,function(item,index){
                   item.readMsgs = [];
                   self.manRecords[item.name] = item;
                 })
              }
              storage.setObject('manRecords', this.manRecords);
            };
    
            this.sendMessage = function (message) {
              this.mywebsocket.send(JSON.stringify(message));
            }
              
        } 
    
        return new mywebscoket();
    })
    View Code

      主要页面

    'use strict';
    
    /**
     * @ngdoc function
     * @name hrchatbotAdminApp.controller:MainCtrl
     * @description
     * # MainCtrl
     * Controller of the hrchatbotAdminApp
     */
    angular.module('hrchatbotAdminApp')
      .controller('MainCtrl', function ($scope, storage, $interval) {
       $scope.tab = 1;//设置tab默认值
        //获取对话
        $scope.chat = {
          readmessage: [],
          chatContent: [],//聊天内容
          sendTime: null,
          sendContent: null,//发送内容
          currUserId: null //当前聊天用户id
        }
        $scope.chatList = storage.getObject('robotRecords');
        
        console.log('聊天列表'+$scope.chatList);
        $scope.selectItem = function (key) {
          $scope.chat.currUserId = key;
          angular.forEach($scope.chatList, function (item, index) {
            if (key == index) {
              item.selected = true;
              item.readMsg = item.messages.length;
              $scope.chat.chatContent = item.messages;
            } else {
              item.selected = false;
            }
          });
          $('#sidebar').removeClass('active');
          $('.overlay').fadeOut();
          console.log($scope.chat.chatContent);
        }
        $scope.setReadMsgs = function (key) {
          if(key){
            var item = $scope.chatList[key];
            if (item) {
              item.selected =true;
    
              $scope.chat.chatContent = item.messages;
              item.readMsgs = item.messages;
            } else {
              $scope.chat.chatContent = [];
            }
          }else{
            return false;
          }
          
        }
        $scope.setinter = function () {
         var promise = $interval(function () {
          var chatList = $scope.chatList; 
          var newRobotRecords = storage.getObject('robotRecords');
          angular.forEach(newRobotRecords,function(item,index){
              if(chatList[index] != null && chatList[index] != undefined){
                item.readMsgs = chatList[index].readMsgs;
                if($scope.chat.currUserId == index){
                  //设置已读消息
                  $scope.chat.readmessage = item.readMsgs;
                }
              }
          })
          $scope.chatList = newRobotRecords;
          storage.setObject('robotRecords',newRobotRecords);
          if (!jQuery.isEmptyObject($scope.chatList)) {
            if ($scope.chat.currUserId) {
                $scope.setReadMsgs($scope.chat.currUserId);
                
            }
          }
         }, 1000);
         return promise;
        }
        var promise = $scope.setinter();
        $scope.$on("$destroy", function () {
         $interval.cancel(promise);
        });
        $scope.$watch('chat.chatContent + chatlist', function () {
          setTimeout(function () {
            //根据未读消息来判断滚动条是否应该滚动到消息最底部
            var unread = $scope.chat.chatContent.length - $scope.chat.readmessage.length;
            if (unread > 0 && $('#chat-log')[0]) {
              $('#chat-log').scrollTop($('#chat-log')[0].scrollHeight);
            }
          }, 0);
        });
    });
    

      

      html:

    <div class="warp-out">
      <div id="vue-root">
        <div class="header">
          <div class="container">
            <div class="row">
              <div class="col-md-6">
                <h3 class="logo">HRChatbot Admin</h3>
              </div> 
              <div class="col-md-6">
                <span class="logout">Hi yishan! <a ng-click="logout()" class="logouts">logout</a></span>
              </div>
            </div> 
          <div class="bg-img"></div>
          </div>
        </div>
        <div class="mainContainers">
          <div class="container" style="height: 100%">
            <div class="row">
              <div class="col-md-12">
                <div class="tab-ul clearfix">
                  <div ng-class="{active: tab===1}">
                    <a href ng-click="tab=1">Intelligent service</a>
                  </div>
                  <div ng-class="{active: tab===2}">
                    <a href ng-click="tab=2">Artificial service</a>
                  </div>
                  <a class="letter-link" href="http://13.114.198.184/letter/">Letter</a>
                </div>
              </div>
            </div>
          
            <div class="row">
              <div class="tab-container">
                <div class="tab-pane1" ng-show="tab===1">
                  <div class="chat-contain clearfix">
                    <div class="col-md-3 chat-left">
                      <div class="panel panel-default">
                        <div class="panel-heading">
                          <h4 class="panel-title">Conversations</h4>
                        </div>
                        <div id="conversation-list" class="panel-body conversation-list">
                          <ul class="nav nav-pills nav-stacked">
                            <li class="list-groups" ng-repeat="(key,chatlist) in chatList" ng-class="{'select m-l-none': chatlist.selected }" ng-click="selectItem(key)">
                              <a ng-class="{'m-l-none': chatlist.selected }">{{chatlist.eid}}</a>
                              <span class="new-info">{{(chatlist.messages.length - chatlist.readMsgs.length) > 0 ? (chatlist.messages.length - chatlist.readMsgs.length) : ''}}</span>
                              <sup style="color: lawngreen; font-weight: 900;">{{chatlist.isVIP == false ? '' : 'VIP'}}</sup>
                            </li>
                          </ul>
                        </div>
                      </div>
    
                    </div>
    
                    <div class="col-md-9 chat-right">
                      <div class="panel panel-default panel-border-left">
                        <div class="panel-heading">
                          <h4 class="panel-title">Messages</h4>
                        </div>
                        <!--chat-->
                        <div id="chat-log" class="panel-body">
                          <div ng-repeat="chat in chat.chatContent">
                            <div class="row" ng-if="chat.name != 'HR'">
                              <div class="btn btn-success pull-right">
                                <span>{{chat.text}}</span>
                              </div>
                            </div>
                            <div class="row" ng-if="chat.name == 'HR'">
                              <div class="btn btn-default pull-left clearfix">
                                <span>{{chat.text}}</span>
                                <!--<div class="media-contain">
                      <div class="thumbnail">
                        <img src="../images/photo.jpg" />
                        <div class="caption">
                          <h3 class="imgchat-title">Thumbnail label</h3>
                          <p>Cras justo odio</p>
                        </div>
                      </div>
                    </div>
                    <div class="media-contain">
                      <div class="thumbnail">
                        <img src="../images/photo.jpg" />
                        <div class="caption">
                          <h3 class="imgchat-title">Thumbnail label</h3>
                          <p>Cras justo odio</p>
                        </div>
                      </div>
                    </div>
                    <div class="media-contain">
                      <div class="thumbnail">
                        <img src="../images/photo.jpg" />
                        <div class="caption">
                          <h3 class="imgchat-title">Thumbnail label</h3>
                          <p>Cras justo odio</p>
                        </div>
                      </div>
                    </div>-->
                              </div>
                            </div>
                          </div>
                        </div>
                        <div class="input-group">
                          <input type="text" placeholder="Please input..." id="input-text" disabled="disabled" class="txtInput">
                          <span class="input-group-btn"><button type="button" id="btn-say" disabled="disabled" class="btn">Send</button></span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="tab-pane1" ng-show="tab===2">
                  <div ng-include="'views/humanService.html'"></div>
                </div>
              </div>
              
            </div>
          </div>
        </div>
      </div>
      <div id="footer">
        <div class="contentWrapper"><p>© 2017, Bertha All Rights Reserved</p></div>
      </div>
    </div>
    

      最终websocket代码:

      1 'use strict';
      2 
      3 /**
      4  * @ngdoc function
      5  * @name hrchatbotAdminApp.factory:myWebsocket
      6  * @description
      7  * # MainCtrl
      8  * Controller of the hrchatbotAdminApp
      9  */
     10 
     11 
     12 angular.module('hrchatbotAdminApp')
     13   .factory('myWebsocket', function ($websocket, storage, $http, $state, $interval) {
     14 
     15     function mywebscoket(){
     16       this.newMessage = {};
     17         this.mywebsocket = null;
     18         this.manRecords = {};//
     19       this.robotRecords = {};//机器
     20       this.socketStatus = true;//网络连接状态
     21       var inter = null;
     22       var self = this;
     23       this.human_log_out = false;
     24       this.isConnected = false;
     25       self.tanchuang = function(){
     26         inter = setTimeout(function() {
     27           if(!self.socketStatus){
     28             $('.socket-line').html('The network connection has been disconnected, and the connection is being reconnected...');
     29             $('.socket-line').fadeIn("fast");
     30             self.openWebSocket();
     31             $('.socket-line').fadeOut(2000);
     32           }
     33         }, 5000);
     34       }
     35         this.openWebSocket = function(){
     36         //if websocket has been connected
     37           if(self.isConnected)
     38             return;
     39             var dataStream = $websocket('ws://10.202.10.99:8070/app/echo');
     40             dataStream.socket.onopen = function (evnt) {  
     41                self.socketStatus = true;
     42                self.isConnected = true;
     43                self.human_log_out = false;
     44                 console.log("Webscoket opened." + self.socketStatus);
     45                 $('.socket-line').html('');
     46             };  
     47             dataStream.socket.onmessage  = function (evnt) {  
     48               self.onMessage(evnt);
     49             };  
     50             dataStream.socket.onclose = function (evnt) {
     51               self.isConnected = false; 
     52               self.socketStatus = false;
     53               
     54                 console.log("Webscoket closed." + self.socketStatus);
     55                 if(!self.human_log_out && !self.isConnected){
     56                   self.tanchuang();
     57                 } else {
     58                     storage.remove('user');
     59                     storage.remove('token');
     60                     storage.remove('manRecords');
     61                     storage.remove('robotRecords');
     62                     $http.defaults.headers.common["Authorization"] = undefined;
     63                     //clearInterval(inter);
     64                 }
     65                
     66                 //$state.go('login');
     67             };  
     68             dataStream.socket.onerror = function (evnt) { 
     69                self.isConnected = false; 
     70                console.log("Webscoket Error.");
     71                 self.socketStatus = false;
     72                 if(!self.human_log_out && !self.isConnected){
     73                    //tanchuang();
     74                 }else{
     75                   //clearInterval(inter);
     76                 }
     77                
     78             };  
     79             self.mywebsocket =  dataStream;
     80           //self.isConnected = true;
     81         }
     82         
     83         this.closeWebSocket = function(){
     84             if(self.mywebsocket != null){
     85                 self.mywebsocket.close();
     86             }
     87         }
     88         
     89         this.onMessage = function(evnt) {
     90           var message = JSON.parse(evnt.data);
     91           //机器人
     92           var storeRobotRecords = storage.getObject('robotRecords');
     93           if(storeRobotRecords != null && storeRobotRecords != undefined && !jQuery.isEmptyObject(storeRobotRecords)){
     94             var conversations_robot_new = {}  
     95             angular.forEach(message.conversations_robot,function(item,index){
     96                item.readMsgs = [];
     97                conversations_robot_new[item.name] = item;
     98                if(storeRobotRecords[item.name] != null && storeRobotRecords[item.name] != undefined){
     99                   item.readMsgs = storeRobotRecords[item.name].readMsgs;
    100                   self.robotRecords[item.name] = item;
    101                }else{
    102                  self.robotRecords[item.name] = item;
    103                }
    104              });
    105              
    106              angular.forEach(self.robotRecords,function(value,index){
    107                 var conversation = conversations_robot_new[index];
    108                 if(conversation == null || conversation == undefined){
    109                   delete self.robotRecords[index];
    110                 }
    111              });
    112              storage.setObject('robotRecords', this.robotRecords);
    113 
    114           }else{
    115              angular.forEach(message.conversations_robot,function(item,index){
    116                item.readMsgs = [];
    117                self.robotRecords[item.name] = item;
    118              })
    119           }
    120           console.log(message);
    121           storage.setObject('robotRecords', this.robotRecords);
    122      
    123           //人工
    124           var storeManRecords = storage.getObject('manRecords');
    125           if(storeManRecords != null && storeManRecords != undefined && !jQuery.isEmptyObject(storeManRecords)){
    126             var conversations_hr_new = {}   
    127             angular.forEach(message.conversations_hr,function(item,index){
    128                item.readMsgs = [];
    129                conversations_hr_new[item.name] = item;
    130                if(storeManRecords[item.name] != null && storeManRecords[item.name] != undefined){
    131                   item.readMsgs = storeManRecords[item.name].readMsgs;
    132                   self.manRecords[item.name] = item;
    133                }else{
    134                 self.manRecords[item.name] = item;
    135                }
    136              })
    137              angular.forEach(self.manRecords,function(value,index){
    138               var conversation = conversations_hr_new[index];
    139               if(conversation == null || conversation == undefined){
    140                 delete self.manRecords[index];
    141               }
    142            });
    143 
    144           }else{
    145              angular.forEach(message.conversations_hr,function(item,index){
    146                item.readMsgs = [];
    147                self.manRecords[item.name] = item;
    148              })
    149           }
    150           storage.setObject('manRecords', this.manRecords);
    151         };
    152 
    153         this.sendMessage = function (message) {
    154           this.mywebsocket.send(JSON.stringify(message));
    155         }
    156           
    157     } 
    158 
    159     return new mywebscoket();
    160 })
    View Code
  • 相关阅读:
    HTML5之特效
    css3圆角矩形、盒子阴影
    vertical-align垂直居中
    CSS3选择器
    经典导航栏
    C#获得时间段
    C#抓取和分析网页的类
    c#基础知识索引器
    强制浏览器重定向到另一页
    雅虎公司C#笔试题及参考答案
  • 原文地址:https://www.cnblogs.com/bertha-zm/p/8610391.html
Copyright © 2020-2023  润新知