Flo  D'Amore

Flo D'Amore

1621484694

How to Build a Slack Bot in JavaScript with Bolt API

Develop and customize your own Slackbot using the Bolt API, the newest library for programming with Slack in JavaScript.

Originally published by Adebola Adeniran at https://blog.logrocket.com/

The new Bolt API

I recently tried to develop a Slackbot with the Node Slack SDK but, unfortunately, I ran into some bugs. That was when I stumbled upon the new Bolt API. According to Slack, it’s the “swiftest way to start programming with the Slack Platform in JavaScript.”

There are a number of reasons to try the new Bolt API from Slack to build your next Slack app or bot. For one, it’s a well-documented library that will help you avoid running into weird bugs and issues further down the line. Secondly, the API is developed and maintained by Slack, which ensures that it’ll be updated frequently.

Developing with this API has been a breeze, and I can assure you that the Bolt API library is the way to go when it comes to developing Slack apps. In this tutorial, you’ll learn how to create your own Slackbot with the Bolt API.

Setup

Prerequisites

To follow along with this tutorial, you’ll need:

  • Basic knowledge of JavaScript and Node.js
  • Node.js v12 or higher
  • npm

Create a workspace

To get started, we’ll need a workspace to install our bot in. A Slack workspace is a way to group communication within an organization. Everyone in an organization can belong to one workspace, which is then subdivided into multiple channels.

Install Slack on your device and create a new workspace. Slack will then send a 6-digit code to your email that you can use for verification. Now for the fun part! Give your workspace a name; for this tutorial, we’ll create a fictional company called The Zobo Tea Company.

Note: If you’re feeling curious, you can read more about hibiscus teas (also known as Zobo).

Company Name Slack Screen

Next, Slack will prompt you to enter the name of the project you’re working on. You can call the project whatever you want. You can skip the last step where Slack prompts you to add other team members.

Create a new Slack application

Now, we’ll create a new Slack app. Slack apps are small applications that provide specific functionalities within a workspace. You can install a preexisting Slack application by signing into your Slack workspace and searching for applications within the Slack app directory.

The Slack app we’ll create is a knowledge base that helps employees within our fictional organization quickly find answers to FAQs.

To create a new Slack application, head to the Slack API dashboard. Click the Create New App button on the top right. Give your bot a name, then select what workspace you would like to install the app to. We’ve called ours ask-ztc-bot.

Create Slack App

Hit Create App and you’ll be redirected to the dashboard for your new app.

0Auth and Permissions

We need to give our new application certain permissions for it to access data and perform actions within our Slack workspace.

On your Slack dashboard, you’ll find the OAuth and Permissions menu option on the left sidebar. Once you navigate here, scroll down to Scopes. We need our ask-ztc-bot to be able to read instant messages from users and respond to those messages. Here’s a screenshot of the scopes we’ve given our bot:

Slack Bot Token Scopes

Install the app to your workspace

With that done, we can now install the app to our workspace. From the left sidebar, navigate to Settings > Install Apps > Install to Workspace.

Set up the Slackbot server

Next, it’s time to write some code. We’ll need to set up a server for our Slackbot that we can send requests to. Let’s get into it!

Create a directory called ask-ztc-bot and initialize npm:

mkdir ask-ztc-bot && cd ask-ztc-bot 
npm init -y

Install the following packages in the ask-ztc-bot directory:

  • @slack/bolt: a JavaScript framework for building Slack apps in a flash using the latest platform features
  • nodemon: a tool that automatically restarts a Node.js application when file changes in the directory are detected
  • dotenv: a zero-dependency module that loads environment variables from a .env file into process.env

I’ll be using the Yarn package manager to install these packages, but you can also use npm:

yarn add @slack/bolt
yarn add -D nodemon dotenv

We need to make a little tweak to our package.json file. Let’s add a new script called dev that runs nodemon app.js. Your package.json should look something like this:

...
  "main": "index.js",
  "scripts": {
    "dev": "nodemon app.js"
  },
....

The dev script automatically restarts our server in app.js when we make changes to any file within our codebase. Next, create the app.js file that will contain the code for our server:

touch app.js

Authentication with tokens and secrets

Slack will need to authenticate our bot to connect it. Slack authenticates apps using a SIGNING_SECRET and a BOT_TOKEN. We’ll need to store both the SLACK_SIGNING_SECRET and SLACK_BOT_TOKEN in a .env file to prevent them from being exposed when using version control.

To find your SLACK_SIGNING_SECRET, navigate to Basic Information > App Credentials > Signing Secret. To get your SLACK_BOT_TOKEN, head to Settings > Install App > Bot User oAuth Token. Your SLACK_BOT_TOKEN should begin with xoxb.

Create a .env in the root directory of your project and assign the SECRET and TOKEN you obtained from the step above:

SLACK_SIGNING_SECRET="YOUR SIGNING SECRET"
SLACK_BOT_TOKEN="YOUR BOT TOKEN"

Setting up the server

Head into the app.js file we created earlier and add the code below:

const { App } = require("@slack/bolt");
require("dotenv").config();
// Initializes your app with your bot token and signing secret
const app = new App({
  token: process.env.SLACK_BOT_TOKEN,
  signingSecret: process.env.SLACK_SIGNING_SECRET,
});

(async () => {
  const port = 3000
  // Start your app
  await app.start(process.env.PORT || port);
  console.log(` Slack Bolt app is running on port ${port}!`);

})();

Run the yarn run dev script we created earlier to make sure everything works correctly. You should get a message in your terminal reading “Slack Bolt app is running on port 3000!”

Setting up ngrok

We need a way for our Slack app/bot to reach the server we’ve created on our localhost. To do this, we can proxy to localhost via a public URL created by a service like ngrok. Once you’ve got ngrok installed, run the following command in the directory:

./ngrok http 3000

This creates a public URL that proxies to your localhost running on port 3000. Now, ensure that your server on localhost:3000 is still running.

Socket Mode

Slack also has a feature called Socket Mode, which allows Slack to connect to our application server using WebSockets instead of HTTP like we did with ngrok above. Socket Mode offers us a much faster development experience because we can skip setting up ngrok.

Getting started with Socket Mode

First, navigate to Settings > Basic Information > App-Level Tokens. Once there, click the Generate Token and Scopes button. Give your token a name, and give your app the two available scopes: connections:write _a_nd authorizations:read. Hit the generate button. Then, copy the token on the next screen into your .env file.

Next, head to Settings > Socket Mode. Toggle the Enable Socket Mode toggler. Finally, head into your app.js file and update the code that initializes your app with socketMode:true and your appToken:

const app = new App({
  token: process.env.SLACK_BOT_TOKEN,
  signingSecret: process.env.SLACK_SIGNING_SECRET,
  socketMode:true, // enable the following to use socket mode
  appToken: process.env.APP_TOKEN
});

With that completed, all requests to your development server will now happen via WebSockets and not HTTP.

Slash Commands

Now that we’ve given our app some permissions and set up a server and a public URL, the next step is to allow it listen for Slash Commands. In Slack, you can trigger an action by sending a command as a message. For example, a Slash Command could be /knowledge to show all the content in our knowledge base.

To enable Slash Commands, click the Slash Commands menu option on the left sidebar. Then click the Create New Command button. Fill out the form using the image below as a guide. The request URL should be the custom URL automatically generated by ngrok for your application.

Slack Create New Command

Hit the save button located on the bottom right side of the screen. Slack will prompt you to reinstall the app to your workspace for your changes to take effect. Follow those instructions, and your /knowledge command should now be created!

Testing the /knowledge command

Now, we can test the /knowledge command from inside Slack. First, we’ll create a listener to listen for events that include the /knowledge command. In your app.js file, add the following code:

const { App } = require("@slack/bolt");
require("dotenv").config();
// Initializes your app with your bot token and signing secret
const app = new App({
  token: process.env.SLACK_BOT_TOKEN,
  signingSecret: process.env.SLACK_SIGNING_SECRET,
});

app.command("/knowledge", async ({ command, ack, say }) => {
    try {
      await ack();
      say("Yaaay! that command works!");
    } catch (error) {
        console.log("err")
      console.error(error);
    }
});

(async () => {
  const port = 3000
  // Start your app
  await app.start(process.env.PORT || port);
  console.log(` Slack Bolt app is running on port ${port}!`);

})();

Let’s test our code! In the Slack app, you should see the ask-ztc-bot app just under the Your Apps section. Click that to send messages to the bot. Type /knowledge and hit enter. You should receive a message reading “Yaaay! that command works!”.

Bot Working Message Slack

Messages in Slack

We can also mention or @ the bot and include additional text to be sent to the bot as a message.

In Slack, mentioning an app is a type of event. We can also listen for other events like when new users join a channel, a new channel is created, etc. For our bot/app to listen for events, we need to set up event subscriptions.

Event subscriptions

To enable events, navigate to Features > Event Subscriptions from your Slack app dashboard. Toggle the Enable Events button on.

For Slack to notify our app of events, we’ll need to provide a public URL that Slack can verify. Copy the ngrok URL we created earlier and paste that into the Request URL input field. You’ll need to append /slack/events to the URL because Slack will verify your URL by sending a POST request.

Enable Event Subscriptions Slack

Once you see the green verified text with the tick sign, you know your app has been successfully verified by Slack, and you’re ready to go!

Next, we need to give the app some event permissions. Click the subscribe to bot events dropdown and add the following events. There are four events related to messages:

  • message.channels: listens for messages in public channels
  • message.groups: listens for messages in private channels
  • message.im: listens for messages in your app’s DMs with users
  • message.mpim: listens for messages in multi-person DMs

In this tutorial, we’ll only subscribe to message.im because we only want users to DM our bot.

Subscribe Bot Events Slack

Hit the Save Changes button in the bottom right corner of the screen to save your changes.

Now, we can test our app to make sure it can receive and respond to messages. In your app.js, add the following piece of code:

app.message("hey", async ({ command, say }) => {
    try {
      say("Yaaay! that command works!");
    } catch (error) {
        console.log("err")
      console.error(error);
    }
});

Head back to the azk-ztc-bot app and send it a message like @ask-ztc-bot hey. You should get a response back.

Slackbot Command Works Message

For an app like a knowledge base, we can’t really match exact words. We need a way to check if the message a user is sending to our bot contains a keyword that matches a keyword in our knowledge base. For that, Slack allows us to use regex expressions. For example, let’s update the code block that we used above to look like this:

// matches any string that contains the string hey
app.message(/hey/, async ({ command, say }) => {
    try {
      say("Yaaay! that command works!");
    } catch (error) {
        console.log("err")
      console.error(error);
    }
});

Send a message that includes the string hey in the format Well, hey there Mr.bot!. Our bot will still respond correctly since the message contains the string hey.

String Message Bot Response

Creating the knowledge base

Now, we can get into actually creating the knowledge base.

First, we’ll create a mini database to store frequently asked questions and answers. Our database will be a simple JSON file on our server. You may want to consider a DBMS like MongoDB if your data requirements become large and complex.

In the root directory of your project, create a db.json file and add the following data:

{
    "data":[
        {
            "keyword": "products",
            "question": "How many different products do we sell at ZTC?",
            "answer": "ZTC currently has 3 products on the market. Hibiscus tea with a hint of one of Lemon/Pineapple or ginger."
        },
        {
            "keyword": "products",
            "question": "What online stores sell our products?",
            "answer": "Amazon, Macy's and Shoprite."
        },
        {
            "keyword": "people",
            "question": "How many people work at ZTC?",
            "answer": "ZTC currently employs 250 people from 21 different countries."
        },
        {
            "keyword": "reset password",
            "question": "How do I reset my password?",
            "answer": "To reset your company E-mail password, call Ola on ext.8099."
        }

    ]
}

We’ve created a set of four questions with their answers and grouped them under certain keywords for easy reference.

Responding to commands

With our JSON database set up, we need a way to read the data in it. We’ll use the built-in fs module from Node.js to read from the db.json file. At the top level of your app.js file, add the following block of code:

// require the fs module that's built into Node.js
const fs = require('fs')
// get the raw data from the db.json file
let raw = fs.readFileSync('db.json');
// parse the raw bytes from the file as JSON
let faqs= JSON.parse(raw);

Now, we can write the code for responding to the /knowledge command. This command will display all the questions and answers in our database to the user:

app.command("/knowledge", async ({ command, ack, say }) => {
  try {
    await ack();
    let message = { blocks: [] };
    faqs.data.map((faq) => {
      message.blocks.push(
        {
          type: "section",
          text: {
            type: "mrkdwn",
            text: "*Question*",
          },
        },
        {
          type: "section",
          text: {
            type: "mrkdwn",
            text: faq.question,
          },
        },
        {
            type: "section",
            text: {
              type: "mrkdwn",
              text: "*Answer*",
            },
          },
          {
            type: "section",
            text: {
              type: "mrkdwn",
              text: faq.answer,
            },
          }
      );
    });
    say(message);
  } catch (error) {
    console.log("err");
    console.error(error);
  }
});

We’re using blocks (provided by the Slack Bolt API) and markdown to format the messages we’ll be displaying to users. To further customize messages from your bot when they’re sent to the user, Slack provides a Block Kit Builder that you can use to get your desired template.

You can test this out by typing the command /knowledge in the private conversation with the ask-ztc-bot.

Test Command Bot Conversation

As you can see, it correctly lists all the FAQs in our knowledge base.

Next, we’ll use a simple regular expression to detect if a user has included the keyword products in their question. If they have, we’ll show them FAQs with the keyword products:

app.message(/products/, async ({ command, say }) => {
  try {
    let message = { blocks: [] };
    const productsFAQs = faqs.data.filter((faq) => faq.keyword === "products");

    productsFAQs.map((faq) => {
      message.blocks.push(
        {
          type: "section",
          text: {
            type: "mrkdwn",
            text: "*Question *",
},
        },
        {
          type: "section",
          text: {
            type: "mrkdwn",
            text: faq.question,
          },
        },
        {
          type: "section",
          text: {
            type: "mrkdwn",
            text: "*Answer *",
},
        },
        {
          type: "section",
          text: {
            type: "mrkdwn",
            text: faq.answer,
          },
        }
      );
    });

    say(message);
  } catch (error) {
    console.log("err");
    console.error(error);
  }
});

To test this out, send a message to the bot that includes the word products, and the bot will respond with all the information that has to do with the products keyword.

Test Bot Keywords Response

Updating the knowledge base

Finally, we want to give users the ability to add their own data to the knowledge base.

Create a new Slash Command called /update. This command will be called by users to add new data to our knowledge base.

Slack Create New Slash Command

We’ve made a slight change to this command. In the usage hint, we’ve specified that users should separate the different fields using the pipe | character. This way, we can take the input string sent by a user and split it using the pipe character.

Note: If you plan to add your Slackbot to a channel and think that there might be other apps with similar commands to yours, it may be worth creating one command, e.g ., /ask-ztc, and having users append an additional string to the command. For example, use /ask-ztc knowledge to display all the FAQs in the knowledge base.

Here’s the code that handles the /update slash command. We update the db.json file by first reading the data in the file and appending the new data sent by the user to it:

app.command("/update", async ({ command, ack, say }) => {
  try {
    await ack();
    const data = command.text.split("|");
    const newFAQ = {
      keyword: data[0].trim(),
      question: data[1].trim(),
      answer: data[2].trim(),
    };
    // save data to db.json
    fs.readFile("db.json", function (err, data) {
      const json = JSON.parse(data);
      json.data.push(newFAQ);
      fs.writeFile("db.json", JSON.stringify(json), function (err) {
        if (err) throw err;
        console.log("Successfully saved to db.json!");
      });
    });
    say(`You've added a new FAQ with the keyword *${newFAQ.keyword}.*`);
  } catch (error) {
    console.log("err");
    console.error(error);
  }
});

Let’s test this out!

We’ll call the /update command with the following text: “people | Who should I contact if I’m having issues with my Internet? | Call the IT Department on Ext.9090”.

The /update endpoint will respond with the message:

Update Endpoint Message Response

Now, when we call our /knowledge command, we should see our newly added FAQ as part of the FAQs returned from our database.

Slack Slash Command New FAQ

And there you have it!

You’ve successfully created a Slackbot that can respond to commands and mentions. It can also accept new data from users and store it in the database.

The source code for this example is available on my GitHub.

Deploying

You can deploy your app to a platform like Heroku in the same way you would deploy a regular Node.js application. Don’t forget to change the URL in the event subscription section to the new one provided by Heroku.

You can visit the Bolt API documentation for your reference.

#javascript #slack #api #chatbot

What is GEEK

Buddha Community

How to Build a Slack Bot in JavaScript with Bolt API

Top 10 API Security Threats Every API Team Should Know

As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.

Insecure pagination and resource limits

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:

First Call: GET /items?skip=0&take=10 
Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync a large number of records such as via cron jobs. Artificially small pagination limits can force your API to be very chatty decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:    response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip),                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})    print("Fetched 10 items")    sleep(randint(100,1000))    skip += 10

How to secure against pagination attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.

Insecure API key generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to secure against API key pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

Accidental key exposure

APIs are used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials such as when debugging via Postman or CURL. It only takes a single developer to accidently copy/pastes the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.

How to prevent accidental key exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)

Exposure to DDoS attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.

Stopping DDoS attacks

The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this such as leaky bucket and fixed window counters.

Incorrect server security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.

How to ensure proper SSL

Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs

Incorrect caching headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.

#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys

Autumn  Blick

Autumn Blick

1601381326

Public ASX100 APIs: The Essential List

We’ve conducted some initial research into the public APIs of the ASX100 because we regularly have conversations about what others are doing with their APIs and what best practices look like. Being able to point to good local examples and explain what is happening in Australia is a key part of this conversation.

Method

The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following:

  1. Whether the company had a public API: this was found by googling “[company name] API” and “[company name] API developer” and “[company name] developer portal”. Sometimes the company’s website was navigated or searched.
  2. Some data points about the API were noted, such as the URL of the portal/documentation and the method they used to publish the API (portal, documentation, web page).
  3. Observations were recorded that piqued the interest of the researchers (you will find these below).
  4. Other notes were made to support future research.
  5. You will find a summary of the data in the infographic below.

Data

With regards to how the APIs are shared:

#api #api-development #api-analytics #apis #api-integration #api-testing #api-security #api-gateway

Flo  D'Amore

Flo D'Amore

1621484694

How to Build a Slack Bot in JavaScript with Bolt API

Develop and customize your own Slackbot using the Bolt API, the newest library for programming with Slack in JavaScript.

Originally published by Adebola Adeniran at https://blog.logrocket.com/

The new Bolt API

I recently tried to develop a Slackbot with the Node Slack SDK but, unfortunately, I ran into some bugs. That was when I stumbled upon the new Bolt API. According to Slack, it’s the “swiftest way to start programming with the Slack Platform in JavaScript.”

There are a number of reasons to try the new Bolt API from Slack to build your next Slack app or bot. For one, it’s a well-documented library that will help you avoid running into weird bugs and issues further down the line. Secondly, the API is developed and maintained by Slack, which ensures that it’ll be updated frequently.

Developing with this API has been a breeze, and I can assure you that the Bolt API library is the way to go when it comes to developing Slack apps. In this tutorial, you’ll learn how to create your own Slackbot with the Bolt API.

Setup

Prerequisites

To follow along with this tutorial, you’ll need:

  • Basic knowledge of JavaScript and Node.js
  • Node.js v12 or higher
  • npm

Create a workspace

To get started, we’ll need a workspace to install our bot in. A Slack workspace is a way to group communication within an organization. Everyone in an organization can belong to one workspace, which is then subdivided into multiple channels.

Install Slack on your device and create a new workspace. Slack will then send a 6-digit code to your email that you can use for verification. Now for the fun part! Give your workspace a name; for this tutorial, we’ll create a fictional company called The Zobo Tea Company.

Note: If you’re feeling curious, you can read more about hibiscus teas (also known as Zobo).

Company Name Slack Screen

Next, Slack will prompt you to enter the name of the project you’re working on. You can call the project whatever you want. You can skip the last step where Slack prompts you to add other team members.

Create a new Slack application

Now, we’ll create a new Slack app. Slack apps are small applications that provide specific functionalities within a workspace. You can install a preexisting Slack application by signing into your Slack workspace and searching for applications within the Slack app directory.

The Slack app we’ll create is a knowledge base that helps employees within our fictional organization quickly find answers to FAQs.

To create a new Slack application, head to the Slack API dashboard. Click the Create New App button on the top right. Give your bot a name, then select what workspace you would like to install the app to. We’ve called ours ask-ztc-bot.

Create Slack App

Hit Create App and you’ll be redirected to the dashboard for your new app.

0Auth and Permissions

We need to give our new application certain permissions for it to access data and perform actions within our Slack workspace.

On your Slack dashboard, you’ll find the OAuth and Permissions menu option on the left sidebar. Once you navigate here, scroll down to Scopes. We need our ask-ztc-bot to be able to read instant messages from users and respond to those messages. Here’s a screenshot of the scopes we’ve given our bot:

Slack Bot Token Scopes

Install the app to your workspace

With that done, we can now install the app to our workspace. From the left sidebar, navigate to Settings > Install Apps > Install to Workspace.

Set up the Slackbot server

Next, it’s time to write some code. We’ll need to set up a server for our Slackbot that we can send requests to. Let’s get into it!

Create a directory called ask-ztc-bot and initialize npm:

mkdir ask-ztc-bot && cd ask-ztc-bot 
npm init -y

Install the following packages in the ask-ztc-bot directory:

  • @slack/bolt: a JavaScript framework for building Slack apps in a flash using the latest platform features
  • nodemon: a tool that automatically restarts a Node.js application when file changes in the directory are detected
  • dotenv: a zero-dependency module that loads environment variables from a .env file into process.env

I’ll be using the Yarn package manager to install these packages, but you can also use npm:

yarn add @slack/bolt
yarn add -D nodemon dotenv

We need to make a little tweak to our package.json file. Let’s add a new script called dev that runs nodemon app.js. Your package.json should look something like this:

...
  "main": "index.js",
  "scripts": {
    "dev": "nodemon app.js"
  },
....

The dev script automatically restarts our server in app.js when we make changes to any file within our codebase. Next, create the app.js file that will contain the code for our server:

touch app.js

Authentication with tokens and secrets

Slack will need to authenticate our bot to connect it. Slack authenticates apps using a SIGNING_SECRET and a BOT_TOKEN. We’ll need to store both the SLACK_SIGNING_SECRET and SLACK_BOT_TOKEN in a .env file to prevent them from being exposed when using version control.

To find your SLACK_SIGNING_SECRET, navigate to Basic Information > App Credentials > Signing Secret. To get your SLACK_BOT_TOKEN, head to Settings > Install App > Bot User oAuth Token. Your SLACK_BOT_TOKEN should begin with xoxb.

Create a .env in the root directory of your project and assign the SECRET and TOKEN you obtained from the step above:

SLACK_SIGNING_SECRET="YOUR SIGNING SECRET"
SLACK_BOT_TOKEN="YOUR BOT TOKEN"

Setting up the server

Head into the app.js file we created earlier and add the code below:

const { App } = require("@slack/bolt");
require("dotenv").config();
// Initializes your app with your bot token and signing secret
const app = new App({
  token: process.env.SLACK_BOT_TOKEN,
  signingSecret: process.env.SLACK_SIGNING_SECRET,
});

(async () => {
  const port = 3000
  // Start your app
  await app.start(process.env.PORT || port);
  console.log(` Slack Bolt app is running on port ${port}!`);

})();

Run the yarn run dev script we created earlier to make sure everything works correctly. You should get a message in your terminal reading “Slack Bolt app is running on port 3000!”

Setting up ngrok

We need a way for our Slack app/bot to reach the server we’ve created on our localhost. To do this, we can proxy to localhost via a public URL created by a service like ngrok. Once you’ve got ngrok installed, run the following command in the directory:

./ngrok http 3000

This creates a public URL that proxies to your localhost running on port 3000. Now, ensure that your server on localhost:3000 is still running.

Socket Mode

Slack also has a feature called Socket Mode, which allows Slack to connect to our application server using WebSockets instead of HTTP like we did with ngrok above. Socket Mode offers us a much faster development experience because we can skip setting up ngrok.

Getting started with Socket Mode

First, navigate to Settings > Basic Information > App-Level Tokens. Once there, click the Generate Token and Scopes button. Give your token a name, and give your app the two available scopes: connections:write _a_nd authorizations:read. Hit the generate button. Then, copy the token on the next screen into your .env file.

Next, head to Settings > Socket Mode. Toggle the Enable Socket Mode toggler. Finally, head into your app.js file and update the code that initializes your app with socketMode:true and your appToken:

const app = new App({
  token: process.env.SLACK_BOT_TOKEN,
  signingSecret: process.env.SLACK_SIGNING_SECRET,
  socketMode:true, // enable the following to use socket mode
  appToken: process.env.APP_TOKEN
});

With that completed, all requests to your development server will now happen via WebSockets and not HTTP.

Slash Commands

Now that we’ve given our app some permissions and set up a server and a public URL, the next step is to allow it listen for Slash Commands. In Slack, you can trigger an action by sending a command as a message. For example, a Slash Command could be /knowledge to show all the content in our knowledge base.

To enable Slash Commands, click the Slash Commands menu option on the left sidebar. Then click the Create New Command button. Fill out the form using the image below as a guide. The request URL should be the custom URL automatically generated by ngrok for your application.

Slack Create New Command

Hit the save button located on the bottom right side of the screen. Slack will prompt you to reinstall the app to your workspace for your changes to take effect. Follow those instructions, and your /knowledge command should now be created!

Testing the /knowledge command

Now, we can test the /knowledge command from inside Slack. First, we’ll create a listener to listen for events that include the /knowledge command. In your app.js file, add the following code:

const { App } = require("@slack/bolt");
require("dotenv").config();
// Initializes your app with your bot token and signing secret
const app = new App({
  token: process.env.SLACK_BOT_TOKEN,
  signingSecret: process.env.SLACK_SIGNING_SECRET,
});

app.command("/knowledge", async ({ command, ack, say }) => {
    try {
      await ack();
      say("Yaaay! that command works!");
    } catch (error) {
        console.log("err")
      console.error(error);
    }
});

(async () => {
  const port = 3000
  // Start your app
  await app.start(process.env.PORT || port);
  console.log(` Slack Bolt app is running on port ${port}!`);

})();

Let’s test our code! In the Slack app, you should see the ask-ztc-bot app just under the Your Apps section. Click that to send messages to the bot. Type /knowledge and hit enter. You should receive a message reading “Yaaay! that command works!”.

Bot Working Message Slack

Messages in Slack

We can also mention or @ the bot and include additional text to be sent to the bot as a message.

In Slack, mentioning an app is a type of event. We can also listen for other events like when new users join a channel, a new channel is created, etc. For our bot/app to listen for events, we need to set up event subscriptions.

Event subscriptions

To enable events, navigate to Features > Event Subscriptions from your Slack app dashboard. Toggle the Enable Events button on.

For Slack to notify our app of events, we’ll need to provide a public URL that Slack can verify. Copy the ngrok URL we created earlier and paste that into the Request URL input field. You’ll need to append /slack/events to the URL because Slack will verify your URL by sending a POST request.

Enable Event Subscriptions Slack

Once you see the green verified text with the tick sign, you know your app has been successfully verified by Slack, and you’re ready to go!

Next, we need to give the app some event permissions. Click the subscribe to bot events dropdown and add the following events. There are four events related to messages:

  • message.channels: listens for messages in public channels
  • message.groups: listens for messages in private channels
  • message.im: listens for messages in your app’s DMs with users
  • message.mpim: listens for messages in multi-person DMs

In this tutorial, we’ll only subscribe to message.im because we only want users to DM our bot.

Subscribe Bot Events Slack

Hit the Save Changes button in the bottom right corner of the screen to save your changes.

Now, we can test our app to make sure it can receive and respond to messages. In your app.js, add the following piece of code:

app.message("hey", async ({ command, say }) => {
    try {
      say("Yaaay! that command works!");
    } catch (error) {
        console.log("err")
      console.error(error);
    }
});

Head back to the azk-ztc-bot app and send it a message like @ask-ztc-bot hey. You should get a response back.

Slackbot Command Works Message

For an app like a knowledge base, we can’t really match exact words. We need a way to check if the message a user is sending to our bot contains a keyword that matches a keyword in our knowledge base. For that, Slack allows us to use regex expressions. For example, let’s update the code block that we used above to look like this:

// matches any string that contains the string hey
app.message(/hey/, async ({ command, say }) => {
    try {
      say("Yaaay! that command works!");
    } catch (error) {
        console.log("err")
      console.error(error);
    }
});

Send a message that includes the string hey in the format Well, hey there Mr.bot!. Our bot will still respond correctly since the message contains the string hey.

String Message Bot Response

Creating the knowledge base

Now, we can get into actually creating the knowledge base.

First, we’ll create a mini database to store frequently asked questions and answers. Our database will be a simple JSON file on our server. You may want to consider a DBMS like MongoDB if your data requirements become large and complex.

In the root directory of your project, create a db.json file and add the following data:

{
    "data":[
        {
            "keyword": "products",
            "question": "How many different products do we sell at ZTC?",
            "answer": "ZTC currently has 3 products on the market. Hibiscus tea with a hint of one of Lemon/Pineapple or ginger."
        },
        {
            "keyword": "products",
            "question": "What online stores sell our products?",
            "answer": "Amazon, Macy's and Shoprite."
        },
        {
            "keyword": "people",
            "question": "How many people work at ZTC?",
            "answer": "ZTC currently employs 250 people from 21 different countries."
        },
        {
            "keyword": "reset password",
            "question": "How do I reset my password?",
            "answer": "To reset your company E-mail password, call Ola on ext.8099."
        }

    ]
}

We’ve created a set of four questions with their answers and grouped them under certain keywords for easy reference.

Responding to commands

With our JSON database set up, we need a way to read the data in it. We’ll use the built-in fs module from Node.js to read from the db.json file. At the top level of your app.js file, add the following block of code:

// require the fs module that's built into Node.js
const fs = require('fs')
// get the raw data from the db.json file
let raw = fs.readFileSync('db.json');
// parse the raw bytes from the file as JSON
let faqs= JSON.parse(raw);

Now, we can write the code for responding to the /knowledge command. This command will display all the questions and answers in our database to the user:

app.command("/knowledge", async ({ command, ack, say }) => {
  try {
    await ack();
    let message = { blocks: [] };
    faqs.data.map((faq) => {
      message.blocks.push(
        {
          type: "section",
          text: {
            type: "mrkdwn",
            text: "*Question*",
          },
        },
        {
          type: "section",
          text: {
            type: "mrkdwn",
            text: faq.question,
          },
        },
        {
            type: "section",
            text: {
              type: "mrkdwn",
              text: "*Answer*",
            },
          },
          {
            type: "section",
            text: {
              type: "mrkdwn",
              text: faq.answer,
            },
          }
      );
    });
    say(message);
  } catch (error) {
    console.log("err");
    console.error(error);
  }
});

We’re using blocks (provided by the Slack Bolt API) and markdown to format the messages we’ll be displaying to users. To further customize messages from your bot when they’re sent to the user, Slack provides a Block Kit Builder that you can use to get your desired template.

You can test this out by typing the command /knowledge in the private conversation with the ask-ztc-bot.

Test Command Bot Conversation

As you can see, it correctly lists all the FAQs in our knowledge base.

Next, we’ll use a simple regular expression to detect if a user has included the keyword products in their question. If they have, we’ll show them FAQs with the keyword products:

app.message(/products/, async ({ command, say }) => {
  try {
    let message = { blocks: [] };
    const productsFAQs = faqs.data.filter((faq) => faq.keyword === "products");

    productsFAQs.map((faq) => {
      message.blocks.push(
        {
          type: "section",
          text: {
            type: "mrkdwn",
            text: "*Question *",
},
        },
        {
          type: "section",
          text: {
            type: "mrkdwn",
            text: faq.question,
          },
        },
        {
          type: "section",
          text: {
            type: "mrkdwn",
            text: "*Answer *",
},
        },
        {
          type: "section",
          text: {
            type: "mrkdwn",
            text: faq.answer,
          },
        }
      );
    });

    say(message);
  } catch (error) {
    console.log("err");
    console.error(error);
  }
});

To test this out, send a message to the bot that includes the word products, and the bot will respond with all the information that has to do with the products keyword.

Test Bot Keywords Response

Updating the knowledge base

Finally, we want to give users the ability to add their own data to the knowledge base.

Create a new Slash Command called /update. This command will be called by users to add new data to our knowledge base.

Slack Create New Slash Command

We’ve made a slight change to this command. In the usage hint, we’ve specified that users should separate the different fields using the pipe | character. This way, we can take the input string sent by a user and split it using the pipe character.

Note: If you plan to add your Slackbot to a channel and think that there might be other apps with similar commands to yours, it may be worth creating one command, e.g ., /ask-ztc, and having users append an additional string to the command. For example, use /ask-ztc knowledge to display all the FAQs in the knowledge base.

Here’s the code that handles the /update slash command. We update the db.json file by first reading the data in the file and appending the new data sent by the user to it:

app.command("/update", async ({ command, ack, say }) => {
  try {
    await ack();
    const data = command.text.split("|");
    const newFAQ = {
      keyword: data[0].trim(),
      question: data[1].trim(),
      answer: data[2].trim(),
    };
    // save data to db.json
    fs.readFile("db.json", function (err, data) {
      const json = JSON.parse(data);
      json.data.push(newFAQ);
      fs.writeFile("db.json", JSON.stringify(json), function (err) {
        if (err) throw err;
        console.log("Successfully saved to db.json!");
      });
    });
    say(`You've added a new FAQ with the keyword *${newFAQ.keyword}.*`);
  } catch (error) {
    console.log("err");
    console.error(error);
  }
});

Let’s test this out!

We’ll call the /update command with the following text: “people | Who should I contact if I’m having issues with my Internet? | Call the IT Department on Ext.9090”.

The /update endpoint will respond with the message:

Update Endpoint Message Response

Now, when we call our /knowledge command, we should see our newly added FAQ as part of the FAQs returned from our database.

Slack Slash Command New FAQ

And there you have it!

You’ve successfully created a Slackbot that can respond to commands and mentions. It can also accept new data from users and store it in the database.

The source code for this example is available on my GitHub.

Deploying

You can deploy your app to a platform like Heroku in the same way you would deploy a regular Node.js application. Don’t forget to change the URL in the event subscription section to the new one provided by Heroku.

You can visit the Bolt API documentation for your reference.

#javascript #slack #api #chatbot

An API-First Approach For Designing Restful APIs | Hacker Noon

I’ve been working with Restful APIs for some time now and one thing that I love to do is to talk about APIs.

So, today I will show you how to build an API using the API-First approach and Design First with OpenAPI Specification.

First thing first, if you don’t know what’s an API-First approach means, it would be nice you stop reading this and check the blog post that I wrote to the Farfetchs blog where I explain everything that you need to know to start an API using API-First.

Preparing the ground

Before you get your hands dirty, let’s prepare the ground and understand the use case that will be developed.

Tools

If you desire to reproduce the examples that will be shown here, you will need some of those items below.

  • NodeJS
  • OpenAPI Specification
  • Text Editor (I’ll use VSCode)
  • Command Line

Use Case

To keep easy to understand, let’s use the Todo List App, it is a very common concept beyond the software development community.

#api #rest-api #openai #api-first-development #api-design #apis #restful-apis #restful-api

Marcelle  Smith

Marcelle Smith

1598083582

What Are Good Traits That Make Great API Product Managers

As more companies realize the benefits of an API-first mindset and treating their APIs as products, there is a growing need for good API product management practices to make a company’s API strategy a reality. However, API product management is a relatively new field with little established knowledge on what is API product management and what a PM should be doing to ensure their API platform is successful.

Many of the current practices of API product management have carried over from other products and platforms like web and mobile, but API products have their own unique set of challenges due to the way they are marketed and used by customers. While it would be rare for a consumer mobile app to have detailed developer docs and a developer relations team, you’ll find these items common among API product-focused companies. A second unique challenge is that APIs are very developer-centric and many times API PMs are engineers themselves. Yet, this can cause an API or developer program to lose empathy for what their customers actually want if good processes are not in place. Just because you’re an engineer, don’t assume your customers will want the same features and use cases that you want.

This guide lays out what is API product management and some of the things you should be doing to be a good product manager.

#api #analytics #apis #product management #api best practices #api platform #api adoption #product managers #api product #api metrics