File size: 2,153 Bytes
52d5007
 
 
 
 
 
fc49625
52d5007
 
 
 
 
 
 
 
3aa2e72
fc49625
52d5007
 
 
 
fc49625
 
52d5007
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc49625
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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 = "";
    });
});