At its most basic, Slack is a messaging system; however, it can be infinitely extended and customised. It provides a flexible system to customise your team's integration by creating custom welcome messages, your own applications and Slack bots just to name a few. In this tutorial, we’ll be building a very basic app in Node.js, running it on your laptop or desktop computer, connecting it to Slack and finally forwarding the Slack messages to your mobile.
Prerequisites
Step 1: Setting up ngrok
So that we can move through this tutorial fairly quickly, we'll be setting up a server locally. Installing ngrok is basically extracting a file; the way I like to do it is by extracting ngrok to my preferred folder and adding it to my system's PATH. The advantage is that you'll be able to run ngrok from any path on the command line. If ngrok is on your PATH, then simply type the following from any directory:
ngrok http 3000
If all goes well, you should see the following:
The online status is a good sign which means the tunnel is working and your app is now accessible on port 3000. The address to access it from the internet would be the one next to Forwarding, with the ngrok domain. In my case its https://e7c068d8.ngrok.io
Step 2: Create a simple HTTP server
Let's set up a simple web server to processes all incoming HTTP requests. For this part, you'll need a code editor such as Sublime Text or Atom. We'll be using Node.js to develop our app, so you'll need to make sure you've installed it on your machine as well. Now create an empty folder for your project, let's name it testApp. Create an index.js file inside that folder and open it up in your editor. Write down the following code. I've commented it so you can understand what's going on with each line:
// This imported module contains all the logic for dealing with HTTP requests.
var http = require('http');
// We define the port we want to listen to, and it should be the same port than we specified on ngrok.
const PORT=3000;
// We create a function which handles any requests and sends a simple response
function handleRequest(request, response){
response.end('Ngrok is working!');
}
// Passing our request function onto createServer guarantees the function is called once for every HTTP request that's made against the server
var server = http.createServer(handleRequest);
// Finally we start the server
server.listen(PORT, function(){
// Callback triggered when server is successfully listening.
console.log("Server listening on: http://localhost:%s", PORT);
});
To run the app type the following from your testApp directory using the Terminal:
node index.js
Now try visiting your ngrok address once more and you should be pleasantly greeted with a “Ngrok is working!” message.
Step 3: Adding and configuring outgoing Webhooks to your Slack workspace
First you'll need to sign into your workspace via https://slack.com/signin. Once signed it, you need to to the App manager screen which can be found at https://xyz.slack.com/apps/manage (replace "xyz" with the name of your workspace).
Now follow these next few steps to add and configure outgoing Webhooks: 1. Click on App Directory at the very top and in the search bar that appears, type in Outgoing WebHooks 2. Enable it by clicking on the Add Configuration -> Add Outgoings Webhooks integration 3. You will be directed to a page that displays Outgoing Payload and Responses and other details of the integration 4. Scroll down until you see Integration Settings. This where we’ll be configuring the webhook.
5. The trigger word is what your message should begin with if you want to send data to your Node.js application. We will set this to :phone for the purpose of this tutorial but you can change it to anything you like.
6. The URL is where you’ll be sending your data to. In our case, this is https://e7c068d8.ngrok.io/events
7. Leave the rest of the settings the same and save your changes
Step 4: Refactoring Script
We'll need to modify the code so it can interact correctly with Slack. To keep our script concise, we'll use a few essential third-party packages – express, request and body-parser. Express is a web application framework that allows us to set up a simple web server. It makes it easy to set up the routing logic we need for the requests we'll receive from Slack. Request is a handy package to make HTTP calls. We'll use it to interact with Slack's web API. Body-parser is an npm plugin for Express that we need to use in order to be able to capture data coming via a POST request. To install the packages, open the command line from the root directory of your folder and run the following commands separately:
npm install express
npm install request
npm install body-parser
Now let’s refactor our code:
// Import express, request and body-parser modules
var express = require('express');
var request = require('request');
var bodyParser = require('body-parser');
// Instantiates Express and assigns our app variable to it
var app = express();
// Basically telling our Express app to use the bodyParser package
app.use(bodyParser.urlencoded({ extended: false }));
// Define a port we want to listen to
const PORT=3000;
// Lets start our server
app.listen(PORT, function () {
//Callback triggered when server is successfully listening.
console.log("Example app listening on port " + PORT);
});
// Route the endpoint that our outgoing webhook will point to and send back a simple response
app.post('/events', function(req, res) {
console.log(req.body.text);
});
// This route handles GET requests to our root ngrok address and responds with the same "Ngrok is working message" we used before
app.get('/', function(req, res) {
res.send('Ngrok is working!');
});
Step 5: Testing script
Before we can start testing, ensure your Node app is running alongside ngrok:
Go to your Slack messaging workspace and open up any one of your channels and type :phone hello and send the message. Now try visiting your Node console and the message should appear over there:
Step 6: Adding messaging functionality
We'll be using MessageMedia's Node.js SDK for messaging. Run the following command from the root directory of your folder to install it:
npm install messagemedia-messages-sdk
Let's refactor our code again to add messaging support. Don't forget to add in your API credentials.
// Import the modules
var express = require('express');
var request = require('request');
var bodyParser = require('body-parser');
var sdk = require('messagemedia-messages-sdk');
// Create the messages controller
var controller = sdk.MessagesController;
// Instantiates Express and assigns our app variable to it
var app = express();
// Basically telling our Express app to use the bodyParser package
app.use(bodyParser.urlencoded({ extended: false }));
// Setting your auth keys for accessing the Messages API. You app will not work without these!
sdk.Configuration.basicAuthUserName = "API_KEY";
sdk.Configuration.basicAuthPassword = "API_SECRET";
// Define a port we want to listen to
const PORT=3000;
// Lets start our server
app.listen(PORT, function () {
//Callback triggered when server is successfully listening.
console.log("Example app listening on port " + PORT);
});
// Route the endpoint that our outgoing webhook will point to and send back a simple response
app.post('/events', function(req, res) {
var slackResponse = req.body.text;
// Remove trigger word from string. You can replace :phone to whatever your trigger word is
var msg = slackResponse.replace(":phone", "").trim();
let body = new sdk.SendMessagesRequest();
body.messages = [];
body.messages[0] = new sdk.Message();
body.messages[0].content = msg;
body.messages[0].destinationNumber = '+61491570156';
controller.sendMessages(body, function(error, response, context) {
if (error) {
console.log(error);
res.send({
"text": "Text failed to deliver :("
})
return;
} else {
console.log(response);
res.send({
"text": "Text delivered :)"
})
}
});
});
// This route handles GET requests to our root ngrok address and responds with the same "Ngrok is working message" we used before
app.get('/', function(req, res) {
res.send('Ngrok is working!');
});
Go back to your Slack channel and try sending another message beginning with :phone. We've tried sending :phone Greetings from Slack!
A successful response from the console should look like this:
And on my mobile phone:
Congratulations!
You've created an app that receives Slack messages and forwards them to your mobile phone. Now you can start adding complex logic to your application and perhaps forward the message to different mobile numbers based on names mentioned in the Slack messages. The possibilities are endless.
Comments
0 comments
Article is closed for comments.