Javascript бот подсказывает пользователю?

Я создаю простого бота javascript, и мне было интересно, есть ли способ заставить бота запрашивать пользователя. Так что он сказал бы: "Привет, как дела?" или что-то еще до того, как пользователь что-нибудь введет. У меня есть код ниже, помощь будет очень признательна!

<script type = "text/javascript">
var trigger = [
	["hi","hey","hello"], 
	["how are you", "how is life", "how are things"],
	["what are you doing", "what is going on"]
];
var reply = [
	["Hi","Hey","Hello"], 
	["Fine", "Pretty well", "Fantastic"],
	["Nothing much", "About to go to sleep", "Can you guest?", "I don't know actually"],
];

var alternative = ["Haha...", "Eh..."];
document.querySelector("#input").addEventListener("keypress", function(e){
	var key = e.which || e.keyCode;
	if (key === 13){ //Enter button
		var input = document.getElementById("input").value;
		document.getElementById("user").innerHTML = input;
		output(input);
	}
});
function output(input){
	try{
		var product = input + " = " + eval(input);
	} catch(e){
		var text = (input.toLowerCase()).replace(/[^\w\s\d]/gi, ""); //remove all chars except words, space and 
		text = text.replace(/ a /g, " ").replace(/i feel /g, "").replace(/whats/g, "what is").replace(/please /g, "").replace(/ please/g, "");
		if (compare(trigger, reply, text)){
			var product = compare(trigger, reply, text);
		} else {
			var product = alternative[Math.floor(Math.random()*alternative.length)];
		}
	}
	document.getElementById("system").innerHTML = product;
	speak(product);
	document.getElementById("input").value = ""; //clear input value
}
function compare(arr, array, string){
	var item;
	for(var x=0; x<arr.length; x++){
		for(var y=0; y<array.length; y++){
			if (arr[x][y] == string){
				items = array[x];
				item =  items[Math.floor(Math.random()*items.length)];
			}
		}
	}
	return item;
}

function speak(string){

}
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
0
163
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Я смешал часть вашего кода с простым чат-ботом, над которым я работал, используя jQuery. Ответ по-прежнему такой же, как ваш код. Я просто меняю манипуляции с DOM.

<html>
    <body>
        <div class = "container" id = "content"> 
            <p id = "out">
            </p>
            <p id = "inp">
                <span id = "dir">Message: </span>
                <div id = "stretchbox">
                    <input type = "text" 
                           id = "txt-inp"
                           autocomplete = "off"             
                           autocorrect = "off"
                           autocapitalize = "off" 
                           autofocus = "autofocus"
                           spellcheck = "false">
                    </input>
                </div>
            </p>
        </div>
        <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        <script>
          $(function() {
            var trigger = [
              ["hi","hey","hello"], 
              ["how are you", "how is life", "how are things"],
              ["what are you doing", "what is going on"]
            ];
            var reply = [
              ["Hi","Hey","Hello"], 
              ["Fine", "Pretty well", "Fantastic"],
              ["Nothing much", "About to go to sleep", "Can you guest?", "I don't know actually"],
            ];

            println('Bot: ' + trigger[1][0]);

            var alternative = ["Haha...", "Eh..."];

            let textInput = $('#txt-inp');
            let messageOutput = $('#out');
            let processingStatus = $('<span>Bot: Processing...<br></span>');
            let name = 'cds1170';
            function println(text) {
              let newSpan = document.createElement("SPAN");
              let newLine = document.createElement("BR");
              let textNode = document.createTextNode(text);
              newSpan.appendChild(textNode);
              document.getElementById("out").appendChild(newSpan);
              document.getElementById("out").appendChild(newLine);
              gotoBottom();
            }
            function print(text) {
              let newSpan = document.createElement("SPAN");
              let textNode = document.createTextNode(text);
              newSpan.appendChild(textNode);
              document.getElementById("out").appendChild(newSpan);
            }
            function gotoBottom() {
              window.scrollTo(0,document.body.scrollHeight);
            }
            function sendMessage() {
              let data = {
                'reply': textInput.val()
              };
              if (!data['reply']) {
                return;
              }
              println(name + ': ' + data['reply']);
              textInput.val('');
              messageOutput.append(processingStatus);
              textInput.attr('disabled', 'disabled');
              messageOutput.children().last().remove();
              textInput.removeAttr('disabled');
              output(data['reply']);
            }
            $('#txt-inp').keypress(function(e) {
              if (e.which == 13) {
                sendMessage();
              }
            });

            function output(input){
              try{
                var product = input + " = " + eval(input);
              } catch(e){
                var text = (input.toLowerCase()).replace(/[^\w\s\d]/gi, ""); //remove all chars except words, space and 
                text = text.replace(/ a /g, " ").replace(/i feel /g, "").replace(/whats/g, "what is").replace(/please /g, "").replace(/ please/g, "");
                if (compare(trigger, reply, text)){
                  var product = compare(trigger, reply, text);
                } else {
                  var product = alternative[Math.floor(Math.random()*alternative.length)];
                }
              }
              println(product);
            }

            function compare(arr, array, string){
              var item;
              for(var x=0; x<arr.length; x++){
                for(var y=0; y<array.length; y++){
                  if (arr[x][y] == string){
                    items = array[x];
                    item =  items[Math.floor(Math.random()*items.length)];
                  }
                }
              }
              return item;
            }
          });
        </script>
    </body>
</html>

Обновление: я добавил некоторые элементы HTML, которые пытается найти ваш код. Я не сильно изменился в вашей манипуляции с DOM. Будет ли это работать?

<!doctype html>
<html>
  <body>


    <div id = "user"></div>
    <div id = "system"></div>
    <input id = "input" type = "text">

    <script type = "text/javascript">
var trigger = [
  ["hi","hey","hello"], 
  ["how are you", "how is life", "how are things"],
  ["what are you doing", "what is going on"]
];
var reply = [
  ["Hi","Hey","Hello"], 
  ["Fine", "Pretty well", "Fantastic"],
  ["Nothing much", "About to go to sleep", "Can you guest?", "I don't know actually"],
];

var alternative = ["Haha...", "Eh..."];
console.info('a');
document.getElementById("input").addEventListener("keypress", function(e){
  var key = e.which || e.keyCode;
  if (key === 13){ //Enter button
    var input = document.getElementById("input").value;
    document.getElementById("user").innerHTML = input;
    output(input);
  }
});
function output(input){
  try{
    var product = input + " = " + eval(input);
  } catch(e){
    var text = (input.toLowerCase()).replace(/[^\w\s\d]/gi, ""); //remove all chars except words, space and 
    text = text.replace(/ a /g, " ").replace(/i feel /g, "").replace(/whats/g, "what is").replace(/please /g, "").replace(/ please/g, "");
    if (compare(trigger, reply, text)){
      var product = compare(trigger, reply, text);
    } else {
      var product = alternative[Math.floor(Math.random()*alternative.length)];
    }
  }
  document.getElementById("system").innerHTML = product;
  speak(product);
  document.getElementById("input").value = ""; //clear input value
}
function compare(arr, array, string){
  var item;
  for(var x=0; x<arr.length; x++){
    for(var y=0; y<array.length; y++){
      if (arr[x][y] == string){
        items = array[x];
        item =  items[Math.floor(Math.random()*items.length)];
      }
    }
  }
  return item;
}

function speak(string){

}
    </script>
  </body>
</html>

Я действительно понимаю это, но есть ли способ сделать это без изменения DOM или самого кода? Есть ли что-то, что я могу просто добавить? Если нет, то все в порядке! Мне просто интересно. Большое спасибо за помощь.

cds1170 06.03.2019 04:30

Да, я добавил новый код в свой ответ. Ваш код JavaScript работает хорошо. Я только что добавил несколько элементов HTML, чтобы ваш код мог их читать или писать. Вероятно, вам не нужна функция speak(), так как вы уже использовали строку document.getElementById("system").innerHTML = product; для отображения ответа.

VietHTran 06.03.2019 04:59

Другие вопросы по теме