Slack needs little introduction and if you’re familiar or aware, they also have apps within Slack that help you with your workflow and day-to-day tasks. If you can’t find an app from the official Slack App directory, you can always build your own.
In this post, I’ll be covering how to build a simple Slack app which get’s the latest crypto prices using a third party API and displaying them in Slack.
Here it is in action.
All this is from my learnings from building my side projects, both of which are Slack apps.
If you’re a starting out, this guide may help you kick start your development in building your Slack app. Meandering through Slack’s documentation can be rather daunting at first as there is a lot to cover, however it is very comprehensive and has a wealth of information and all you need is documented there.
What kind of Slack App can you build?
Well, I like to think there are three kinds of Slack apps you can build.
- Bots. As the name suggests, you can build Slack Bots. These bots act like users within your Slack workspace. They can accept user requests within Slack and also respond to you or another user or carry out a background task. Bots are probably the most complex as it involves reading a user’s message and interpreting it can be tricky. This of course depends on the type bot you are building.
- Slash Commands. If you’re not familiar with Slash commands, they are literally slash commands which you can use within Slack to execute a particular action or task. A built in slash command within Slack is
/remind
. As the name suggests, it let’s you add a personal reminder within Slack. If you would like to build a simple Slack action or task, slash commands are a good approach. - Incoming webhooks. If you do not need any direct input from a user to trigger an action and you just want to push messages or data to a specific Slack channel, incoming webhooks is the easiest way to go. When creating a Slack app and enabling incoming webhooks, it will provide you with a custom url. Using this url you can post messages directly into Slack. This is generally useful for perhaps daily reports or when incidents happen or notifications.
I should point out that there are no restrictions that your app has to be exclusively one of the 3 kinds above. You can of course implement all the above features for your app.
Internal or Public Slack App
Building Slack apps can be either internal to your Slack workspace or they can be public to other workspaces. If you intend to build a Slack app which is predominantly for your group or organisation that addresses a particular niche, need, or requirement, then creating internal apps makes sense. If, however you wish to share your Slack app to the world, then a public app would be an option here. The only difference between internal and public apps are that with public apps, they require additional security measures that you will need to implement. These include SSL and verifying Slack requests. Also, you will have to submit your app for review where Slack will carry out a review process and approve it. Currently it’s free and there is no cost. Having gone through this process twice myself personally, the Slack team are very helpful with reviewing and providing suggestions and feedback.
Building a Real World Slack Crypto Slash command App
Here, we will be creating a simple crypto pricing Slack app. It will be a slash command where it will get the price of a particular crypto currency and report back to the user. Although this example will be using C# .NET Core, you can use any language as the principle is the same.
The slash command we will be building will be:
/crypto [crypto symbol] in [currency]
Example usage to get the price of Bitcoin in US dollars:
/crypto BTC in USD
Another example for getting the price of Bitcoin in British pound sterling.
/crypto BTC in GBP
Here it is in action again.
Summary of steps
There is no particular strict order in which things needs to be done. However, the steps below outline what needs to be done.
- Sign up and get a free API key from CryptoCompare.
- Create an API to receive the slash command from Slack and respond with the correct message.
- Use ngrok to expose your API publicly.
- Register and create a Slack app.
Get a Free Crypto API Key
I’m using CyrptoCompare’s API as they have a simple API with a free tier. At the time of writing they have up to 100,000 calls per month, which is plenty for this demonstration. Once you have an API key, a simple HTTP GET can be made to obtain a price. Something like this:
HTTP GET
https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD,EUR,GBP&api_key={your-api-key-here}
Here’s an example response.
{
"USD": 10487.76,
"EUR": 9441.86,
"GBP": 8650.6
}
Constructing Slack messages
Slack offers a relatively rich method of composing messages. You can send basic text or markdown messages (with limits, which I will get onto in a bit). Slack also provides different layouts or formats. The best way to describe this is to checkout Slack’s block kit builder. They have a few examples demonstrating the types of messages you can build. As mentioned before, there are some limits. For instance, you can’t add any colors to the messages. Or, you won’t be able to change font sizes. This is understandable as to adhere to Slack’s messaging standards. But Slack’s block kit builder is definitely an upgrade and once you get your creative hat on, you can create some pretty impressive messages.
For this post, we are going to build a simple markdown message like so.
This is what the json representation of the message.
[
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": ":chart_with_upwards_trend: *1 BTC* is currently equals *1,0487.76 USD*"
}
}
]
As you can see, you can add emoji’s to messages as well as making text bold using the asterisk, such as *1 BTC*
.
Create the API
We need to create an API to receive the slash commands that the user enters in Slack. We then need to interpret the command and extract the crypto currency symbol, the target currency that needs to be converted into and pass these parameters into CryptoCompare’s API. Finally, we need to construct a Slack message with the response.
I’m using C# .NET Core in this example. However, feel free to chose whatever is comfortable and familiar to you.
All source code can be found in my GitHub repo
Below is a snippet which handles a POST request from Slack and extracts Slack’s POST parameters which can be found here.
The code exposes a POST endpoint /api/slack/commands/
which accepts a form encoded dictionary input.
[HttpPost]
[Route("api/slack/commands")]
[Consumes("application/x-www-form-urlencoded")]
public async Task<IActionResult> ReceiveSlackSlashCommand([FromForm] IDictionary<string, string> slackParameters)
{
var responseUrl = slackParameters["response_url"];
var text = slackParameters["text"];
var parts = text.Split(" ");
var cryptoSymbol = parts[0].ToUpper(); // extract the crypto symbol, e.g. BTC, ETH, LTC
var targetCurrency = parts[2].ToUpper(); // extract the currency
// Call the cryptocompare API
var responseMessage = await _httpClient.GetAsync(
$"https://min-api.cryptocompare.com/data/price?fsym={cryptoSymbol}&tsyms={targetCurrency}&api_key={cryptoCompareApiKey}");
// read the response
var content = await responseMessage.Content.ReadAsStringAsync();
// parse the json
var jToken = JToken.Parse(content);
var price = jToken[targetCurrency].Value<decimal>();
// create slack message
var slackMessage = new
{
blocks = new[]
{
new
{
type = "section",
text = new
{
type = "mrkdwn",
text = $"*1 {cryptoSymbol}* currently equals *{price:N} {targetCurrency}*"
}
}
}
};
// send to slack
var httpResponseMessage = await _httpClient.PostAsync(responseUrl,
new StringContent(JsonConvert.SerializeObject(slackMessage), Encoding.UTF8, "application/json"));
Setup ngrok
Ngrok is a tunneling tool that allows a localhost url to be public. This is super useful for testing local urls publicly in scenarios such as testing webhooks and in cases such as this.
Go ahead and download ngrok. Once downloaded, you can execute the command line tool and set the parameters like so to your localhost and port.
ngrok.exe http -host-header="localhost:63559" 63559
You should see something like this output:
ngrok by @inconshreveable (Ctrl+C to quit)
Session Status online
Session Expires 7 hours, 59 minutes
Update update available (version 2.3.34, Ctrl-U to update)
Version 2.3.28
Region United States (us)
Web Interface http://127.0.0.1:4040
Forwarding http://b061e557.ngrok.io -> http://localhost:63559
Forwarding https://b061e557.ngrok.io -> http://localhost:63559
Connections ttl opn rt1 rt5 p50 p90
0 0 0.00 0.00 0.00 0.00
If you notice, it has provided a forwarding url http://b061e557.ngrok.io
. This is a public url that you can use temporarily. Verity it works by checking in a browser or testing via Postman.
Make a note of this url as we will be needing to when come to register the url with Slack.
Also, ngrok provides a very useful web interface which it has provided in its output: http://127.0.0.1:4040
. This is really useful for debugging purposes.
Create a Slack App
Next, we need to register and create an App in Slack. Head over to the Your Apps section in Slack, and click on the “Create New App” button. You should see a dialog where you are asked to give it a name. Something like this:
Next, we are provided a choice of app features to build. As we are building a slash command, we are going to select “Slash Commands”.
We shall create a Slash command by clicking “Create New Command”.
Next, we need to provide details of how the command will work and also the API endpoint so that Slack can post data to.
Enter the slash command such as /cryptoprice
and the url of the API. This is where we will be using the ngrok url that was generated http://b061e557.ngrok.io/api/slack/commands/
.
Install it on your workspace.
For Slack apps to work, they need to be installed on a workspace. Slack offers two methods.
- Install via workspace. This is the simplest and fastest way of installing Slack apps. However, they are restricted to internal apps.
- Slack Button. If you are building public apps, the Add to Slack button will need to be implemented. More information can be found at Slack’s documentation about how to integrate the Slack button.
Here, are are going to install the app the easy way.
Testing it out
Finally, we can test out the new command by visiting Slack and firing out the command.
Summary
In this post, we covered how to build an internal Slack app that utilised the slash command to obtain crypto prices.
Slack apps can be as simple or fully comprehensive as you like.
I have built two Slack apps as side projects statusmonitor and gitagent
All the source code can be found at my GitHub repo