This commit is contained in:
everythingonblack
2025-05-29 03:11:22 +07:00
parent 6afcbd8847
commit 6f9e68f431

View File

@@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import styles from './ChatBot.module.css';
const ChatBot = () => {
@@ -17,6 +17,23 @@ const ChatBot = () => {
const [input, setInput] = useState('');
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
if (!localStorage.getItem('session')) {
function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
const sessionId = generateUUID();
const dateNow = new Date().toISOString();
localStorage.setItem('session', JSON.stringify({ sessionId: sessionId, lastSeen: dateNow}))
}
}, []);
const sendMessage = async (textOverride = null) => {
const message = textOverride || input.trim();
if (message === '') return;
@@ -26,6 +43,7 @@ const ChatBot = () => {
{ sender: 'user', text: message, time: getTime() },
...messages,
];
setMessages(newMessages);
setInput('');
setIsLoading(true);
@@ -35,7 +53,7 @@ const ChatBot = () => {
const response = await fetch('https://n8n.kediritechnopark.my.id/webhook/master-agent/ask', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ pertanyaan: newMessages }),
body: JSON.stringify({ pertanyaan: newMessages, sessionId: JSON.parse(localStorage.getItem('session')).sessionId, lastSeen: new Date().toISOString() }),
});
if (!response.ok) throw new Error('Network response was not ok');
@@ -101,7 +119,6 @@ const ChatBot = () => {
)}
<div className={`${styles.message} ${styles[msg.sender]}`}>
{msg.text}
<div className={styles.timestamp}>{msg.time}</div>
{msg.quickReplies && (
<div className={styles.quickReplies}>
{msg.quickReplies.map((reply, i) => (
@@ -115,6 +132,7 @@ const ChatBot = () => {
))}
</div>
)}
<div className={styles.timestamp}>{msg.time}</div>
</div>
{msg.sender === 'user' && (
<img