Spaces:
Running
Running
| document.addEventListener("DOMContentLoaded", function() { | |
| const messageInput = document.getElementById("message-input"); | |
| const sendMessageButton = document.getElementById("send-message"); | |
| const conversationHistory = document.getElementById("conversation-history"); | |
| const newConversationButton = document.getElementById("new-conversation"); | |
| const clearConversationsButton = document.getElementById("clear-conversations"); | |
| function sendMessage() { | |
| const userMessage = messageInput.value; | |
| if (!userMessage) return; | |
| addToConversationHistory("You", userMessage); | |
| getBotResponse(userMessage).then(botMessage => { | |
| addToConversationHistory("Bot", botMessage); | |
| }); | |
| messageInput.value = ""; | |
| } | |
| function addToConversationHistory(sender, message) { | |
| const messageElement = document.createElement("p"); | |
| messageElement.textContent = `${sender}: ${message}`; | |
| conversationHistory.appendChild(messageElement); | |
| } | |
| async function getBotResponse(message) { | |
| try { | |
| const response = await fetch('/chatbot', { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/json' | |
| }, | |
| body: JSON.stringify({ query: message }) | |
| }); | |
| if (!response.ok) { | |
| throw new Error('Network response was not ok'); | |
| } | |
| const responseData = await response.json(); | |
| return responseData.reply; | |
| } catch (error) { | |
| console.error('Error fetching bot response:', error); | |
| return "Sorry, there was an error."; | |
| } | |
| } | |
| sendMessageButton.addEventListener("click", sendMessage); | |
| messageInput.addEventListener("keypress", function(event) { | |
| if (event.key === "Enter") { | |
| sendMessage(); | |
| } | |
| }); | |
| newConversationButton.addEventListener("click", function() { | |
| conversationHistory.innerHTML = ""; | |
| }); | |
| clearConversationsButton.addEventListener("click", function() { | |
| conversationHistory.innerHTML = ""; | |
| }); | |
| }); | |