how to make a chatbot in javascript

Solutions on MaxInterview for how to make a chatbot in javascript by the best coders in the world

showing results for - "how to make a chatbot in javascript"
Naomi
16 Apr 2020
1//index.js
2
3document.addEventListener("DOMContentLoaded", () => {
4  document.querySelector("#input").addEventListener("keydown", function(e) {
5    if (e.code === "Enter") {
6        console.log("You clicked the form and pressed the enter button!")
7    }
8  });
9});
10
11document.addEventListener("DOMContentLoaded", () => {
12    const inputField = document.getElementById("input")
13    inputField.addEventListener("keydown", function(e) {
14        if (e.code === "Enter") {
15            let input = inputField.value;
16            inputField.value = "";
17            output(input);
18    }
19  });
20});
21
22  if (e.code === "Enter") {
23      let input = inputField.value;
24      console.log(`I typed '${input}'`)
25    }
26
27function () {
28
29//remove all characters except word characters, space, and digits
30  let text = input.toLowerCase().replace(/[^\w\s\d]/gi, "");
31
32// 'tell me a story' -> 'tell me story'
33// 'i feel happy' -> 'happy'
34  text = text
35    .replace(/ a /g, " ")
36    .replace(/i feel /g, "")
37    .replace(/whats/g, "what is")
38    .replace(/please /g, "")
39    .replace(/ please/g, "");
40}
41
42const trigger = [
43//0 
44["hi", "hey", "hello"],
45//1
46["how are you", "how are things"],
47//2
48["what is going on", "what is up"],
49//3
50["happy", "good", "well", "fantastic", "cool"],
51//4
52["bad", "bored", "tired", "sad"],
53//5
54["tell me story", "tell me joke"],
55//6
56["thanks", "thank you"],
57//7
58["bye", "good bye", "goodbye"]
59];
60
61const reply = [
62//0 
63["Hello!", "Hi!", "Hey!", "Hi there!"], 
64//1
65[
66    "Fine... how are you?",
67    "Pretty well, how are you?",
68    "Fantastic, how are you?"
69  ],
70//2
71[
72    "Nothing much",
73    "Exciting things!"
74  ],
75//3
76["Glad to hear it"],
77//4
78["Why?", "Cheer up buddy"],
79//5
80["What about?", "Once upon a time..."],
81//6
82["You're welcome", "No problem"],
83//7
84["Goodbye", "See you later"],
85];
86
87const alternative = [
88  "Same",
89  "Go on...",
90  "Try again",
91  "I'm listening...",
92  "Bro..."
93];
94
95function compare(triggerArray, replyArray, text) {
96  let item;
97  for (let x = 0; x < triggerArray.length; x++) {
98    for (let y = 0; y < replyArray.length; y++) {
99      if (triggerArray[x][y] == text) {
100        items = replyArray[x];
101        item = items[Math.floor(Math.random() * items.length)];
102      }
103    }
104  }
105  return item;
106}
107
108function output(input) {
109  let product;
110  let text = input.toLowerCase().replace(/[^\w\s\d]/gi, "");
111  text = text
112    .replace(/ a /g, " ")
113    .replace(/i feel /g, "")
114    .replace(/whats/g, "what is")
115    .replace(/please /g, "")
116    .replace(/ please/g, "");
117
118//compare arrays
119//then search keyword
120//then random alternative
121
122  if (compare(trigger, reply, text)) {
123    product = compare(trigger, reply, text);
124  } else if (text.match(/robot/gi)) {
125    product = robot[Math.floor(Math.random() * robot.length)];
126  } else {
127    product = alternative[Math.floor(Math.random() * alternative.length)];
128  }
129
130  //update DOM
131  addChat(input, product);
132}
133
134
135document.addEventListener("DOMContentLoaded", () => {
136...
137    if (e.code === "Enter") {
138        let input = document.getElementById("input").value;
139        document.getElementById("user").innerHTML = input;
140        output(input);    
141     }
142  });
143});
144
145function output(input) {
146    let product;
147    let text = (input.toLowerCase()).replace(/[^\w\s\d]/gi, "");
148...
149    document.getElementById("chatbot").innerHTML = product;
150    speak(product);
151
152    //clear input value
153    document.getElementById("input").value = "";
154}
155
156function addChat(input, product) {
157  const mainDiv = document.getElementById("main");
158  let userDiv = document.createElement("div");
159  userDiv.id = "user";
160  userDiv.innerHTML = `You: <span id="user-response">${input}</span>`;
161  mainDiv.appendChild(userDiv);
162
163  let botDiv = document.createElement("div");
164  botDiv.id = "bot";
165  botDiv.innerHTML = `Chatbot: <span id="bot-response">${product}</span>`;
166  mainDiv.appendChild(botDiv);
167  speak(product);
168}
169// VIOCE AI IF U WANT TO ADD THIS
170function speak(string) {
171  const u = new SpeechSynthesisUtterance();
172  allVoices = speechSynthesis.getVoices();
173  u.voice = allVoices.filter(voice => voice.name === "Alex")[0];
174  u.text = string;
175  u.lang = "en-US";
176  u.volume = 1; //0-1 interval
177  u.rate = 1;
178  u.pitch = 1; //0-2 interval
179  speechSynthesis.speak(u);
180}