Writing a custom Slash command for Slack
25 Mar 2016I am logged into Slack all day and love most of its features, especially the slash commands. I use the Poncho slash command when I step out from work for lunch, or when leaving home. So, I decided to write a slash command of my own for Slack which takes in a zip code and spits out the weather conditions for that location.
What’s a Slash command?
Messages that start with a slash. The message from the slash command is sent to a configured external URL via HTTP POST. It looks something like,
/CommandName Message
Some examples of built-in slash commands are
-
/giphy : it posts a random gif to a channel
-
/who: lists user in the current channel or group
The WeatherBot
We are going to build ‘WeatherBot’ which takes in a zip code and displays the conditions for that location.
Prerequisites
- Create an account on Heroku.
- Create a developer API key on Weather Underground.
- Make sure you have Node and Git installed. You can use Homebrew to install them.
Create a new directory named weather-slackbot with these files,
Procfile
A Procfile is a mechanism for declaring what commands are run by your application’s dynos on the Heroku platform. Add the following line to it. Heroku looks for index.js to start the app.
package.json
A package.json file contains meta data about your app or module. Most importantly, it includes the list of dependencies to install from npm when running npm install.
Add these lines to the json file:
index.js
Installation and running
Once you have the 3 files setup, jump to weather-slackbot folder and install all the dependencies.
After npm is finished installing dependencies, run:
The app is running. Visit http://localhost:9001. You should see “Running!!”. It is now listening for requests at port 9001.
Deploying to Heroku
Now we have to deploy this code to Heroku where Slack can send requests. If you haven’t signed up for a Heroku account yet, do it now. Then install the heroku toolbelt, login, create the app, and finally push it. Follow and run these commands:
To check if it is working, type:
and you see see the “Running!!” message. Now go ahead and add the Weather Underground API key under WU_ACCESS
Check the Heroku dashboard to see if your app is there.
Slack setup
Open slack, go to your team’s custom integration page and add a slash command.
All set! Go ahead and try out WeatherBot.