Build a bot: Use Your Own Express Server with Botkit

Jon Church
Howdy
Published in
2 min readJun 20, 2017

--

Plus Express!

Why roll your own express server for your bot?

  • Separation of concerns
  • Extensibility
  • No Black Box code

Bot platforms typically require you to receive messages at a webhook. Botkit has built in helper functions to create a server for you, but you can maintain your own easily with Express.

Note: Facebook will only send requests over HTTPS to a publicly accessible server. For local development, you need a tool like or localtunnel to expose a port, or just remix this project on Glitch.

Let’s get our project setup and dependencies installed:

mkdir bot-server && cd bot-server
touch bot.js server.js incoming-webhook.js
npm install --save botkit express body-parser

Or, clone from github

git clone https://github.com/jonchurch/botkit-express-example.git
cd botkit-express-example && npm install

Create an Express server

This is a basic express server. We are using body-parser to parse request bodies and put them conveniently on req.body

Then register our routes from incoming_webhook.js with express.

Create the webhook routes

Pass the server and controller into this file in order to register the routes with express, and then call Botkit’s handleWebhookPayload function to process our messages from the platform.

Our routes are:

  • /facebook/receive POST — Acknowledge and process messages sent via POST request to our webhook with Botkit.
  • /facebook/receive GET — Facebook also needs a handshake verification from our server when setting up the webhook.

Here is where we create our Botkit controller and pass it into the webserver!

The controller accepts configuration options particular to the platform you are using. These should be passed in as environment variables when you run your bot.

Checkout the Botkit docs for for your chosen platform’s configuration options.

Run your bot with the following command, filling in your tokens as environment variables.

verify_token=<VTOKEN> page_token=<PTOKEN> node bot.js

If everything goes well*, you should be able to register the webhook with your Facebook app, and the bot will respond with “Hello World” to your messages.

This is the same way the express server is handled in the Botkit starter kits, so, if you want to test out a bot, go ahead and grab one of those and get going!

Jon Church is a software developer, open source contributor, and chatbot expert. Look for him contributing over at Botkit and wp-Calypso, answering questions on Stack Overflow, or follow him on Github.

Interested in writing for the Howdy blog about ways you work with Botkit? Contact us!

*If you’re having trouble with facebook validating your url, check the note at the top of the article about exposing a public port!

--

--