Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

372
LINES

< > BotCompany Repo | #1030242 // ADAptive Chat Bot Template As JavaScript [with text opener, LIVE]

Document

1  
// runnable: function($)
2  
function dynamicallyLoadJQuery(runnable) {
3  
  console.log("document.jQuery: " + document.jQuery);
4  
  console.log("$: " + $);
5  
  if (document.jQuery != null)
6  
    jQuery(document).ready(runnable);
7  
  else if (typeof $ !== 'undefined')
8  
    $(document).ready(runnable);
9  
  else {
10  
    console.log("need to load jquery");
11  
    var script = document.createElement("SCRIPT");
12  
    script.src = 'https://code.jquery.com/jquery-1.10.2.js';
13  
    script.type = 'text/javascript';
14  
    script.onload = function() {
15  
      console.log("jquery loaded");
16  
      jQuery(document).ready(runnable);
17  
    };
18  
    document.getElementsByTagName("head")[0].appendChild(script);
19  
  }
20  
}
21  
22  
var chatBot_autoOpen = #AUTOOPEN#;
23  
var chatBot_n = #N#;
24  
var chatBot_interval = 1000;
25  
var chatBot_nInitial = chatBot_n;
26  
var chatBot_showActions = false;
27  
var chatBot_language = "";
28  
var chatBot_started = false;
29  
var chatBot_cookie = localStorage.getItem('chatbot-cookie');
30  
31  
// polyfill for URLSearchParams
32  
33  
(function (w) {
34  
  w.URLSearchParams = w.URLSearchParams || function (searchString) {
35  
      var self = this;
36  
      self.searchString = searchString;
37  
      self.get = function (name) {
38  
          var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(self.searchString);
39  
          if (results == null) {
40  
              return null;
41  
          }
42  
          else {
43  
              return decodeURI(results[1]) || 0;
44  
          }
45  
      };
46  
  }
47  
})(window);
48  
49  
const urlParams = new URLSearchParams(window.location.search);
50  
const botEnable = urlParams.get('bot');
51  
52  
// allow cookie override in URL
53  
var cookie2 = urlParams.get('cookie');
54  
if (cookie2) {
55  
  chatBot_cookie = cookie2;
56  
  console.log("Cookie override >> " + cookie2);
57  
}
58  
59  
if (#BOT_ON# || botEnable == "1") {
60  
61  
console.log("cookie 1: " + chatBot_cookie);
62  
if (!chatBot_cookie) {
63  
  chatBot_cookie = Math.random().toString(36).substr(2, 9);
64  
  localStorage.setItem('chatbot-cookie', chatBot_cookie);
65  
  console.log("cookie 2: " + chatBot_cookie);
66  
}
67  
68  
// workaround to get $ from wordpress version of jQuery
69  
dynamicallyLoadJQuery(function ($) {
70  
  console.log("loading 2");
71  
  
72  
  function dynamicallyLoadScript(url) {
73  
    var script = document.createElement("script");
74  
    script.src = url;
75  
    document.head.appendChild(script);
76  
  }
77  
  
78  
  function loadStyleSheet(url, onLoad) {
79  
    var link = document.createElement('link');
80  
    link.setAttribute("rel", "stylesheet");
81  
    link.setAttribute("type", "text/css");
82  
    link.onload = onLoad;
83  
    link.setAttribute("href", url);
84  
    document.head.appendChild(link);
85  
  }
86  
  
87  
  // load fonts & style sheets
88  
  
89  
  loadStyleSheet("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css");
90  
  loadStyleSheet("https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800&display=swap");
91  
  
92  
  var shouldOpenBot = false, styleSheetLoaded = false;
93  
  
94  
  // bot styles
95  
  loadStyleSheet("https://adaptivechatbot.com/serve/#CSS_ID#?ct=text%2Fcss", function() {
96  
    if (!styleSheetLoaded) {
97  
      console.log("style sheet loaded");
98  
      styleSheetLoaded = true;
99  
      if (shouldOpenBot) chatBot_actualOpen();
100  
    }
101  
  });
102  
103  
  // scripts for bot
104  
  
105  
  function chatBot_open() {
106  
    shouldOpenBot = true;
107  
    if (styleSheetLoaded) chatBot_actualOpen();
108  
  }
109  
  
110  
  function chatBot_actualOpen() {
111  
    console.log("Opening chat bot");
112  
    toggleFab();
113  
    //$("#chat_converse").scrollTop(1000000);
114  
    $('#chat_message').focus();
115  
    if (!chatBot_started) {
116  
      chatBot_started = true;
117  
      try {
118  
        if (window.GTranslateGetCurrentLang)
119  
          chatBot_language = window.GTranslateGetCurrentLang();
120  
        console.log("lang: " + chatBot_language);
121  
      } catch (err) {
122  
        console.log(err);
123  
      }
124  
125  
      chatBot_start();
126  
    }
127  
  }
128  
  
129  
  $(function(){
130  
    $(".chatOpenAction").click(function () {
131  
      chatBot_open();
132  
      return false;
133  
    });
134  
      
135  
    $(".chatCloseAction").click(function () {
136  
      $('.opener-box').show();
137  
      $('#qnimate').removeClass('popup-box-on');
138  
      return false;
139  
    });
140  
  });
141  
  
142  
  function chatBot_showAction(action) {
143  
    if (chatBot_showActions) {
144  
      $("#actionMsg").html(action);
145  
      $("#actionMsg").show();
146  
    }
147  
    console.log(action);
148  
  }
149  
    
150  
  window.chatBot_appendAction = function(action) {
151  
    if (chatBot_showActions) {
152  
      $("#actionMsg").append(" | " + action);
153  
      $("#actionMsg").show();
154  
    }
155  
  };
156  
  
157  
  window.chatBot_hideAction = function() {
158  
    $("#actionMsg").hide();
159  
    $("#actionMsg").html("");
160  
  };
161  
  
162  
  window.chatBot_start = function() {
163  
    url = "#INCREMENTALURL#";
164  
    if (url != '' && url != ("#INC" + "REMENTALURL#")) {
165  
      url += chatBot_n + "&cookie=" + chatBot_cookie + "&rand=" + Math.random();
166  
      if (chatBot_language) url += "&language_default=" + chatBot_language;
167  
      chatBot_showAction("Loading " + url);
168  
      $.get(url, function(src) {
169  
        chatBot_showAction("Loaded " + src.length + " chars");
170  
        var match = src.match(/\d+/);
171  
        if (match != null) {
172  
          var newN = parseInt(match[0]);
173  
          if (src.match(/NEW DIALOG -->/))
174  
            $("#chat_converse").html(src);
175  
          else {
176  
            // hide old buttons
177  
            $(".chat_buttons, .chat-button-span, .chatbot-choice-button").hide();
178  
            $("#chat_converse").append(src);
179  
          }
180  
          var oldN = chatBot_n;
181  
          chatBot_n = newN;
182  
          $("#chat_converse").scrollTop(1000000);
183  
          chatBot_showAction("Appended " + src.length);
184  
          console.log(src);
185  
          //if (oldN != 0 && newN > oldN) window.playChatNotification();
186  
        } else
187  
          chatBot_showAction("chatBot_n=" + chatBot_n + " (initial=" + chatBot_nInitial + ")");
188  
        chatBot_appendAction("Rescheduling");
189  
        //var interval = src == '' ? chatBot_interval*10 : chatBot_interval; // slowdown when bug
190  
        var interval = chatBot_interval;
191  
        setTimeout(chatBot_start, interval);
192  
        chatBot_appendAction("Rescheduled");
193  
      }, 'text')
194  
        .fail(function() {
195  
          chatBot_showAction("Rescheduling after fail");
196  
          setTimeout(chatBot_start, chatBot_interval);
197  
        });
198  
    }
199  
  };
200  
201  
  // also focuses input field  
202  
  window.chatBot_setInput = function(text, placeholder) {
203  
    if (placeholder == '') placeholder = "Type a message...";
204  
    $('#chat_message')
205  
      .attr('placeholder', placeholder);
206  
    if (text)
207  
      $('#chat_message').val(text).select().focus();
208  
  };
209  
  
210  
  window.allowEmptyMsg = false;
211  
  
212  
  window.submitAMsg = function(msg) {
213  
    if (!window.allowEmptyMsg && msg == "") return;
214  
    chat_message.value = msg;
215  
    submitMsg();
216  
  };
217  
  
218  
  window.submitMsg = function() {
219  
    /*if (chat_message.value == 'new dialog')
220  
      document.forms['msgform'].submit();
221  
    else*/ {
222  
      url = '#MSGURL#' + encodeURIComponent(chat_message.value) + "&cookie=" + chatBot_cookie + "&rand=" + Math.random();
223  
      if (chatBot_language) url += "&language_default=" + chatBot_language;
224  
      chatBot_showAction('Submitting ' + url);
225  
      $.get(url);
226  
      chat_message.value = '';
227  
    }
228  
  };
229  
  
230  
  window.playChatNotification = function() {
231  
    if (window.chatNotificationWav == null) {
232  
      console.log("Loading notification wav");
233  
      window.chatNotificationWav = new Audio("https://adaptivechatbot.com/1028300/notification.mp3");
234  
      if ("#WORKERMODE" != "true")
235  
        window.chatNotificationWav.volume = 0.5;
236  
    }
237  
    console.log("Playing notification mp3");
238  
    window.chatNotificationWav.play();
239  
  };
240  
  
241  
  var originalTitle;
242  
  
243  
  window.setTitleStatus = function(status) {
244  
    if (originalTitle == null)
245  
      originalTitle = document.title;
246  
    if (!document.hasFocus() || document.activeElement !== document.getElementById('chat_message')) {
247  
      if (status) status = status + " ";
248  
    } else status = "";
249  
    document.title = status + originalTitle;
250  
  };
251  
  
252  
  function resetTitle() {
253  
    window.setTitleStatus("");
254  
  }
255  
  
256  
  window.onfocus = resetTitle;
257  
  $('#chat_message').on("focus", resetTitle);
258  
  
259  
  var sendTyping_sent = 0, sendTyping_interval = 5000;
260  
  window.sendTyping = function() {
261  
    var time = Date.now();
262  
    if (time > sendTyping_sent+sendTyping_interval) {
263  
      sendTyping_sent = time;
264  
      var url = "#TYPINGURL#&cookie=" + chatBot_cookie + "&rand=" + Math.random();
265  
      console.log("Loading " + url);
266  
      $.get(url);
267  
    }
268  
  };
269  
  
270  
  var typingCounter = 0, showTyping_interval = 5000;
271  
  window.showTyping = function() {
272  
    console.log("showTyping " + typingCounter);
273  
    typingCounter++;
274  
    if (typingCounter == 1)
275  
      $('#otherSideTyping').css('display', 'block');
276  
    setTimeout(function() {
277  
      console.log("showTyping end " + typingCounter);
278  
      if (--typingCounter <= 0)
279  
        $('#otherSideTyping').css('display', 'none');
280  
    }, showTyping_interval);
281  
  };
282  
  
283  
  console.log("defined functions");
284  
  
285  
  $('body').append(`
286  
287  
  <div aria-live="polite" aria-atomic="true" aria-relevant="all" id="screenreadertrick"></div>
288  
  <div class="chatbot">
289  
      <div class="chat-box" role="region" aria-labelledby="tchat-label">
290  
          <h2 id="tchat-label" class="sr-only" tabindex="-1">Chat window</h2>
291  
          <div class="chat">
292  
              <div class="chat_header">
293  
                  <h3>$HEADING</h3>
294  
              </div>
295  
              <div id="chat_converse" class="chat_conversion chat_converse" tabindex="0" aria-live="polite">
296  
              </div>
297  
              <div id="otherSideTyping" aria-hidden="true" style="display: none">
298  
                  <h4 class="sr-only">#OTHERSIDE# typing</h4>
299  
                  <span class="dot"></span>
300  
                  <span class="dot"></span>
301  
                  <span class="dot"></span>
302  
              </div>
303  
              <div class="chat-bottom">
304  
305  
                  <textarea id="chat_message" class="chat_field chat_message" title="Message to send" aria-label="message to send" placeholder="Type a message..." rows="10" cols="30" name="message" onkeydown="if (event.keyCode == 13) { submitMsg(); return false; } else if (event.keyCode >= 32 && event.keyCode < 128) sendTyping();"></textarea>
306  
                  <!--<a class="send-icon" title="Send this message" aria-label="Send"><button class="fas fa-paper-plane" title="Send this message" onclick="submitMsg()"></button></a>-->
307  
                  <div class="send-icon"><button class="fas fa-paper-plane" title="Send this message" onclick="submitMsg()"></button></div>
308  
              </div>
309  
          </div>
310  
          <!--<a class="chat-icon" title="Open Chat Bot"><button id="chatbot" class="fas fa-comment-dots" title="Open Chat Bot"></button></a>-->
311  
          <button class="chat-contact">
312  
<span class="for-desk">Chat with an expert now</span>
313  
<span class="for-mobile">Chat now</span>
314  
</button>
315  
316  
          <div class="chat-icon"><button id="chatbot" class="fas fa-comment-dots" title="Open Chat Bot"></button></div>
317  
      </div>
318  
  </div>
319  
  `);
320  
  
321  
  // design javascripts
322  
  
323  
  hideChat(0);
324  
325  
  $('.chat-icon').click(function() {
326  
    chatBot_open();
327  
  });
328  
  $('.chat-contact').click(function() {
329  
    chatBot_open();
330  
  });
331  
332  
  //Toggle chat and links
333  
  function toggleFab() {
334  
      $('.chat-icon i, .chat-icon button').toggleClass('fa-comment-dots');
335  
      $('.chat-icon i, .chat-icon button').toggleClass('fa-times');
336  
      $('.chat-icon i, .chat-icon button').toggleClass('is-active');
337  
      $('.chat-icon button').toggleClass('is-visible');
338  
      
339  
      var text = $('.chat-icon button').hasClass('is-visible') ? "Close chat bot" : "Open chat bot";
340  
      $('.chat-icon button').attr("title", text);
341  
      $('.chat-icon').toggleClass('is-float');
342  
      $('.chat').toggleClass('is-visible');
343  
      $('.fab').toggleClass('is-visible');
344  
  }
345  
346  
  function hideChat(hide) {
347  
      switch (hide) {
348  
      case 1:
349  
          $('#chat_converse').css('display', 'block');
350  
          break;
351  
      }
352  
  }
353  
354  
  // for skip link
355  
  $("a[href='#chatbot']").click(function() { chatBot_open(); return false; });
356  
357  
  // design javascripts end
358  
  
359  
  //MOREINIT
360  
  
361  
  console.log("done init");
362  
  // onLoad
363  
  if (chatBot_autoOpen) {
364  
    console.log("auto-opening chat bot");
365  
    //window.addEventListener('DOMContentLoaded', chatBot_open, false);
366  
    chatBot_open();
367  
  }
368  
  
369  
  // end of bot scripts
370  
});
371  
372  
} // if botEnable

Author comment

Began life as a copy of #1028982

download  show line numbers   

Travelled to 5 computer(s): bhatertpkbcr, djztyncnmsck, mqqgnosmbjvj, pyentgdyhuwx, vouqrxazstgt

No comments. add comment

Snippet ID: #1030242
Snippet name: ADAptive Chat Bot Template As JavaScript [with text opener, LIVE]
Eternal ID of this version: #1030242/12
Text MD5: 53121b541d1e15d02b480b8129ce1f61
Author: husain
Category: javax / web chat bots
Type: Document
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2020-12-07 16:34:37
Source code size: 12512 bytes / 372 lines
Pitched / IR pitched: No / No
Views / Downloads: 304 / 289
Version history: 11 change(s)
Referenced in: [show references]