diff --git a/index.html b/index.html index a71e656e..6314b6ea 100644 --- a/index.html +++ b/index.html @@ -589,30 +589,29 @@

Start Your Journey Now!💡

} - - - + + +
+
+

Chatbot

+
+ +
+ + Send +
+ +
+ + +
diff --git a/script.js b/script.js new file mode 100644 index 00000000..f9a7eaf8 --- /dev/null +++ b/script.js @@ -0,0 +1,63 @@ +const chatInput = document.querySelector(".chat-input textarea"); +const sendChatBtn = document.querySelector(".chat-input span"); +const chatbox = document.querySelector(".chatbox"); + +let userMessage = ""; +const API_KEY=""; + +const createChatLi = (message, className) => { + const chatLi = document.createElement("li"); + chatLi.classList.add("chat", className); + let chatContent = + className === "outgoing" + ? `

` + : `smart_toy

`; + chatLi.innerHTML = chatContent; + chatLi.querySelector("p").textContent = message; + return chatLi; +}; + +const generateResponse = (incomingChatLi) => { + const API_URL = `https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent?key=${API_KEY}`; + const messageElement = incomingChatLi.querySelector("p"); + const requestOptions = { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + contents: [ + { + role: "user", + parts: [{ text: userMessage }], + }, + ], + }), + }; + fetch(API_URL, requestOptions) + .then((res) => res.json()) + .then((data) => { + messageElement.textContent = data.candidates[0].content.parts[0].text; + }) + .catch((error) => { + messageElement.textContent = + "Oops! Something went wrong. Please try again later."; + }) + .finally(() => chatbox.scrollTo(0, chatbox.scrollHeight)); +}; + +const handleChat = () => { + userMessage = chatInput.value.trim(); + if (!userMessage) return; + chatInput.value = ""; + + chatbox.appendChild(createChatLi(userMessage, "outgoing")); + chatbox.scrollTo(0, chatbox.scrollHeight); + + setTimeout(() => { + const incomingChatLi = createChatLi("Thinking....", "incoming"); + chatbox.appendChild(incomingChatLi); + chatbox.scrollTo(0, chatbox.scrollHeight); + generateResponse(incomingChatLi); + }, 600); +}; + +sendChatBtn.addEventListener("click", handleChat);