Building a Slack Bot to Get Currency Exchange Using NodeJs

Slack is without a doubt a widely adopted messaging tool. It’s been used in companies ranging from startups to fortune 1000. Slack offers various features such as integration, groups, private chat and bots.

Bots are one of the exciting features of slack for the developers. Slack offers SDK’s which we can integrate it into various programming languages.

In this tutorial, we are going to build one simple Slack bot that will fetch the latest currency exchange rates of various currencies whenever we ask for it.

Download Code

Prerequisites

You need Slack installed in your machine and slack workspace in place before proceeding ahead with the article. It’s really easy to set up the Slack and workspace. Just head over to Slack download page and download the latest version.

You need to have the latest Node.js installed in your system.

About Nodejs

Nodejs is a JavaScript runtime framework that allows us to execute JavaScript in the Server. Nodejs comes with asynchronous I/O and a single threaded execution system that allows programmers to write code that is free of deadlock and increases the I/O throughput of the overall system.

Related reading: Learn all about Node!

Node package manager or NPM, in short, is the package manager for Nodejs. Due to NPM, Nodejs has become an ecosystem and used by the front end, backend teams to develop the applications.

Head over toNode.js official site and download the latest stable version in your machine.

About Slack

Slack was originally meant to be the collaboration tool and it evolves into the complete ecosystem, thanks to the slack developer’s platform.

Slack allows developers to create bots that run on top of Slack. Majority of the companies such as Google, Pinterest has their bots available on Slack app directory, a repository of the slack bots.

Creating Slack Bot and getting API Keys

Go to Slack Developers page and register your application. Click here to create your new app on Slack developer registry.

Type in the name of your app and select the workspace.

Create Slack Bot

Once your App is created, Slack will ask you to choose various features. Select the Bots feature.

Create Slack Bot

Finish the creation of your app. After that click on OAuth and Permission button and authenticate your app. After authentication, Application tokens will be generated. We will use those values in our code.

Create Slack Bot

Before moving ahead, install your app in your workspace. Click on Basic information under setting tab menu and then click on Install your app to your workspace.

Your app should be visible in your Slack like this.

Currency Exchange API

Now we have our bot ready with all the tokens we need for your code. Before that, we need to have a system that can get us real-time currency exchange data in a simple JSON format.

I am going to use currencylayer.com for this. They offer really great and easy to use API to fetch real time exchange data.

Related learning: Basic HTTP calls using Node.js

Head over to currency layer website and create your account. Once your account is created, copy the access key. We will use it call currency layer API and get the latest currency exchange information in simple JSON format.

Building NodeJS App to communicate to bot

We need to write code to listen to commands coming from Slack bot and if it matches to our predefined command then call the currencylayer API to get latest currency exchange data.

The predefined command would be report. So when we type report in our slack bot, it will do its job else ignore.

In simple steps, our Node.js code should do the following:

  1. Listen to the slack messages and filter out the text message (excluding media messages).
  2. Check if the user types the command report as an exact match in the message. We don’t want our code to react whenever someone types report in general messages.
  3. If the user has requested the currency report, then our code should call the currencylayer API and format the response.
  4. Our code should send the formatted response back to the user as a Slack message.

Enough talking, let’s head over to the code.

First, create a fresh directory and initialize Nodejs project using the following command.

npm init --y

Then install the following dependency.

npm i --S slackbots request

Then create a file and name it config.js and copy paste the following code in it.

config.js
module.exports = {
    slack: {
        token: '<copy Bot User OAuth Access Token from Slack API dashboard>',
        channelName: 'general' // change it other channel if you want
    },
    currencyLayer: {
        apiKey: '<currency layer api key>',
        apiEndPoint: 'http://apilayer.net/api/live?access_key=$ACCESS_KEY$',
        sourceCurrency: 'USD'
    }
}

Create a new file name it app.js and copy/paste the following code in it.

app.js
const SlackBot = require("slackbots");
const request = require("request");
const config = require('./config');

// initialize bot
const bot = new SlackBot({
    token: config.slack.token,
    name: "Currency Bot"
});

bot.on("start", () => {
    console.log("Bot is ready.");
});

// event raised when we type something on bot
// on each received message, filter it out
// the type 'message' is classified as a user-generated message

bot.on("message", (data) => {
    if(data.type==='message') {
        filterMessage(data)
    }
})

async function filterMessage(message) {
    // when user types report
    if(message.text === 'report') {
        let data = await getAllPair();
        let formattedData = "";
        Object.keys(data.quotes).forEach((singlePair) => {
            formattedData += singlePair;
            formattedData += ' : ' + data.quotes[singlePair] + '\n';
        })
        postMessage(formattedData)
    } else {
        // further processing can be done
        // such as custom commands
        return;
    }
}

function getAllPair() {
    return new Promise((resolve, reject) => {
        let apiEndPoint = config.currencyLayer.apiEndPoint.replace('$ACCESS_KEY$',config.currencyLayer.apiKey);
        request(apiEndPoint,(error,response,body) => {
            if(error) {
                return reject(error);
            }
            resolve(JSON.parse(body));
        })
    })
}

function postMessage(message) {
    bot.postMessageToChannel(config.slack.channelName, message);
}

Code explanation

We have stored our configuration details in a separate file named config.js. The code which does the magic is in app.js file.

We are listening to the events provided by the Slack API and on each message executing our function.

We have three important functions:

1: filterMessage(): In this function, we are checking whether the user has typed our command i.e report. If yes, then we are going to fetch the currency details using getAllPair() function and post the currency details to the Slack group using postMessage() function.

2: getAllPair(): In this function, we are calling the currencylayer API to fetch the latest currency exchange. We are using request node modules to achieve the same.

3: postMessage(): In this function, we are sending the message to the Slack group. The message is our currency exchange information.

In a nutshell, whenever you type something on the bot, an event will be generated and we can listen to that event in Nodejs using a simple event listener.

If the user has typed the predefined command, then we will call the currency layer API using our request module, parse the data and send it back to the Slack.

Running the code

Assuming you are using general channel name, invite your bot in the channel by typing @botname and hit enter.

Now run the app using the following command.

node app.js

Once a message is printed on the console saying ‘Bot is ready’ Like this.

Now in Slack, select your bot and type report. You should see the currency exchange data like this.

Try a few more commands and it won’t react because we have only configured the report command.

Deploying the Slack app

We have developed our Slack app and Node.js server. It’s time to let the world see it. In order to make it publicly accessible, we need to deploy the Slack app and deploy Node.js code.

In order to deploy the Slack app, we need to submit it to the Slack developer’s platform. In order to do so, open up the Slack app from slack apps page and go to Manage distribution section.

We need to perform the submission checklists and once everything is completed we can hit on Submit App button and your Slack app will be live. Install the app again in your workspace to update the app setting.

You can deploy the Nodejs app on Heroku platform in few clicks. Once everything is deployed, you can share the URL of your bot to the public and be ready for the feedback and appreciations.

Further reading

Conclusion

Slack bots are really fun. We can develop amazing apps to help us automate lots of tasks while we do our work. For example, we can code Stack overflow bot that can look up the solution for us. We can build a simple bot to check weather and many more.

I hope you have learned bits and pieces of developing Slack bot using Nodejs.

Pankaj Kumar
Pankaj Kumar
Articles: 207