Making A Simple Slack Application (Part 2)

Making A Simple Slack Application
Slack socks, San Francisco, California, November 21st, 2014.

In the last post, we discussed how to start on making a simple slack application. We setup NPM packages, setup the application on Slack and how to send commands to our Node application which is deployed on Heroku.

Here, we will make application’s real purpose. To declare the message to channels and users.

The command we are using is /ideclare @user1 #channel m"Hello Guys!". Now, here when we want to communicate with to other users or channels, we are posting message.

We can use Slack’s Web API here, which consist of method chat.postMessage. This method is used to post a message to a public channel or user’s channel or multiple user private channel. More Info: chat.postMessage.

To use this message method, 3 things are required: token, channel and text.

The token here is different than the token we had in the previous post. This is a authentication token, which is different for each team on slack. It is actually different for each team and according to permissions scope you have requested for slack.

More on permissions scope later.

Second, the channel is the field which requires the channel code or channel name. Most preferable is channel code but it is little bit tricky to get for now. We will stick to channel names, which includes both usernames and channel names.

Third, the text field is where the actual message goes. But if you have included attachments, you won’t need text field.

Let us get OAuth test token, to get you started on the next phase of the application. Go to this link, and generate your OAuth token.

Warning: Do not share your token anywhere. Do not publish test tokens in public code repositories.

Now that we have OAuth token, we can use chat.postMessage to post messages to channels and users. Let’s expand on the application, we drew out in the last post

     var http = require("http"),
         express = require("express"),
         request = require("request"),
         //Slack accepts time stamp in Unix Epoch Time
         timeStamp = Math.floor((new Date).getTime()/1000),
         app = express(),
          * Part 2.1: Saving OAuth Token for universal usage in script.
         oToken = "YOUR OAUTH TOKEN";'/ideclare',function(req,res){
        //Check if request coming from slack
        if(req.body.token === TOKEN){
            var response_url = req.body.response_url,
                timeStamp = Math.floor((new Date).getTime()/1000),
                arr = req.body.text.split(" "),
                appIcon = "",
                 * Part 2.2: Making the postMessage URL.
                postMessURL = "";
            //Check if the first word is "help"
            if(arr[0] === "help"){
                 res.setHeader('Content-Type', 'application/text');
                 res.send("iDeclare Help!");
                         //There are two types of "ephemeral" and "in_channel"
                         "response_type": "ephemeral",
                         "attachments": [{
                             "fallback": "/ideclare (@username | #channel) m'Your Declaration' /ideclare help",
                             "title": "iDeclare Commands:",
                             "text": ":small_blue_diamond:`/ideclare (@username | #channel) m'Your Declaration'`  "+
                                "_(For example: `/ideclare @john #general m'Meeting at 5pm'`)_ \n" +                 
                            ":small_blue_diamond:`/ideclare help` Lists available commands \n"+
                                "For more features, visit: ",
                             "footer": "iDeclare",
                             "footer_icon": appIcon,
                             "ts": timeStamp 

                     //Handling Errors
                         throw err;
             * Part 2.3: Check if first alphabet of first word is "@" or "#".
             else if(arr[0][0] === "@" || arr[0][0] === "#"){
                  * Part 2.4: Extract the message from the array.
                  var message;
                      if(elem[0] === "m"){
                         message = elem.substring(2, elem.length - 1);

                   * Part 2.5: Sending acknowledgement to the person who called it.

                   * Part 2.6: Sending message to everyone
                  //Adding token
                  postMessURL += "token=" + oToken;
                  //Adding icon of app
                  postMessURL += "&icon_url=" +encodeURIComponent(appIcon);
                  //Adding username 
                  postMessURL += "&username=iDeclare";
                  //Attaching message to URL
                  postMessURL += '&attachments=' + encodeURIComponent('[{"fallback": "'+message+'","text":"'+message+'"}]');

                      if(elem[0] !== "m"){
                         if(elem[0] === "@"){
                            postMessURL += "&channel=%40"+elem.substring(1);
                         }else if(elem[0] === "#"){
                            postMessURL += "&channel="+elem.substring(1);
                         //Posting message to slack
                            throw err;

Now, redeploy the app on Heroku and try it out in your slack channel. Try following command in your slack:

/ideclare #general m"Meeting at 5"

If you coders have any questions or better way to do something in this application. Please let me know, I would love to answer each and every one of you. Moving forward, I will be writing on other types of slack integration using Bots and WebHooks, so stay tuned!

Be the first to comment

Leave a Reply

Your email address will not be published.