Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 66 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,67 @@
# Chatbot
# Week8 - Chatbot

Please see the instructions [here](https://docs.google.com/document/d/1BP27Tjgit66o6kLpzu8RMnPr7M5GWpC_2N05DvMMTUE/).
See the instructions [here](https://docs.google.com/document/d/1123vh08osRkCyqsnyR0SQMC1n4l0DlDIS0OYSrPSlY0/edit?usp=sharing) for the first part of your chatbot, or read below:

**Due Date: Sunday, September 15 at 6:00 p.m.**

Complete the following assignment and create a pull request to GitHub for reviewing by the instructor.

The homework assignments for the next few lectures will be interconnected. By the end of JavaScript 2, you will have developed a fully functional chatbot. These assignments will build on the previous week's assignment, therefore, it is very important that you complete the assignment in a timely manner (i.e. by the due date).

## CHATBOT PART I

In this first assignment, you will begin by building a very simple chatbot. As you progress through the remaining JavaScript weeks, you will add more and more functionality to the chatbot.

You are provided the HTML and CSS code for this assignment in this repository. Your task will be to write the JavaScript portion to make the chatbot functional and interactive. Remember to add comments to your code, describing what it does.

1. In your JavaScript code, declare a variable and initialize it as an object.
2. Add two properties to the object: ‘input’ and ‘output’.
1. To the ‘input’ property/key assign a greeting or a question that you want the chatbot to reply to. Some examples are:
* Hello
* How are you?
* What is your favourite colour?
2. To the ‘output’ property/key assign answers to the greetings or questions you wrote in part a. Some examples to the inputs above are:
* Hi
* Great!
* I have so many favorites it's hard to choose one.
3. console.log() your variable to confirm that you have assigned the values correctly. If done correctly, you output should look similar to:
```js
{ input: 'input1', output: 'output1' }
```

4. Below your variable declaration, create a function called ‘reply’.
5. In the ‘reply’ function, declare a variable called ‘question’ and assign to it the **value**of the HTML `<input>` element.
- HINT: use the id assigned to the `<input>` element to get access to the element.
6. Use a conditional statement to check if the value you stored in the 'question' variable matches the 'input' defined in the object you first created.
1. If it does, assign the corresponding output to the **value** of the <textarea> element.
- HINT: use the id assigned to the `<textarea>` element to get access to the element.
2. if it does not, assign the string "I don't understand that command. Please enter another." to the **value** of the `<textarea>` element.
- HINT: use the id assigned to the `<textarea>` element to get access to the element.
7. Below your 'reply' function, attach a 'click' event listener to the `<button>` element defined in the HTML file.
- HINT: use the id assigned to the `<button>` element to get access to the element.
Alternatively, you can modify the HTML to add a `<form>` element around the `<input>` and `<button>` and attach an event listener the form's `submit` event. This will allow you to use the enter key to enter input as well.
8. Save your JavaScript code. You now have a functional simple chatbot. Try it out by opening the 'index.html' file in your browser. REMEMBER to include your JavaScript code in the ‘index.html’ file either internally or externally.

### SUBMISSION

Before submitting your assignment, remember to organize your code according to the best practices for structuring code files. This means:

* HTML, CSS, and JS code should be in separate files
* All files should be organized into their respective folders
* [Read this article for more info](https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files)

### EVALUATION

When evaluating this assignment, we will be looking for:

* Proper code formatting
* Correct structuring of code files
* Descriptive comments within code
* Functionality of the chatbot (if it’s working or not)

### BONUS

Try out different ‘input’ and ‘output’ statements with the chatbot.
HINT: you will need these in part 2.

Add your own CSS and/or restructure the HTML to your liking. Make your chatbot unique!
114 changes: 61 additions & 53 deletions chatbot_style.css → css/style.css
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,53 +1,61 @@
button {
font-family: Helvetica;
font-size: 10pt;
/*width: 92px;*/
}

textarea {
font-family: arial;
font-size: 10pt;
}

body {
color: #333;
background-color: #efefef;
font: 13px helvetica, arial, freesans, clean, sans-serif;
}

#demo {
width: 80%;
max-width: 1000px;
margin-left: auto;
margin-right: auto;
padding: 20px;

background-color: #F8F8F8;
border: 1px solid #ccc;
box-shadow: 0 0 10px #999;
line-height: 1.4em;
font: 13px helvetica, arial, freesans, clean, sans-serif;
color: black;
}

#demo #input {
padding: 8px;
font-size: 14px;
border: 1px solid #ddd;
width: 400px;
}

#demo textarea {
padding: 8px;
font-size: 14px;
border: 1px solid #ddd;
width: 800px;
}

input:focus {
outline: none;
}

textarea:focus {
outline: none;
}
button {
font-family: Helvetica;
font-size: 10pt;
/*width: 92px;*/
}

textarea {
font-family: arial;
font-size: 10pt;
}

body {
color: #333;
background-color: #efefef;
font: 13px helvetica, arial, freesans, clean, sans-serif;
margin: 0px;
}

#demo {
width: 80%;
max-width: 1000px;
margin-left: auto;
margin-right: auto;
padding: 20px;

background-color: #F8F8F8;
border: 1px solid #ccc;
box-shadow: 0 0 10px #999;
line-height: 1.4em;
font: 13px helvetica, arial, freesans, clean, sans-serif;
color: black;
margin-top: 80px;
}

#demo #input {
padding: 8px;
font-size: 14px;
border: 1px solid #ddd;
width: 400px;
}

#demo textarea {
padding: 8px;
font-size: 14px;
border: 1px solid #ddd;
width: 800px;
}

input:focus {
outline: none;
}

textarea:focus {
outline: none;
}


.weather{
font-size: 40px;
color: orange;
}
29 changes: 19 additions & 10 deletions index.html
Original file line number Diff line number Diff line change
@@ -1,33 +1,42 @@
<!DOCTYPE HTML>
<head>
<title>My First Chatbot</title>
<link rel="stylesheet" type="text/css" href="chatbot_style.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js" defer></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
</head>

<body>

<div id="demo">

<h1> My first chatbot! </h1>
<h3> Talk to your bot!</h3>

<div id="user">
<input id="input" type="text" placeholder="Say something" />
<button id="submit">Submit</button>
<form id="chatbot-form">
<input id="input" type="text" placeholder="Say something" />
<button id="submit">Submit</button>

<input type="radio" name="filterType" class="filterType" id="random" value="Random" checked> Random
<input type="radio" name="filterType" class="filterType" id="shortest" value="Shortest Answer"> Shortest Answer
<input type="radio" name="filterType" class="filterType" id="longest" value="Longest Answer"> Longest Answer
<input type="radio" name="filterType" class="filterType" id="random" value="Random" checked> Random
<input type="radio" name="filterType" class="filterType" id="shortest" value="Shortest Answer"> Shortest Answer
<input type="radio" name="filterType" class="filterType" id="longest" value="Longest Answer"> Longest Answer
</form>
</div>

<br />

<h3> Chat history </h3>
<div id="chatBot">
<textarea id="output" name="ChatHistory" rows="15"></textarea>
<br />
</div>
</div>

</div>

<!-- sweetalert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script>

</body>

</html>
</html>
156 changes: 156 additions & 0 deletions js/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
//1.In your JavaScript code, declare a variable and initialize it as an object.
//2.Add two properties to the object: ‘input’ and ‘output’.
const chatbot = [
{
input: ['hello', 'hi', 'greetings'],
output: ['hello', 'hey', 'greetings']
},
{
input: ['how are you?', 'how is the weather today?', 'how is Canada doing in the Olympics?'],
output: ['fine', 'great', 'not so good']
},
{
input: ['what is your favourite colour?', 'who is your favourite HYF instructor?', 'who is your role model?'],
output: ['i am not sure', 'i have so many favorites it\'s hard to choose one.', 'i like every one']
},
{
input: ['show me a dog'],
output: [showMeADog]
},
{
input: ['set an alarm'],
output: [delayedAlert]
},
{
input: ['show me the weather'],
output: [showMeWeather]
}

];



function reply() {
//get a random number between 0 and 2
let randomNumber = Math.floor((Math.random() * 3));

//get the input value ,, and convert it to lowercase
let question = document.getElementById('input').value.toLowerCase();
let filterType = null;
//get the array mach the input value
const output = chatbot.filter(item => item.input.includes(question));

//if there is nothing inside the input then do nothing
if(question === ''){ return false; }
appendToOutput(question);
//check if question founded on the chatbot object
if(output.length > 0){
if(document.getElementById('longest').checked){
lOutput = output[0].output.sort((a, b) => b.length - a.length);
appendToOutput(lOutput[0], 1);
}else if(document.getElementById('shortest').checked){
sOutput = output[0].output.sort((a, b) => a.length - b.length );
appendToOutput(sOutput[0], 1);
}else{
//check if the output array has more than value,, if yes get a random one else git the first one
(output[0]['output'].length > 1)? appendToOutput(output[0].output[randomNumber], 1):appendToOutput(output[0].output[0], 1);
}
}else{
//if the question not found in out dataDase show this msg to the user
appendToOutput("I don't understand that command. Please enter another.",1);
}
}

//this function to add a new message to the top of the textarea
function appendToOutput(msg, sender) {
if (typeof msg == 'function') {
msg();//call the function ,, which got from the output

//add an answer on the chat history
appendToOutput("With pleasure", 1)
return false;
}
//who send the msg ? bot or user(you)
sender = (sender) ? 'ChatBot':'You';
let newLine = (sender === 'ChatBot')? '\n':'\n\n';
//get the old value ot textarea and add to it the new msg
document.getElementById('output').textContent = sender + ' : ' + msg + newLine + document.getElementById('output').textContent;
}

//when the form submited do this >>> ,, i have already changed the type of button to submit , so each click of the button will submit the form
document.getElementById('chatbot-form').addEventListener('submit', function(e) {
e.preventDefault();
reply();
document.getElementById('chatbot-form').reset();
});


//function to get a dog image from API and show it on the HTML page
function showMeADog(){
//get a dog image from API
let image = new XMLHttpRequest();
image.onreadystatechange = function(){
if(image.readyState == 4){
//change the returned data from API to Object, and get the url from .message
let url = JSON.parse(image.responseText).message;

Swal.fire({
imageUrl: url,
})
}
}
//the url for API ,, and then send the request
image.open('GET', 'https://dog.ceo/api/breeds/image/random', true);
image.send();
}

function delayedAlert(){
setTimeout(function(){
alert("Did you forget about me? it's your friend, the Alarm!")
}, 2000);
}

async function showMeWeather() {
//i did it here with async await with XMLHttpRequest
// let weather = new XMLHttpRequest();
// await weather.open('GET', 'http://api.openweathermap.org/data/2.5/forecast?q=TORONTO,CA&APPID=1fa7aca95de2f89319fa141b4476eebb', false);
// await weather.send();
// let data = JSON.parse(weather.responseText).list[0];
// console.log(data)

//here with fetch
// fetch('http://api.openweathermap.org/data/2.5/forecast?q=TORONTO,CA&APPID=1fa7aca95de2f89319fa141b4476eebb')
// .then(function(response) {
// return response.json();
// })
// .then(function(data) {
// let data = data.list[0];
// });

// and here with async await and fetch
try {
let response = await fetch('http://api.openweathermap.org/data/2.5/forecast?q=TORONTO,CA&units=metric&APPID=1fa7aca95de2f89319fa141b4476eebb');
let data = await response.json();
data = data.list[0];

//show wither using sweetAletr2
Swal.fire({
imageUrl: `http://openweathermap.org/img/wn/${data['weather'][0]['icon']}@2x.png`,
html:
`<b>Current weather for Toronto</b> <br> ` +
`<span class="weather">${data['main']['temp']}</span> <br>` +
`Min. ${data['main']['temp_min']} - Max. ${data['main']['temp_max']} <br>` +
`Weather : ${data['weather'][0]['main']} <br>` +
`Description : ${data['weather'][0]['description']}<br>` +
`Humidity : ${data['main']['humidity']} <br>`
});
}catch(error){
appendToOutput(error, 1)
}

}