Building A Slack Bot With Node.js And WordPress REST API
March 24, 2016
development wordpress projectsSome 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). [caption id="attachment_3354" align="aligncenter" width="660"] Kramer Bot using Slack RTM API[/caption]
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](http://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 good 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.
Active Projects
Here are some of the projects I am currently working on. Some are side projects, some are client projects, and some are just for fun. I like to build things and I like to share what I learn along the way. If you have any questions about any of these projects, feel free to reach out.
🏗️ JSONL Tools
I am working on a set of tools to help me work with JSONL. JSONL is a simple format for working with JSON data. I am working on a set of tools to help me work with JSONL data. I will use these tools to help me work with my own data as well as help me build my own APIs. Read more about this project in my blog post about building JSONL Tools.
🤖 Make Storytime
Personalized children's stories generated by AI. This is an app I am building with my kids.
📠 Fax Online
Yea, I know. But there is a long tail for everything and believe it or not there was an underserved market for people that need to send a fax online. Some people (like me!) just need to send a one time fax.
Read more about this micro Saas project in a blog post about building an online fax service.
🥑 Free URL Indexer
Free URL Indexer is a free tool to help you index your backlinks and get them into Google faster. It's a simple tool that I built to help me with my own SEO efforts and I decided to share it with the world. It's a free tool and I don't even ask for your email address. Just paste in your URL and click the button.
👉 See all projects