Giter Club home page Giter Club logo

react-chatbotify's Introduction

React ChatBotify

Table of Contents

Introduction

React ChatBotify is an intuitive and versatile chatbot library tailored to streamline your development process while providing the flexibility to implement advanced features. It is crafted to meet a wide range of requirements, whether you're building a straightforward FAQ chatbot, an intricate conversational interface or even an integration with Large Language Models (LLMs).

React ChatBotify aims to simplify the creation of chatbots by offering a user-friendly experience while accommodating the diverse needs of developers. With its extensive capabilities, you can easily customize and expand your chatbot's functionalities. From basic interactions to sophisticated conversational flows, React ChatBotify empowers you to build chatbots that meet your specific project goals. Head over to our community showcases and get inspired to start your own today!

npm install react-chatbotify --save

Note that this repository contains the code for the library. If you're looking for the repository for the React ChatBotify user guide, you may look here.

Features

React ChatBotify offers a wide array of features designed to enhance your chatbot experience. Here are just a few of the key features:

  • Dynamic Attributes: Create interactive conversations by dynamically generating messages and defining multiple conversation paths based on user inputs.
  • Custom Rendering of Components: Seamlessly integrate your own custom components into the chatbot interface to boast your application's unique design and functionality.
  • Stream Responses: Integrate with LLM models and custom endpoints to stream (or even simulate) your bot responses for an elevated user experience.
  • Timeouts and Auto-Transitions: Set timeouts and automate transitions between chatbot paths, providing users with a guided flow and journey.
  • Voice Input & Audio Output: Enable voice input for users to interact with the chatbot through speech, and leverage audio output capabilities to provide spoken responses or prompts.
  • Chat Notifications: Keep users informed with real-time chat notifications, ensuring they never miss important updates or new messages.
  • Checkbox & Options Support: Utilize checkboxes and options within the chatbot interface, allowing users to select from a list of choices and easily make selections.
  • Emoji Picker: Enhance the chatbot's expression and engagement with users by incorporating emojis into messages, adding a touch of personality and emotion.
  • File Attachments: Seamlessly handle file attachments within the chatbot, enabling users to share and receive documents, images, or other relevant files during conversations.
  • Mobile-Friendly Interface: Provide smooth user experience across various devices with our mobile-friendly chatbot interface.

These features, along with many others, empower developers to create highly interactive and personalized chatbot experiences tailored to their specific application requirements.

Technologies

Technologies used by React ChatBotify are as below:

Done with:

ReactJS

Typescript

Project Repository

Quickstart

For a thorough walkthrough on getting started, you may refer to the Quickstart Guide on the Documentation Website.

Documentation

A full documentation (along with a live playground) for the library can be found at the following link:

Examples on the website are also run on a live editor so feel free to explore to your heart's content!

Team

Contributing

If you are looking to contribute to the project, you may find the Developer Guide useful.

In general, the forking workflow is encouraged and you may open a pull request with clear descriptions on the changes and what they are intended to do (enhancement, bug fixes etc). Alternatively, you may simply raise bugs or suggestions by opening an issue or raising it up on discord.

Note: Templates have been created for pull requests and issues to guide you in the process.

Support

If there are any questions pertaining to the application itself (usage or implementation wise), you may create an issue, raise it up on discord, or drop me an email at: [email protected].

Attributions

Images

Credits are to be given for the following images:

Sound

Credits are to be given for the notification sound:

Inspirations

As I have used similar alternatives at some point in my developer journey, some inspirations have been taken from them and they ought to be credited here:

Note: All other media content are hand-drawn unless otherwise stated, feel free to use them!

react-chatbotify's People

Contributors

cubiquitous avatar dependabot[bot] avatar filmel avatar haecheonlee avatar i-vishal-kumar avatar leesinchen avatar mushroomgenie avatar sharabhh avatar tjtanjin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

react-chatbotify's Issues

Need to Control Initial start Message Delay in React Chatbotify

Hello,

I am using React Chatbotify for a project and I've encountered an issue. There seems to be a delay before the start message is shown when the chatbot is initialized. I would like to control this delay, ideally setting it to zero so that the start message appears immediately.

I've looked through the documentation and the source code, but I couldn't find a specific setting or property that controls this delay. It's possible that I've missed it, or that this feature is not directly configurable.

Could you please provide some guidance on how to control the delay of the start message in React Chatbotify? If this feature is not currently available, could it be considered for a future update?

[Task] Update test cases for new features

Description
The library currently runs a suite of test cases using selenium webdriver. However, the test cases have not been expanded to include the new features. For a start, it would be great to add the following 3 test cases:

  • User cannot type above character limit if it is set (characterLimit)
  • When new messages are received, the new message popup is shown (showMessagePrompt)
  • When user clicks on new message prompt, it automatically scrolls down to the latest message (autoJumpToBottom)

[Task] Add versioning logic to themes as part of v2.0.0

Description:
Currently, working-branch-2.0.0 is able to support themes provided from the themes repository. However, it identifies themes only by name and this can be an issue if themes are abruptly updated by authors in the future. Ideally, themes should be versioned such that once published, a version cannot be modified. That way, users can select themes based on a version and "lock" onto it without worrying about the theme suddenly changing its appearance.

In lieu of that, the main repository needs to support the following logic:

  • If user specifies only a theme by name, grab the latest version that is specified inside meta.json.
  • If user specifies a theme with version, grab the theme version files.
  • If user specifies a theme with an invalid version, fallback to the latest version (similar to the first bullet point)

On top of these changes, the structure of the themes repository would also need to be updated to nest another layer. Currently, the structure is as such:

|- themes
    |- minimal_midnight
        |- meta.json
        |- styles.css
        |- options.json
        |- display.png
    |- retro
        |- meta.json
        |- styles.css
        |- options.json
        |- display.png

To support versioning, the following structure is proposed:

|- themes
    |- minimal_midnight
        |-0.1.0
            |- meta.json
            |- styles.css
            |- options.json
            |- display.png
    |- retro
        |-0.1.0
            |- meta.json
            |- styles.css
            |- options.json
            |- display.png

Developers who are taking on this task should take note that changes are required to be made both on this main repository and on the themes repository.

[Task] Add support for input validation within input textarea

Description:
Several users have brought up request for feature of allowing input validation to be done within the input textarea. Currently, the only way to do validation is after user sends the message. It would be great if validation can be done before a user even sends it. The tentative suggested approach is as follows:

  • Add a new inputValidator attribute to block which accepts 2 properties validator and errorMessage
  • The validator property will return true or false and if false, then the errorMessage is displayed

Position of the error message is tentatively above chat input container in the form of a small popup bar. The chat input textarea itself should also be outlined in red when error is shown. Upon displaying the error, it should only be dismissed when user make changes to the textarea.

[Feat] User Experience Window

Is your feature request related to a problem? Please describe.
Not exactly a problem, instead is related to the Chat Bot user experience (chat bot window behavior minimize, close, maximize / restore).

Describe the solution you'd like
I would like that the chat bot window behavior, would be as the classical window explorer:

Describe alternatives you've considered

  1. The actual close button, behaves as minimize button, when you click on it, minimizes the chat bot window, so i suggest to change the X close icon, for a - minimize icon.
  2. Next to the minimize icon, add a second icon (X close button), when you click on it, should trigger a close function that delete all the chat bot messages, including history and minimize the chat bot window. This could be a re render of the chat bot component.
  3. Add a third icon maximize / restore size, as it name suggest, it should maximize - restore the chat bot window size, as a window explorer item.

Also you could add new options, to asign a function to be executed when OnClick over close button.

Just a couples of suggestions.

Best regards,
Alberto

[Help] How to keep bot typing status while Backend call is being made

Bug Description
I am follow this example to make an api call based on the user option selection.
https://react-chatbotify.tjtanjin.com/docs/examples/smart_conversation

The api call might take a while to return, is there a way to persist the Both typing indicator, so the user knows that something is happing.
Currently the bot typing indicator shows up for a brief moment, and then disappears, and the api call has still not returned.
So the user is unsure whether they need to take some action or its still processing.

Either a way to show a loading indicator or bot typing indicator while the call is in flight, would be super helpful from UX perspective.

[Feat] Implement dotenv to manage environment variables

Description
The project should have at least one .env file to store multiple environment variables used in the codebase.

The solution
Fortunately, as this projects uses vite, we can take advantage to the fact that vite uses dotenv by default. It just requires a simple configuration to start using environment variables. Check the documentation

Alternatives
There's really no better way to handle the issue. Other options are to use secret management platforms like Infiscal. However, as vite is already using dotenv by default, we should go ahead with dot env.

Additional context
Having an environment variable configuration is a core functionality for any project. I may be a little troublesome at first due to the fact that every developer must create a new non-tracked file for their cloned repository. However, like I said before, this is a core functionality.

An example
This is a basic example of the implementation of a dotenv configuration.

In file BotOptionsService.tsx
Screenshot 2024-05-02 at 2 52 11 PM

The idea is to replace the static variable for the CDN link and have the option to get it from the .env file.

Screenshot 2024-05-02 at 2 52 43 PM

Then, in the .env file, we will be able to switch between a production environment link and a local development link.

[Bug] Fix load & previous chat history text overflow

Bug Description
The bug occurs when a user modifies the load chat history button text or previous chat history line break text with a very long message. Basically, the button/line break will then expand to fill up the entire width of the chat window and possibly break into the next line as well. This is visually unappealing, and there should be a maximum width set such that beyond a certain text length, the characters are replaced with ellipsis.

Steps To Reproduce
Steps to reproduce the bug behavior:

  1. Modify the load/previous chat history text with a very long message
  1. Observe the visual differences

Expected behavior
Long text should be trimmed and replaced with ellipsis at the end.

[Help] Using multiple advance options

In my project i want to use multiple advance options namely useCustomBotOptions & useCustomMessages.
This has resulted in some problems. Mainly that the customMessages disregard the customBotOptions entirely. i use audio but it dosen't make any sound i also use simstream which dosen't do anything

I don't know if i set it properly i will share code below

    const defaultBotOptions = getDefaultBotOptions()
    const { voice, audio, chatHistory, botBubble,advance, tooltip, header } = defaultBotOptions
    const [botOptions, setBotOptions] = useState<Options>({
        ...defaultBotOptions,
        isOpen: false,
        audio: {
            ...audio,
            language: 'es-ES',
            volume: 1,
            voiceNames: ['Google español'],
            rate: 1,
            disabled: false,
            defaultToggledOn: true,
        },
        voice: {
            ...voice,
            disabled: false,
        },
        chatHistory: {
            ...chatHistory,
            disabled: true,
        },
        header: {
            ...header,
            title: 'Chatbot',
        },
        tooltip: {
            ...tooltip,
            text: '¡Háblame!',
            mode: 'START'
        },
        botBubble: {
            ...botBubble,
            simStream: true,
            streamSpeed: 60
        },
        advance: {
            ...advance,
            useCustomBotOptions: true,
            useCustomMessages: true
        }
    })
    const [messages, setMessages] = useState<any[]>([])

    useEffect(() => {
        if (botOptions.isOpen) {
            setTimeout(() => {
                setMessages(prev => [...prev, { content: '¿Necesitamos tu información para hacer un formulario?', sender: 'bot' }])
            }, 2000);
        }
    }, [botOptions])

    return (
        <>
            <Homepage />
            <div style={{ position: 'fixed', bottom: 20, right: 20 }}>
                <BotOptionsContext.Provider value={{ botOptions, setBotOptions }}>
                    <MessagesContext.Provider value={{ messages, setMessages }}>
                        <ChatBot 
                            options={botOptions} 
                            flow={{
                                start: {
                                    message: '¿Como te llamas?'
                                }
                            }} 
                        />
                    </MessagesContext.Provider>
                </BotOptionsContext.Provider>
            </div>
        </>
    );

Any form of help is greatly apreciated 😊

[Bug] duplicate messages

when setting chatHistory:{disabled:true} , the first 2 messages are always a duplicate,

i solved it by simply adding the following in ChatBotContainer.tsx line 108 (an empty message if history is disabled )
but i don't think that's a good way to fix it , so if you can find the bug it would be amazing , best of luck!

if (botOptions.chatHistory?.disabled) {
localStorage.removeItem(botOptions.chatHistory?.storageKey as string);
//added to prevent bug
const messageContent = {
content: <></>,
type: "object",
isUser: false,
timestamp: null,
};
setMessages([messageContent]);

[Task] Add test cases for sensitive text and markup language

Description:
In v1.6.0, new features for handling sensitive input (sensitiveInput) and markup language (userBubble.dangerouslySetInnerHtml, botbubble.dangerousSetInnerHtml) have been added. It'll be great to add test cases to cover the following:

  • Add a new block to the existing flow in App.tsx that has isSensitive set to true. User input in textarea should be masked and when message is sent, chat bubble should also be masked.
  • Markup language is disabled by default, so attempts to sender <b>hello</b> or similar texts should result in an unformatted plain text string.

Similar approach can be referenced here: #29

Note:
The current testing approach is not ideal, as it does not allow for varying the initial configuration (e.g. testing with markup language enabled instead). This can be supported if the <ChatBot/> inside App.tsx is wrapped by the custom BotOptionsContext and then external buttons are provided for varying configurations (selenium webdriver would then be used to interact with these buttons). Good to explore this down the line.

[Task] Compress/resize the image/audio assets to an appropriate size to reduce build package size

Description:
Currently, in v1.5.1, the build size is around 1.7mb. This is an improvement from previous versions where the build size goes up to 4mb (yikes!). Moving forward, there is room to further reduce the build package size by compressing/resizing the image/audio assets. Some of them are still larger than they need to be.

Note:

  • Pull requests should be opened to the branch working-branch-2.0.0 instead of master

[Help] How to support new lines in message content

Hello,
My api returns some content which is formatted with new lines and some lists. Something like this:

Details for the product:
 - A 
 - B
 - C
Another detail:
 - X
 - Y

How can I suppose this in the message rendering when a bot responds ?

[Bug] ReferenceError: window is not defined and flow not working and flow not working properly

Bug Description

Hello! I am having the error below when i use chatbotify with Nextjs (yes i am using "use client" on the component). This error is happening everytime when a refresh the page. Yet the flow is not working properly.

//console error

⨯ node_modules\react-chatbotify\dist\index.js (914:1) @ eval ⨯ ReferenceError: window is not defined at __webpack_require__ (C:\Users\Suave\Documents\sandbox\suave-chat-bot-v2\.next\server\webpack-runtime.js:33:42) at eval (./src/components/SuaveChatBot/SuaveChatBot.tsx:9:74) at (ssr)/./src/components/SuaveChatBot/SuaveChatBot.tsx (C:\Users\Suave\Documents\sandbox\suave-chat-bot-v2\.next\server\app\page.js:173:1) at __webpack_require__ (C:\Users\Suave\Documents\sandbox\suave-chat-bot-v2\.next\server\webpack-runtime.js:33:42) at eval (./src/app/page.tsx:7:95) at (ssr)/./src/app/page.tsx (C:\Users\Suave\Documents\sandbox\suave-chat-bot-v2\.next\server\app\page.js:162:1) at __webpack_require__ (C:\Users\Suave\Documents\sandbox\suave-chat-bot-v2\.next\server\webpack-runtime.js:33:42) at JSON.parse (<anonymous>) null

//Component code.

`
"use client";
import React, { useState } from "react";
import ChatBot from "react-chatbotify";

const SuaveChatBot = () => {
const [form, setForm] = useState({});
const flow = {
start: {
message: "Olá! Tudo bem ? Meu nome é Érica",
function: (params: any) => setForm({ ...form, name: params.userInput }),
path: "presentation",
},
presentation: {
message: "Tenho ótimos negócios este mês para sair com seu novo Audi.",
path: "ask_name",
},
ask_name: {
message:
"Mas antes de prosseguir, preciso de algumas informações. Qual é o seu nome?",
chatDisabled: false,
path: "end",
},
end: {
message: (params: any) => I see you are ${params.userInput}!,
chatDisabled: true,
},
};
return (
<>

</>
);
};

export default SuaveChatBot;
`

Steps To Reproduce
Steps to reproduce the bug behavior:

  1. Start a new clean Nextjs Project
  2. Import the bot css on layout.tsx
  3. Create a new component (e.g MyCustomBot.tsx)
  4. Set "use client" at the top
  5. Import the component to your desired page

Expected behavior
You can see on the console the error mentioned above

Desktop (please complete the following information):

  • OS: [Windows 11]
  • Browser: chrome

[Task] Refactor chatinput component to support custom buttons

Description:
Chatinput components currently support the following buttons that are pre-determined and can be configured to be shown or hidden:

  • Voice Button
  • Send Button

However, custom buttons are not allowed. It would be great to allow users to define their own button components for chatinput as well. Below I share a possible approach:

  • Include a buttons prop in chatinput that takes in either a keyword (string) or a custom component (which would be buttons provided by the user)
  • By default, buttons prop would look as such: ["voice", "send"] (it essentially contains 2 keywords representing the default buttons)
  • A user can specify a custom component within it so for example: ["voice", <CustomButton/>, "send"]
  • Buttons would be rendered in the order specified within the array

Feel free to take on a different approach if you have other ideas. Bear in mind that users need to be able to control the order of the buttons and that the configuration should be kept as simple as possible.

Related to #23

[Epic] Add New Themes to Project Styling

Description:
This epic encompasses the task of introducing new themes to the project as part of the v2.0.0 update. By adding a variety of themes, we aim to enhance user experience and provide easy access to more customization options. Note that themes are managed within a separate themes repository and all pull requests to create new themes should be made there. However, the tracking of progress for v2.0.0 will be done in this main repository.

Note:

  • Theme authors should open pull requests here when submitting new themes
  • This epic will be resolved when the set of themes to release in v2.0.0 are completed

[Bug] duplicate first message when chat history is disabled

Bug Description

When i disable ChatHistory using disabled option, the first message comes duplicated.

Steps To Reproduce
Steps to reproduce the bug behavior:

   chatHistory: {
          disabled: true,
    },

Expected behavior
Duplicated first message

Screenshots
image

Desktop (please complete the following information):

  • OS: Linux
  • Browser: Chrome, FIrefox

[Feat] Update and improve existing image assets

Is your feature request related to a problem? Please describe.
Some of the image assets are poorly drawn and unnecessarily large in size. It'll be great to redraw these assets (e.g. using draw.io which allows svg exports) to reduce the bundle size and improve the quality of the assets used.

Describe the solution you'd like
New updated and better drawn assets!

[Feat] Support dark mode

Is your feature request related to a problem? Please describe.
No, it's a new feature. It would be nice to have dark mode.

[Epic] Refactor Options Prop in ChatBot

Description:
In lieu of the upcoming theme changes, there may be potential confusions with the options prop for the following reasons:

  • Within options, there is currently a theme section that contains several properties such as showHeader and fontFamily (can be confused with the upcoming theme prop
  • Styles are currently nested on the same level as configurations (i.e. header and headerStyles are on the same level), and it would be clearer if all styles are nested within a styles section instead

Note:

  • As this is a breaking change and we should minimize this as much as possible, thorough work should be done to review and evaluate all existing options and cleanly reorganize options

[Task] Refactor footer component to support custom buttons

Description:
Footer components currently support the following buttons that are pre-determined and can be configured to be shown or hidden:

  • File Attachment Button
  • Emoji Button

However, custom buttons are not allowed. It would be great to allow users to define their own button components for the footer as well. Below I share a possible approach:

  • Include a buttons prop in footer that takes in either a keyword (string) or a custom component (which would be buttons provided by the user)
  • By default, buttons prop would look as such: ["file_attachment", "emoji"] (it essentially contains 2 keywords representing the default buttons)
  • A user can specify a custom component within it so for example: ["file_attachment", <CustomButton/>, "emoji"]
  • Buttons would be rendered in the order specified within the array

Feel free to take on a different approach if you have other ideas. Bear in mind that users need to be able to control the order of the buttons and that the configuration should be kept as simple as possible.

Related to #23

[Task] Bump up to React 19

Description:
Users on ReactJS 19/NextJS 15 are reporting issues using React ChatBotify. It's worth bumping up to support React 19. Have gone through the React 19 changelog and there aren't significant code changes required. Also good to take the chance to update the workflows to test against multiple React versions.

[Task] Add pre-commit hooks to check for lint

Description:
Lint, build and test is currently done only on the GitHub CI/CD pipeline. It would be great to have a pre-commit hook that minimally does linting locally to reduce instances of failed pipelines.

[Help] Simulate Stream is not working

First let me tell you that this is a so great library! very usfeul! I have tested with my own logic, API request messages, options etc...

I just want to simulate stream in messages, by setting botBubble: {simStream: true}, but nothing happens, it is not simulating stream messages behavior, any advice?

[Bug] Fix chat history loading spinner height

Bug Description
For chatbots configured to support chat history, you will notice a button at the top of the chat window that users can click to view historical messages. Upon clicking the button, the chat messages shift slightly as the loading spinner element that replaces the original button has a slightly different height. This does not cause issues functionally but is a small visual bug that would be nice fix.

Steps To Reproduce
Steps to reproduce the bug behavior:

  1. Go to chatbot
  2. Click on load chat history button
  3. Notice existing messages shift slightly

Expected behavior
Existing messages should not even budge until the chat history is loaded

[Feat] Possibility to apply input masks

Is your feature request related to a problem? Please describe.

It's a good practice to sanitze input fields on any type of input. So for example, when the bot asks a name, the user can't type numbers or when the bot asks a phone number, the user can't type letters and have a limited characters to type (we can use regexe for this and apply input maks).

Describe the solution you'd like

For phone example, something like this:

image

Describe alternatives you've considered

I think the easiest way to implement this would be to allow the developer to implement custom regex in the bot's input. However, the ideal way would be to allow the user to use their own input component instead of the bot's current input.

[Bug] NextJs Window not defined issue

Bug Description

./app/globals.css
 ⚠ Fast Refresh had to perform a full reload due to a runtime error.
 ⚠ Fast Refresh had to perform a full reload due to a runtime error.
 ⨯ node_modules/react-chatbotify/dist/index.js (915:8) @ window
 ⨯ ReferenceError: window is not defined
    at __webpack_require__ (/Users/kavinsharma/Desktop/work/MediExplore/.next/server/webpack-runtime.js:33:42)
    at eval (./app/component/atom/Banner.js:13:74)
    at (ssr)/./app/component/atom/Banner.js (/Users/kavinsharma/Desktop/work/MediExplore/.next/server/app/page.js:283:1)
    at __webpack_require__ (/Users/kavinsharma/Desktop/work/MediExplore/.next/server/webpack-runtime.js:33:42)
null
 ⨯ node_modules/react-chatbotify/dist/index.js (915:8) @ window
 ⨯ ReferenceError: window is not defined
    at __webpack_require__ (/Users/kavinsharma/Desktop/work/MediExplore/.next/server/webpack-runtime.js:33:42)
    at eval (./app/component/atom/Banner.js:13:74)
    at (ssr)/./app/component/atom/Banner.js (/Users/kavinsharma/Desktop/work/MediExplore/.next/server/app/page.js:283:1)
    at __webpack_require__ (/Users/kavinsharma/Desktop/work/MediExplore/.next/server/webpack-runtime.js:33:42)
null
 ⨯ node_modules/react-chatbotify/dist/index.js (915:8) @ window
 ⨯ ReferenceError: window is not defined
    at __webpack_require__ (/Users/kavinsharma/Desktop/work/MediExplore/.next/server/webpack-runtime.js:33:42)
    at eval (./app/component/atom/Banner.js:13:74)
    at (ssr)/./app/component/atom/Banner.js (/Users/kavinsharma/Desktop/work/MediExplore/.next/server/app/page.js:283:1)
    at __webpack_require__ (/Users/kavinsharma/Desktop/work/MediExplore/.next/server/webpack-runtime.js:33:42)
null
 ⨯ node_modules/react-chatbotify/dist/index.js (915:8) @ window
 ⨯ ReferenceError: window is not defined
    at __webpack_require__ (/Users/kavinsharma/Desktop/work/MediExplore/.next/server/webpack-runtime.js:33:42)
    at eval (./app/component/atom/Banner.js:13:74)
    at (ssr)/./app/component/atom/Banner.js (/Users/kavinsharma/Desktop/work/MediExplore/.next/server/app/page.js:283:1)
    at __webpack_require__ (/Users/kavinsharma/Desktop/work/MediExplore/.next/server/webpack-runtime.js:33:42)
null

Code Snippet

"use client";
"use strict";
import { lazy, Suspense, useContext, useEffect, useState } from "react";
import ChatBot, { getDefaultBotOptions } from "react-chatbotify";
// import { useAiState } from "../atom/AistateProvier";
import { BotOptionsContext } from "react-chatbotify";
import { useRouter } from "next/navigation";
import { AiStateContext } from "../atom/AistateProvier";

const MyChatBot = () => {
  const [form, setForm] = useState({});
  // const { isOpen, setIsOpen } = useAiState();
  const { isOpen, setIsOpen } = useContext(AiStateContext);

  const defaultBotOptions = getDefaultBotOptions();
  const router = useRouter();
  const [option, setOption] = useState({
    ...defaultBotOptions,
    theme: {
      ...defaultBotOptions.theme,
      embedded: false,
      secondaryColor: "#1A3057",
      primaryColor: "#077D65",
    },
    header: {
      ...defaultBotOptions.header,
      title: <h3>AI Assitant!!</h3>,
      avatar: "https://img.icons8.com/color/48/message-bot.png",
    },
    chatHistory: {
      ...defaultBotOptions.chatHistory,
      storageKey: "example_advanced_form",
    },
    chatButton: {
      ...defaultBotOptions.chatButton,
      icon: "https://img.icons8.com/color/48/message-bot.png",
    },
    tooltip: {
      ...defaultBotOptions.tooltip,
      mode: "CLOSE",
      text: "AI Assistant! 😊",
    },
    isOpen: isOpen,
    advance: {
      useCustomBotOptions: true,
    },
    footer: {
      ...defaultBotOptions.footer,
      text: (
        <div style={{ cursor: "pointer" }} onClick={() => router.push("/")}>
          <span>Powered By </span>
          <span style={{ fontWeight: "bold" }}>
            <span> MediXplore.co</span>
          </span>
        </div>
      ),
    },
  });
  useEffect(() => {
    setOption((prev) => ({ ...prev, isOpen }));
  }, [isOpen]);

  console.log("&&&&&&&", isOpen);
  const fetchMinMax = async () => {
    let countryURL = ``;
    for (let index in form.countries) {
      countryURL += `&filters[$or][${index}][hospital_form][country][id][$eq]=${form.countries[index]}`;
    }
    const maxURL = `https://cms-backend.medixplore.co/api/hospitaltreatmentprices?sort=max:desc&pagination[page]=1&pagination[pageSize]=1&filters[treatment][id][$eq]=${form.treatment}${countryURL}`;
    const getMax = fetch(maxURL);
    const minURL = `
		https://cms-backend.medixplore.co/api/hospitaltreatmentprices?sort=min&pagination[page]=1&pagination[pageSize]=1&filters[treatment][id][$eq]=${form.treatment}${countryURL}`;
    const getMin = fetch(minURL);

    const [min, max] = await Promise.allSettled([getMin, getMax]);
    const minData = await min.value.json();
    const maxData = await max.value.json();
    return {
      min: minData.data[0].attributes.min,
      max: maxData.data[0].attributes.max,
    };
  };

  const flow = {
    start: {
      message:
        "I'm Amy from MediXplore. We help people find the best medical treatments, whether you're looking for options close to home or considering treatment abroad. ",
      transition: { duration: 1000 },
      path: "init",
    },
    init: {
      message: "Here is list of most popular treatments.",
      options: ["Knee replacement", "Heart Bypass surgery", "Spinal Fusion"],
      chatDisabled: true,
      function: (params) => {
        // to be replaced via api calls l
        const idMappings = {
          "Knee replacement": 3,
          "Heart Bypass surgery": 56,
          "Spinal Fusion": 51,
        };

        const val = idMappings[params.userInput];

        console.log("val is", val);
        setForm({ ...form, treatment: val });
      },
      path: "ask_countries",
    },
    ask_countries: {
      message:
        "Great! To help narrow down your options, tell me, in which country are you generally interested in receiving treatment? We have several destinations known for their quality and affordability. Some top destinations include:",
      checkboxes: {
        items: ["Singapore", "Malaysia", "Thailand"],
        min: 1,
        max: 3,
      },
      chatDisabled: false,
      function: (params) => {
        const countriesMapping = {
          Singapore: 1,
          Malaysia: 2,
          Thailand: 4,
        };
        let selections = [];

        for (let country of params.userInput.split(",")) {
          if (countriesMapping[country.trim()]) {
            selections.push(countriesMapping[country.trim()]);
          }
        }
        setForm({ ...form, countries: selections });
        console.log("selections", selections);
      },
      path: "ask_budget",
    },
    ask_budget: {
      message: async (params) => {
        const val = await fetchMinMax();
        console.log("val", val);
        setForm({ ...form, range: val });
        return `Wonderful! To give you the most relevant options, it helps to know your budget for the procedure. Minimum: ${val.min}$ Maximum : ${val.max}$`;
      },

      function: (params) => setForm({ ...form, budget: params.userInput }),
      path: async (params) => {
        console.log("val is", form.range);
        if (isNaN(Number(params.userInput))) {
          await params.injectMessage("Budget needs to be a number!");
          return;
        }
        if (params.userInput < form.range.min) {
          await params.injectMessage(
            `Budget can't be less then specified range i.e. Minimum: ${form.range.min}$ Maximum : ${form.range.max}$`
          );
          return;
        }
        return "input_name";
      },
    },

    input_name: {
      message: "Kindly enter your name",
      chatDisabled: false,
      function: (params) => setForm({ ...form, name: params.userInput }),
      path: "input_email",
    },
    input_email: {
      message: "Enter your email",
      chatDisabled: false,
      function: (params) => setForm({ ...form, email: params.userInput }),
      path: "input_phone",
    },
    input_phone: {
      message: "Enter your phone",
      chatDisabled: false,
      function: (params) => setForm({ ...form, phone: params.userInput }),
      path: "prepare_search",
    },
    prepare_search: {
      message:
        "Yipee!! Your search results are ready!! Kindly click below to view them!!",
      options: ["See Search Results!!", "Retry"],
      chatDisabled: true,
      path: "process_input",
    },
    process_input: {
      transition: { duration: 0 },
      chatDisabled: true,
      path: async (params) => {
        switch (params.userInput) {
          case "See Search Results!!":
            let link = `/search?budget=${form.budget}&tr=${form.treatment}`;

            for (let country of form.countries) {
              link += `&co=${country}`;
            }
            await params.injectMessage("Sit tight! I'll send you right there!");
            setTimeout(() => {
              router.push(link);
            }, 1000);
            return "repeat";
          case "Retry":
            return "repeat";
            break;
        }
      },
    },
    repeat: {
      transition: { duration: 1000 },
      path: "start",
    },
  };
  const [isLoaded, setIsLoaded] = useState(false);
  useEffect(() => {
    setIsLoaded(true);
  }, []);
  return (
    <BotOptionsContext.Provider
      value={{ botOptions: option, setBotOptions: setOption }}
    >
      {isLoaded && (
        <Suspense fallback={<div>Loading...</div>}>
          <ChatBot flow={flow} options={option} />
        </Suspense>
      )}
    </BotOptionsContext.Provider>
  );
};

export default MyChatBot;

as per given solution in this issue https://github.com/tjtanjin/react-chatbotify/issues/19
it works to import the ChatBot but i am also using getDefaultBotOptions and BotOptionsContext and they are not working while trying with lazy function.

resizing not working on safari and chrome (mobile) [Bug]

hello,

i tried to fix it be myslef but failed,

the chatbot is not resizing correctly in mobile when opening the keyboard (issue only on safari and chrome mobile)

as you can see when opening the keyboard on mobile , the chatbots input is hidden, you will need to scroll to see it

chrome 1
chrome 2
samsung internet

[Task] Refactor header component to support custom buttons

Description:
Header components currently support the following buttons that are pre-determined and can be configured to be shown or hidden:

  • Notification Button
  • Audio Button
  • Close Button

However, custom buttons are not allowed. It would be great to allow users to define their own button components for the header as well. Below I share a possible approach:

  • Include a buttons prop in header that takes in either a keyword (string) or a custom component (which would be buttons provided by the user)
  • By default, buttons prop would look as such: ["notification", "audio", close"] (it essentially contains 3 keywords representing the default buttons)
  • A user can specify a custom component within it so for example: ["notification", <CustomButton/>, "audio", "close"]
  • Buttons would be rendered in the order specified within the array

Feel free to take on a different approach if you have other ideas. Bear in mind that users need to be able to control the order of the buttons and that the configuration should be kept as simple as possible.

Related to #23

[Epic] Add Custom Component Buttons in Header/Footer

Description:
The current header/footer has a set of buttons that are pre-determined by the chatbot. Users may have use-cases beyond what the chatbot provides and it would be great if they can add their own buttons with their own logic.

Note:

  • As a stretch goal, one may also consider adding custom components for the chat input textarea (where the send button is)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.