Slack Slash Command With WordPress REST API Backend
March 11, 2016
development projects wordpressI've spent the last several weeks building Slack bots and other custom integrations. One of the simplest types of Slack integration to build is the Slash Command - which can be a way for a user to interact with a bot or to provide functionality to a team or channel. Slack provides built in commands (like /topic and /remind) or you can develop custom commands either through a Slack app or just a one off implementation. Setting up a slash command is pretty easy, because all you need to provide is a RESTful endpoint that returns data to post to a channel. [caption id="attachment_3331" align="aligncenter" width="660"] Hey Kramer bot slash command integration[/caption] Slack will do a POST or GET to your endpoint with either JSON or query string parameters giving you information about the command that was given. [caption id="attachment_3332" align="aligncenter" width="660"]
Slash Command POST Data[/caption] And your endpoint can simply return a string to send back to the user who initiated the slash command. Or you can send back a formatted message which is essentially a JSON package with the message to send back and some options along with it.
This is where WordPress and its REST API come in. This is also where WordPress starts to become a platform. I'm not designing a theme or even building a website with WordPress. I'm creating a RESTful API with a nice simple way for users to enter data. In less than 5 minutes you can have a fully functional API outputting JSON via RESTful URLs backed by an easy to use and extend CMS. Out of the box you have access to all data in your WP backend with a simple URL schema.... ie '/posts' get a paged list of posts, '/posts/{id}' to get a specific post. Here is an example from the Seinfeld API I am developing for the Kramer bot. Notice the URL structure: https://heykramer.com/wp-json/wp/v2/posts [caption id="attachment_3334" align="alignnone" width="660"]
WordPress REST API JSON Output[/caption] Great! But not so fast ... Slack is expecting something specific back. Well thankfully the REST API is easily extendible. Below is an example plugin I created to show how easy it is to extend the WP REST API to provide Slack what it needs back. (here it is on Github) To extend WP REST API, I register a custom endpoint and define a callback function to execute when that URL is requested. In this instance we are expecting a GET request with query string parameters from Slack. It expects one of two commands: gif or image. Based on the command, it will query different categories of content on WP backend and return one random result to be posted in the Slack channel where the slash command was initiated.
Next up - building out a full Slack bot on NodeJS with a WordPress backend...