Building A Slack Bot With Node.js And WordPress REST API

Some of my first experiments in the world of building a slack bot was to develop a basic Slash command using the WordPress REST API as a backend. If you or your team are the only users that intend to use it, you can just set it up as a simple integration. However if you wish to distribute it for others to use you can package it into a Slack bot.

An advantage of building a Slack bot versus a slash command is the additional features of the Slack API you can leverage — in this example, the RTM (Real Time Messaging) API. That allows you to listen and respond to messages in real-time. I started out building this layer as a WordPress plugin so anyone could install the plugin and build a WP powered bot. Not only was that out of scope for a fun side project, Node is really the right tool for the job — asynchronous, great packages for the Slack API, easy to deploy and scale (because who doesn’t wan’t a Kramer bot).

Building A Slack Bot With Node.js

If you are looking for an in-depth, step by step tutorial — check out Building a Slack Bot with Node.js and Chuck Norris Super Powers.

Assuming you have Node.js installed, your first step is to setup a basic project and gather up some dependencies. This bot is essentially headless so no need for anything like Express to handle routing and no need for a view engine to render any pages. What we will need are two packages specifically — one for Slack and one for grabbing content from the WordPress backend via its REST API.

First off you need a way to talk to Slack, specifically the RTM API. The examples in this post use the slackbots package which is a pretty simple Slack API client for Node.js. However, my next bot project will use botkit (for reasons that belong in separate post). For WordPress, we’ll use a nice WordPress REST API client for Node.js called wordpress-rest-api.

npm install --save wordpress-rest-api npm install --save slackbots

That’s it for dependencies. Now, lets build the Node.js Slack bot.

Building A Basic Bot

Being the pragmatic developer you are, you start simple. Lets talk to Slack. This snippet has no backend, is pretty ugly Javascript really, and the bot’s random messages are powered by an array. But we all start somewhere.

This is a pretty simple example of building a Slack bot in Node.js. You need to swap ‘XXXX’ out with your actual Slack token, which you can get when you create a new bot in Slack. Once you do that, you can run ‘node kramerbot.js’ this and it will be alive.

node kramerbot.js

This is a pretty straightforward and basic bot. First, define an array of messages for Kramerbot to respond with. Then, setup the bot with its token and name then listen for messages. By default this bot will be listening to any Slack channel it’s been invited to via the ‘bot.on( event, callback )’ function (line 21).

When messages come in, do some basic validation (lines 27–33). First off, you don’t to respond to yourself or that creates an infinite loop of messages (fun if your trying to troll your team). In this case we are checking to see if someone has mentioned the bots name or if it’s an @ mention directed to the bot. You could feasibly listen for any keywords, for instance in this example we could return a Newman quote if the user mentions the keyword ‘newman’. That wouldn’t scale well in this code, but you get the gist. More on building intelligent, conversational bots later.

Back to the snippet. Listen for messages with specific content and respond. Once the message passes all the hard to read (hey I told you this was bad Javascript) conditional logic the bot will grab a random message from the hardcoded array (line 47) and post a reply back to the user in the channel (line 49).

Boom. Building a Slack bot with Node.js is easy, right?

WordPress REST API Backend

So far our bot is pretty dumb and has hardcoded messages. In the previous post on building a Slack slash command with the WordPress REST API I showed how to extend the API to work well with Slack. This example does something very similar, however modifying the response for Slack is not needed since that will be the bot’s job.

A custom plugin extending the default behavior of the WP REST API isn’t required in this example as you can just call the standard endpoints used by the plugin passing in the ‘orderby’ => ‘rand’, ‘posts_per_page => 1 parameters. However since this is the beginning of something much more complex I am abstracting it out now so the data access logic will live in simple API endpoints, in this case ‘/api/any’ endpoint will grab a single random post.

That’s it — that’s our backend endpoint. The bot is only going to be slightly more intelligent by giving it a messages backend powered by this single WordPress REST API endpoint. At least now a Node.js bot code release isn’t required to add a message to the system. Now just wire up the bot to the backend…

Node.js and WordPress REST API

Here comes more bad Javascript… Sorry but it’s easier to demonstrate procedurally and I promise I’ll show you better code at the end.

This looks similar to the snippet above… Use the slackbots package to listen for messages, do some basic validation, and post a reply mentioning the user to the Slack channel. However there are a few lines of code that have changed in order to grab the random message from the WordPress REST API. First, it requires the wordpress-rest-api node.js package and sets up a simple object with the endpoint (lines 3–4).

Moving along, the bot will query the ‘/api/any’ endpoint for the random message to send back to the user. This couldn’t really be much simpler and actually requires less lines of code (lines 39–43).

wp.root('api/any').get(function( err, data ) {
if ( err ) {
// should probably do something more here, but meh its a demo
console.log("nothing there");
}

bot.postMessageToChannel(channel.name, '@' + fromUser + ' ' + data[0]['post_content'], params);
});

At this point, you have a Slack bot written in Node.js that listens for messages and responds with messages pulled from the WordPress REST API.

The bot is going to be lonely and generally unreachable running on your computer alone. While it’s out of scope of this post (because it got long fast) you should checkout Heroku or AWS Lamda for hosting your bot and Siteground (affiliate link for a product I use) for hosting your WordPress API.

About that better Javascript code for the Slack bot…

You Made It This Far

Check out the full, production ready-ish Hey Kramer Slack bot on Github. Check out the full WP repo with custom REST API extensions on the Github as well.

Want Hey Kramer in your Slack? Get an ever evolving (get it?) version at heykramer.com.

Next up? Crowdsourcing bot content with WordPress. Twitter bots using the WP REST API. And more fun as I explore botty bot bots.


Originally published at brudtkuhl.com on March 24, 2016.

Show your support

Clapping shows how much you appreciated andy brudtkuhl’s story.