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

347
LINES

< > BotCompany Repo | #1028952 // Exodontia Chat Bot Template As JavaScript [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://botcompany.de/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  
  window.chatBot_toggle = function() {
106  
    const chatCommentIcon = document.querySelector(".chat-btn .comment-icon");
107  
    const chatCloseIcon = document.querySelector(".chat-btn .close-icon");
108  
  
109  
    if (chatCloseIcon.classList.contains("hide")) {
110  
      chatCommentIcon.classList.add("hide");
111  
      chatCloseIcon.classList.remove("hide");
112  
      chatBot_open();
113  
    } else {
114  
      chatCloseIcon.classList.add("hide");
115  
      chatCommentIcon .classList.remove("hide");
116  
      $('.chat').removeClass('is-visible');
117  
    }
118  
  }
119  
120  
  function chatBot_open() {
121  
    shouldOpenBot = true;
122  
    if (styleSheetLoaded) chatBot_actualOpen();
123  
  }
124  
  
125  
  function chatBot_actualOpen() {
126  
    console.log("Opening chat bot");
127  
    $('.chat').addClass('is-visible');
128  
    $('#chat_message').focus();
129  
    if (!chatBot_started) {
130  
      chatBot_started = true;
131  
      try {
132  
        if (window.GTranslateGetCurrentLang)
133  
          chatBot_language = window.GTranslateGetCurrentLang();
134  
        console.log("lang: " + chatBot_language);
135  
      } catch (err) {
136  
        console.log(err);
137  
      }
138  
139  
      chatBot_start();
140  
    }
141  
  }
142  
  
143  
  function chatBot_showAction(action) {
144  
    if (chatBot_showActions) {
145  
      $("#actionMsg").html(action);
146  
      $("#actionMsg").show();
147  
    }
148  
    console.log(action);
149  
  }
150  
    
151  
  window.chatBot_appendAction = function(action) {
152  
    if (chatBot_showActions) {
153  
      $("#actionMsg").append(" | " + action);
154  
      $("#actionMsg").show();
155  
    }
156  
  };
157  
  
158  
  window.chatBot_hideAction = function() {
159  
    $("#actionMsg").hide();
160  
    $("#actionMsg").html("");
161  
  };
162  
  
163  
  window.chatBot_start = function() {
164  
    url = "#INCREMENTALURL#";
165  
    if (url != '' && url != ("#INC" + "REMENTALURL#")) {
166  
      url += chatBot_n + "&cookie=" + chatBot_cookie + "&rand=" + Math.random();
167  
      if (chatBot_language) url += "&language_default=" + chatBot_language;
168  
      chatBot_showAction("Loading " + url);
169  
      $.get(url, function(src) {
170  
        chatBot_showAction("Loaded " + src.length + " chars");
171  
        var match = src.match(/\d+/);
172  
        if (match != null) {
173  
          var newN = parseInt(match[0]);
174  
          if (src.match(/NEW DIALOG -->/))
175  
            $("#chat_converse").html(src);
176  
          else {
177  
            // hide old buttons
178  
            $(".chat_buttons, .chat-button-span, .chatbot-choice-button").hide();
179  
            $("#chat_converse").append(src);
180  
          }
181  
          var oldN = chatBot_n;
182  
          chatBot_n = newN;
183  
          $("#chat_converse").scrollTop(1000000);
184  
          chatBot_showAction("Appended " + src.length);
185  
          console.log(src);
186  
          //if (oldN != 0 && newN > oldN) window.playChatNotification();
187  
        } else
188  
          chatBot_showAction("chatBot_n=" + chatBot_n + " (initial=" + chatBot_nInitial + ")");
189  
        chatBot_appendAction("Rescheduling");
190  
        //var interval = src == '' ? chatBot_interval*10 : chatBot_interval; // slowdown when bug
191  
        var interval = chatBot_interval;
192  
        setTimeout(chatBot_start, interval);
193  
        chatBot_appendAction("Rescheduled");
194  
      }, 'text')
195  
        .fail(function() {
196  
          chatBot_showAction("Rescheduling after fail");
197  
          setTimeout(chatBot_start, chatBot_interval);
198  
        });
199  
    }
200  
  };
201  
202  
  // also focuses input field  
203  
  window.chatBot_setInput = function(text, placeholder) {
204  
    if (placeholder == '') placeholder = "Type a message...";
205  
    $('#chat_message').attr('placeholder', placeholder)
206  
      .val(text)
207  
      .select()
208  
      .focus();
209  
  };
210  
  
211  
  window.allowEmptyMsg = false;
212  
  
213  
  window.submitAMsg = function(msg) {
214  
    if (!window.allowEmptyMsg && msg == "") return;
215  
    chat_message.value = msg;
216  
    submitMsg();
217  
  };
218  
  
219  
  window.submitMsg = function() {
220  
    /*if (chat_message.value == 'new dialog')
221  
      document.forms['msgform'].submit();
222  
    else*/ {
223  
      url = '#MSGURL#' + encodeURIComponent(chat_message.value) + "&cookie=" + chatBot_cookie + "&rand=" + Math.random();
224  
      if (chatBot_language) url += "&language_default=" + chatBot_language;
225  
      chatBot_showAction('Submitting ' + url);
226  
      $.get(url);
227  
      chat_message.value = '';
228  
    }
229  
  };
230  
  
231  
  window.playChatNotification = function() {
232  
    if (window.chatNotificationWav == null) {
233  
      console.log("Loading notification wav");
234  
      window.chatNotificationWav = new Audio("https://botcompany.de/files/1400403/notification.mp3");
235  
      if ("#WORKERMODE" != "true")
236  
        window.chatNotificationWav.volume = 0.5;
237  
    }
238  
    console.log("Playing notification mp3");
239  
    window.chatNotificationWav.play();
240  
  };
241  
  
242  
  var originalTitle;
243  
  
244  
  window.setTitleStatus = function(status) {
245  
    if (originalTitle == null)
246  
      originalTitle = document.title;
247  
    if (!document.hasFocus() || document.activeElement !== document.getElementById('chat_message')) {
248  
      if (status) status = status + " ";
249  
    } else status = "";
250  
    document.title = status + originalTitle;
251  
  };
252  
  
253  
  function resetTitle() {
254  
    window.setTitleStatus("");
255  
  }
256  
  
257  
  window.onfocus = resetTitle;
258  
  $('#chat_message').on("focus", resetTitle);
259  
  
260  
  var sendTyping_sent = 0, sendTyping_interval = 5000;
261  
  window.sendTyping = function() {
262  
    var time = Date.now();
263  
    if (time > sendTyping_sent+sendTyping_interval) {
264  
      sendTyping_sent = time;
265  
      var url = "#TYPINGURL#&cookie=" + chatBot_cookie + "&rand=" + Math.random();
266  
      console.log("Loading " + url);
267  
      $.get(url);
268  
    }
269  
  };
270  
  
271  
  var typingCounter = 0, showTyping_interval = 5000;
272  
  window.showTyping = function() {
273  
    console.log("showTyping " + typingCounter);
274  
    typingCounter++;
275  
    if (typingCounter == 1)
276  
      $('#otherSideTyping').css('display', 'block');
277  
    setTimeout(function() {
278  
      console.log("showTyping end " + typingCounter);
279  
      if (--typingCounter <= 0)
280  
        $('#otherSideTyping').css('display', 'none');
281  
    }, showTyping_interval);
282  
  };
283  
  
284  
  console.log("defined functions");
285  
  
286  
  $('body').append(`
287  
288  
  <div aria-live="polite" aria-atomic="true" aria-relevant="all" id="screenreadertrick"></div>
289  
  <div class="chatbot">
290  
      <div class="chat-box" role="region" aria-labelledby="tchat-label">
291  
          <h1 id="tchat-label" class="sr-only" tabindex="-1">Chat window</h1>
292  
          <div class="chat">
293  
              <div class="chat_header">
294  
                  <h2>$HEADING</h2>
295  
                  <button id="" class="fas fa-redo" title="Restart Chat Bot" onclick="submitAMsg('new dialog');"></button>
296  
              </div>
297  
              <div id="chat_converse" class="chat_conversion chat_converse" tabindex="0" aria-live="polite">
298  
              </div>
299  
              <div id="otherSideTyping" aria-hidden="true" style="display: none">
300  
                  <h4 class="sr-only">#OTHERSIDE# typing</h4>
301  
                  <span class="dot"></span>
302  
                  <span class="dot"></span>
303  
                  <span class="dot"></span>
304  
              </div>
305  
              <div class="chat-bottom">
306  
                  <!--<a class="camera-icon"><i class="fas fa-camera"></i></a>-->
307  
                  <!--<a class="send-icon" title="Send this message" aria-label="Send"><i class="fas fa-paper-plane"></i></a>-->
308  
                  
309  
                  <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>
310  
                  <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>
311  
              </div>
312  
          </div>
313  
          <!--<a class="chat-icon" title="Open Chat Bot"><button id="chatbot" class="fas fa-comment-dots" title="Open Chat Bot"></button></a>-->
314  
          <a href="#" id="chat-btn" class="chat-btn" title="Open Chat Bot" onclick="chatBot_toggle()">
315  
            <div class="comment-icon"><i class="fas fa-comment-dots"></i></div>
316  
            <div class="close-icon hide"><i class="fas fa-times"></i></div>
317  
        </a>
318  
319  
      </div>
320  
  </div>
321  
  `);
322  
  
323  
  // design javascripts
324  
  
325  
  /*$('.chat-icon').click(function() {
326  
    chatBot_open();
327  
  });*/
328  
329  
  // for skip link
330  
  $("a[href='#chatbot']").click(chatBot_open);
331  
332  
  // design javascripts end
333  
  
334  
  //MOREINIT
335  
  
336  
  console.log("done init");
337  
  // onLoad
338  
  if (chatBot_autoOpen) {
339  
    console.log("auto-opening chat bot");
340  
    //window.addEventListener('DOMContentLoaded', chatBot_open, false);
341  
    chatBot_open();
342  
  }
343  
  
344  
  // end of bot scripts
345  
});
346  
347  
} // if botEnable

Author comment

Began life as a copy of #1028282

download  show line numbers   

Travelled to 7 computer(s): bhatertpkbcr, lqnftawlhpir, mqqgnosmbjvj, pyentgdyhuwx, tvejysmllsmz, vouqrxazstgt, xrpafgyirdlv

No comments. add comment

Snippet ID: #1028952
Snippet name: Exodontia Chat Bot Template As JavaScript [LIVE]
Eternal ID of this version: #1028952/7
Text MD5: 59a937496b1a430e18205f67b06b48aa
Author: stefan
Category: javax / web chat bots
Type: Document
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2020-07-14 17:55:33
Source code size: 12008 bytes / 347 lines
Pitched / IR pitched: No / No
Views / Downloads: 204 / 213614
Version history: 6 change(s)
Referenced in: [show references]