BUILDING YOUR FIRST BUTTON
In this tutorial, I will 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 in which we send a score to our application
Node.js and provide another endpoint to retrieve the requested score.
Let us begin…
STARTING
Make sure you have Node.js and NPM installed on your
machine; otherwise, visit the Node.js website to install the latest version.
Let's start by creating a folder for our application. Run
the following commands on your favorite terminal:
mkdir first-slack-bot
cd first-slack-bot
Now let's add a package.json file to import all our
dependencies for our application:
{
"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 do not need too many dependencies:
Babel-cli, babel-preset-env and babel-preset-stage-2 help us
compile ES6.
Nodemon is a dependency that will monitor any changes in
your node.js application and automatically restart the server, perfect for
development.
Express is a flexible and minimal web application that
provides HTTP and middleware utility methods to quickly create a robust API.
Execute the following command to install our dependencies:
npm install
To make the Babel compilation work, we must add a small file
called '.babelrc' in which we define our presets.
touch .babelrc
and add the following code:
{
"presets": ["env", "stage-2"],
"accessories": []
}
We are ready to start coding.
BUILDING OUR PACKAGE
Next, let's start with the creation of 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 './paths / score'
/ * Initialize the application 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 path * /
app.get ('/', (req, res) => {
res.send ('The application runs correctly!')
})
/ * CORS * /
app.use ((req, res, next) => {
// Website that you want to allow to connect
res.setHeader ('Access-Control-Allow-Origin', '*')
// Request the methods you want to allow
res.setHeader ('Access-Control-Allow-Methods', 'GET, POST,
OPTIONS, PUT, PATCH, DELETE')
// Request the headers you want to allow
res.setHeader ('Access-Control-Allow-Headers', 'Origin,
X-Requested With, content type')
// Go to the next layer of middleware.
following()
});
/ * Serve API * /
app.listen (port, () => {
console.log ('Slack Bot listening on port 3005!')
})
There are some things that happen here:
We are importing essential modules: express and body-parser.
In addition, we are importing our 'scoreRouter' that we will create later.
Attach the 'scoreRouter' to the '/ score' route. The
scoreRouter will contain the actual endpoints.
We define a test route at the root of our project to make
sure that everything works correctly.
We deal with possible CORS problems.
In the lower part of the file, we serve our application with
"app.listen". We use the variable "port" defined above to
tell this function to serve our application on port 3005.
We can move forward to create our final point.
ENDPOINT ROUTE API SCORE
Let's start by creating a folder of "routes" and
create a file inside this folder called "score.js" that will contain
the API end points:
mkdir routes and cd routes
touch score.js
and add the following content to 'score.js':
import {Router} from 'express'
Import score from '../models/score'
/ **
* Handles all requests related to the scores.
* /
router const = router ()
const score = 0
export default router
/ **
* Add new score
* @param {String} req.body.text: Slack sends everything
after the bar command as a text string
* /
const addScore = (req, res) => {
score = req.body.text.trim ()
// Create payload for Slack API
const payload = {"text": "The score has been
added!" }
// Send the payload to Slack
return res.status (200) .json (payload)
}
/ **
* Get score
* /
const getScore = (req, res) => {
// Create payload for Slack API
payload of const = {
"response_type": "in_channel",
"text": "Highscore:" + score,
"attached files": [
{
"text": "What a high score, wow!"
}
]
}
// Send the payload to Slack
return res.status (200) .json (payload)
}
router.ruta ('/ getScore')
.post (getScore)
router.ruta ('/ add')
.post (addScore)
We define a global variable called score that will contain
the actual score.
Let's take a look at the first 'addScore' function.
const addScore = (req, res) => {
score = req.body.text.trim ()
// Create payload for Slack API
const payload = {"text": "The score has been
added!" }
// Send the payload to Slack
return res.status (200) .json (payload)
}
This function will receive a score of the Slack API. The
Slack API will send the data as a later request. The actual data can be found
in the text field: 'req.body.text'. Let's suppose that the user who sends the
request fills in a number, so we only have to cut the data.
In addition, we create a payload that we will return to the
Slack API. We just returned a short text informing the user that a score has
been added.
The "getScore" function will retrieve the
published score. Since Slack can not send a GET request, this will also be a
POST request. This function is returning a more advanced payload to the Slack
API.
payload of const = {
"response_type": "in_channel",
"text": "Highscore:" + score,
"attached files": [
{
"text": "What a high score, wow!"
}
]
}
We want our bot to explicitly post a message on our channel
with the text "Score: 10" for example. In addition, we want to add a
sub-text (attachment parameter) with additional information such as: "What
a high score, wow!".
Deployment application
OK, let's implement the application that we have created.
Because the actual implementation process is out of reach, I recommend that you
use a free service such as Heroku or Now.sh (great resource:
https://www.sitepoint.com/how-to-deploy-node-applications- heroku- vs-now-sh
/).
Now that we have implemented our application, we can use the
following API endpoints:
[deploy-url] / score / getScore: get the last score of the
application
[display-url] / score / add: publish score in the
application
We can use these routes to configure our first Slack bot.
CONFIGURATION OF THE PACKAGE PACKAGE
Before starting, you must 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 implement the
Slack bot.
1. CREATE A NEW BOT
Go to https://api.slack.com/apps?new_app=1 and click on the
green "Create new application" button. A pop-up window will appear.
Fill in the name of your application and select the correct
Slack workspace that you created.
Create the application and select the newly created Slack
application.
2. DEFINE THE COMMANDS OF SLASH
The 'Features' menu gives 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
that you can use in Slack chat.
2.1 ADD SCORING COMMAND
Let's start with the definition of the command to add a
score. To do so, we want to write '/ add [score]' in our chat.
- Command: The command that we write in the Slack
application.
- Request URL: the URL of its implementation with the
correct endpoint added.
- Brief description: brief description of use.
- Suggestion of use: tell your users to complete a score.
2.2 Get scoring command
For this command, we will only request the score of our
application through "/ score / getScore". It is not necessary to pass
any parameter.
3. APPLICATION OF THE APPLICATION TO THE ESCAPE SPACE
Finally, we have to implement our application to be able to
use our defined bar commands. Let's go to the "Install application"
option in the "Settings" menu or visit this URL:
https://api.slack.com/apps/APP-ID/install-on-team
Click on the large green button "Install application in
the work area". Slack will ask you to authorize the installation of this
application for your work area, press "Authorize".
We are ready Let's finish with testing our commands.
TEST SLACK BOT
First, 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 recover the established score. Write '/
getScore' in the chat.
The Slack robot will respond with a message that will be
visible to anyone who shows the score and the command he wrote. The Slack bot
acts in this way because we define a type of response " in_channel
"in our payload.
NEXT STEPS
Many more things are possible with the Slack API for bar
commands. A slash command sends much more information than just the text
parameter. This is the full load 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 = / climate
text = 94070
response_url = https: //hooks.slack.com/commands/1234/5678
trigger_id = 13345224609.738474920.8088930838d88f008e0
Comments
Post a Comment