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

361
LINES

< > BotCompany Repo | #1031827 // AVOR Demonstrator Template As JavaScript 2021

Document

// runnable: function($)
function dynamicallyLoadJQuery(runnable) {
  console.log("document.jQuery: " + document.jQuery);
  console.log("$: " + (typeof $ === 'undefined' ? "none" : $));
  if (document.jQuery != null)
    jQuery(document).ready(runnable);
  else if (typeof $ !== 'undefined')
    $(document).ready(runnable);
  else {
    console.log("need to load jquery");
    var script = document.createElement("SCRIPT");
    script.src = 'https://code.jquery.com/jquery-1.10.2.js';
    script.type = 'text/javascript';
    script.onload = function() {
      console.log("jquery loaded");
      jQuery(document).ready(runnable);
    };
    document.getElementsByTagName("head")[0].appendChild(script);
  }
}

var chatBot_autoOpen = #AUTOOPEN#;
var chatBot_n = #N#;
var chatBot_interval = 1000;
var chatBot_nInitial = chatBot_n;
var chatBot_showActions = false;
var chatBot_language = "";
var chatBot_started = false;
var chatBot_cookie = localStorage.getItem('chatbot-cookie');

// polyfill for URLSearchParams

(function (w) {
  w.URLSearchParams = w.URLSearchParams || function (searchString) {
      var self = this;
      self.searchString = searchString;
      self.get = function (name) {
          var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(self.searchString);
          if (results == null) {
              return null;
          }
          else {
              return decodeURI(results[1]) || 0;
          }
      };
  }
})(window);

const urlParams = new URLSearchParams(window.location.search);
const botEnable = urlParams.get('bot');
const domain = urlParams.get('_simulateDomain');

// allow cookie override in URL
var cookie2 = urlParams.get('cookie');
if (cookie2) {
  chatBot_cookie = cookie2;
  console.log("Cookie override >> " + cookie2);
}

if (#BOT_ON# || botEnable == "1") {

console.log("cookie 1: " + chatBot_cookie);
if (!chatBot_cookie) {
  chatBot_cookie = Math.random().toString(36).substr(2, 9);
  localStorage.setItem('chatbot-cookie', chatBot_cookie);
  console.log("cookie 2: " + chatBot_cookie);
}

// workaround to get $ from wordpress version of jQuery
dynamicallyLoadJQuery(function ($) {
  console.log("loading 2");
  
  function dynamicallyLoadScript(url) {
    var script = document.createElement("script");
    script.src = url;
    document.head.appendChild(script);
  }
  
  function loadStyleSheet(url, onLoad) {
    var link = document.createElement('link');
    link.setAttribute("rel", "stylesheet");
    link.setAttribute("type", "text/css");
    link.onload = onLoad;
    link.setAttribute("href", url);
    document.head.appendChild(link);
  }
  
  // load fonts & style sheets
  
  loadStyleSheet("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css");
  loadStyleSheet("https://fonts.googleapis.com/css2?family=Roboto:wght@100;300;400;500;700;900&display=swap");
  
  var shouldOpenBot = false, styleSheetLoaded = false;
  
  // bot styles
  loadStyleSheet("https://botcompany.de/serve/#CSS_ID#?ct=text%2Fcss", function() {
    if (!styleSheetLoaded) {
      console.log("style sheet loaded");
      styleSheetLoaded = true;
      $('.chatbot').show(); // show opener
      if (shouldOpenBot) chatBot_actualOpen();
    }
  });

  // scripts for bot
  
  window.chatBot_toggle = function() {
    const chatCommentIcon = document.querySelector(".chat-btn .comment-icon");
    const chatCloseIcon = document.querySelector(".chat-btn .close-icon");
  
    if (chatCloseIcon.classList.contains("hide")) {
      chatCommentIcon.classList.add("hide");
      chatCloseIcon.classList.remove("hide");
      chatBot_open();
    } else {
      chatCloseIcon.classList.add("hide");
      chatCommentIcon .classList.remove("hide");
      $('.chat').removeClass('is-visible');
    }
  }

  function chatBot_open() {
    shouldOpenBot = true;
    if (styleSheetLoaded) chatBot_actualOpen();
  }
  
  function chatBot_actualOpen() {
    console.log("Opening chat bot");
    $('.chat').addClass('is-visible');
    $('#chat_message').focus();
    if (!chatBot_started) {
      chatBot_started = true;
      try {
        if (window.GTranslateGetCurrentLang)
          chatBot_language = window.GTranslateGetCurrentLang();
        console.log("lang: " + chatBot_language);
      } catch (err) {
        console.log(err);
      }

      chatBot_start();
    }
  }
  
  function chatBot_showAction(action) {
    if (chatBot_showActions) {
      $("#actionMsg").html(action);
      $("#actionMsg").show();
    }
    console.log(action);
  }
    
  window.chatBot_appendAction = function(action) {
    if (chatBot_showActions) {
      $("#actionMsg").append(" | " + action);
      $("#actionMsg").show();
    }
  };
  
  window.chatBot_hideAction = function() {
    $("#actionMsg").hide();
    $("#actionMsg").html("");
  };
  
  window.chatBot_start = function() {
    url = "#INCREMENTALURL#";
    if (url != '' && url != ("#INC" + "REMENTALURL#")) {
      url += chatBot_n + "&cookie=" + chatBot_cookie + "&rand=" + Math.random() + (!domain ? "" : "&_simulateDomain=" + encodeURI(domain));
      if (chatBot_language) url += "&language_default=" + chatBot_language;
      chatBot_showAction("Loading " + url);
      $.get(url, function(src) {
        chatBot_showAction("Loaded " + src.length + " chars");
        var match = src.match(/\d+/);
        if (match != null) {
          var newN = parseInt(match[0]);
          if (src.match(/NEW DIALOG -->/))
            $("#chat_converse").html(src);
          else {
            // hide old buttons and special input fields
            $(".chat_buttons, .chat-button-span, .chatbot-choice-button").hide();
            $("#chat_countrycode").removeClass("visible");
            // now append new stuff
            $("#chat_converse").append(src);
          }
          var oldN = chatBot_n;
          chatBot_n = newN;
          $("#chat_converse").scrollTop(1000000);
          chatBot_showAction("Appended " + src.length);
          console.log(src);
          //if (oldN != 0 && newN > oldN) window.playChatNotification();
        } else
          chatBot_showAction("chatBot_n=" + chatBot_n + " (initial=" + chatBot_nInitial + ")");
        chatBot_appendAction("Rescheduling");
        //var interval = src == '' ? chatBot_interval*10 : chatBot_interval; // slowdown when bug
        var interval = chatBot_interval;
        setTimeout(chatBot_start, interval);
        chatBot_appendAction("Rescheduled");
      }, 'text')
        .fail(function() {
          chatBot_showAction("Rescheduling after fail");
          setTimeout(chatBot_start, chatBot_interval);
        });
    }
  };

  // also focuses input field  
  window.chatBot_setInput = function(text, placeholder) {
    if (placeholder == '') placeholder = "Type a message...";
    $('#chat_message').attr('placeholder', placeholder)
      .val(text)
      .select()
      .focus();
  };
  
  window.allowEmptyMsg = false;
  
  window.submitAMsg = function(msg) {
    if (!window.allowEmptyMsg && msg == "") return;
    chat_message.value = msg;
    submitMsg();
  };
  
  window.submitMsg = function() {
    var msg = chat_message.value;
    if ($("#chat_countrycode").hasClass("visible"))
      msg = $("#chat_countrycode").val() + " " + msg;
      
    url = '#MSGURL#' + encodeURIComponent(msg) + "&cookie=" + chatBot_cookie + "&rand=" + Math.random() + (!domain ? "" : "&_simulateDomain=" + encodeURI(domain));
    if (chatBot_language) url += "&language_default=" + chatBot_language;
    chatBot_showAction('Submitting ' + url);
    $.get(url);
    chat_message.value = '';
  };
  
  window.playChatNotification = function() {
    if (window.chatNotificationWav == null) {
      console.log("Loading notification wav");
      window.chatNotificationWav = new Audio("https://botcompany.de/files/1400403/notification.mp3");
      if ("#WORKERMODE" != "true")
        window.chatNotificationWav.volume = 0.5;
    }
    console.log("Playing notification mp3");
    window.chatNotificationWav.play();
  };
  
  var originalTitle;
  
  window.setTitleStatus = function(status) {
    if (originalTitle == null)
      originalTitle = document.title;
    if (!document.hasFocus() || document.activeElement !== document.getElementById('chat_message')) {
      if (status) status = status + " ";
    } else status = "";
    document.title = status + originalTitle;
  };
  
  function resetTitle() {
    window.setTitleStatus("");
  }
  
  window.onfocus = resetTitle;
  $('#chat_message').on("focus", resetTitle);
  
  var sendTyping_sent = 0, sendTyping_interval = 5000;
  window.sendTyping = function() {
    var time = Date.now();
    if (time > sendTyping_sent+sendTyping_interval) {
      sendTyping_sent = time;
      var url = "#TYPINGURL#&cookie=" + chatBot_cookie + "&rand=" + Math.random();
      console.log("Loading " + url);
      $.get(url);
    }
  };
  
  var typingCounter = 0, showTyping_interval = 3000;
  window.showTyping = function() {
    console.log("showTyping " + typingCounter);
    typingCounter++;
    if (typingCounter == 1)
      $('#otherSideTyping').css('display', 'block');
    setTimeout(function() {
      console.log("showTyping end " + typingCounter);
      if (--typingCounter <= 0)
        $('#otherSideTyping').css('display', 'none');
    }, showTyping_interval);
  };
  
  console.log("defined functions");
  
  $('body').append(`

  <div aria-live="polite" aria-atomic="true" aria-relevant="all" id="screenreadertrick"></div>
  <div class="chatbot" style="display: none">
      <div class="chat-box" role="region" aria-labelledby="tchat-label">
          <h1 id="tchat-label" class="sr-only" tabindex="-1">Chat window</h1>
          <div class="chat">
          <div class="main-header">
              <div class="chat_header">
                  <img src="#BOTIMG#" class="header-user">
                  <h2>$HEADING</h2>
                  <button id="" class="fas fa-redo" title="Restart Chat Bot" onclick="submitAMsg('new dialog');"></button>
              </div>
              <div class="header-bottom" style="display: none">
<span class="online">We're online! </span>
</div>
</div>
              <div id="chat_converse" class="chat_conversion chat_converse" tabindex="0" aria-live="polite">
              </div>
              <div id="otherSideTyping" aria-hidden="true" style="display: none">
                  <h4 class="sr-only">#OTHERSIDE# typing</h4>
                  <span class="dot"></span>
                  <span class="dot"></span>
                  <span class="dot"></span>
              </div>
              <div class="chat-bottom">
                  <!--<a class="camera-icon"><i class="fas fa-camera"></i></a>-->
                  <!--<a class="send-icon" title="Send this message" aria-label="Send"><i class="fas fa-paper-plane"></i></a>-->
                  
                  <select name="chat_countrycode" id="chat_countrycode">#COUNTRYCODE_OPTIONS#</select>
                  <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>
                  <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>
              </div>
          </div>
          <!--<a class="chat-icon" title="Open Chat Bot"><button id="chatbot" class="fas fa-comment-dots" title="Open Chat Bot"></button></a>-->
          <a href="#" id="chat-btn" class="chat-btn" title="Open Chat Bot" onclick="chatBot_toggle()">
            <div class="comment-icon">
              <i class="fas fa-comment-dots"></i>
              <i class="fas fa-pencil-alt"></i>
            </div>
            <div class="close-icon hide"><i class="fas fa-times"></i></div>
        </a>

      </div>
  </div>
  `);
  
  // design javascripts
  
  /*$('.chat-icon').click(function() {
    chatBot_open();
  });*/

  // for skip link
  $("a[href='#chatbot']").click(chatBot_open);

  // design javascripts end
  
  //MOREINIT
  
  console.log("done init");
  // onLoad
  if (chatBot_autoOpen) {
    console.log("auto-opening chat bot");
    //window.addEventListener('DOMContentLoaded', chatBot_open, false);
    chatBot_open();
  }
  
  // end of bot scripts
});

} // if botEnable

Author comment

Began life as a copy of #1029809

download  show line numbers   

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

No comments. add comment

Snippet ID: #1031827
Snippet name: AVOR Demonstrator Template As JavaScript 2021
Eternal ID of this version: #1031827/2
Text MD5: 4cd56b12f93748aa45dca16eea92f8d4
Author: stefan
Category: javax / web chat bots
Type: Document
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-07-14 20:00:21
Source code size: 12825 bytes / 361 lines
Pitched / IR pitched: No / No
Views / Downloads: 189 / 164
Version history: 1 change(s)
Referenced in: [show references]