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

489
LINES

< > BotCompany Repo | #1029632 // GAIPP Chat Bot Template As JavaScript [LIVE]

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');
var chatBot_notificationsOn = true;

// 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 botConfig = urlParams.get('_botConfig');

// 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 ($) {
  // from here on we have JQuery
  console.log("loading 2");
  
  // helper for inserting emojis

  $.fn.insertIntoTextArea = function(textToInsert) {
    return this.each(function () {
      var txt = $(this);
      var cursorPosStart = txt.prop('selectionStart');
      var cursorPosEnd = txt.prop('selectionEnd');
      var v = txt.val();
      var textBefore = v.substring(0,  cursorPosStart);
      var textAfter  = v.substring(cursorPosEnd, v.length);
      txt.val(textBefore + textToInsert + textAfter);
      txt.prop('selectionStart', cursorPosStart + textToInsert.length);
      txt.prop('selectionEnd', cursorPosStart + textToInsert.length);
      txt.focus();
    });
  };

  function dynamicallyLoadScript(url, onload, asModule) {
    var script = document.createElement("script");
    script.src = url;
    script.onload = onload;
    if (asModule) script.type = "module";
    document.head.appendChild(script);
  }
  
  function dynamicallyLoadModule(code) {
    var script = document.createElement("script");
    script.type = "module";
    script.appendChild(document.createTextNode(code));
    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");
  
  // intTelInput.min.css
  loadStyleSheet("https://botcompany.de/serve/1029819?ct=text/css");

  // intlTelInput.min.js
  dynamicallyLoadScript("https://botcompany.de/serve/1029820?ct=text/javascript", function() {
    window.telInput = document.querySelector("#chat_telephone");
    console.log("telInput: " + telInput);
    window.telHandler = window.intlTelInput(window.telInput, {
      utilsScript: "https://botcompany.de/serve/1029822?ct=text/javascript", 
      preferredCountries: ["in", "gb"],
      separateDialCode: true,
      initialCountry: "#COUNTRY#"
    });
  });

  dynamicallyLoadScript("https://gaippbots.com/bot/emoji-picker/index.js", function() {
    console.log("emoji picker loaded");
    
    dynamicallyLoadModule(`
      import { EmojiButton } from "https://gaippbots.com/bot/emoji-picker/index.js";
  
      const picker = new EmojiButton();
      const trigger = document.querySelector('#bot-emoji-trigger');
  
      picker.on('emoji', selection => {
        console.log(selection.emoji);
        $("#chat_message").insertIntoTextArea(selection.emoji);
        setTimeout(function() {
          $("#chat_message").focus();
        }, 250);
      });
  
      trigger.addEventListener('click', () => picker.togglePicker(trigger));
    `);
  }, true);
  
  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_isOpen = function() {
    const chatCloseIcon = document.querySelector(".chat-btn .close-icon");
    return !chatCloseIcon.classList.contains("hide");
  }
  
  window.chatBot_toggle = function() {
    const chatCommentIcon = document.querySelector(".chat-btn .comment-icon");
    const chatCloseIcon = document.querySelector(".chat-btn .close-icon");
  
    var openerText;
    if (!chatBot_isOpen()) {
      chatCommentIcon.classList.add("hide");
      chatCloseIcon.classList.remove("hide");
      chatBot_open();
      openerText = "Send Message";
    } else {
      chatCloseIcon.classList.add("hide");
      chatCommentIcon .classList.remove("hide");
      $('.chat').removeClass('is-visible');
      openerText = "Open Chat Bot";
    }
    $('.chat-btn').attr("title", openerText);
  }

  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) {
    console.log(action);
  }
    
  window.chatBot_appendAction = function(action) {
  };
  
  window.chatBot_hideAction = function() {
  };
  
  function standardParams() {
    return "&cookie=" + chatBot_cookie + "&rand=" + Math.random() + (!botConfig ? "" : "&_botConfig=" + encodeURIComponent(botConfig));
  }
  
  window.chatBot_start = function() {
    var url = "#INCREMENTALURL#";
    if (url != '' && url != ("#INC" + "REMENTALURL#")) {
      url += chatBot_n + standardParams();
      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_telephone, .iti").hide();
            $("#chat_message").show();
            // 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);
        } 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);
    if (text)
      $('#chat_message').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_telephone").is(":visible") && !/^!/.test(msg))
      msg = window.telHandler.getNumber();

    var url = '#MSGURL#' + encodeURIComponent(msg) + standardParams();
    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("#NOTIFICATIONSOUND#");
      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#" + standardParams();
      console.log("Loading " + url);
      $.get(url);
    }
  };
  
  window.notiToggle = function() {
    submitAMsg('!toggle notifications');
    var text = $("#chatBot_notiToggleText");
    text.text("Turn " + (/Turn on/.test(text.text()) ? "off" : "on") + " notifications");
  };
  
  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);
  };
  
  window.chat_keyDown = function(event) {
    if (event.keyCode == 13) { submitMsg(); return false; }   
    else if (event.keyCode >= 32 && event.keyCode < 128) sendTyping();
  };
  
  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">
              <div class="four-people" style="
                ">
                <div class="users user-1"></div>
                <div class="users user-2"></div>
                <div class="users user-3"></div>
                <div class="users user-4"></div>
                
                </div>
                  <img src="#BOTIMG#" class="header-user">
                  <h2>$HEADING</h2>
                  <div class="buttons">
                  <!--<button class="fas fa-ellipsis-v"></button>-->
                  <label class="head-dropdown">
                    <div class="head-button">
                      <i class="fas fa-ellipsis-v"></i>
                    </div>
                  
                    <input type="checkbox" class="head-input" id="test">
                  
                    <ul class="head-menu">
                      <li onclick="notiToggle()"><i class="far fa-bell-slash"></i><span id="chatBot_notiToggleText">Turn off notifications</span></li>
                      <li onclick="submitAMsg('!rate conversation')"><i class="fas fa-star"></i>Rate this conversation</li>
                    </ul>
                    
                  </label>
                  <button id="" class="fas fa-chevron-down" title="Close Chat Bot" onclick="chatBot_toggle()"></button>
                  </div>
              </div>
              <div class="header-bottom">
<span class="online">We're online! </span>
<!--<div class="bot-restart" style="">
<button class="fas fa-sync-alt" onclick="submitAMsg('!new dialog')"></button>
</div>-->
</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>-->
                  
                  <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>
                  <input type="tel" id="chat_telephone" style="display: none" onkeydown="return chat_keyDown(event);">

                  <div class="footer-bottom">
                    <ul>
        <li>
    <a href="#" onclick="submitAMsg('!new dialog'); return false;" class="play-icon" title="Restart Chat Bot"><i class="fa fa-play"></i></a>
        </li>
<li>
    <a href="#" id="bot-emoji-trigger"><i class="far fa-smile-beam"></i></a>
        </li> 
<li>
    <!--<a href="#"><i class="fas fa-paperclip"></i></a>
        </li>-->
<li class="powered-by">
    Powered By
    <a href="http://gaippbots.com/"> <img src="https://gaippbots.com/bot/uploaded-image/146135"></a>
        </li>


    </ul>
                  </div>
                  <!--<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 href="#" id="chat-btn" class="chat-btn" title="Open Chat Bot" onclick="if (chatBot_isOpen()) submitMsg(); else 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-paper-plane"></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_toggle();
  }
  
  // end of bot scripts
});

} // if botEnable

Author comment

Began life as a copy of #1028952

download  show line numbers   

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

No comments. add comment

Snippet ID: #1029632
Snippet name: GAIPP Chat Bot Template As JavaScript [LIVE]
Eternal ID of this version: #1029632/87
Text MD5: 4f61a53d0cb48da557149ada2dc2d404
Author: stefan
Category: javax / web chat bots
Type: Document
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2020-11-12 11:36:03
Source code size: 17420 bytes / 489 lines
Pitched / IR pitched: No / No
Views / Downloads: 341 / 2394
Version history: 86 change(s)
Referenced in: [show references]