-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathLiveChat.js
212 lines (204 loc) · 6.95 KB
/
LiveChat.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
var botId = "st-f82726cb-4cd6-5ec4-bd35-7f5542b616dc";
var botName = "AgentTransferDemoBot";
var sdk = require("./lib/sdk");
var Promise = require('bluebird');
var api = require('./LiveChatAPI.js');
var _ = require('lodash');
var config = require('./config.json');
var debug = require('debug')("Agent");
var schedular = require('node-schedule');
var _map = {}; //used to store secure session ids //TODO: need to find clear map var
var userDataMap = {};//this will be use to store the data object for each user
var userResponseDataMap = {};
/**
* getPendingMessages
*
* @param {string} visitorId user id
* @param {string} ssid session id of the live chat
* @param {string} last message sent/received to/by agent
*/
function getPendingMessages( visitorId, ssid, last_message_id){
debug("getPendingMessages: %s %s ", visitorId, ssid);
var licence_id = config.liveagentlicense;
return api.getPendingMessages(visitorId, ssid,last_message_id, licence_id)
.then(function(res){
_.each(res.events, function(event){
var data = userDataMap[visitorId];
if(event.type === "message" && event.user_type !== "visitor"){
data.message = event.text;
data._originalPayload.message = data.text;
debug('replying ', event.text);
_map[visitorId].last_message_id = event.message_id;
return sdk.sendUserMessage(data, function(err){
console.log("err", err);
}).catch(function(e){
console.log(e);
debug("sending agent reply error", e);
delete userResponseDataMap[visitorId];
delete _map[visitorId];
});
} else if (event.type==="chat_closed"){
console.log('chat_closed');
delete userResponseDataMap[visitorId];
delete _map[visitorId];
sdk.clearAgentSession(data);
}
});
})
.catch(function(e){
console.error(e);
delete userDataMap[visitorId];
delete _map[visitorId];
});
}
/*
* Schedule a joob to fetch messages every 5 seconds
*/
schedular.scheduleJob('*/5 * * * * *', function(){
debug('schedular triggered');
var promiseArr = [];
_.each(_map, function(entry){
promiseArr.push(getPendingMessages(entry.visitorId, entry.secured_session_id, entry.last_message_id));
});
return Promise.all(promiseArr).then(function(){
debug('scheduled finished');
}).catch(function(e) {
debug('error in schedular', e);
});
});
function gethistory(req, res){
var userId = req.query.userId;
var data = userDataMap[userId];
if(data) {
data.limit = 100;
return sdk.getMessages(data, function(err, resp){
if(err){
res.status(400);
return res.json(err);
}
var messages = resp.messages;
res.status(200);
return res.json(messages);
});
} else {
var error = {
msg: "Invalid user",
code: 401
};
res.status(401);
return res.json(error);
}
}
/**
* connectToAgent
*
* @param {string} requestId request id of the last event
* @param {object} data last event data
* @returns {promise}
*/
function connectToAgent(requestId, data, cb){
var formdata = {};
formdata.licence_id = config.liveagentlicense;
formdata.welcome_message = "";
var visitorId = _.get(data, 'channel.channelInfos.from');
if(!visitorId){
visitorId = _.get(data, 'channel.from');
}
userDataMap[visitorId] = data;
data.message="An Agent will be assigned to you shortly!!!";
sdk.sendUserMessage(data, cb);
formdata.welcome_message = "Link for user Chat history with bot: "+ config.app.url +"/history/index.html?visitorId=" + visitorId;
return api.initChat(visitorId, formdata)
.then(function(res){
_map[visitorId] = {
secured_session_id: res.secured_session_id,
visitorId: visitorId,
last_message_id: 0
};
});
}
/*
* onBotMessage event handler
*/
function onBotMessage(requestId, data, cb){
debug("Bot Message Data",data);
var visitorId = _.get(data, 'channel.from');
var entry = _map[visitorId];
if(data.message.length === 0 || data.message === '') {
return;
}
var message_tone = _.get(data, 'context.dialog_tone');
if(message_tone && message_tone.length> 0){
var angry = _.filter(message_tone, {tone_name: 'angry'});
if(angry.length){
angry = angry[0];
if(angry.level >=2){
connectToAgent(requestId, data);
}
else {
sdk.sendUserMessage(data, cb);
}
}
else {
sdk.sendUserMessage(data, cb);
}
}
else if(!entry)
{
sdk.sendUserMessage(data, cb);
}else if(data.message === "skipUserMessage"){ // condition for skipping a user message
sdk.skipUserMessage(data, cb);
}
}
/*
* OnUserMessage event handler
*/
function onUserMessage(requestId, data, cb){
debug("user message", data);
var visitorId = _.get(data, 'channel.from');
var entry = _map[visitorId];
if(entry){//check for live agent
//route to live agent
var formdata = {};
formdata.secured_session_id = entry.secured_session_id;
formdata.licence_id = config.liveagentlicense;
formdata.message = data.message;
return api.sendMsg(visitorId, formdata)
.catch(function(e){
console.error(e);
delete userDataMap[visitorId];
delete _map[visitorId];
return sdk.sendBotMessage(data, cb);
});
}
else {
if(data.message === "skipBotMessage") // condition for skipping a bot message
return sdk.skipBotMessage(data, cb);
else
return sdk.sendBotMessage(data, cb);
}
}
/*
* OnAgentTransfer event handler
*/
function onAgentTransfer(requestId, data, callback){
connectToAgent(requestId, data, callback);
}
module.exports = {
botId : botId,
botName : botName,
on_user_message : function(requestId, data, callback) {
console.log('data', data);
debug('on_user_message');
onUserMessage(requestId, data, callback);
},
on_bot_message : function(requestId, data, callback) {
debug('on_bot_message');
onBotMessage(requestId, data, callback);
},
on_agent_transfer : function(requestId, data, callback) {
debug('on_webhook');
onAgentTransfer(requestId, data, callback);
},
gethistory: gethistory
};