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

491
LINES

< > BotCompany Repo | #1030642 // FIA Bot Template [LIVE]

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

Author comment

Began life as a copy of #1029632

download  show line numbers   

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

No comments. add comment

Snippet ID: #1030642
Snippet name: FIA Bot Template [LIVE]
Eternal ID of this version: #1030642/26
Text MD5: 4558363712f46c16380edfe51cc99ab2
Author: stefan
Category: javax / web chat bots
Type: Document
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-02-26 14:25:07
Source code size: 17585 bytes / 491 lines
Pitched / IR pitched: No / No
Views / Downloads: 240 / 452
Version history: 25 change(s)
Referenced in: [show references]