Building WhatsApp Chatbots in React with Botonic
Published: 2021-07-29 11:29:44

You need to build a chatbot. Maybe it’s a pre-sales chat panel on your company’s marketing page, maybe it’s a customer service WhatsApp account (or maybe it’s both!). You have a lot of experience with React, and would rather not mess around with Python or other backend technologies with complicated deployment processes. And you want to experiment with using inline UI elements, instead of solely relying on natural language understanding, because working with a buggy AI is a frustrating experience. But you don’t know where to start.

In this blog post, I want to introduce Botonic, an open source framework for building conversational apps with React. We’ve been building conversational apps at Hubtype, and we needed a framework that supported our own development workflow. It’s helped us build effective bots for our own clients reliably and quickly, and we think it would be really helpful for you too. We’ve designed Botonic specifically for React developers, so you can leverage your existing web skills for building apps for chat platforms.

In this tutorial, we want to show you how Botonic can help you quickly build conversational apps that work across WhatsApp, Telegram, Messenger, and embedded web chat boxes using familiar React components, and test them live without having to deploy a thing.

## Getting started with Botonic

Today we're excited to release an alpha version of Botonic 1.0 so we can get early feedback from the community. We know there are still many rough edges but we'd like to talk to as many early adopters as possible, that's why we're also giving away subscriptions to [egghead.io](https://egghead.io) to everyone that completes this short tutorial and schedules a 30min call with us.

Let's get started!

### 1. Create a new Botonic project

As pre-requisites you'll need at least [Yarn v1.15](https://classic.yarnpkg.com/en/docs/install) and [Node v12](https://nodejs.org/en/download/)

```bash
yarn create botonic-app myApp
```

This will scaffold a new Botonic project and install all the required dependencies. Botonic projects are self-contained full-stack apps, with `api`, `webchat` and `bot` sub-packages. We'll explain this organization in detail in another post.

### 2. Start your local dev server

```bash
cd myApp
yarn serve
```

This command will start 3 servers: the REST API, the Websocket server and the frontend that includes the webchat and QR connectors to messaging APIs. Your browser should be opened automatically and display a screen like this:

![Botonic Serve](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pwp35yxniaalr381b6sa.png)

> NOTE: Due to a [long standing Yarn bug](https://github.com/yarnpkg/yarn/issues/4667), exiting the serve command with `CTRL-C` will leave your terminal in a bad state. You can either do `CTRL-C` again or `ENTER` to fix it.

### 3. Try your bot on webchat

Now let's first try the webchat by clicking on the bottom right bubble. It will open a chat UI and you can start typing. You'll see that the bot responds "I don't understand you" all the time which is the default `404` route. Try typing "Hi" and the bot should respond with "Welcome to Botonic!"

![Try Webchat](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fj5mcvlgsvosbwkczhrx.png)

### 4. Try your bot on WhatsApp

It's time to feel the magic! Take your phone and scan the QR code you'll find in the WhatsApp tab. It will open a deeplink to the Botonic Playground Whatsapp account. Notice that you'll have a pre-filled text in the form of `CODE=XYZXYZ` ready to send. Send it. You should get a success message saying that your current session is linked to your local app. Congrats! You can now test your local bot right from WhatsApp, no need to create any accounts or setup any webhooks 🚀

![Botonic Whatsapp Bot 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ubgg0os64no0yob0ar7f.jpg)

You can also try the other channels. The only difference is that instead of sending a `CODE=XYZXYZ` text, you'll tap on a "Get Started" button that will send the code under the hood to connect your session.

### 5. Create your bot flow

#### 5.1 Add a main menu action

Awesome, now you're ready to build your conversational app.

[Actions](https://botonic.io/docs/concepts/actions) are one of the core concepts in Botonic. They're just React components that perform some operation and display a message to the user. In this case we want to take a collection of pizzas and display an intro text with buttons to select a pizza.

Open your project on your favourite IDE, create a new file `bot/src/actions/PizzaMenu.jsx` and paste this code:

```jsx
import React from 'react'
import { Text, Button } from '@botonic/react'

const pizzas = [
  { id: '1', name: 'Margherita' },
  { id: '2', name: 'Pepperoni' },
  { id: '3', name: 'Veggie' },
]

const PizzaMenu = () => (
  <Text>
    We have the best pizzas in town! Which one would you like?
    {pizzas.map(p => (
      <Button key={p.id} payload={`select-pizza-${p.id}`}>
        {p.name}
      </Button>
    ))}
  </Text>
)

export default PizzaMenu
```

You'd typically load the pizzas from an API, but we've hardcoded them here for simplicity.

#### 5.2 Add a route that triggers the main menu

Now you need a way to tell the framework when to trigger that action. You can do this with [routes](https://botonic.io/docs/concepts/routes), another core concept in Botonic. A route basically matches user inputs with actions. This match can be done in many different ways: using NLU, regex, custom functions... In this post we'll keep it simple by using regex to capture keywords. Edit your `bot/src/routes.js` file to look like this:

```jsx
import Welcome from './actions/Welcome'
import PizzaMenu from './actions/PizzaMenu'

export const routes = [
  { text: 'hi', action: Welcome },
  { text: /(pizza|menu)/i, action: PizzaMenu },
]
```

Once you have the new action and route in place, you can try it right away. The servers will auto-reload on save and your WhatsApp session will keep working. So go back to WhatsApp and type `what's on the menu`, you should get the response with three buttons that we created in the PizzaMenu action.

#### 5.3 Add another route and action to capture the selected pizza

Ok, so let's complete the flow by capturing the button clicks. As you can see in the first action, each Button has a payload property of the form "select-pizza-1".

Now we need to capture this on our routes like this:

```jsx
import Welcome from './actions/Welcome'
import PizzaMenu from './actions/PizzaMenu'
import PizzaSelect from './actions/PizzaSelect'

export const routes = [
  { text: 'hi', action: Welcome },
  { text: /(pizza|menu)/i, action: PizzaMenu },
  { payload: /^select-pizza-(?<pizzaId>[123])/, action: PizzaSelect },
]
```

We're capturing the ID of the pizza by using a [regex named group](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges).

The next step is to create the `bot/src/actions/PizzaSelect.jsx` action:

```jsx
import React from 'react'
import { Text, Button } from '@botonic/react'

const pizzas = [
  { id: '1', name: 'Margherita' },
  { id: '2', name: 'Pepperoni' },
  { id: '3', name: 'Veggie' },
]

export default class extends React.Component {
  static async botonicInit({ params }) {
    const pizza = pizzas.find(p => p.id === params.pizzaId)
    return { pizzaName: pizza.name }
  }

  render() {
    return (
      <Text>
        Great! Your {this.props.pizzaName} pizza is on its way! 🍕🍕🍕
      </Text>
    )
  }
}
```

The captured pizza ID arrives in the `params` object in a special `botonicInit` method (if you're familiar with Next.js, this works like [getInitialProps](https://nextjs.org/docs/api-reference/data-fetching/getInitialProps)). Then we pass the pizza name as a prop to the render method.

#### 5.4 Try the whole flow

That's it! You can now play with your bot and visualize how the same flow behaves on different channels.

As you can see it's very easy to create multichannel experiences with Botonic!

**WhatsApp**
![Whatsapp Pizza Bot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dxj0728psgsk7cc86r5s.jpg)

**Telegram**
![Telegram Pizza Bot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3w20e00joquw9zqtl91k.jpg)

**Facebook Messenger**
![Messenger Pizza Bot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/57dcncdvtlgftj47vbjg.jpg)

**Webchat**
![Webchat Pizza Bot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kdq941jpjxh3d1mflq7x.png)

> NOTE: If this is the first time trying Botonic and you're wondering how to add natural language understanding we suggest you have a look at the [NLU example](https://botonic.io/examples/nlu-assistant/) or wait for an upcoming post that will cover the new NLP packages in Botonic 1.0

### 6. What's next?

Ah, pizzabot. What we’ve got now is good old pizzabot running on your computer, and communicating with you on your phone or browser via four different chat platforms, all at the same time. Not too bad, right? I know you’ve likely got questions, though. How do you actually deploy the bot? How do you add NLU? Wouldn’t integrating a headless CMS like Contentful be awesome, so you could get your creative team involved in the conversational design? All these things are of course possible, and we’re working on a series of tutorials to answer all of these questions.

In the meantime, as we mentioned above, we need your help! So please don’t forget to `/feedback` in the running app, and set up a time to share your story with us. We’re eager to help you succeed.

![Botonic Feedback](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xsag49cta2bnzlkabx9m.jpg)

> NOTE: You can send us feedback anytime you want just by sending "/feedback [your feedback]", for instance `/feedback I wish you had more examples!`


Happy coding!