File size: 2,190 Bytes
494d6fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
62
63
64
65
66
67
68
// Lấy các phần tử DOM
var messages = document.querySelector('.message-list');
var btn = document.querySelector('.btn');
var input = document.querySelector('input');

// Thêm sự kiện cho nút Send và phím Enter
btn.addEventListener('click', sendMessage);
input.addEventListener('keyup', function(e) {
    if (e.key === 'Enter') sendMessage();
});

// Tải lịch sử chat khi trang load
function loadHistory() {
    fetch('/history')
    .then(response => response.json())
    .then(data => {
        for (let i = 0; i < data.length; i++) {
            if (data[i].role === 'User') {
                addMessage({ FROM: 'User', MESSAGE: data[i].content }, 'primary');
            } else if (data[i].role === 'assistant') {
                addMessage({ FROM: 'Oshi no Ko', MESSAGE: data[i].content }, 'secondary');
            }
        }
    })
    .catch(error => console.error('Error:', error));
}

loadHistory();

// Hàm gửi tin nhắn
function sendMessage() {
    var msg = input.value.trim();
    if (!msg) return; // Không gửi tin nhắn rỗng

    // Hiển thị tin nhắn người dùng
    addMessage({ FROM: 'User', MESSAGE: msg }, 'primary');

    // Xóa input sau khi gửi
    input.value = '';

    // Gửi request đến server Flask
    fetch('/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: msg })
    })
    .then(response => response.json())
    .then(data => {
        // Hiển thị phản hồi từ chatbot
        addMessage({ FROM: 'Oshi no Ko', MESSAGE: data.MESSAGE }, 'secondary');
    })
    .catch(error => console.error('Error:', error));
}

// Hàm thêm tin nhắn vào giao diện
function addMessage(msg, typeMessage = 'primary') {
    writeLine(`<span>${msg.FROM}</span><br><br> ${msg.MESSAGE}`, typeMessage);
}

// Hàm tạo dòng tin nhắn
function writeLine(text, typeMessage) {
    var message = document.createElement('li');
    message.classList.add('message-item', 'item-' + typeMessage);
    message.innerHTML = text;
    messages.appendChild(message);
    messages.scrollTop = messages.scrollHeight; // Cuộn xuống cuối cùng
}