Build a “Serverless” Slack Bot in 9 Minutes with Node.js and StdLib

Slack bots — they’re fun, they’re useful, and people are building new businesses around bot interaction models on a daily basis. A few weeks ago we launched a quick guide to building an Alexa Skill in 7 Minutes with StdLib to a great response, and we’re excited to show off more of the capabilities of the platform we’re building at Standard Library alongside with Slack (who, as of July 11th 2017, is officially an investor)!

StdLib + Slack = ❤

If you’re not familiar with Standard Library, we’re a Function as a Service software library. The easiest way to think of us is to imagine if AWS Lambda and GitHub had a child, then asked NPM and Twilio to be the godparents — scalable microservices with no server administration, easy command line management, version immutability, service discovery, and the ability to charge customers for premium services you’ve built on a per-request basis.

We’re confident you’ll find StdLib to be the fastest way to get a Slack Bot up and running in production, so without further ado, let’s get started building!

Once you’ve created your StdLib service in Minute 5, you’ll get a README.md file but can also follow along via GitHub in the stdlib/utils.templates slack folder.

What You’ll Need Beforehand

  • 1x Slack Team
  • 1x Command Line Terminal
  • 9x Minutes (or 540x Seconds)

Minute 1: Preparing Your New Slack App

First, make sure you’re signed in to Slack. Next, visit your Slack Apps page at https://api.slack.com/apps. You’ll see a screen that looks like the following, though you may not have any existing apps yet.

Click “Create New App”

Simply click Create New App to create your app. You’ll be presented with a modal to enter in your App Name (I recommend “Test App” for the purposes of this tutorial) and the Development Slack Team you’d like to add it to.

From here, click Create App and you’ll find yourself on a Basic Information page. Keep this page open in your browser, we’ll be using it in a second.


Minute 2: Add a Bot to Your Slack App

Any interaction models that involve conversation, uploading files, etc. will rely on a bot, so let’s make sure we add one. Find the Bot Users option on the left sidebar, under the Features heading.

Click “Add a Bot User”

Click Add a Bot User to create your bot. You’ll be given an option to enter in the bot username — @test_app should work just fine. Click Add Bot User to complete the process, and that’s it! Your bot user is now added and ready to be used.


Minute 3: StdLib Account Setup

Next, you’ll need a StdLib Account to deploy your Slack App (bot) as a “serverless” scalable web service, as well as use your StdLib credentials to access the utils.storage service. This handles simple data persistence for your Slack App — like team data for when others install your app. Visit https://stdlib.com and click Sign Up to create your account.

Click “Sign Up” to Register

Minute 4: Create a StdLib Workspace

To use StdLib, you’ll want Node.js version 6.9.x or higher installed from the Official Node.js Website. Once complete, open up your Terminal or Command Line and install the StdLib Command Line Tools with the following:

$ npm install lib.cli -g

This gives you access to the lib command for service management and execution. Next, create a stdlib directory for your StdLib services.

$ mkdir stdlib
$ cd stdlib
$ lib init

You’ll be asked to log in using the credentials you created your account with. That’s it!


Minute 5: StdLib Service Creation

You’ll now want to create a StdLib service for your Slack App. We’ve built a slack template for you to use to get a bot up and running with very little effort. In the stdlib directory you just created, type:

$ lib create -t slack

You’ll be asked to enter a Service Name, we recommend slack-app for the purposes of this tutorial.

This will fetch the slack template from our utils.templates service that’s available open source on GitHub. It will run an npm installation locally for necessary files, you can read additional documentation here. Once complete, you will be instructed to enter the project directory.

$ cd <username>/slack-app

To make sure your slack-app is ready, let’s run a test “Slash” command — for example, this would respond to /hello hey there when run in your team in the channel “general” by the user “test”.

$ lib .commands.hello test general "hey there"

You’ll get a result that looks like this:

Example Response to “/hello” command

Great! To see what’s happening behind the scenes, run the exact same command with a -d flag (debug mode on):

$ lib .commands.hello test general "hey there" -d

This will show what’s going on in the background, using a local version of the StdLib gateway for testing purposes.

We can test events as well. For example, this as a “message” event that will be triggered any time a message is posted to a public channel (somebody writes “hey”):

$ lib .events.message test general "hey"
Sample Event Response

Finally, deploy your service live to StdLib — your app won’t quite be ready to use yet, but we need it to talk to Slack to verify that it’s working.

$ lib up dev
StdLib Service Deployment Takes Only a Few Seconds

Minute 6: Enable Commands, OAuth and Events

We’ll want to enable some Slack features for our App to make sure we can interact with our bot successfully. Make sure you’re in your Slack App settings before continuing.


Enable Slash Commands

Slash Commands are how Slack Apps respond to /command style queries. You can read more about them on the Slack Slash Commands API Reference. We know from the last step that our service has a pre-built response to /hello, so let’s add that first. Click Slash Commands on the sidebar.

Click “Create New Command”

After clicking Create New Command, you’ll be asked to enter some command details, make sure you enter the following:

  • Command: /hello
  • Request URL:https://<username>.lib.id/slack-app@dev/commands/:bg
  • Short Description: Hello World

The “:bg” indicator at the end of the URL indicates we’re running this as a background function. This means the StdLib gateway will immediately return an HTTP 202 Accepted status, but continue execution in the background (this tells Slack the service is working ASAP). When you’re finished, hit Save in the bottom right corner of your screen. If you encounter a warning about app permissions, you can ignore it for now.


Enable OAuth

Next, we’ll enable OAuth. On the sidebar menu, click OAuth & Permissions. Once there, you’ll want to enter in a Redirect URL as follows: https://<username>.lib.id/slack-app@dev/auth/

Add your Auth endpoint, make sure username is correct!

Hit Add and then click Save URLs. You should get a success message, and OAuth is ready!


Enable Event Subscriptions

Finally, we want to enable Event Subscriptions. Events are anything that can happen in your public channels, groups and messages. You can read more about the Slack Events API here. To enable them, click on Event Subscriptions option on the left sidebar. Toggle events to On in the top right, and then put in your Request URL: https://<username>.lib.id/slack-app@dev/events/:bg

Slack sends a challenge parameter to this endpoint, which is why we had to make sure we deployed our service earlier. This endpoint should get automatically verified, if not, make sure you go back to Minute 5 to ensure you deployed your service.

Finally, scroll down a bit to Subscribe to Team Events and add message.channels. Make sure to hit Save Changes in the bottom right corner!

Hit “Save Changes” Once You’ve Added Your Team Event

Minute 7: Adding Your Slack App Credentials

You should now make sure your Slack App Credentials are properly assigned to your StdLib service. It’s time to switch back to your command line — you’ll want to open your env.json (environment variables) file in your main service directory, open the file in your text editor of choice. We’ll be making modifications to the "dev" environment variables — make sure you’re modifying the right set!

Your StdLib Environment Variables, env.json

First, fetch your StdLib Token from the StdLib Dashboard. You’ll be asked to log in again — once you’ve done so, click on Library Tokens on the left and you’ll see this page:

Click “Show Token” to See Your Library Token

This is your StdLib auth token, click Show token to see its value and copy and paste it to your env.json file under STDLIB_TOKEN. Please note that dev values are for your dev environment and release values should only be populated when you’re ready to release your app.

Next, fill out SLACK_APP_NAME. You should differentiate between your dev / release apps — make sure this is unique for every app you build, as it sets a unique identifier for data storage / retrieval. For the dev environment you can set this to "Test App".

Finally, go back to your Slack App, and scroll down on the Basic Information panel:

Copy each of these values to dev section of env.json: SLACK_CLIENT_ID, SLACK_CLIENT_SECRET, and SLACK_VERFICIATION_TOKEN.

As a last step, modify SLACK_REDIRECT to https://<username>.lib.id/slack-app@dev/auth/ where <username> is your StdLib username.


Minute 8: Deploying Your Slack App

Now that we’ve set added our commands, subscribed to events, and set the appropriate environment variables in our StdLib Slack service, we’re ready to push our app live! Simply redeploy with:

$ lib up dev

Once complete, visit https://<username>.lib.id/slack-app@dev/ in your web browser — it should be available to be copy-and-pasted from your command line output. You’ll see a very simple “Add to Slack” button.

Add Your App to Slack

Click this button, and accept the requested permissions (we set them up previously), you’ll have to scroll down and click Authorize.

Accept the Permissions Required by Your Test App

You’ll be returned to your specified auth callback, which should give a success message:

Great! You can now use your Slack App!

Please note, your bot is now “production-ready,” by authorizing access above and setting up commands and events, your bot is all ready to go — though you can invite your bot to specific channels, it is not necessary for the basic interaction model.


Minute 9: Playing With Your New Slack App

You’re all done. Try it out! Your Slack App is now available for use in the Slack Team you authorized it for. By default, “Test App” should respond to a /hello command and to the regex pattern /hi|hello|sup|hey/ in normal channel messages. It will also welcome members when they join channels.

Test App in Action!

You can modify these behaviors in your StdLib service directory at functions/commands/hello.js, functions/events/message/__main__.js, and functions/events/message/channel_join.js. You can even create your own event responses and commands — just make sure for Slash Commands that you enable them via the Slack App management portal and your app has the correct permissions.

You can also Enable Distribution for this app and share it with other people by linking them to https://<username>.lib.id/slack-app@dev/, but we recommend creating a separate Slack App for this purpose and using lib release (so you don’t need the @dev qualifier). Full documentation for the StdLib command line tools is available on GitHub.


That’s it! Your Slack App is live!

Thanks for reading, and we hope we’ve been helpful showing you how easy it is to create a Slack App using Standard Library! Feel free to dig around in the template-generated codebase and make modifications or add new features. If there’s something you think the slack template is missing, it’s available open source at https://github.com/stdlib/utils.templates under the templates/slack directory. We welcome contributions and bugfixes!

We would love for you to comment here or e-mail me at keith [at] stdlib [dot] com, or follow us on Twitter, @StdLibHQ. Please let us know if you’ve built anything exciting that you would like us to feature or share!