Build a dice-rolling FB Messenger Bot with Botkit

In this tutorial, we will learn how you can do a dice rolling messenger bot with Facebook Messenger and Botkit, one of the most popular open-source bot frameworks.

Introduction

In this tutorial, we will learn to build a dice-rolling Facebook Messenger bot using Botkit that have been taking the world by storm. As more tools and libraries surface, it becomes easier for anyone to create a chatbot.

Today we’re going to go over one of the most popular open-source bot frameworks, Botkit. Botkit was created by Howdy in order to let people build interactive narrative experiences without worrying about API implementations. Botkit abstracts the hard parts away so you can focus on crafting a great bot.

Install Botkit and dependencies

To get started, you’ll need to install a few dependencies. If you have npm and git installed, this should be no sweat.

To get the sample project Botkit provides, clone this repository:

1git clone https://github.com/howdyai/botkit.git

To install the dependencies, just run npm install from the project folder. Navigate to the examples/ folder, and open up facebook_bot.js. That’s what we’ll use as our starting point.

Connect Botkit and Facebook

Now you need to tell Facebook about your bot and give it a place to live. If you haven’t already, you’ll need to create a Facebook page and create an app to use the API.

There are three pieces of information you’ll need to run your bot:

  • App Secret — this can be obtained from your app dashboard on Facebook’s developer portal. It’s unique to your app.
  • Page Token — you’ll need to select a preexisting Page to connect your app to. This is under the Messenger menu on the sidebar of the developer portal. You can use a Page you already have, or create a new one for this purpose. I created one called “Dice Roll Bot.” Copy that Page Token as well.
  • Verify Token — this can be whatever string you choose. Make sure it is the same in the app configuration and in your code. We don’t need to enter this anywhere yet, but note down what Verify Token you want to use. We’ll need it when deploying our code.

Once you’ve got those three keys, we can move on.

Roll ‘em: a dice-rolling bot

Here’s what we’re going to make: a dice-rolling bot to generate random numbers for giveaways, tabletop games, or cryptography.

Format: user types “roll ” where *<*``*num*``*>* is the number of sides of the die (upper limit of numbers to generate.) For example, if you wanted to roll a 20-sided die, you would type “roll 20”.

The controller is what sits in your chat and looks for new messages, events, or interactions. You can add controller actions (this is where the conversation logic goes) and helper functions.

Listen for the command

Our bot needs to listen for a keyword so it knows we’re talking to it. Above, we decided you should be able to type “roll num” and have it spit out an output as if you were rolling a die with that many sides. So what should the controller be listening for?

Yes, the word “roll”.

To do this, we need to define the pattern we’re looking for as a regular expression to the controller.hears function.

Let’s add it now:

1controller.hears(['^roll [0-9]+'], 'message_received', function(bot, message) {
2    });

^roll [0-9]+ is a regular expression pattern that just means ‘look for any time someone types the pattern “roll” and then a number’. The ^ means we don’t match if someone types “unroll”. It has to start with “roll” to get matched.

We trigger on the '``message_received``' action.

Parse user input

Okay, so what do we do once we hear the magic word? For the bot to know what kind of die to roll, we need to grab the user’s input. The controller sees all input that comes through the bot, and we trigger it to listen when it hears the roll command. Now how do we get the number that comes after it?

The received message is passed into the function by the variable message. All we need to do is grab the important parts. message is actually an object with a couple of different properties, like who sent it, what time, and what the text is, among other fields. We just want to grab the text. To do that, let’s access message.text and save it in a variable.

We use the split(' ') string processing function to grab the number after “roll”, and then parseInt() to transform it into a number.

Let’s add that into the code:

1var roll = 1; // the die roll generated by the bot
2    var sides = 1; // number of sides on the die
3
4    controller.hears('^roll [0-9]+', 'message_received', function(bot, message) {
5      msg = message.text;
6      // check for the number after "roll"
7      splitstr = msg.split(' ');
8      // transform that number into an int so we can do math on it
9      sides = parseInt(splitstr[1]);
10    });

Generate random numbers

Now that we can read the user’s input, we need to do something with it. Luckily, JavaScript comes built in with a random number function. We just need to massage it a little.

Outside of the controller.hears block, we need to build a new utility function to roll the die for us. Let’s call it roll:

1function roll(sides) {
2    }

All this function needs to do is take in the number of sides on the die and return a random integer between 1 and the upper bound (number of sides). To do this, we can use the Math.random() and Math.floor() functions like so:

1function roll(sides) {
2      return Math.floor(Math.random() * sides + 1);
3    }

What this does is generate a random number between 0 and 1 (this is what Math.random() does), then scale it up by the number of sides (this is our max value) and add 1 (the minimum number for our roll). We then apply a floor function to make sure it’s an integer.

With this function in place, let’s go use it in our bot!

Putting it all together

Going back to the controller.hears block, we have some unfinished business after we parse the user’s input. Currently, the bot doesn’t do anything with that input. But using the helper function we just wrote, it can!

We just need to add in a line to call the roll(sides) function and then reply to the user.

This is what it looks like all put together:

1var roll = 1; // the die roll generated by the bot
2    var sides = 1; // number of sides on the die
3
4    controller.hears('^roll', 'message_received', function(bot, message) {
5        msg = message.text;
6        // check for the number after "roll"
7        splitstr = msg.split(' ');
8        // transform that number into an int so we can do math on it
9        sides = parseInt(splitstr[1]);
10        // call the 'roll' helper function
11        theroll = roll(sides);
12        // return the roll to the user in a message
13        bot.reply(message, String(theroll));
14      }
15
16    function roll(sides) {
17      return Math.floor(Math.random() * sides + 1);
18    }

Deploy it to Facebook

Now that we’ve got our code written, we can deploy it to Facebook! Using those three keys we defined above, we’ll run the bot on a localtunnel instance using this snippet on your terminal:

1app_secret='my_secret' page_token='my_token' verify_token='my_verify' node examples/facebook_bot.js --lt

--lt means that this code will run on a localtunnel instance. This is a quick and easy way to get your Webhook set up so you can test your bot as soon as possible. You can use localtunnel while testing, but when you’re ready to move your bot to production, you may want to invest in a VPS or a service like Heroku to host your bot.

After running that command, you should see confirmation that your bot is running and a URL that can be used to accept message requests. Copy that URL and let’s go back to our App Dashboard.

Under the Messenger product configuration for your app (the same place you generated the Page Access Token), you’ll see a dialog to set up Webhooks. That’s what we need to do next.

As for the Subscription Fields, you can learn more about which ones to turn on and off in Facebook’s documentation. For the purposes of this tutorial, we only need the first one, ‘messages’.

Test the bot

Now if you navigate to your Facebook Page and initiate a conversation there, you should be able to use the new roll command. Give it a try!

Sample Code Repo

If you’re getting stuck, or just want to see what the finished product looks like, you can look at my edited version of the botkit repository. Nothing’s been changed besides the examples/facebook_bot.js file to add the dice rolling functionality. Still, check it out and post in the comments if you have any questions.

And Beyond…

Of course, this is just the tip of the iceberg of things you can do with Facebook Messenger Bots. Here are a couple ideas of ways that we could extend and improve this bot:

  • Add more variable responses to give the bot some “personality”
  • Allow various formats of input (e.g. ‘roll a d20’ or ‘roll 2d6’)
  • Create whole new “generators” to do more than just dice rolling. Name generators, setting descriptions, image searches…the possibilities are endless.

Do you have a cool example of something you’ve built with a Facebook Messenger Bot? Share it with us in the comments below!