리액트 react-chatbot-kit 버튼형

안녕하세요·2024년 3월 21일
1

react

목록 보기
17/32

챗봇 설정 (config.js)

챗봇의 초기 메시지 설정과 사용자와의 인터랙션을 위한 버튼 위젯 등 주요 설정을 포함합니다. 사용자 정보를 로컬 스토리지에서 불러와 사용하며, 다양한 액션에 대응하는 버튼을 제공합니다.

import { createChatBotMessage } from 'react-chatbot-kit';
import Buttons from './Buttons';
import { getUser } from '../util/localStorage';
import MoreButton from './MoreButton';

const userInfo = getUser() ? getUser().userInfo : '';
const botName = '책박사';
const config = {
    botName: botName,
    initialMessages: [
        createChatBotMessage(<span>안녕하세요 책박사입니다. 무엇을 도와드릴까요</span>, {
            withAvatar: true,
            delay: 500,
            widget: 'firstButtons',
        }),
    ],
    widgets: [
        { widgetName: 'bookName', widgetFunc: () => {} },
        {
            widgetName: 'firstButtons',
            widgetFunc: (props) => <Buttons {...props} />,
            props: {
                buttons: [
                    {
                        text: (
                            <span>
                                bookbooking 사이트에 <br />
                                대해 설명해줘!
                            </span>
                        ),
                        action: 'accountBookbooking',
                    },
                    { text: <span>책검색 하고싶어</span>, action: 'bookName' },
                    { text: <span>신간도서 알려줘</span>, action: 'newBook' },
                    { text: <span>책 대여 순위 알려줘</span>, action: 'rentRanking' },
                    { text: <span>책 좋아요 순위 알려줘</span>, action: 'likeRanking' },
                    { text: <span>상담원과 연결</span>, action: `joinChatRoom` },
                ],
            },
        },
        {
            widgetName: 'showMore',
            widgetFunc: (props) => <MoreButton {...props} />,
            props: {
                buttons: [{ text: '또 다른 정보가 필요하신가요?', action: 'moreInfo' }],
            },
        },
    ],
};

export default config;

설명:

초기 메시지: 챗봇이 사용자에게 처음으로 표시하는 메시지입니다. 여기서는 사용자에게 인사말을 전달하고, 다음 단계의 행동을 유도합니다.
버튼 위젯: 사용자의 다양한 요구에 대응할 수 있는 버튼들을 설정합니다. 각 버튼은 특정 액션을 트리거합니다.

버튼 컴포넌트 (Buttons.js)

사용자의 액션에 따라 적절한 함수를 실행하는 버튼들을 생성합니다.

// Buttons.js
import React from 'react';

const Buttons = ({ buttons, actionProvider }) => {

    const handleClick = (action) => {
        actionProvider[action]();
    };

    return (
        <div className="buttons">
            {buttons.map((button, index) => (
                <button key={index} onClick={() => handleClick(button.action)}>
                    {button.text}
                </button>
            ))}
        </div>
    );
};

export default Buttons;

설명:

버튼 로직: 각 버튼은 클릭 시 actionProvider를 통해 정의된 함수를 호출합니다. 이를 통해 챗봇이 사용자의 요구에 동적으로 반응할 수 있습니다.

액션 함수 예시 (likeRanking)

likeRanking 액션은 책의 좋아요 순위를 불러오고, 결과를 챗봇에 표시합니다. 오류 발생 시 적절한 메시지를 표시합니다.

  likeRanking = async () => {
    try {
      const response = await axios.get(`${process.env.REACT_APP_SERVER_URL}main`);
      const bookData = response.data.likeCounts.slice(0, 4);

      let messageContent;

      if (bookData.length) {
        const bookMessages = bookData.map(book => (
          <BookInfo bookData={book} />
        ));

        // 여기서 추가 메시지를 배열에 추가합니다.
        bookMessages.unshift(
          <span>좋아요 랭킹의 정보 입니다.</span>
        );


        messageContent = bookMessages;
      } else {
        messageContent = <span>해당 책의 정보를 찾을 수 없습니다.</span>;
      }

      const message = this.createChatBotMessage(messageContent, { widget: 'showMore' });

      this.updateChatbotState(message);
    } catch (error) {
      // 에러 처리
      const errorMessage = this.createChatBotMessage("죄송합니다, 책 정보를 불러오는 데 실패했습니다.",
        { widget: "showMore" });
      this.updateChatbotState(errorMessage);
    }
  };

설명:

데이터 요청 및 처리: axios를 통해 서버로부터 책의 좋아요 순위 데이터를 요청하고, 받은 데이터를 기반으로 챗봇 메시지를 생성합니다.
오류 처리: 요청이 실패하면 사용자에게 오류 메시지를 표시합니다.

0개의 댓글