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

455
LINES

< > BotCompany Repo | #1029873 // GAIPP Chat Bot Template As JavaScript [backup before emoji picker]

Document

1  
// runnable: function($)
2  
function dynamicallyLoadJQuery(runnable) {
3  
  console.log("document.jQuery: " + document.jQuery);
4  
  console.log("$: " + (typeof $ === 'undefined' ? "none" : $));
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  
var chatBot_notificationsOn = true;
31  
32  
// polyfill for URLSearchParams
33  
34  
(function (w) {
35  
  w.URLSearchParams = w.URLSearchParams || function (searchString) {
36  
      var self = this;
37  
      self.searchString = searchString;
38  
      self.get = function (name) {
39  
          var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(self.searchString);
40  
          if (results == null) {
41  
              return null;
42  
          }
43  
          else {
44  
              return decodeURI(results[1]) || 0;
45  
          }
46  
      };
47  
  }
48  
})(window);
49  
50  
const urlParams = new URLSearchParams(window.location.search);
51  
const botEnable = urlParams.get('bot');
52  
const botConfig = urlParams.get('_botConfig');
53  
54  
// allow cookie override in URL
55  
var cookie2 = urlParams.get('cookie');
56  
if (cookie2) {
57  
  chatBot_cookie = cookie2;
58  
  console.log("Cookie override >> " + cookie2);
59  
}
60  
61  
if (#BOT_ON# || botEnable == "1") {
62  
63  
console.log("cookie 1: " + chatBot_cookie);
64  
if (!chatBot_cookie) {
65  
  chatBot_cookie = Math.random().toString(36).substr(2, 9);
66  
  localStorage.setItem('chatbot-cookie', chatBot_cookie);
67  
  console.log("cookie 2: " + chatBot_cookie);
68  
}
69  
70  
// workaround to get $ from wordpress version of jQuery
71  
dynamicallyLoadJQuery(function ($) {
72  
  console.log("loading 2");
73  
  
74  
  function dynamicallyLoadScript(url, onload) {
75  
    var script = document.createElement("script");
76  
    script.src = url;
77  
    script.onload = onload;
78  
    document.head.appendChild(script);
79  
  }
80  
  
81  
  function loadStyleSheet(url, onLoad) {
82  
    var link = document.createElement('link');
83  
    link.setAttribute("rel", "stylesheet");
84  
    link.setAttribute("type", "text/css");
85  
    link.onload = onLoad;
86  
    link.setAttribute("href", url);
87  
    document.head.appendChild(link);
88  
  }
89  
  
90  
  // load fonts & style sheets
91  
  
92  
  loadStyleSheet("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css");
93  
  loadStyleSheet("https://fonts.googleapis.com/css2?family=Roboto:wght@100;300;400;500;700;900&display=swap");
94  
  
95  
  // intTelInput.min.css
96  
  loadStyleSheet("https://botcompany.de/serve/1029819?ct=text/css");
97  
98  
  // intlTelInput.min.js
99  
  dynamicallyLoadScript("https://botcompany.de/serve/1029820?ct=text/javascript", function() {
100  
    window.telInput = document.querySelector("#chat_telephone");
101  
    console.log("telInput: " + telInput);
102  
    window.telHandler = window.intlTelInput(window.telInput, {
103  
      utilsScript: "https://botcompany.de/serve/1029822?ct=text/javascript", 
104  
      preferredCountries: ["in", "gb"],
105  
      separateDialCode: true,
106  
      initialCountry: "#COUNTRY#"
107  
    });
108  
  });
109  
110  
  loadStyleSheet("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css");
111  
  loadStyleSheet("https://fonts.googleapis.com/css2?family=Roboto:wght@100;300;400;500;700;900&display=swap");
112  
113  
  var shouldOpenBot = false, styleSheetLoaded = false;
114  
  
115  
  // bot styles
116  
  loadStyleSheet("https://botcompany.de/serve/#CSS_ID#?ct=text%2Fcss", function() {
117  
    if (!styleSheetLoaded) {
118  
      console.log("style sheet loaded");
119  
      styleSheetLoaded = true;
120  
      $('.chatbot').show(); // show opener
121  
      if (shouldOpenBot) chatBot_actualOpen();
122  
    }
123  
  });
124  
125  
  // scripts for bot
126  
  
127  
  window.chatBot_toggle = function() {
128  
    const chatCommentIcon = document.querySelector(".chat-btn .comment-icon");
129  
    const chatCloseIcon = document.querySelector(".chat-btn .close-icon");
130  
  
131  
    var openerText;
132  
    if (chatCloseIcon.classList.contains("hide")) {
133  
      chatCommentIcon.classList.add("hide");
134  
      chatCloseIcon.classList.remove("hide");
135  
      chatBot_open();
136  
      openerText = "Close Chat Bot";
137  
    } else {
138  
      chatCloseIcon.classList.add("hide");
139  
      chatCommentIcon .classList.remove("hide");
140  
      $('.chat').removeClass('is-visible');
141  
      openerText = "Open Chat Bot";
142  
    }
143  
    $('.chat-btn').attr("title", openerText);
144  
  }
145  
146  
  function chatBot_open() {
147  
    shouldOpenBot = true;
148  
    if (styleSheetLoaded) chatBot_actualOpen();
149  
  }
150  
  
151  
  function chatBot_actualOpen() {
152  
    console.log("Opening chat bot");
153  
    $('.chat').addClass('is-visible');
154  
    $('#chat_message').focus();
155  
    if (!chatBot_started) {
156  
      chatBot_started = true;
157  
      try {
158  
        if (window.GTranslateGetCurrentLang)
159  
          chatBot_language = window.GTranslateGetCurrentLang();
160  
        console.log("lang: " + chatBot_language);
161  
      } catch (err) {
162  
        console.log(err);
163  
      }
164  
165  
      chatBot_start();
166  
    }
167  
  }
168  
  
169  
  function chatBot_showAction(action) {
170  
    console.log(action);
171  
  }
172  
    
173  
  window.chatBot_appendAction = function(action) {
174  
  };
175  
  
176  
  window.chatBot_hideAction = function() {
177  
  };
178  
  
179  
  function standardParams() {
180  
    return "&cookie=" + chatBot_cookie + "&rand=" + Math.random() + (!botConfig ? "" : "&_botConfig=" + encodeURIComponent(botConfig));
181  
  }
182  
  
183  
  window.chatBot_start = function() {
184  
    url = "#INCREMENTALURL#";
185  
    if (url != '' && url != ("#INC" + "REMENTALURL#")) {
186  
      url += chatBot_n + standardParams();
187  
      if (chatBot_language) url += "&language_default=" + chatBot_language;
188  
      chatBot_showAction("Loading " + url);
189  
      $.get(url, function(src) {
190  
        chatBot_showAction("Loaded " + src.length + " chars");
191  
        var match = src.match(/\d+/);
192  
        if (match != null) {
193  
          var newN = parseInt(match[0]);
194  
          if (src.match(/NEW DIALOG -->/))
195  
            $("#chat_converse").html(src);
196  
          else {
197  
            // hide old buttons and special input fields
198  
            $(".chat_buttons, .chat-button-span, .chatbot-choice-button").hide();
199  
            $("#chat_telephone, .iti").hide();
200  
            $("#chat_message").show();
201  
            // now append new stuff
202  
            $("#chat_converse").append(src);
203  
          }
204  
          var oldN = chatBot_n;
205  
          chatBot_n = newN;
206  
          $("#chat_converse").scrollTop(1000000);
207  
          chatBot_showAction("Appended " + src.length);
208  
          console.log(src);
209  
        } else
210  
          chatBot_showAction("chatBot_n=" + chatBot_n + " (initial=" + chatBot_nInitial + ")");
211  
        chatBot_appendAction("Rescheduling");
212  
        //var interval = src == '' ? chatBot_interval*10 : chatBot_interval; // slowdown when bug
213  
        var interval = chatBot_interval;
214  
        setTimeout(chatBot_start, interval);
215  
        chatBot_appendAction("Rescheduled");
216  
      }, 'text')
217  
        .fail(function() {
218  
          chatBot_showAction("Rescheduling after fail");
219  
          setTimeout(chatBot_start, chatBot_interval);
220  
        });
221  
    }
222  
  };
223  
224  
  // also focuses input field  
225  
  window.chatBot_setInput = function(text, placeholder) {
226  
    if (placeholder == '') placeholder = "Type a message...";
227  
    if (text)
228  
      $('#chat_message').val(text);
229  
    $('#chat_message').attr('placeholder', placeholder)
230  
      .select()
231  
      .focus();
232  
  };
233  
  
234  
  window.allowEmptyMsg = false;
235  
  
236  
  window.submitAMsg = function(msg) {
237  
    if (!window.allowEmptyMsg && msg == "") return;
238  
    chat_message.value = msg;
239  
    submitMsg();
240  
  };
241  
  
242  
  window.submitMsg = function() {
243  
    var msg = chat_message.value;
244  
    
245  
    if ($("#chat_telephone").is(":visible") && !/^!/.test(msg))
246  
      msg = window.telHandler.getNumber();
247  
248  
    url = '#MSGURL#' + encodeURIComponent(msg) + standardParams();
249  
    if (chatBot_language) url += "&language_default=" + chatBot_language;
250  
    chatBot_showAction('Submitting ' + url);
251  
    $.get(url);
252  
    chat_message.value = '';
253  
  };
254  
  
255  
  window.playChatNotification = function() {
256  
    if (window.chatNotificationWav == null) {
257  
      console.log("Loading notification wav");
258  
      window.chatNotificationWav = new Audio("https://botcompany.de/files/1400403/notification.mp3");
259  
      if ("#WORKERMODE" != "true")
260  
        window.chatNotificationWav.volume = 0.5;
261  
    }
262  
    console.log("Playing notification mp3");
263  
    window.chatNotificationWav.play();
264  
  };
265  
  
266  
  var originalTitle;
267  
  
268  
  window.setTitleStatus = function(status) {
269  
    if (originalTitle == null)
270  
      originalTitle = document.title;
271  
    if (!document.hasFocus() || document.activeElement !== document.getElementById('chat_message')) {
272  
      if (status) status = status + " ";
273  
    } else status = "";
274  
    document.title = status + originalTitle;
275  
  };
276  
  
277  
  function resetTitle() {
278  
    window.setTitleStatus("");
279  
  }
280  
  
281  
  window.onfocus = resetTitle;
282  
  $('#chat_message').on("focus", resetTitle);
283  
  
284  
  var sendTyping_sent = 0, sendTyping_interval = 5000;
285  
  window.sendTyping = function() {
286  
    var time = Date.now();
287  
    if (time > sendTyping_sent+sendTyping_interval) {
288  
      sendTyping_sent = time;
289  
      var url = "#TYPINGURL#" + standardParams();
290  
      console.log("Loading " + url);
291  
      $.get(url);
292  
    }
293  
  };
294  
  
295  
  window.notiToggle = function() {
296  
    submitAMsg('!toggle notifications');
297  
    var text = $("#chatBot_notiToggleText");
298  
    text.text("Turn " + (/Turn on/.test(text.text()) ? "off" : "on") + " notifications");
299  
  };
300  
  
301  
  var typingCounter = 0, showTyping_interval = 3000;
302  
  window.showTyping = function() {
303  
    console.log("showTyping " + typingCounter);
304  
    typingCounter++;
305  
    if (typingCounter == 1)
306  
      $('#otherSideTyping').css('display', 'block');
307  
    setTimeout(function() {
308  
      console.log("showTyping end " + typingCounter);
309  
      if (--typingCounter <= 0)
310  
        $('#otherSideTyping').css('display', 'none');
311  
    }, showTyping_interval);
312  
  };
313  
  
314  
  window.chat_keyDown = function(event) {
315  
    if (event.keyCode == 13) { submitMsg(); return false; }   
316  
    else if (event.keyCode >= 32 && event.keyCode < 128) sendTyping();
317  
  };
318  
  
319  
  console.log("defined functions");
320  
  
321  
  $('body').append(`
322  
323  
  <div aria-live="polite" aria-atomic="true" aria-relevant="all" id="screenreadertrick"></div>
324  
  <div class="chatbot" style="display: none">
325  
      <div class="chat-box" role="region" aria-labelledby="tchat-label">
326  
          <h1 id="tchat-label" class="sr-only" tabindex="-1">Chat window</h1>
327  
          <div class="chat">
328  
          <div class="main-header">
329  
              <div class="chat_header">
330  
              <div class="four-people" style="
331  
                ">
332  
                <div class="users user-1"></div>
333  
                <div class="users user-2"></div>
334  
                <div class="users user-3"></div>
335  
                <div class="users user-4"></div>
336  
                
337  
                </div>
338  
                  <img src="#BOTIMG#" class="header-user">
339  
                  <h2>$HEADING</h2>
340  
                  <div class="buttons">
341  
                  <!--<button class="fas fa-ellipsis-v"></button>-->
342  
                  <label class="head-dropdown">
343  
                    <div class="head-button">
344  
                      <i class="fas fa-ellipsis-v"></i>
345  
                    </div>
346  
                  
347  
                    <input type="checkbox" class="head-input" id="test">
348  
                  
349  
                    <ul class="head-menu">
350  
                      <li onclick="notiToggle()"><i class="far fa-bell-slash"></i><span id="chatBot_notiToggleText">Turn off notifications</span></li>
351  
                      <li onclick="submitAMsg('!rate conversation')"><i class="fas fa-star"></i>Rate this conversation</li>
352  
                    </ul>
353  
                    
354  
                  </label>
355  
                  <button id="" class="fas fa-chevron-down" title="Close Chat Bot" onclick="chatBot_toggle()"></button>
356  
                  </div>
357  
              </div>
358  
              <div class="header-bottom">
359  
<span class="online">We're online! </span>
360  
<div class="bot-restart" style="">
361  
<button class="fas fa-sync-alt" onclick="submitAMsg('!new dialog')"></button>
362  
</div>
363  
</div>
364  
</div>
365  
              <div id="chat_converse" class="chat_conversion chat_converse" tabindex="0" aria-live="polite">
366  
              <div class="bot-questions">
367  
<div class="question-title">
368  
    <h4>Choose the below answer</h4>
369  
</div>
370  
    <div class="all-options">
371  
        <a href="#" class="option-single">Training for Students</a>
372  
        <a href="#" class="option-single"> Training for Working Professionals
373  
374  
</a>
375  
        <a href="#" class="option-single"> Training for Business
376  
377  
</a>
378  
        <a href="#" class="option-single"> Training for Entrepreneurs
379  
380  
</a>
381  
    </div>
382  
</div>
383  
              </div>
384  
              <div id="otherSideTyping" aria-hidden="true" style="display: none">
385  
                  <h4 class="sr-only">#OTHERSIDE# typing</h4>
386  
                  <span class="dot"></span>
387  
                  <span class="dot"></span>
388  
                  <span class="dot"></span>
389  
              </div>
390  
              <div class="chat-bottom">
391  
                  <!--<a class="camera-icon"><i class="fas fa-camera"></i></a>-->
392  
                  <!--<a class="send-icon" title="Send this message" aria-label="Send"><i class="fas fa-paper-plane"></i></a>-->
393  
                  
394  
                  <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="return chat_keyDown(event);"></textarea>
395  
                  <input type="tel" id="chat_telephone" style="display: none" onkeydown="return chat_keyDown(event);">
396  
397  
                  <div class="footer-bottom">
398  
                    <ul>
399  
        <li>
400  
    <a href="#" class="play-icon"><i class="fa fa-play"></i></a>
401  
        </li>
402  
<li>
403  
    <a href="#"><i class="far fa-smile-beam"></i></a>
404  
        </li>
405  
<li>
406  
    <a href="#"><i class="fas fa-paperclip"></i></a>
407  
        </li>
408  
<li class="powered-by">
409  
    Powered By
410  
    <a href="http://gaippbots.com/"> <img src="https://gaippbots.com/bot/uploaded-image/146135"></a>
411  
        </li>
412  
413  
414  
    </ul>
415  
                  </div>
416  
                  <!--<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>-->
417  
              </div>
418  
          </div>
419  
          <a href="#" id="chat-btn" class="chat-btn" title="Open Chat Bot" onclick="chatBot_toggle()">
420  
            <div class="comment-icon">
421  
              <i class="fas fa-comment-dots"></i>
422  
              <i class="fas fa-pencil-alt"></i>
423  
            </div>
424  
            <div class="close-icon hide"><i class="fas fa-paper-plane"></i></div>
425  
        </a>
426  
427  
      </div>
428  
  </div>
429  
  `);
430  
  
431  
  // design javascripts
432  
  
433  
  /*$('.chat-icon').click(function() {
434  
    chatBot_open();
435  
  });*/
436  
437  
  // for skip link
438  
  $("a[href='#chatbot']").click(chatBot_open);
439  
440  
  // design javascripts end
441  
  
442  
  //MOREINIT
443  
  
444  
  console.log("done init");
445  
  // onLoad
446  
  if (chatBot_autoOpen) {
447  
    console.log("auto-opening chat bot");
448  
    //window.addEventListener('DOMContentLoaded', chatBot_open, false);
449  
    chatBot_open();
450  
  }
451  
  
452  
  // end of bot scripts
453  
});
454  
455  
} // if botEnable

Author comment

Began life as a copy of #1029632

download  show line numbers   

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

No comments. add comment

Snippet ID: #1029873
Snippet name: GAIPP Chat Bot Template As JavaScript [backup before emoji picker]
Eternal ID of this version: #1029873/1
Text MD5: 567e098f5a87d495d56a27ed2ed584c3
Author: stefan
Category: javax / web chat bots
Type: Document
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2020-09-24 14:15:49
Source code size: 15942 bytes / 455 lines
Pitched / IR pitched: No / No
Views / Downloads: 117 / 61
Referenced in: [show references]