-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscript.js
233 lines (207 loc) · 7.59 KB
/
script.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
$(document).ready(function() {
// Credentials
var baseUrl = "https://api.api.ai/v1/query?v=20160910&";
var accessToken = "553ab6017e584e0fa351952c8c9ca956";
//---------------------------------- Add dynamic html bot content(Widget style) ----------------------------
// You can also add the html content in html page and still it will work!
var mybot = '<div class="chatCont" id="chatCont">'+
'<div class="bot_profile">'+
'<img src="assets/img/bot2.svg" class="bot_p_img">'+
'<div class="close">'+
'<i class="fa fa-times" aria-hidden="true"></i>'+
'</div>'+
'</div><!--bot_profile end-->'+
'<div id="result_div" class="resultDiv"></div>'+
'<div class="chatForm" id="chat-div">'+
'<div class="spinner">'+
'<div class="bounce1"></div>'+
'<div class="bounce2"></div>'+
'<div class="bounce3"></div>'+
'</div>'+
'<input type="text" id="chat-input" autocomplete="off" placeholder="Try typing here"'+ 'class="form-control bot-txt"/>'+
'</div>'+
'</div><!--chatCont end-->'+
'<div class="profile_div">'+
'<div class="row">'+
'<div class="col-hgt">'+
'<img src="assets/img/bot2.svg" class="img-circle img-profile">'+
'</div><!--col-hgt end-->'+
'<div class="col-hgt">'+
'<div class="chat-txt">'+
'Chat with us now!'+
'</div>'+
'</div><!--col-hgt end-->'+
'</div><!--row end-->'+
'</div><!--profile_div end-->';
$("mybot").html(mybot);
// ------------------------------------------ Toggle chatbot -----------------------------------------------
$('.profile_div').click(function() {
$('.profile_div').toggle();
$('.chatCont').toggle();
$('.bot_profile').toggle();
$('.chatForm').toggle();
document.getElementById('chat-input').focus();
});
$('.close').click(function() {
$('.profile_div').toggle();
$('.chatCont').toggle();
$('.bot_profile').toggle();
$('.chatForm').toggle();
});
// Session Init (is important so that each user interaction is unique)--------------------------------------
var session = function() {
// Retrieve the object from storage
if(sessionStorage.getItem('session')) {
var retrievedSession = sessionStorage.getItem('session');
} else {
// Random Number Generator
var randomNo = Math.floor((Math.random() * 1000) + 1);
// get Timestamp
var timestamp = Date.now();
// get Day
var date = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var day = weekday[date.getDay()];
// Join random number+day+timestamp
var session_id = randomNo+day+timestamp;
// Put the object into storage
sessionStorage.setItem('session', session_id);
var retrievedSession = sessionStorage.getItem('session');
}
return retrievedSession;
// console.log('session: ', retrievedSession);
}
// Call Session init
var mysession = session();
// on input/text enter--------------------------------------------------------------------------------------
$('#chat-input').on('keyup keypress', function(e) {
var keyCode = e.keyCode || e.which;
var text = $("#chat-input").val();
if (keyCode === 13) {
if(text == "" || $.trim(text) == '') {
e.preventDefault();
return false;
} else {
$("#chat-input").blur();
setUserResponse(text);
send(text);
e.preventDefault();
return false;
}
}
});
//------------------------------------------- Send request to API.AI ---------------------------------------
function send(text) {
$.ajax({
type: "GET",
url: baseUrl+"query="+text+"&lang=en-us&sessionId="+mysession,
contentType: "application/json",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
// data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }),
success: function(data) {
main(data);
// console.log(data);
},
error: function(e) {
console.log (e);
}
});
}
//------------------------------------------- Main function ------------------------------------------------
function main(data) {
var action = data.result.action;
var speech = data.result.fulfillment.speech;
// use incomplete if u use required in api.ai questions in intent
// check if actionIncomplete = false
var incomplete = data.result.actionIncomplete;
if(data.result.fulfillment.messages) { // check if messages are there
if(data.result.fulfillment.messages.length > 0) { //check if quick replies are there
var suggestions = data.result.fulfillment.messages[1];
}
}
switch(action) {
// case 'your.action': // set in api.ai
// Perform operation/json api call based on action
// Also check if (incomplete = false) if there are many required parameters in an intent
// if(suggestions) { // check if quick replies are there in api.ai
// addSuggestion(suggestions);
// }
// break;
default:
setBotResponse(speech);
if(suggestions) { // check if quick replies are there in api.ai
addSuggestion(suggestions);
}
break;
}
}
//------------------------------------ Set bot response in result_div -------------------------------------
function setBotResponse(val) {
setTimeout(function(){
if($.trim(val) == '') {
val = 'I couldn\'t get that. Let\' try something else!'
var BotResponse = '<p class="botResult">'+val+'</p><div class="clearfix"></div>';
$(BotResponse).appendTo('#result_div');
} else {
val = val.replace(new RegExp('\r?\n','g'), '<br />');
var BotResponse = '<p class="botResult">'+val+'</p><div class="clearfix"></div>';
$(BotResponse).appendTo('#result_div');
}
scrollToBottomOfResults();
hideSpinner();
}, 500);
}
//------------------------------------- Set user response in result_div ------------------------------------
function setUserResponse(val) {
var UserResponse = '<p class="userEnteredText">'+val+'</p><div class="clearfix"></div>';
$(UserResponse).appendTo('#result_div');
$("#chat-input").val('');
scrollToBottomOfResults();
showSpinner();
$('.suggestion').remove();
}
//---------------------------------- Scroll to the bottom of the results div -------------------------------
function scrollToBottomOfResults() {
var terminalResultsDiv = document.getElementById('result_div');
terminalResultsDiv.scrollTop = terminalResultsDiv.scrollHeight;
}
//---------------------------------------- Ascii Spinner ---------------------------------------------------
function showSpinner() {
$('.spinner').show();
}
function hideSpinner() {
$('.spinner').hide();
}
//------------------------------------------- Suggestions --------------------------------------------------
function addSuggestion(textToAdd) {
setTimeout(function() {
var suggestions = textToAdd.replies;
var suggLength = textToAdd.replies.length;
$('<p class="suggestion"></p>').appendTo('#result_div');
$('<div class="sugg-title">Suggestions: </div>').appendTo('.suggestion');
// Loop through suggestions
for(i=0;i<suggLength;i++) {
$('<span class="sugg-options">'+suggestions[i]+'</span>').appendTo('.suggestion');
}
scrollToBottomOfResults();
}, 1000);
}
// on click of suggestions get value and send to API.AI
$(document).on("click", ".suggestion span", function() {
var text = this.innerText;
setUserResponse(text);
send(text);
$('.suggestion').remove();
});
// Suggestions end -----------------------------------------------------------------------------------------
});