โ ์ด ๋ถ๋ถ์ ์์ ๋ง๋ค์๋ TextQuery Route์ EventQuery Route ๋ฑ์ ์๋ฒ ๋ถ๋ถ๊ณผ ์๋ตํ๋ React ๋ถ๋ถ์ผ๋ก ํ์์ ์ํด ์๋ต ๊ฐ๋ฅํฉ๋๋ค!
1. ์ ์ฒด ์ฝ๋
// Chatbot.js
import React, { useEffect } from "react";
import Axios from "axios";
function Chatbot() {
useEffect(() => {
eventQuery("greeting"); // Dialogflow์ ๋ฑ๋กํด๋ Event
}, []);
// Text Query
const textQuery = async (text) => {
// ๋ด๊ฐ ๋ณด๋ธ ๋ฉ์ธ์ง ๋ณด๊ด
let conversation = {
who: "user",
content: {
text: {
text: text,
},
},
};
// chatbot์ด ๋ณด๋ธ ๋ฉ์ธ์ง ๋ณด๊ด
const textQueryVariables = {
text: text,
};
try {
// text query route์ request ์ ์ก
const response = await Axios.post(
"api/dialogflow/textQuery",
textQueryVariables
);
const content = response.data.fulfillmentMessages[0];
conversation = {
who: "bot",
content: {
text: {
text: content,
},
},
};
console.log(conversation);
} catch (error) {
conversation = {
who: "bot",
content: {
text: {
text: "Error juse occured, please check the problem",
},
},
};
console.log(conversation);
}
};
// Event Query
const eventQuery = async (event) => {
const eventQueryVariables = {
event,
};
try {
const response = await Axios.post(
"api/dialogflow/eventQuery",
eventQueryVariables
);
const content = response.data.fulfillmentMessages[0];
let conversation = {
who: "bot",
content: {
text: {
text: content,
},
},
};
console.log(conversation);
} catch (error) {
let conversation = {
who: "bot",
content: {
text: {
text: "Error juse occured, please check the problem",
},
},
};
console.log(conversation);
}
};
const keyPressHandler = (e) => {
if (e.key === "Enter") {
if (!e.target.value) {
return alert("you need to type something first");
}
// text query route๋ก request ์ ์ก
textQuery(e.target.value);
e.target.value = "";
}
};
return (
<div
style={{
height: 700,
width: 700,
border: "3px solid black",
borderRadius: "7px",
}}
>
<div style={{ height: 639, width: "100%", overflow: "auto" }}></div>
<input
style={{
margin: 0,
width: "98.5%",
height: 50,
borderRadius: "4px",
padding: "5px",
fontSize: "1rem",
}}
placeholder="Send a message..."
onKeyDown={keyPressHandler}
type="text"
/>
</div>
);
}
export default Chatbot;
2. ๊ฒฐ๊ณผ ๐
โ ๋ฐ๋ผํ๋ฉฐ ๋ฐฐ์ฐ๋ ๋ ธ๋, ๋ฆฌ์กํธ ์๋ฆฌ์ฆ - ์ฑ๋ด ์ฌ์ดํธ ๋ง๋ค๊ธฐ ๊ฐ์๋ฅผ ์ฐธ๊ณ ํฉ๋๋ค.