Я создаю простого бота 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){
}


![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Я смешал часть вашего кода с простым чат-ботом, над которым я работал, используя 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>
Да, я добавил новый код в свой ответ. Ваш код JavaScript работает хорошо. Я только что добавил несколько элементов HTML, чтобы ваш код мог их читать или писать. Вероятно, вам не нужна функция speak(), так как вы уже использовали строку document.getElementById("system").innerHTML = product; для отображения ответа.
Я действительно понимаю это, но есть ли способ сделать это без изменения DOM или самого кода? Есть ли что-то, что я могу просто добавить? Если нет, то все в порядке! Мне просто интересно. Большое спасибо за помощь.