/* eslint-disable max-len */ /* eslint-disable linebreak-style */ /* eslint-disable no-undef */ /* eslint-disable operator-linebreak */ /* eslint-disable no-console */ /* eslint-disable camelcase */ var hasaudio if ('speechSynthesis' in window) { hasaudio = true console.log("speech synthesis"); } else { hasaudio = false console.log("no speech synthesis"); } speechSynthesis.cancel(); var sentences = [] var current_response; var current_counter; var wrong_counter; var voices = [] setTimeout(() => { voices = speechSynthesis.getVoices(); //console.log(voices) voices.forEach(function(voice, i) { console.log(voice.name); }); }, 60); const action_name = "action_greet_user"; //const rasa_server_url = "http://localhost:5005/webhooks/rest/webhook"; //const rasa_server_url = "http://localhost:5005/socketio"; //const rasa_server_url = "http://localhost:5005/webhooks/myio/webhook"; //const rasa_server_url = "http://127.0.0.1:5055/async"; const rasa_server_url = "/bot/ajax"; //const sender_id = uuidv4(); var sender_id = "" var socket //var mediaRecorder; //var chunks = []; // //var AudioContext = window.AudioContext || window.webkitAudioContext; //var audioContext; //audio context to help us record //var recorder; // //if (navigator.mediaDevices.getUserMedia) { // const constraints = { audio: true }; // navigator.mediaDevices.getUserMedia(constraints).then( // stream => { // console.log("授权成功!"); // // audioContext = new AudioContext(); // var source = audioContext.createMediaStreamSource(stream); // recorder = new Recorder(source, { sampleBits: 16, sampleRate: 16000, numChannels: 1 }); // // //mediaRecorder = new MediaRecorder(stream); // // //mediaRecorder.ondataavailable = e => { // // chunks.push(e.data); // //}; // // //mediaRecorder.onstop = e => { // // var blob = new Blob(chunks, { type: "audio/ogg; codecs=opus" }); // // chunks = []; // // var audioURL = window.URL.createObjectURL(blob); // // // new Audio(audioURL).play() // //}; // }, // () => { // console.error("授权失败!"); // } // ); //} else { // console.error("浏览器不支持 getUserMedia"); //} // Bot pop-up intro //document.addEventListener("DOMContentLoaded", () => { // const elemsTap = document.querySelector(".tap-target"); // // eslint-disable-next-line no-undef // const instancesTap = M.TapTarget.init(elemsTap, {}); // instancesTap.open(); // setTimeout(() => { // instancesTap.close(); // }, 4000); //}); // initialization $(document).ready(() => { // Bot pop-up intro $("div").removeClass("tap-target-origin"); // drop down menu for close, restart conversation & clear the chats. $(".dropdown-trigger").dropdown(); // initiate the modal for displaying the charts, // if you dont have charts, then you comment the below line $(".modal").modal(); $(".widget").show(); $(".profile_div").hide(); $(".usrInput").focus(); sender_id = document.getElementById("sid").innerHTML; first_sen = document.getElementById("first_sen").innerHTML; sentences = (document.getElementById("post_body").innerHTML || '').split(/[,,;,!,?,。]+/).map((item)=>item.trim()); const br = '










Welcome to wordeffy.











'; $(br).appendTo(".chats"); $(".filldiv").show(); scrollToBottomOfResults(); setTimeout(() => { //message = [{buttons: [{'title': 'anonymous'}, {'title': 'login'}, {'title': 'register'}]}] message = [{text: 'type /help to get help'}] //message = [{fileupload: ''}] setBotResponse(message); }, 500); // enable this if u have configured the bot to start the conversation. // showBotTyping(); // $("#userInput").prop('disabled', true); // if you want the bot to start the conversation // customActionTrigger(); //socket = io.connect('http://127.0.0.1:5055', {transports: ['websocket']}); console.log("sender id: " + sender_id) console.log("cookie: " + getACookie("effwords")) //socket = io.connect('https://wordeffy.top', {transports: ['websocket'], query: {token: sender_id}}); socket = io.connect('https://wordeffy.top', {transports: ['websocket'], query: {audio: hasaudio, effy: getACookie("effwords")}}); socket.on('connect', function() { //socket.emit('my_event', {data: 'I\'m connected!'}); console.log('Connected ' + sender_id); }); socket.on('disconnect', function(e) { console.log('Disconnected ' + e.code + ' ' + e.reason + ' ' + e.wasClean); }); socket.on('bot_uttered', function(msg) { console.log(msg) botResponse = msg current_response = msg setBotResponse(botResponse); }); }); /** * scroll to the bottom of the chats after new message has been added to chat */ function scrollToBottomOfResults() { const terminalResultsDiv = document.getElementById("chats"); terminalResultsDiv.scrollTop = terminalResultsDiv.scrollHeight; } /** * removes the bot typing indicator from the chat screen */ function hideBotTyping() { $("#botAvatar").remove(); $(".botTyping").remove(); } /** * adds the bot typing indicator from the chat screen */ function showBotTyping() { const botTyping = //'
'; '
'; $(botTyping).appendTo(".chats"); $(".botTyping").show(); scrollToBottomOfResults(); } /** * Set user response on the chat screen * @param {String} message user message */ function setUserResponse(message) { //const user_response = `

${message}

`; const user_response = `

${message}

`; $(user_response).appendTo(".chats").show("slow"); $(".usrInput").val(""); $(".usrInput").focus(); scrollToBottomOfResults(); //showBotTyping(); $(".suggestions").remove(); } /** * adds vertically stacked buttons as a bot response * @param {Array} suggestions buttons json array */ function addSuggestion(suggestions) { setTimeout(() => { const suggLength = suggestions.length; $( '
' ) .appendTo(".chats") .hide() .fadeIn(1000); // Loop through suggestions for (let i = 0; i < suggLength; i += 1) { $( `` ).appendTo(".menu"); } scrollToBottomOfResults(); }, 1000); } function findDeckIndex(detail, tgt) { for (let j = 0; j < detail.length; j += 1) { if (detail[j].name == tgt) { return j } } return -1 } /** * creates horizontally placed cards carousel * @param {Array} cardsData json array */ function createCardsCarousel(cardsData) { category = cardsData.cate maxid = cardsData.max detail = cardsData.detail let cards = ""; let group = ""; for (let i = 1; i <= cardsData.max; i += 1) { deckid = findDeckIndex(detail, i) if (deckid == -1) { text = "d" + i + ": 0" group += `
  • ${text}
  • `; } else { text = "d" + i + ": " + detail[deckid].desc color = detail[deckid].color if (detail[deckid].ratings == 0) { group += `
  • ${text}
  • `; } else if (detail[deckid].ratings == 1) { group += `
  • ${text}
  • `; } else { group += `
  • ${text}
  • `; } } if ( i == 10 * Math.round(i / 10)) { const item = ``; cards += item; group = "" } } if (group.length > 0) { const item = ``; cards += item; } /*for (let i = 0; i < cardsData.length; i += 1) { const title = cardsData[i].name; const ratings = `${Math.round((cardsData[i].ratings / 5) * 100)}%`; const decks = title.split('
    ') let group = ""; for (let i = 0; i < decks.length; i += 1) { const decki = decks[i] const item = `
  • ${decki}
  • `; group += item; } const item = ``; const item = ``;*/ /*const item = ``; cards += item; } */ const cardContents = `
    ${cards}
    `; //const cardContents = `
    ${cards}
    `; return cardContents; } /** * appends cards carousel on to the chat screen * @param {Array} cardsToAdd json array */ function showCardsCarousel(cardsToAdd) { // We will show based on max, not detail if (cardsToAdd.max == 0) { const category = cardsToAdd.cate const cards = `

    No information on ${category}.

    `; $(cards).appendTo(".chats").show(); scrollToBottomOfResults(); return } const cards = createCardsCarousel(cardsToAdd); $(cards).appendTo(".chats").show(); //if (cardsToAdd.length <= 2) { if (cardsToAdd.detail.length <= 2) { //$(`.cards_scroller>div.carousel_cards:nth-of-type(${i})`).fadeIn(3000); } else { for (let i = 0; i < cardsToAdd.detail.length; i += 1) { $(`.cards_scroller>div.carousel_cards:nth-of-type(${i})`).fadeIn(3000); } $(".cards .arrow.prev").fadeIn("3000"); $(".cards .arrow.next").fadeIn("3000"); } scrollToBottomOfResults(); const card = document.querySelector("#paginated_cards"); const card_scroller = card.querySelector(".cards_scroller"); const card_item_size = 225; /** * For paginated scrolling, simply scroll the card one item in the given * direction and let css scroll snaping handle the specific alignment. */ function scrollToNextPage() { card_scroller.scrollBy(card_item_size, 0); } function scrollToPrevPage() { card_scroller.scrollBy(-card_item_size, 0); } card.querySelector(".arrow.next").addEventListener("click", scrollToNextPage); card.querySelector(".arrow.prev").addEventListener("click", scrollToPrevPage); } /** * appends horizontally placed buttons carousel * on to the chat screen * @param {Array} quickRepliesData json array */ function showQuickReplies(quickRepliesData) { let chips = ""; for (let i = 0; i < quickRepliesData.length; i += 1) { const chip = `
    ${quickRepliesData[i].title}
    `; chips += chip; } const quickReplies = `
    ${chips}
    `; $(quickReplies).appendTo(".chats").fadeIn(1000); scrollToBottomOfResults(); const slider = document.querySelector(".quickReplies"); let isDown = false; let startX; let scrollLeft; slider.addEventListener("mousedown", (e) => { isDown = true; slider.classList.add("active"); startX = e.pageX - slider.offsetLeft; scrollLeft = slider.scrollLeft; }); slider.addEventListener("mouseleave", () => { isDown = false; slider.classList.remove("active"); }); slider.addEventListener("mouseup", () => { isDown = false; slider.classList.remove("active"); }); slider.addEventListener("mousemove", (e) => { if (!isDown) return; e.preventDefault(); const x = e.pageX - slider.offsetLeft; const walk = (x - startX) * 3; // scroll-fast slider.scrollLeft = scrollLeft - walk; }); } /** * renders pdf attachment on to the chat screen * @param {Object} pdf_data json object */ function renderPdfAttachment(pdf_data) { const { url: pdf_url } = pdf_data.custom; const { title: pdf_title } = pdf_data.custom; const pdf_attachment = `
    `; $(".chats").append(pdf_attachment); scrollToBottomOfResults(); } /** * renders the dropdown message and * handles the user selection * @param {Array} drop_down_data json array */ function renderDropDwon(drop_down_data) { let drop_down_options = ""; for (let i = 0; i < drop_down_data.length; i += 1) { drop_down_options += ``; } const drop_down_select = ``; $(".chats").append(drop_down_select); scrollToBottomOfResults(); // add event handler if user selects a option. // eslint-disable-next-line func-names $("select").on("change", function () { let value = ""; let label = ""; $("select option:selected").each(() => { label += $(this).val(); value += $(this).val(); }); setUserResponse(label); // eslint-disable-next-line no-use-before-define send(value); $(".dropDownMsg").remove(); }); } /** * sends the user location to rasa * @param {Object} position json object */ function getUserPosition(position) { // here you to add the intent which you want to trigger const response = `/inform{"latitude":${position.coords.latitude},"longitude":${position.coords.longitude}}`; $("#userInput").prop("disabled", false); // eslint-disable-next-line no-use-before-define send(response); showBotTyping(); } /** * handles error while accessing the user's geolocation * @param {Object} error json object */ function handleLocationAccessError(error) { switch (error.code) { case error.PERMISSION_DENIED: console.log("User denied the request for Geolocation."); break; case error.POSITION_UNAVAILABLE: console.log("Location information is unavailable."); break; case error.TIMEOUT: console.log("The request to get user location timed out."); break; case error.UNKNOWN_ERROR: console.log("An unknown error occurred."); break; default: break; } const response = '/inform{"user_location":"deny"}'; // eslint-disable-next-line no-use-before-define send(response); showBotTyping(); $(".usrInput").val(""); $("#userInput").prop("disabled", false); } /** * fetches the user location from the browser */ function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( getUserPosition, handleLocationAccessError ); } else { console.log("Geolocation is not supported by this browser."); } } /** * creates collapsible * for more info refer:https://materializecss.com/collapsible.html * @param {Array} collapsible_date json array */ function createCollapsible(collapsible_data) { // sample data format: // var collapsible_data=[{"title":"abc","description":"xyz"},{"title":"pqr","description":"jkl"}] let collapsible_list = ""; for (let i = 0; i < collapsible_data.length; i += 1) { const collapsible_item = `
  • ${collapsible_data[i].title}
    ${collapsible_data[i].description}
  • `; collapsible_list += collapsible_item; } const collapsible_contents = ``; $(collapsible_contents).appendTo(".chats"); // initialize the collapsible $(".collapsible").collapsible(); scrollToBottomOfResults(); } /** * creates a div that will render the * charts in canvas as required by charts.js * for more info. refer: https://www.chartjs.org/docs/latest/getting-started/usage.html * @param {String} title chart title * @param {Array} labels chart label * @param {Array} backgroundColor chart's background color * @param {Object} chartsData chart's data * @param {String} chartType chart type * @param {String} displayLegend chart's legend */ function createChart( title, labels, backgroundColor, chartsData, chartType, displayLegend ) { const html = '
    '; $(html).appendTo(".chats"); // create the context that will draw the charts over the canvas in the ".chart-container" div const ctx = $("#chat-chart"); // Once you have the element or context, instantiate the chart-type by passing the configuration, // for more info. refer: https://www.chartjs.org/docs/latest/configuration/ const data = { labels, datasets: [ { label: title, backgroundColor, data: chartsData, fill: false, }, ], }; const options = { title: { display: true, text: title, }, layout: { padding: { left: 5, right: 0, top: 0, bottom: 0, }, }, legend: { display: displayLegend, position: "right", labels: { boxWidth: 5, fontSize: 10, }, }, }; // draw the chart by passing the configuration // eslint-disable-next-line no-undef chatChart = new Chart(ctx, { type: chartType, data, options, }); scrollToBottomOfResults(); } // function to render the charts in the modal /** * creates a modal that will render the * charts in canvas as required by charts.js * for more info. refer: https://www.chartjs.org/docs/latest/getting-started/usage.html * * if you want to display the charts in modal, * make sure you have configured the modal in `index.html` * @param {String} title chart title * @param {Array} labels chart label * @param {Array} backgroundColor chart's background color * @param {Object} chartsData chart's data * @param {String} chartType chart type * @param {String} displayLegend chart's legend */ function createChartinModal( title, labels, backgroundColor, chartsData, chartType, displayLegend ) { // create the context that will draw the charts // over the canvas in the `#modal-chart` div of the modal const ctx = $("#modal-chart"); // Once you have the element or context, instantiate the chart-type by passing the configuration, // for more info. refer: https://www.chartjs.org/docs/latest/configuration/ const data = { labels, datasets: [ { label: title, backgroundColor, data: chartsData, fill: false, }, ], }; const options = { title: { display: true, text: title, }, layout: { padding: { left: 5, right: 0, top: 0, bottom: 0, }, }, legend: { display: displayLegend, position: "right", }, }; // eslint-disable-next-line no-undef modalChart = new Chart(ctx, { type: chartType, data, options, }); } /** * renders bot response on to the chat screen * @param {Array} response json array containing different types of bot response * * for more info: `https://rasa.com/docs/rasa/connectors/your-own-website#request-and-response-format` */ function setBotResponse(response) { // renders bot response after 500 milliseconds setTimeout(() => { hideBotTyping(); if (response.length < 1) { // if there is no response from Rasa, send fallback message to the user const fallbackMsg = "I am facing some issues, please try again later!!!"; //const BotResponse = `

    ${fallbackMsg}

    `; const BotResponse = `

    ${fallbackMsg}

    `; $(BotResponse).appendTo(".chats").hide().fadeIn(1000); scrollToBottomOfResults(); } else { // if we get response from Rasa for (let i = 0; i < response.length; i += 1) { // check if the response contains "text" if (Object.hasOwnProperty.call(response[i], "text")) { if (response[i].text != null) { var target = response[i].text; var tvoice = target if (response[i].text.startsWith("^^")) { textes = target.substr(2).split("^^") tvoice = textes[0] target = textes[1]; } if (response[i].text.startsWith("@@")) { target = '..........'; tvoice = response[i].text.substr(2) } if (response[i].text.startsWith("##")) { textes = target.substr(2).split("##") tvoice = textes[1] target = replaceKeyword(textes[1], textes[0]) } if (response[i].text.startsWith("&&")) { target = response[i].text.substr(2) tvoice = '' } //const BotResponse = `

    ${target}

    `; const BotResponse = `

    ${target}

    `; $(BotResponse).appendTo(".chats").hide().fadeIn(1000); console.log(target) speak(tvoice); // current_response = target; } } if (Object.hasOwnProperty.call(response[i], "typer")) { if (response[i].typer != null) { var target = response[i].typer; var uid = getUUID() //const BotResponse = `

    _

    `; const BotResponse = `

    _

    `; $(BotResponse).appendTo(".chats").hide().fadeIn(1000); if (target.includes('*')) { startTyping(target, document.getElementById(uid), target) } else if (target.startsWith("@@")) { startBrowsing(target.substr(2), document.getElementById(uid), '........') } else { startTyping(target, document.getElementById(uid), '........') if (!target.includes('-')) { speak(target); } } } } // check if the response contains "images" if (Object.hasOwnProperty.call(response[i], "image")) { if (response[i].image !== null) { const BotResponse = `
    `; $(BotResponse).appendTo(".chats").hide().fadeIn(1000); } } if (Object.hasOwnProperty.call(response[i], "uploadfile")) { //const BotResponse = `

    Pick up one .txt file and send


    `; const BotResponse = `

    Pick up one .txt file and send


    `; $(BotResponse).appendTo(".chats").hide().fadeIn(1000); document.querySelector('#uploadWords').addEventListener('change', event => { handleUpload(event) }) } // check if the response contains "buttons" if (Object.hasOwnProperty.call(response[i], "buttons")) { if (response[i].buttons.length > 0) { addSuggestion(response[i].buttons); } } // check if the response contains "attachment" if (Object.hasOwnProperty.call(response[i], "attachment")) { if (response[i].attachment != null) { if (response[i].attachment.type === "video") { // check if the attachment type is "video" const video_url = response[i].attachment.payload.src; const BotResponse = `
    `; $(BotResponse).appendTo(".chats").hide().fadeIn(1000); } else if (response[i].attachment.type === "audio") { const audio_url = response[i].attachment.payload.src; console.log("from bot audio"); new Audio(audio_url).play() } } } // check if the response contains "custom" message if (Object.hasOwnProperty.call(response[i], "custom")) { const { payload } = response[i].custom; if (payload === "quickReplies") { // check if the custom payload type is "quickReplies" const quickRepliesData = response[i].custom.data; showQuickReplies(quickRepliesData); return; } // check if the custom payload type is "pdf_attachment" if (payload === "pdf_attachment") { renderPdfAttachment(response[i]); return; } // check if the custom payload type is "dropDown" if (payload === "dropDown") { const dropDownData = response[i].custom.data; renderDropDwon(dropDownData); return; } // check if the custom payload type is "location" if (payload === "location") { $("#userInput").prop("disabled", true); getLocation(); scrollToBottomOfResults(); return; } // check if the custom payload type is "cardsCarousel" if (payload === "cardsCarousel") { const restaurantsData = response[i].custom.data; showCardsCarousel(restaurantsData); return; } // check if the custom payload type is "chart" if (payload === "chart") { /** * sample format of the charts data: * var chartData = { "title": "Leaves", "labels": ["Sick Leave", "Casual Leave", "Earned Leave", "Flexi Leave"], "backgroundColor": ["#36a2eb", "#ffcd56", "#ff6384", "#009688", "#c45850"], "chartsData": [5, 10, 22, 3], "chartType": "pie", "displayLegend": "true" } */ const chartData = response[i].custom.data; const { title, labels, backgroundColor, chartsData, chartType, displayLegend, } = chartData; // pass the above variable to createChart function createChart( title, labels, backgroundColor, chartsData, chartType, displayLegend ); // on click of expand button, render the chart in the charts modal $(document).on("click", "#expand", () => { createChartinModal( title, labels, backgroundColor, chartsData, chartType, displayLegend ); }); return; } // check of the custom payload type is "collapsible" if (payload === "collapsible") { const { data } = response[i].custom; // pass the data variable to createCollapsible function createCollapsible(data); } } } scrollToBottomOfResults(); } }, 500); } /** * sends an event to the bot, * so that bot can start the conversation by greeting the user * * `Note: this method will only work in Rasa 1.x` */ function actionTrigger() { $.ajax({ url: `http://localhost:5005/conversations/${sender_id}/execute`, type: "POST", contentType: "application/json", data: JSON.stringify({ name: action_name, policy: "MappingPolicy", confidence: "0.98", }), success(botResponse, status) { console.log("Response from Rasa: ", botResponse, "\nStatus: ", status); if (Object.hasOwnProperty.call(botResponse, "messages")) { setBotResponse(botResponse.messages); } $("#userInput").prop("disabled", false); }, error(xhr, textStatus) { // if there is no response from rasa server setBotResponse(""); console.log("Error from bot end: ", textStatus); $("#userInput").prop("disabled", false); }, }); } /** * sends an event to the custom action server, * so that bot can start the conversation by greeting the user * * Make sure you run action server using the command * `rasa run actions --cors "*"` * * `Note: this method will only work in Rasa 2.x` */ // eslint-disable-next-line no-unused-vars function customActionTrigger() { $.ajax({ url: "http://localhost:5055/webhook/", type: "POST", contentType: "application/json", data: JSON.stringify({ next_action: action_name, tracker: { sender_id, }, }), success(botResponse, status) { console.log("Response from Rasa: ", botResponse, "\nStatus: ", status); if (Object.hasOwnProperty.call(botResponse, "responses")) { setBotResponse(botResponse.responses); } $("#userInput").prop("disabled", false); }, error(xhr, textStatus) { // if there is no response from rasa server setBotResponse(""); console.log("Error from bot end: ", textStatus); $("#userInput").prop("disabled", false); }, }); } function getCookie(name) { var r = document.cookie.match("\\b" + name + "=([^;]*)\\b"); return r ? r[1] : undefined; } function send(message) { console.log(message) //socket.emit('user_uttered', JSON.stringify({ message, sender: sender_id })) socket.emit('user_uttered', JSON.stringify({ message })) } /** * sends the user message to the rasa server, * @param {String} message user message */ function sendAjax(message) { $.ajax({ url: rasa_server_url, type: "POST", headers: { 'X-CSRFTOKEN': getCookie("csrftoken") }, // 这里是headers,不是data contentType: "application/json", data: JSON.stringify({ message, sender: sender_id }), success(botResponse, status) { console.log("Response from Rasa: ", botResponse, "\nStatus: ", status); // if user wants to restart the chat and clear the existing chat contents if (message.toLowerCase() === "/restart") { $("#userInput").prop("disabled", false); // if you want the bot to start the conversation after restart // customActionTrigger(); return; } setBotResponse(botResponse); }, error(xhr, textStatus) { if (message.toLowerCase() === "/restart") { $("#userInput").prop("disabled", false); // if you want the bot to start the conversation after the restart action. // actionTrigger(); // return; } // if there is no response from rasa server, set error bot response setBotResponse(""); console.log("Error from bot end: ", textStatus); }, }); } /** * clears the conversation from the chat screen * & sends the `/resart` event to the Rasa server */ function restartConversation() { $("#userInput").prop("disabled", true); // destroy the existing chart $(".collapsible").remove(); if (typeof chatChart !== "undefined") { chatChart.destroy(); } $(".chart-container").remove(); if (typeof modalChart !== "undefined") { modalChart.destroy(); } $(".chats").html(""); $(".usrInput").val(""); send("/restart"); } // triggers restartConversation function. $("#restart").click(() => { restartConversation(); }); /** * if user hits enter or send button * */ $(".usrInput").on("keyup keypress", (e) => { const keyCode = e.keyCode || e.which; const text = $(".usrInput").val(); if (keyCode === 13) { if (text === "" || $.trim(text) === "") { e.preventDefault(); return false; } // destroy the existing chart, if yu are not using charts, then comment the below lines $(".collapsible").remove(); $(".dropDownMsg").remove(); if (typeof chatChart !== "undefined") { chatChart.destroy(); } $(".chart-container").remove(); if (typeof modalChart !== "undefined") { modalChart.destroy(); } $("#paginated_cards").remove(); $(".suggestions").remove(); $(".quickReplies").remove(); $(".usrInput").blur(); setUserResponse(text); send(text); e.preventDefault(); return false; } return true; }); function createLink(blob) { var url = URL.createObjectURL(blob); new Audio(url).play() const request = new XMLHttpRequest(); request.open('GET', url, true); request.responseType = 'blob'; request.onload = function() { const reader = new FileReader(); reader.readAsDataURL(request.response); reader.onload = function(el) { // console.log('DataURL:', el.target.result); console.log('SEND RESULT TO THE BOT'); send(el.target.result); }; }; request.send(); } function nextWord() { if (current_counter + 1 >= sentences.length) { current_counter = 0; } else { current_counter += 1; } current_response = sentences[current_counter]; message = {text: current_response}; setBotResponse([message]); wrong_counter = 0; } $("#uploadFile").on("click", (e) => { send('/uploadfile') $(".usrInput").focus(); }); $("#nextWord").on("click", (e) => { send('/nx') $(".usrInput").focus(); }); $("#meaning").on("click", (e) => { send('/mn') $(".usrInput").focus(); }); $("#spell").on("click", (e) => { send('/spell') $(".usrInput").focus(); }); $("#mark").on("click", (e) => { send('/mk') $(".usrInput").focus(); }); $("#volume").on("click", (e) => { var vv = document.getElementById("voli"); if (vv.title == "sound on") { vv.className = "fa fa-volume-off" vv.title = "sound off" } else { vv.className = "fa fa-volume-up" vv.title = "sound on" } $(".usrInput").focus(); }); $("#repeatWord").on("click", (e) => { //setBotResponse(current_response) send('/rp') $(".usrInput").focus(); }); $("#boltWord").on("click", (e) => { send("/bolt"); $(".usrInput").val(""); $(".usrInput").focus(); scrollToBottomOfResults(); //showBotTyping(); e.preventDefault(); return false; }); $("#sendButton").on("click", (e) => { //if (recorder.recording) { // recorder.stop(); // recorder.exportWAV(createLink); // recorder.clear(); // console.log("stop record"); //} else { // recorder.record(); // window.setTimeout(() => { // if (recorder.recording) { // recorder.stop(); // recorder.exportWAV(createLink); // recorder.clear(); // console.log('10 seconds, stop recording'); // } // }, 10000); // console.log("recording..."); //} ////if (mediaRecorder.state === "recording") { //// mediaRecorder.stop(); //// //recordBtn.textContent = "record"; //// console.log("录音结束"); ////} else { //// mediaRecorder.start(); //// console.log("录音中..."); //// //recordBtn.textContent = "stop"; ////} ////console.log("录音器状态:", mediaRecorder.state); const text = $(".usrInput").val(); if (text === "" || $.trim(text) === "") { e.preventDefault(); return false; } // destroy the existing chart if (typeof chatChart !== "undefined") { chatChart.destroy(); } $(".chart-container").remove(); if (typeof modalChart !== "undefined") { modalChart.destroy(); } $(".suggestions").remove(); $("#paginated_cards").remove(); $(".quickReplies").remove(); $(".usrInput").blur(); $(".dropDownMsg").remove(); setUserResponse(text); send(text); e.preventDefault(); return false; }); // Toggle the chatbot screen $("#profile_div").click(() => { $(".profile_div").toggle(); $(".widget").toggle(); }); // on click of suggestion's button, get the title value and send it to rasa $(document).on("click", ".menu .menuChips", function () { const text = this.innerText; const payload = this.getAttribute("data-payload"); console.log("payload: ", this.getAttribute("data-payload")); setUserResponse(text); // send(payload); send(text); // delete the suggestions once user click on it. $(".suggestions").remove(); }); // clear function to clear the chat contents of the widget. $("#clear").click(() => { $(".chats").fadeOut("normal", () => { $(".chats").html(""); $(".chats").fadeIn(); }); }); // close function to close the widget. $("#close").click(() => { $(".profile_div").toggle(); $(".widget").toggle(); scrollToBottomOfResults(); }); // on click of carousel cards, get the payload value and send it to rasa $(document).on("click", ".cardTitle .deck", function () { const text = this.innerText; const cate = this.getAttribute("cate"); const payload = this.getAttribute("title"); cmd = "/"+cate+" "+payload; setUserResponse(cmd) send(cmd); // delete the carsousel cards $("#paginated_cards").remove(); }); // on click of quickreplies, get the payload value and send it to rasa $(document).on("click", ".quickReplies .chip", function () { const text = this.innerText; const payload = this.getAttribute("data-payload"); console.log("chip payload: ", this.getAttribute("data-payload")); setUserResponse(text); send(payload); // delete the quickreplies $(".quickReplies").remove(); }); function speak(text) { if (text == '') { return } if (text.includes("XXX ")) { var textes = text.split("XXX "); speakExt(textes[0], 1.0); speakExt(textes[1], 2.0); } else { speakExt(text, 1.0); } } function isChinese(str) { var pattern = new RegExp("[\u4E00-\u9FA5]+"); if(pattern.test(str)){ return true; } return false; } // Create a new utterance for the specified text and add it to // the queue. function speakExt(text, rate) { // Create a new instance of SpeechSynthesisUtterance. var msg = new SpeechSynthesisUtterance(); // Set the text. msg.text = text; // Set the attributes. //msg.volume = 0.5; //msg.rate = 1.1; //msg.pitch = 1.0; // If a voice has been selected, find the voice and set the // utterance instance's voice attribute. //if (voiceSelect.value) { //msg.voice = speechSynthesis.getVoices().filter(function(voice) { return voice.name == voiceSelect.value; })[0]; //} console.log(isChinese(text)); if (isChinese(text)==false) { //msg.voice = voices[19] //msg.lang = "en-US" } else { //msg.voice = voices[57] //alex 19 ting-ting 57 //msg.lang = "zh-CN" } console.log(msg) // Queue this utterance. window.speechSynthesis.speak(msg); } function replaceKeyword(string, word) { var dmp = new diff_match_patch(); dmp.Diff_Timeout = parseFloat(100); dmp.Diff_EditCost = parseFloat(4); var max = 0 var max_word var textes = string.split(" "); textes.forEach(function(text, i) { var diff = dmp.diff_main(word, text); var counter = 0 for(let i=0; i max) { max = counter max_word = text } }); return string.replace(max_word, "***") } const handleUpload = event => { const files = event.target.files const formData = new FormData() const newFile = new window.File([files[0]], files[0].name+'.'+sender_id, {type: files[0].type}) //formData.append('file', files[0]) formData.append('file', newFile) console.log(newFile.name) $(".uploadform").remove(); // 发送跨域请求 //fetch("https://api.example.com/data", { // mode: "cors", // headers: { // "Content-Type": "application/json", // "Access-Control-Allow-Origin": "https://example.com", // }, //}) setUserResponse("send file "+files[0].name); fetch('/upload', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { console.log(data) console.log(data['code']) if (data['code'] == 0) { send("send file"); } else { setUserResponse("failed sending file"); } }) .catch(error => { console.error(error) }) } function startTyping(str, msgnode, end) { if (str.length > 20) { startTypingSentence(str, msgnode, end) return } let str_ = '' let i = 0 let content = msgnode let timer = setInterval(()=> { if(str_.length { if(str_.length { if(i < texts.length) { str_ = texts[i++] //content.innerHTML = '    ' + str_ content.innerHTML = '
    ' + str_ + '
    ' } else { clearInterval(timer) //content.innerHTML = str_ setTimeout(function () { content.innerHTML = end }, 1500); } },1500) } function getUUID(){ var rn = Number(Math.random().toString().substr(2,10) + Date.now()).toString(36) return rn.substr(2, 8) } function getACookie(cookieName) { let nameOfCookie = cookieName + '='; let cookieDecoded = decodeURIComponent(document.cookie); let cookieArray = cookieDecoded.split(';'); for (let i = 0; i < cookieArray.length; i++) { let cIndex = cookieArray[i]; while (cIndex.charAt(0) == ' ') { cIndex = cIndex.substring(1); } if (cIndex.indexOf(nameOfCookie) == 0) { return cIndex.substring(nameOfCookie.length, cIndex.length); } } return ''; }