Skip to content

Instantly share code, notes, and snippets.

@FredrikOseberg
Last active July 19, 2021 09:29
Show Gist options
  • Save FredrikOseberg/8b3cfadeb1980bdb7b52cd4138d64542 to your computer and use it in GitHub Desktop.
Save FredrikOseberg/8b3cfadeb1980bdb7b52cd4138d64542 to your computer and use it in GitHub Desktop.
import React, { useState } from "react";
import Chatbot from "react-chatbot-kit";
import config from "./config";
import actionProvider from "./actionProvider.js";
import messageParser from "./messageParser.js";
function App() {
const [showBot, toggleBot] = useState(false);
const saveMessages = (messages) => {
localStorage.setItem("chat_messages", JSON.stringify(messages));
};
const loadMessages = () => {
const messages = JSON.parse(localStorage.getItem("chat_messages"));
return messages;
};
return (
<div className="App">
{showBot && (
<Chatbot
config={config}
actionProvider={actionProvider}
messageHistory={loadMessages()}
messageParser={messageParser}
saveMessages={saveMessages}
/>
)}
<button onClick={() => toggleBot((prev) => !prev)}>Bot</button>
</div>
);
}
export default App;
@g4rry420
Copy link

Got it, Thank You.

@g4rry420
Copy link

The messages only get to save to the localstorage when the chatbot unmounts. Is isn't it possible that whenever the user types the message to the chatbot, it got saved to the localstorage while the chatbot is still mounted.

@FredrikOseberg
Copy link
Author

FredrikOseberg commented Dec 30, 2020 via email

@g4rry420
Copy link

Also, is that possible to control the calling of loadMessages() function. I mean I want to call this method everytime there is a change in the localStorage ?

@ForeverKetone
Copy link

@g4rry420 were you able to create chat saving and loading? I'm stuck on same thing :)

@dtcyad1
Copy link

dtcyad1 commented Feb 23, 2021

Hi Fredrick, the load and save works fine when you minimize the chatbot. I was trying to get it to work in the ActionParser and MessageParser so i could save after each and every message. I was partially successful in saving it in the ActionParser:

var localMessages = JSON.parse(localStorage.getItem("chat_messages"));
if (localMessages)
{
localMessages.push({message});
}
else
{
localMessages = [];
localMessages.push({message});
}

localStorage.setItem("chat_messages", JSON.stringify(localMessages));

However, i was not able to save it in the MessageParser - since i only get the text and not the actual message object(with unique id...)

In any case, this seems a bit overhead to read from the local storage and then save it back. What is a more efficient way to do this and how do we get it working even from the MessageParser?

Thanks

@vasuksh
Copy link

vasuksh commented Jul 19, 2021

The messages only get to save to the localstorage when the chatbot unmounts. Is isn't it possible that whenever the user types the message to the chatbot, it got saved to the localstorage while the chatbot is still mounted.

you could save messages in action provider using an array of objects to save ques and ans like this -

import db from "../firebase";
var chat = [];

async function sendData() {
await db
.collection("bot")
.add({ chatBot: chat })
.then(() => {
console.log("success");
chat = [];
})
.catch((error) => {
console.log(error);
});
}

class ActionProvider {
constructor(createChatBotMessage, setStateFunc, createClientMessage) {
this.createChatBotMessage = createChatBotMessage;
this.setState = setStateFunc;
this.createClientMessage = createClientMessage;
}

handleOptionOne = () => {
const message = this.createChatBotMessage("Whats Your Business?", {
widget: "optionOne",
});

this.addMessageToState(message);

};

handleJavascriptQuiz = (ans) => {
chat[chat.length - 1] = { ...chat[chat.length - 1], ans: ans };

const message = this.createChatBotMessage(
  "Fantastic.So what type of collaborations are you looking for?",
  {
    widget: "optionTwo",
  }
);

this.addMessageToState(message);

};

handleOptionTwo = (ans) => {
chat[chat.length - 1] = { ...chat[chat.length - 1], ans: ans };
const message = this.createChatBotMessage("Whats your budget?", {
widget: "optionThree",
});

this.addMessageToState(message);

};
handleOptionThree = (ans) => {
chat[chat.length - 1] = { ...chat[chat.length - 1], ans: ans };
const message = this.createChatBotMessage(
"Are You looking for Online Collaboration?",
{
widget: "optionFour",
}
);

this.addMessageToState(message);

};
handleOptionFour = (ans) => {
chat[chat.length - 1] = { ...chat[chat.length - 1], ans: ans };
const message = this.createChatBotMessage(
"Thanks for the details,Please drop your contact number",
{
widget: "",
}
);

this.addMessageToState(message);

};
details = (ans) => {
if (ans) {
chat[chat.length - 1] = { ...chat[chat.length - 1], ans: ans };
} else chat.pop();

const message = this.createChatBotMessage(
  "Write additional details,which will help to grab attention of <influencer>(Start with writing 'The Details are:'):"
);
this.addMessageToState(message);

};

greet = (ans) => {
if (ans) {
chat[chat.length - 1] = { ...chat[chat.length - 1], ans: ans };
} else chat.pop();

const message = this.createChatBotMessage(
  "Fabulous,will talk to you soon.Livi"
);
this.addMessageToState(message);

sendData();

};
phonenumber = (inputtxt) => {
var phoneno = /^\d{10}$/;

if (inputtxt)
  chat[chat.length - 1] = { ...chat[chat.length - 1], ans: inputtxt };
else chat.pop();
if (inputtxt.value.match(phoneno)) {
  return true;
} else {
  alert("Not a valid Phone Number");
  return false;
}

};

addMessageToState = (message) => {
chat.push({ ques: message.message });

this.setState((prevState) => ({
  ...prevState,
  messages: [...prevState.messages, message],
}));

};
}

export default ActionProvider;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment