Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Building Slack Bots

You're reading from  Building Slack Bots

Product type Book
Published in Jun 2016
Publisher Packt
ISBN-13 9781786460806
Pages 182 pages
Edition 1st Edition
Languages
Concepts

Chapter 2. Your First Bot

Readers will be amazed at how few lines of code are required to get a basic bot up and running in their Slack environment. This chapter will walk the reader through the basics of building a Slack bot:

  • Preparing your environment

  • Creating a Slack API token

  • Connecting your bot

  • Joining a channel

  • Sending a message to a channel

  • Basic responses

  • Sending a direct message

  • Restricting access

  • Debugging your bot

Although some of the concepts first outlined will be known to a more advanced reader, it is still recommended to read through the first few sections of this chapter to ensure that your environment is up and ready to go.

In this chapter, we will build a bot that performs the following actions:

  • Connects to your Slack team

  • Says hello to all the members of a channel after successfully connecting, distinguishing between real users and bot users

  • Responds to users saying hello

  • Sends a direct message to users who ask for the total amount of time the bot has been running (also known as uptime...

Preparing your environment


Before we can get started with the first bot, the programming environment must be set up and configured to run Node.js applications and packages. Let's start at the very beginning with Node.

In brief, Node.js (also referred to as Node) is a JavaScript runtime built on Chrome's v8 JavaScript Engine. In practice, this means that JavaScript can be run outside of the usual browser environment, making JavaScript both a frontend and backend language.

Google Chrome's v8 JavaScript engine ensures that your JavaScript code runs fast and efficiently. Unlike in the world of browsers (and excepting Node versions), Node is maintained by a single open source foundation with hundreds of volunteer developers. This makes developing for Node much simpler than for browsers as you will not run into problems with varying JavaScript implementations across platforms.

In this book, we will be using major Version 5 (any version starting with 5) of Node. This allows us to use the newly implemented...

Basic responses


The Slack API can be configured to execute methods once certain events are dispatched, as seen earlier with the RTM_CONNECTION_OPENED event. Now, we will dive into other useful events provided to us.

The authenticated event

So far, we have seen how to add functionality to Slack's RTM_CONNECTION_OPENED event triggered by the bot entering a channel and an error occurring, respectively. If you wish to execute some code when a bot logs in but before it connects to a channel, you can use the AUTHENTICATED event:

slack.on(CLIENT_EVENTS.RTM.AUTHENTICATED, (rtmStartData) => {
  console.log(`Logged in as ${rtmStartData.self.name} of team ${rtmStartData.team.name}, but not yet connected to a channel`);
});

This gives the following output:

[Mon Jan 18 2016 21:37:24 GMT-0500 (EST)] INFO Connecting...
Logged in as awesomebot of team Building Bots, but not yet connected to a channel

Now, we will introduce the message event.

Using the message event

The message event will trigger every time...

Sending a direct message


A direct message (DM) channel is a channel that only operates between two users. By design, it cannot have more or less than two users and is meant for private communication. Sending a DM is remarkably similar to sending a message to a channel, as the dm object is almost identical to the channel object.

Consider the following snippet:

slack.on(RTM_EVENTS.MESSAGE, (message) => {
  let user = slack.dataStore.getUserById(message.user)

  if (user && user.is_bot) {
    return;
  }

  let channel = slack.dataStore.getChannelGroupOrDMById(message.channel);

  if (message.text) {
    let msg = message.text.toLowerCase();

    if (/uptime/g.test(msg)) {
      let dm = slack.dataStore.getDMByName(user.name);

      let uptime = process.uptime();

      // get the uptime in hours, minutes and seconds
      let minutes = parseInt(uptime / 60, 10),
          hours = parseInt(minutes / 60, 10),
          seconds = parseInt(uptime - (minutes * 60) - ((hours * 60) * 60...

Restricting access


Occasionally, you might wish to restrict bot commands to administrators of your Slack team. A good example is a bot that controls a project's deploy process. This can be immensely powerful but perhaps not something that you want every user to have access to. Only administrators (also known as admins) should have the authority to access such functions. Admins are special users who have administrative powers over the Slack team. Luckily, restricting such access is easy with the is_admin property attached to a user object.

In the following example, we'll restrict the uptime command demonstrated in the previous topic to admin users, notifying the restricted user that they can't use that command:

slack.on(RTM_EVENTS.MESSAGE, (message) => {
  let user = slack.dataStore.getUserById(message.user)

  if (user && user.is_bot) {
    return;
  }

  let channel = slack.dataStore.getChannelGroupOrDMById(message.channel);

  if (message.text) {
    let msg = message.text.toLowerCase...

Debugging a bot


It is inevitable that eventually you will encounter a bug in your bot that is difficult to squash. The worst are bugs that don't cause your program to crash and thus don't provide a useful stack trace and line number for where the crash happened. For most issues, the console.log() method will be enough to help you track down the bug, for the more tenacious bugs however we will need a true debugging environment. This section will introduce you to iron-node (https://s-a.github.io/iron-node/), a cross-platform JavaScript debugging environment based on Chrome's dev tools.

Start by installing iron-node:

npm install -g iron-node

Note again the use of the -g flag, which installs the application globally.

Before we can start debugging, we need to add a breakpoint to our code, which tells the debugger to stop the code and allow for deeper inspection. Add the debugger statement to our previous code, within the slack.openDM() code block:

if (/uptime/g.test(msg)) {
  debugger;
      
...

Summary


In this chapter, we saw how to install the prerequisite technologies, how to obtain a Slack token for a bot, and how to set up a new Slack bot project. As a result, you can reuse the lessons learned to easily scaffold a new bot project. You should now be able to program a bot that can send messages to channels, direct messages as well as craft basic responses. Finally, we discussed how to debug a Node.js-based bot using the iron-node debugger.

In the next chapter, we will see how to make our bot more complex by adding third-party API support and by programming our first bot command.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Building Slack Bots
Published in: Jun 2016 Publisher: Packt ISBN-13: 9781786460806
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}