Chatbots have become an essential business component. With the increasing demand, there are tools available in the market to develop a chatbot of your own!
One of the most popular methods is with the React Native framework, used for building cross-platform mobile applications with JavaScript. If you'd like to learn more about how Javascript and React Native work, check out All About | React & React Native Programmers.
In today's article, we'll walk through the process of building a chatbot with the Javascript language and React Native framework. If any of this sounds daunting, whether you aren't familiar with code or don't have the time to implement this yourself, we're here to help! BearPeak Technology Group connects people with great ideas (like yourself) to expert software developers.
Now, let's dive in: To build a chatbot using React Native, we will need to use a few additional libraries that will enable us to integrate with chatbot APIs.
Step 1: Set Up the Environment
To build a React Native app, we need to install Node.js and the React Native CLI. We can do this by running the following commands in the terminal:
rubyCopy code
$ brew install node
$ npm install -g react-native-cli
We also need to install the necessary libraries that will enable us to integrate with chatbot APIs. We'll be using these popular libaries:
Axios: A library for making HTTP requests.
Dialogflow: A natural language processing platform that enables us to create chatbots that can understand and respond to user inputs.
Gifted Chat: A library for building chat interfaces.
We can install these libraries by running the following commands:
rubyCopy code
$ npm install axios
$ npm install react-native-dialogflow
$ npm install react-native-gifted-chat
Step 2: Set Up Dialogflow
Depending on how responsive we want the chatbot to be, this will probably be the longest step to finish, but well worth it for the final result! Let's create a chatbot using Google Dialogflow:
Log in or create an account for Dialogflow
Create a new agent: Click on the "Create Agent" button in the Dialogflow console. This will prompt us to enter a name for the agent and choose a default language.
Create intents: An intent is a mapping between what a user says and what action should be taken by your chatbot. To create an intent, navigate to the "Intents" section in the Dialogflow console and click on the "Create Intent" button. This will prompt us to enter a name and provide examples of user inputs that should trigger this intent.
Define training phrases: In the intent editor, we can define training phrases that represent the different ways a user might express a particular intent. For example, if we were creating an intent to handle user requests for the weather, we might define training phrases such as "What is the weather like today?" or "Will it rain this weekend?".
Set up responses: Once we have defined the training phrases for an intent, we can set up responses that our chatbot should provide when this intent is triggered. Responses can include text messages, images, cards, or even custom payloads that can be used to trigger actions in other systems.
Test our bot: After we have created our intents and responses, we can test our chatbot in the Dialogflow console by entering example user inputs and checking the chatbot's responses. This can help us refine our intents and responses and ensure that our chatbot is providing helpful and accurate information to users.
Step 3: Obtain the API key
Obtain the API key, which we will use to integrate Dialogflow with our React Native app. To do this, navigate to the agent settings and select the "Service Account" tab. Create a new service account and download the private key file, which contains the API key.
Step 4: Create the React Native App
Now we can start building our React Native app! We can create it by running the following command:
csharpCopy code
$ react-native init ChatbotApp
This will create a new React Native app called "ChatbotApp". We can then navigate to the project directory and open it in our code editor.
Step 5: Integrate Dialogflow
We'll need to use the "react-native-dialogflow" library to integrate Dialogflow. We can import this into our app by adding the following line at the top of the "App.js" file:
javascriptCopy code
import Dialogflow from 'react-native-dialogflow';
We can then initialize Dialogflow by adding the following code:
phpCopy code
const projectId = '<PROJECT_ID>'; // Replace with your project IDconst privateKey = require('./<PRIVATE_KEY_FILE>'); // Replace with the path to your private key file
Dialogflow.setConfig({
projectId: projectId,
privateKey: privateKey,
language: 'en', // Replace with your preferred language
});
As noted in the code snippet above, we need to replace "<PROJECT_ID>" with our Dialogflow project ID and "<PRIVATE_KEY_FILE>" with the path to our private key file.
Step 6: Create the Chat Interface
We need to import the "react-native-gifted-chat" library this time. Add the following line at the top of the "App.js" file:
arduinoCopy code
import { Gift
Step 7: Handle Sending & Receiving
Next, we need to handle user inputs and responses from the chatbot API. To do so, we can use the "onSend" function provided by the "GiftedChat" component. This function is called when the user sends a message, and it receives an array of messages as an argument. We can then send the user's message to the Dialogflow API using the "react-native-dialogflow" library and handle the response in the callback function:
javascriptCopy code
onSend(messages = []) {
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages),
}));
Dialogflow.requestQuery(
messages[0].text,
result => this.handleResponse(result),
error => console.log(error)
);
}
handleResponse(result) {
const { fulfillmentMessages } = result.queryResult;
const messages = fulfillmentMessages.map(message => ({
_id: Math.random(),
text: message.text.text[0],
createdAt: new Date(),
user: BOT_USER,
}));
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages),
}));
}
In this code snippet above, we update the state of the component with the user's message using the "setState" function. Then, we send the user's message to the Dialogflow API using the "requestQuery" function and handle the response in the "handleResponse" function.
In the "handleResponse" function, we extract the text response from the fulfillment messages and add them as new messages to the chat using the "append" function provided by the "GiftedChat" component.
Step 8: Display the Conversation
To display the chat messages, we need to pass the "messages" state to the "GiftedChat" component as a prop. We can also customize the appearance of the chat messages using the "renderMessage" prop:
javascriptCopy code
render() {
return (
<GiftedChatmessages={this.state.messages}onSend={messages => this.onSend(messages)}
user={USER}
renderMessage={this.renderMessage}
/>
);
}
renderMessage(props) {
const { currentMessage } = props;
if (currentMessage.user._id === BOT_USER._id) {
return (
<View style={styles.botMessage}><Text style={styles.botMessageText}>{currentMessage.text}</Text></View>
);
}
return <MessageBubble {...props} />;
}
In the code snippet above, we pass the "messages" state to the "GiftedChat" component and define the "onSend" function to handle user inputs. We also define the "USER" and "BOT_USER" objects to represent the user and the chatbot, respectively. Finally, we define the "renderMessage" function to customize the appearance of the chat messages based on the user or the chatbot.
And guess what? We're done!
Step 9: Admire Your Work
Test out some questions from step 2. We could have conversations with our chatbot like:
User: Hi
Bot: Hello, how can I help you today?
User: What is the weather like in New York?
Bot: The current temperature in New York is 72 degrees Fahrenheit.
User: Can you recommend a good restaurant in Boulder?
Bot: Sure! How about trying the Dushanbe Teahouse? It's a popular Middle Eastern-style restaurant in downtown Boulder, Colorado.
User: How do I cancel my subscription?
Bot: To cancel your subscription, please visit our website and navigate to the subscription settings page. From there, you can cancel your subscription.
User: Thank you!
Bot: You're welcome! Let me know if you have any other questions.
Ready to Work with a React or React Native Specialist?
If this wasn't your field of expertise, hire someone who can help! Software consultancies like BearPeak Technology Group have expert developers for hire who can do all of these tasks for you. Check us out! We're a Colorado-based team of engineers who help you hire remote software developers efficiently and reliably. We offer free consultations and are dedicated to your startup's success:
It's important for us to disclose the multiple authors of this blog post: The original outline was written by chat.openai, an exciting new AI language model. The content was then edited and revised by Lindey Hoak.
"OpenAI (2023). ChatGPT. Retrieved from https://openai.com/api-beta/gpt-3/"