BUILDING YOUR FIRST SLACK BOT

BUILDING YOUR FIRST SLACK BOT

Date:
Genres:In this tutorial I’m going to show you how to create a simple Slack bot using Express and Node.j…
In this tutorial I’m going to show you how to create a simple Slack bot using Express and Node.js, which will communicate with the Slack API. We will use a simple example where we send a score to our Node.js application, and provide another endpoint for retrieving the pushed score.
Let’s get started…

GETTING STARTED

Make sure that you have Node.js and NPM installed on your machine, if not, visit the Node.js website to install the latest version.
Let’s start by creating a folder for our app. Run the following commands in your favorite terminal:
mkdir first-slack-bot
cd first-slack-bot
Now let’s add a package.json file to import all of our dependencies for our app:
{
 "name": "first-slack-bot",
 "version": "1.0.0",
 "description": "Webdesignerdepot: Build Your First Slack Bot",
 "main": "app.js",
 "scripts": {
 "start": "nodemon app.js --exec babel-node"
 },
 "devDependencies": {
 "babel-cli": "^6.26.0",
 "babel-preset-env": "^1.6.0",
 "babel-preset-stage-2": "^6.24.1",
 "nodemon": "^1.12.1"
 },
 "dependencies": {
 "body-parser": "^1.18.2",
 "express": "^4.16.2"
 }
}
As you can see, we don’t need too many dependencies:
  • Babel-cli, babel-preset-env and babel-preset-stage-2 helps us with compiling ES6.
  • Nodemon is a dependency which will monitor for any changes in your node.js application and automatically restart the server – perfect for development.
  • Express is a flexible and minimal web application which provides HTTP utility methods and middleware for quickly creating a robust API.
Run the following command to install our dependencies:
npm install
To make the Babel compiling work, we have to add a small filed called ‘.babelrc’ in which we define our presets.
touch .babelrc
and add following code:
{
 "presets": ["env", "stage-2"],
 "plugins": []
}
We are ready to start coding.

BUILDING OUR SLACK BOT

Next, let’s begin with creating the app.js file in our root folder called ‘first-slack-bot’:
touch app.js
and add the following to index.js:
import express from ‘express’
import bodyParser from ‘body-parser’
import scoreRouter from ‘./routes/score’
/* Initialize app and configure bodyParser */
const port = process.env.PORT || 3005
const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
/* API Routes */
app.use(‘/score’, scoreRouter)
/* API Test Route */
app.get(‘/’, (req, res) => {
res.send(‘App is running correctly!’)
})
/* CORS */
app.use((req, res, next) => {
// Website you wish to allow to connect
res.setHeader(‘Access-Control-Allow-Origin’, ‘*’)
// Request methods you wish to allow
res.setHeader(‘Access-Control-Allow-Methods’, ‘GET, POST, OPTIONS, PUT, PATCH, DELETE’)
// Request headers you wish to allow
res.setHeader(‘Access-Control-Allow-Headers’, ‘Origin,X-Requested-With,content-type’)
// Pass to next layer of middleware
next()
});
/* Serve API */
app.listen(port, () => {
console.log(‘Slack Bot listening on port 3005!’)
})
There are a few things happening here:
  1. We are importing essential modules: express and body-parser. In addition, we are importing our ‘scoreRouter’ which we will create later on.
  1. We attach the ‘scoreRouter’ to the route ‘/score’. The scoreRouter will contain the actual endpoints.
  1. We define a test route on the root of our project to make sure if everything is working correctly.
  1. We take care of potential CORS issues.
  1. At the bottom of the file, we serve our app with ‘app.listen’. We use the earlier defined variable ‘port’ to tell this function to serve our app on port 3005.
We can move along to create our endpoint.

SCORE ROUTE API ENDPOINT

Let’s start with creating a ‘routes’ folder and create a file inside this folder named ‘score.js’ which will contain the API endpoints:
mkdir routes && cd routes
touch score.js
and add following content to ‘score.js’:
import { Router } from ‘express’
import Score from ‘../models/score’
/**
* Handles all requests related to scores
*/
const router = Router()
const score = 0
export default router
/**
* Add new score
* @param {String} req.body.text : Slack sends everything after slash command as a text string
*/
const addScore = (req, res) => {
score = req.body.text.trim()
// Create payload for Slack API
const payload = { "text": "Score has been added!" }
// Send back payload to Slack
return res.status(200).json(payload)
}
/**
* Get score
*/
const getScore = (req, res) => {
// Create payload for Slack API
const payload = {
"response_type": "in_channel",
"text": "Highscore: " + score,
"attachments": [
{
"text": "Such a high score, wow!"
}
]
}
// Send back payload to Slack
return res.status(200).json(payload)
}
router.route(‘/getScore’)
.post(getScore)
router.route(‘/add’)
.post(addScore)
We defined a global variable called score which will contain the actual score.
Let’s take a look at the first function ‘addScore’.
const addScore = (req, res) => {
score = req.body.text.trim()
// Create payload for Slack API
const payload = { "text": "Score has been added!" }
// Send back payload to Slack
return res.status(200).json(payload)
}
This function will receive a score from the Slack API. The Slack API will send the data as a post request. The actual data can be found in the text field: ‘req.body.text’. Let’s assume that the user sending the request fills in a number so we just have to trim the data.
Furthermore, we create a payload which we will return to the Slack API. We are just returning a short text informing the user that a score has been added.
The function ‘getScore’ will retrieve the posted score. As Slack is not able to send a GET request, this will be as well a POST request. This function is returning a more advanced payload to the Slack API.
const payload = {
"response_type": "in_channel",
"text": "Highscore: " + score,
"attachments": [
{
"text": "Such a high score, wow!"
}
]
}
We want our bot to explicitly post a message in our channel with the text ‘Score: 10’ for example. In addition, we want to add a sub-text (attachments parameter) with some extra information like: ‘Such a high score, wow!’.

DEPLOY APPLICATION

OK, let’s deploy the application we’ve created. Because the actual deployment process is out of scope, I recommend you to use a free service like Heroku or Now.sh (great resource: HERE ).
Now we have our application deployed, we can use following API endpoints:
  • [deployment-url]/score/getScore: get last score from application
  • [deployment-url]/score/add: post score to application
We can use these routes to configure our first Slack bot.

CONFIGURING SLACK BOT

Before we start, you need to have a Slack account and your own space, for example firstbot.slack.com. You can create a new space at https://slack.com/create. We will use this space to configure and deploy the Slack bot.

1. CREATE A NEW BOT

Navigate to https://api.slack.com/apps?new_app=1 and click the green button ‘Create New App’. A pop-up window will be shown.
Fill in the name of your app and select the correct Slack Workspace you have created.
Create the app and select the newly created Slack app.

2. DEFINE SLASH COMMANDS

The ‘Features’ menu provides you the option to set slash commands. You can define them here: https://api.slack.com/apps/APP-ID/slash-commands. A slash command is a command you can use in the Slack chat.

2.1 ADD SCORE COMMAND

Let’s start with defining the command for adding a score. To do so, we want to type ‘/add [score]’ in our chat.
– Command: The command we type in the Slack app.
– Request URL: Your deployment URL with the correct endpoint added.
– Short Description: Short usage description.
– Usage Hint: Tell your users to fill in a score.

2.2 GET SCORE COMMAND

For this command, we will just request the score from our app through ‘/score/getScore’. No parameters need to be passed.

3. DEPLOY APP TO SLACK SPACE

At last, we have to deploy our app so we can use our defined slash commands. Let’s go to the option ‘Install App’ under the ‘Settings’ menu or visit this URL: https://api.slack.com/apps/APP-ID/install-on-team
Click the big green button ‘Install App to Workspace’. Slack will request you to authorize the installation of this app for your workspace, hit ‘Authorize’.
We are all set now. Let’s finish with testing our commands.

TEST SLACK BOT

First, let’s add a score by typing ‘/add 10’. This will add 10 as a score to the Slack bot.
The bot will respond. This is only visible to you.
Next, we want to retrieve the set score. Type ‘/getScore’ in the chat.
The Slack bot will reply with a message which is visible to anyone showing the score and the command you typed. The Slack bot acts like this because we defined a response type ‘in_channel’ in our payload.

NEXT STEPS

Many more things are possible with the Slack API for slash commands. A slash command sends much more information than just the text parameter. This is the full payload of information that is sent with the request.
token=gIkuvaNzQIHg97ATvDxqgjtO
team_id=T0001
team_domain=example
enterprise_id=E0001
enterprise_name=Globular%20Construct%20Inc
channel_id=C2147483705
channel_name=test
user_id=U2147483697
user_name=Steve
command=/weather
text=94070
response_url=https://hooks.slack.com/commands/1234/5678
trigger_id=13345224609.738474920.8088930838d88f008e0
Take a look at the API docs if you want to find out more about this.

0/Post a Comment/Comments

Previous Post Next Post
PopAds.net - The Best Popunder Adnetwork