Ever wanted to create your own chatbot and integrate it into a React app?
With Quickblox, it's easier than you might think!
This guide will walk you through building a chatbot using Quickblox in a React app with Vite.
If you want to follow along or just want a head start, I've got this project up on my GitHub for you to clone. Feel free to grab the code and try it out with me!
I'll keep things simple and straightforward, so you can get your chatbot up and running quickly without needing a Btech Degree :)
Let's get started!
Setting Up Your Project
First things first, let's set up a new React project using Vite.
Vite is a modern build tool that is incredibly fast and developer-friendly. If you haven't used it before, you'll love how quick it makes the setup process.
Open up your terminal.
Navigate to an empty directory where you want to create your project.
Run the following command to create a new React project with TypeScript.
npm create vite@latest my-quickblox-chat -- --template react-ts cd my-quickblox-chat
This command sets up a basic React project for you. Once it’s done, you’ll have a shiny new React app ready for customization!
2. Installing Quickblox and UI Kit
Now, let’s install Quickblox and the Quickblox UI Kit to your project. These tools will provide the core functionality and components for our chatbot.
Run this command in your terminal:
npm install quickblox quickblox-react-ui-kit
Next, clean up the starter code from Vite. Open your src
folder and remove any default components or styles that were created.
3. Configuring Quickblox
You’ll need to configure Quickblox by adding your Quickblox credentials to the project. These credentials are essential for connecting your app to Quickblox services.
Create a new file named qbConfig.js
in the src
directory and add the following:
export const QBConfig: QBUIKitConfig = {
credentials: {
appId: 104157,
accountKey: 'ack_U2gZ9i5KZ4qUNcxpD_d6',
authKey: 'ak_DZjxTT3Ge-P-Xm6',
authSecret: 'as_Byrz8zHZCA4HB49',
sessionToken: '',
},
configAIApi: {
AIAnswerAssistWidgetConfig: {
organizationName: 'Quickblox',
openAIModel: 'gpt-3.5-turbo',
smartChatAssistantId: '',
apiKey: '',
maxTokens: 3584,
useDefault: true,
proxyConfig: {
api: 'v1/chat/completions',
servername: 'https://api.openai.com/',
port: '',
},
},
AITranslateWidgetConfig: {
organizationName: 'Quickblox',
openAIModel: 'gpt-3.5-turbo',
smartChatAssistantId: '',
apiKey: '',
maxTokens: 3584,
useDefault: true,
defaultLanguage: 'Ukrainian',
languages: ['Ukrainian', 'English', 'French', 'Portuguese', 'German'],
proxyConfig: {
api: 'v1/chat/completions',
servername: '',
port: '',
},
// proxyConfig: {
// api: 'v1/chat/completions',
// servername: 'http://localhost',
// port: '3012',
// },
},
Make sure to replace 'YOUR_APP_ID'
, 'YOUR_AUTH_KEY'
, 'YOUR_AUTH_SECRET'
, and 'YOUR_ACCOUNT_KEY'
with your actual Quickblox credentials.
4. Using Quickblox UI Kit Components
To make your chatbot look sleek and modern, we’ll use components from the Quickblox UI Kit. Wrap your main application component with the UIkitProvider
.
Edit your src/App.js
or src/App.tsx
file like this:
return (
<div>
<QuickBloxUIKitProvider
maxFileSize={100 * 1000000}
accountData={{ ...QBConfig.credentials }}
loginData={{
login: currentUser.login,
password: currentUser.password,
}}
qbConfig={{...QBConfig}}
>
<div className="App">
{
// React states indicating the ability to render UI
isSDKInitialized && isUserAuthorized
?
<QuickBloxUIKitDesktopLayout
uikitHeightOffset={"32px"}
// AIAssist={{
// enabled: true,
// default: true,
// }}
/>
:
<div>wait while SDK is initializing...</div>
}
</div>
</QuickBloxUIKitProvider>
</div>
);
5. Adding the SDK Loader
Next, you'll need to add the Quickblox SDK loader to initialize the SDK and make it ready to use.
Add the following code snippet to your component:
const prepareSDK = async (): Promise<void> => {
// check if we have installed SDK
if ((window as any).QB === undefined) {
if (QB !== undefined) {
(window as any).QB = QB;
} else {
let QBLib = require('quickblox/quickblox.min');
(window as any).QB = QBLib;
}
}
const APPLICATION_ID = QBConfig.credentials.appId;
const AUTH_KEY = QBConfig.credentials.authKey;
const AUTH_SECRET = QBConfig.credentials.authSecret;
const ACCOUNT_KEY = QBConfig.credentials.accountKey;
const CONFIG = QBConfig.appConfig;
QB.init(APPLICATION_ID, AUTH_KEY, AUTH_SECRET, ACCOUNT_KEY, CONFIG);
};
6. Completing the Setup and Starting Your Chat
Now, it’s time to put everything together and make your chatbot come to life!
You'll use the useEffect
hook from React to initialize the SDK and load the components.
useEffect(() => {
if (!isSDKInitialized) {
prepareSDK().then(result => {
QB.createSession(currentUser, async function (errorCreateSession: any, session: any) {
if (errorCreateSession) {
console.log('Create User Session has error:', JSON.stringify(errorCreateSession));
} else {
const userId: number = session.user_id;
const password: string = session.token;
const paramsConnect = { userId, password };
QB.chat.connect(paramsConnect, async function (errorConnect: any, resultConnect: any) {
if (errorConnect) {
console.log('Can not connect to chat server: ', errorConnect);
} else {
const authData: AuthorizationData = {
userId: userId,
password: password,
userName: currentUser.login,
sessionToken: session.token
};
await qbUIKitContext.authorize(authData);
setSDKInitialized(true);
setUserAuthorized(true);
}
});
}
});
}).catch(
e => {
console.log('init SDK has error: ', e)
});
}
}, []);
Once your SDK is initialized, you should be able to chat with friends or interact with customers right from your application!
7. Adding Your Own Custom Logic
You can customize your chatbot's behavior by adding more logic to the Quickblox SDK and UI Kit components.
For example, you might want to add custom user authentication, enhanced message formatting, or even integrations with other services.
That's it! You now have a functional chatbot running in your React app using Quickblox. This guide is just the beginning—there's so much more you can do with Quickblox.
Dive into the docs, experiment with the SDK, and make it your own!
Keep Exploring with Quickblox!
If you're excited to learn more, don't stop here!
Check out the Quickblox documentation for more details on how to maximize the platform's potential.
The Quickblox React UI Kit offers ready-to-use components to make building chat applications even easier.
And don't forget to explore their code samples for more inspiration and practical examples!
Remember, building cool stuff should be fun and accessible, so don't hesitate to play around, break things, and learn as you go.