Skip to content

Instantly share code, notes, and snippets.

@fathermerry
Created August 15, 2016 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fathermerry/2ca7a31f0db184a570fd2331fb232385 to your computer and use it in GitHub Desktop.
Save fathermerry/2ca7a31f0db184a570fd2331fb232385 to your computer and use it in GitHub Desktop.
Old Bot Code
(function() {
'use strict';
var pubnub, conversation;
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
var log = [];
var chatInput = document.getElementById('chat-input');
var tagInput = document.getElementById('tag-input');
var chatForm = document.getElementById('chat-form');
var chatField = document.getElementById('chat-field');
var chatWrapper = document.getElementById('chat-wrapper');
var showTriggers = document.getElementsByClassName('show');
var hideTriggers = document.getElementsByClassName('hide');
var overlay = document.getElementById('overlay');
var thread = document.getElementById('thread');
// Start
localforage.getItem('eatdrinkbot:conversation').then(function(data) {
conversation = data;
if (conversation == null || !conversation.uid) {
initialize_pubnub();
} else if (conversation.onboarded) {
setup_conversation();
localforage.getItem('eatdrinkbot:history', function(err, history) {
populate(history || []);
document.body.style.display = '';
});
} else {
onboard();
}
});
chatInput.addEventListener('focus', function() {
setTimeout(function() {
chatWrapper.style.height = window.innerHeight + 'px';
document.body.scrollTop = document.documentElement.scrollTop = 0;
}, 300);
});
chatInput.addEventListener('blur', function() {
chatWrapper.style.height = '100%';
});
for (var i = 0; i < showTriggers.length; i++) {
showTriggers[i].addEventListener('click', function() {
var divName = this.getAttribute('data-div');
var divToShow = document.getElementById(divName);
var animation = divToShow.getAttribute('data-animate');
overlay.style.display = 'block';
if (animation) {
var animation_classes = animation.split(" ");
for (var j = 0; j < animation_classes.length; j++) {
addClass(divToShow, animation_classes[j]);
}
}
divToShow.style.zIndex = '100';
divToShow.style.display = 'block';
});
}
for (var i = 0; i < hideTriggers.length; i++) {
hideTriggers[i].addEventListener('click', function() {
var divName = this.getAttribute('data-div');
var divToHide = document.getElementById(divName);
var animation = divToHide.getAttribute('data-animate');
overlay.style.display = 'none';
if (animation) {
var animation_classes = animation.split(" ");
for (var j = 0; j < animation_classes.length; j++) {
removeClass(divToHide, animation_classes[j]);
}
}
divToHide.style.zIndex = '';
divToHide.style.display = 'none';
});
}
function generateHTML(message, options) {
var options = options || {};
var div = document.createElement("div");
if (!message.type || message.type == 'text' && message.body) {
div.className = message.is_app ? 'from-bot' : 'from-user';
if (options.animate) div.className += ' animated fadeInUp';
var content = document.createElement("p");
content.innerHTML = message.body;
div.appendChild(content);
}
var clear = document.createElement("div");
clear.className = "clear";
thread.appendChild(div);
thread.appendChild(clear);
thread.scrollTop = thread.offsetHeight;
}
function post(message) {
if (message.options) {
chatInput.style.display = 'none';
tagInput.style.display = 'block';
addClass(chatField, 'has-tag-input');
for (var i = 0; i < message.options.length; i++) {
var tag = document.createElement("span");
tag.setAttribute('data-index', i);
tag.innerHTML = message.options[i].name;
tag.addEventListener('click', function() {
var index = this.getAttribute('data-index');
var option = message.options[index];
console.log(option);
post({
type: 'text',
body: option.name
});
post_message(option.id, function(response) {
if (response.status >= 200 && response.status < 400) {
tagInput.style.display = 'none';
tagInput.innerHTML = '';
removeClass(chatField, 'has-tag-input');
chatInput.style.display = 'block';
chatInput.focus();
}
});
});
tagInput.appendChild(tag);
}
}
generateHTML(message, {
animate: true
});
if (log.length == 20) log.shift();
log.push(message);
if (!message.discard) {
localforage.setItem('eatdrinkbot:history', log);
}
}
function populate(history) {
thread.style.opacity = '0';
log = history;
history.forEach(function(message, index) {
generateHTML(message);
if (index + 1 == history.length) {
thread.style.opacity = '';
}
});
}
function demo_conversation(e) {
e.preventDefault();
var message = chatInput.value;
post({
type: 'text',
body: message,
discard: true
});
chatInput.value = '';
}
function onboard() {
document.body.style.display = '';
chatForm.addEventListener('submit', demo_conversation);
var intro_messages = ["How far! I'm here to help you find the ideal restaurant in Lagos.", "What do I call you?"]
function play(messages, callback) {
var delay = 500;
chatInput.setAttribute('disabled', true);
messages.forEach(function(message, index) {
setTimeout(function() {
post({
is_app: true,
type: 'text',
body: message,
discard: true
})
if (index + 1 == messages.length) {
chatInput.removeAttribute('disabled');
chatInput.focus();
if (callback) callback();
}
}, delay);
var next_message = messages[index + 1];
var next_message_delay;
if (next_message) {
next_message_delay = (next_message.length / 15) * 500;
delay += next_message_delay;
}
});
}
var do_introductions = function() {
chatForm.addEventListener('submit', show_help_messages);
}
var show_help_messages = function() {
var help_messages = [];
var name = log[log.length - 1].body;
name.capitalize();
if (name.length > 15) {
name = name.split(" ");
name = name[0];
if (name.length > 15) {
name = name.substring(0, 15);
}
help_messages.push("That's a long one. I'll call you " + name);
help_messages.push("I assume this is your first time here.");
} else {
help_messages.push("Okay, " + name + ". I assume this is your first time here.");
}
help_messages.push("Frequently asked questions are on the left.");
help_messages.push("Your saved restaurants are listed on the right.");
help_messages.push("Type <b>okay</b> to start using the bot");
play(help_messages, start_conversation);
}
var start_conversation = function() {
chatInput.focus();
chatForm.removeEventListener('submit', show_help_messages);
chatForm.addEventListener('submit', call_endpoint);
}
var call_endpoint = function() {
var next_input = log[log.length - 1].body;
next_input = next_input.toLowerCase();
if (next_input == 'ok' || next_input == 'okay') {
chatForm.removeEventListener('submit', call_endpoint);
chatForm.removeEventListener('submit', demo_conversation);
setup_conversation(function() {
post_message("okay");
log = [];
conversation.onboarded = true;
localforage.setItem('eatdrinkbot:conversation', conversation);
});
}
}
play(intro_messages, do_introductions);
}
var initialize_pubnub = function() {
var request = new XMLHttpRequest();
request.open('POST', 'http://eatdrink-api.herokuapp.com/api/start', true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
conversation = JSON.parse(request.responseText);
localforage.setItem('eatdrinkbot:conversation', conversation);
onboard();
}
};
request.onerror = function() {};
var message = "message=okay";
request.send(message);
}
var setup_conversation = function(callback) {
var options = options || {};
chatInput.value = 'Connecting...';
chatInput.setAttribute('disabled', true);
chatForm.addEventListener('submit', live_conversation);
pubnub = PUBNUB({
subscribe_key: 'sub-c-af12bf36-bd26-11e5-8a35-0619f8945a4f',
publish_key: 'pub-c-ecfc3624-b442-47ec-a36d-3f4d35d86e83'
});
pubnub.subscribe({
channel: conversation.uid,
message: function(message, env, channel) {
post(message);
},
connect: function() {
chatInput.value = '';
chatInput.removeAttribute('disabled');
chatInput.focus();
console.log("Connected")
if (callback) callback();
},
disconnect: function() {
console.log("Disconnected")
},
reconnect: function() {
console.log("Reconnected")
},
error: function() {
console.log("Network Error")
},
})
}
function live_conversation(e) {
e.preventDefault();
var message = chatInput.value;
// Hack
if (message == 'rs' || message == 'restart') {
localforage.removeItem('eatdrinkbot:history');
localforage.removeItem('eatdrinkbot:conversation');
location.reload();
return;
}
// Hack
chatInput.setAttribute('disabled', true);
post({
type: 'text',
body: message
});
post_message(message, function(response) {
if (response.status >= 200 && response.status < 400) {
chatInput.value = '';
chatInput.removeAttribute('disabled');
chatInput.focus();
}
});
}
function post_message(message, callback) {
if (!message) return;
var payload = "message=" + message + "&uid=" + conversation.uid;
var request = new XMLHttpRequest();
request.open('POST', 'http://eatdrink-api.herokuapp.com/api/message', true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
if (callback) {
request.onload = function() {
callback.call(this, request);
}
}
request.onerror = function() {};
request.send(payload);
}
// if ('serviceWorker' in navigator) {
// navigator.serviceWorker
// .register('./service-worker.js')
// .then(function() { console.log('Service Worker Registered'); });
// }
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment