Slack API Tutorial: How To Build A Simple Slack App That Tells You Real-Time Cryptocurrency Prices

Get real-time cryptocurrency prices in your slack workspace. An introduction to Slack webhooks, slash commands, events API, and more.

Goal

Today, we are going to build a simple Slack application to get real-time cryptocurrency prices in our Slack workspace, and introduce the basics of the Slack API, including webhooks, slash commands, events, and more.

We will fetch real-time cryptocurrency prices from the coin APIs and, when any user ask for it via the slash command /coinprice, we will return the up-do-date price of the cryptocurrency.

Pre-requisite

  • NodeJs
  • Slack workspace
  • Slack app

Understanding Slack APIs

Slack has very rich APIs. There are thousands of apps and bots on the Slack platform. These serve different purposes and integrate with hundreds of third-party apps. Slack’s API also makes it easy to build customized apps for your own needs.

Let’s begin by reviewing the different mechanisms you can use to interact with Slack apps.

  • Incoming Webhooks

Using incoming webhooks, you can post a message to Slack from your app. Incoming webhooks are specific URLs attached to a specific channel. You can use markup and send attachments with your messages. We will be using this feature to post cryptocurrency prices.

  • Slack Slash Commands

Slash ( / ) commands are one of the richest features of Slack APIs. Using slash commands, you can build complex workflows and integrations. When a user invokes these commands from the message box, your app gets the request and your app can send back whatever response it wants. There are few inbuilt slash commands provided by slack such as /remind and /call.

  • Slack Events API

When you subscribe to Slack events, Slack sends you these events on your specified URL. Slack many different types of events. You can subscribe to multiple types of events at a time.

Building a Slack slash command

We will build a /coinprice command to get the price of cryptocurrencies. Before that, we need to do a few things.

Head over to Slack API platform and create a new app and select your workspace for this app. You need to enable features to use them. So select ‘Slash Commands’ and create a new command.


create a new slack slash command

You need to add a request URL (We will use [ngrok](https://ngrok.com/), to expose our local server to the web while developing the app).

Whenever a user invokes /coinprice command, Slack will send a post request for the above-defined Request URL.

router.post('/', function(req, res) {
   var coinName = req.body.text;
   aggregateDataLast24Hours(coinName , function (err , data){
   var result = createSuccessResponseForLast24Data(data.Data ,coinName);
   res.send(result);
});
});

We will read the body text to get the name of the cryptocurrency. Then, we will get the price and return the request. (Don’t worry, I will attach full code at the end of the article.)

You can use markup to create a beautiful response.


Slash command with the resulting response. (This result is visible to the user only who is invoking the command.)

Here, **cryptotrends** is our slack app name.

Slack Events

Now, we will use Slack events to get the cryptocurrency prices. So let's configure our slack app for this purpose.

Slack event example

We need to provide a URL where Slack will post a request. In the request, Slack will send a challenge parameter, whose value you need to return back to validate the URL.

Slack provides different types of events to which you can subscribe. We will subscribe to the message.channels event type. This will enable us to get every message on the channel.

Whenever users type ?p followed by a cryptocurrency symbol, we will send back the result using webhook URL (we will also see them below). These results will be visible to everyone. So be careful about what at you post. 😉


Above will invoke the slack event and the result is getting posted by Incoming webhook

You can see, we are tackling challenge parameter at the start of the method.

Once user invokes /coinprice btc (we want bitcoin price, BTC is the symbol for bitcoin). Slack will send the post request to our defined URL which is currently forwarding the request using ngrok.

router.post('/message', function(req, res) {
    try {
        if (req.body.challenge != undefined) {
            res.send(req.body.challenge)
        }
var coinName = getCoin(req.body.event.text);
        if (coinName != "nocoin") {
            if (req.body.event.text.substring(0, 3) == "?p ") {
                aggregateDataLast24Hours(coinName, function(err, data) {
                    postToWebhook(data, coinName);
                });
            } else {
                sendChart(coinName, req.body.event_id);
            }
        }
    } catch (err) {
        console.log(err);
    }
});

Let's understand what’s happening above, step by step.

  • If the request has challenge parameter, which Slack sends while URL configuration, we will send that back.
  • Else, we will read the text body and get the cryptocurrency name, whose price user wants. I am returning “nocoin” if we don’t able parse cryptocurrency symbol.
  • As we are getting every message of the channel, that's why we need to come with a unique phrase to reply prices. For this purpose, we will only entertain ?p followed by cryptocurrency name.
  • Once we parse the message we will post the result on the channel using slack incoming webhook.

Slack Incoming Webhook

We will post results for events using the Slack Incoming webhook URL. Let’s configure a webhook URL for this purpose. You need to go to your Slack app and add Incoming Webhook functionality.

You need to select the channel in which you want to post messages. Our webhook URL will be specific to this channel only. In our case, it’s #general channel. For testing purposes, you should create a test channel.

Incoming Webhook

Once authorized, we will get a webhook URL, which we will use in our application. Below is the method, which is posting our response to a Slack channel.

function postToWebhook(data, coinName) {
    rest.post('YOUR_WEBHOOK_URL', {
        data: JSON.stringify(createSuccessResponseForLast24Data(data.Data, coinName))
    }).on('complete', function(data, response) {
        // console.log(response);
    });
}

That’s it! We successfully posted the message on the slack channel. You can use Slack markup and formatting to beautify your message and attach files.

Full working code

You can check the full code here. You need to run below command and configure your Incoming webhook URL and tokens.

npm install
npm start

Also, you need ngrok to expose your local server to the web. You can run this command for that.

./ngrok http 3000

Extra Sauce

In the code, you can also find a way to upload charts, which we didn’t discuss in above tutorial. Slack also provide libraries to make process easy. So you should check out them also. There are so many startups which are earning millions just by build bots on slack. Don’t believe me? Check out this Techcrunch article.

Interesting Fact- Slack ran in stealth mode for more than a year before launching in 2014.

Conclusion

Today, we learned few main features of the Slack API platform. Slack also provides Bots and interactive actions functionality to build more complex apps and integration. Check them out too.

Slack is an awesome tool, which revolutionized the way teams interact. You can build many different kinds of useful apps on slack and you already have an app, you should look into slack integration for it. Slack provides rich APIs to interact with its platform and these APIs are used by thousands of the developers around the world.

Originally published:

December 10, 2018