Building WhatsApp Chatbots in React with Botonic

ericmarcos

Eric Marcos Pitarch

Posted on July 29, 2021

Building WhatsApp Chatbots in React with Botonic

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 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 and Node v12

yarn create botonic-app myApp
Enter fullscreen mode Exit fullscreen mode

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

cd myApp
yarn serve
Enter fullscreen mode Exit fullscreen mode

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

NOTE: Due to a long standing Yarn bug, 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

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

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 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:

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
Enter fullscreen mode Exit fullscreen mode

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, 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:

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

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

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:

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 },
]
Enter fullscreen mode Exit fullscreen mode

We're capturing the ID of the pizza by using a regex named group.

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

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>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

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). 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

Telegram
Telegram Pizza Bot

Facebook Messenger
Messenger Pizza Bot

Webchat
Webchat Pizza Bot

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 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

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!

💖 💪 🙅 🚩
ericmarcos
Eric Marcos Pitarch

Posted on July 29, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024