Building Slack Bots - Paul Asjes - E-Book

Building Slack Bots E-Book

Paul Asjes

0,0
33,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Create powerful, useful, fast, and fun chat bots that make Slack better

About This Book

  • This is the first developer's guide to programming for Slack
  • It covers everything you need to create chat bots for Slack's conversational UI
  • It's full of realistic examples, usable code, and lucid explanations on everything you need to know

Who This Book Is For

This is a book for software developers who want to build Slack bots for their own company's use or for customers. You need to know JavaScript.

What You Will Learn

  • Receive and send messages sent in Slack
  • Respond to user commands
  • Process natural language
  • Perform useful tasks on commands such as fetching data from external sources
  • Use webhooks and slash commands
  • Create a Google Classroom and add customized information for each individual class

In Detail

Slack promises that its users will "be less busy." Slack bots interact with users in Slack chatrooms, providing useful immediate information, and automating work. This book gives you everything you need to build powerful and useful Slack bots.

You'll see how to hook into the Slack API to create software that can read and post to chatrooms, respond to commands and hints given in natural conversational language, and build fun and useful bots for your own place of work, both as a front end to your own service and to distribute and share as apps. You can even sell your bots and build a business as a Slack bot developer.

Throughout the book, you'll build useful and fun example applications that you can modify for your own situations. These range from simple, fun applications to liven up discussions to useful, data-driven apps to help you make decisions quickly and manage work.

Style and approach

This is a friendly step-by-step guide to building powerful, friendly Slack bots.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 177

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Building Slack Bots
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Getting Started with Slack
Introduction to Slack
Slack as a platform
The end goal
Summary
2. Your First Bot
Preparing your environment
Installing Node.js
Installing the development tools using NPM
Creating a new project
Creating a Slack API token
Connecting a bot
Joining a channel
Sending a message to a channel
The slack object
Getting all the channels
Getting all members in a channel
Sending a message to a channel
Basic responses
The authenticated event
Using the message event
Avoiding spam
Sending a direct message
Restricting access
Adding and removing admins
Debugging a bot
Summary
3. Adding Complexity
Responding to keywords
Using classes
Reactive bots
Bot commands
Sanitizing inputs
External API integration
Error handling
Summary
4. Using Data
Introduction to Redis
Installing Redis
Mac OS X
Windows
Unix
Connecting to Redis
Saving and retrieving data
Connecting bots
Dynamic storage
Hashes, lists, and sets
Hashes
Lists
Sets
Sorted sets
Best practices
Simple to-do example
Summary
5. Understanding and Responding to Natural Language
A brief introduction to natural language
Fundamentals of NLP
Tokenizers
Stemmers
String distance
Inflection
Displaying data in a natural way
When to use NLP?
Mentions
Classifiers
Using trained classifiers
Natural language generation
When should we use natural language generation?
The uncanny valley
Summary
6. Webhooks and Slash Commands
Webhooks
Incoming webhooks
Outgoing webhooks
Slash commands
In-channel and ephemeral responses
Using webhooks and slash commands
Summary
7. Publishing Your App
The Slack app directory
Registering your app and obtaining tokens
Understanding the OAuth process
Scopes
Submitting your app to the app directory
Monetizing your bot
Summary
Further reading
Index

Building Slack Bots

Building Slack Bots

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: June 2016

Production reference: 1170616

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78646-080-6

www.packtpub.com

Credits

Author

Paul Asjes

Reviewer

Nicolas Grenié

Commissioning Editor

David Barnes

Acquisition Editor

Usha Iyer

Content Development Editor

Mehvash Fatima

Technical Editor

Siddhi Rane

Copy Editor

Roshni Banerjee

Project Coordinator

Kinjal Bari

Proofreader

Safis Editing

Indexer

Monica Ajmera Mehta

Graphics

Kirk D'Penha

Production Coordinator

Shantanu N. Zagade

Cover Work

Shantanu N. Zagade

About the Author

Paul Asjes started programming on his TI-83 calculator in high school and has been hooked ever since.

Specializing in JavaScript, he is always interested in staying up to date with the latest developments in the field. Currently, he is building universal full-stack apps with technologies such as React, Webpack, and Node when he's not spending far too much time on Slack.

Since his IRC days, he has been interested in chat bots and how they can be used. He has written several Slack bots to date, ranging from bots that facilitate playing games to bots that retrieve important business metrics.

I would like to thank my wife, Caitlin, for being my biggest fan, proofreader, and muse during the writing of this book.

About the Reviewer

Nicolas Grenié is a hacker-in-residence at 3scale, living between Barcelona and San Francisco.

Nicolas built his first website in 2000 using Microsoft Word and since then has not stopped learning about programming.

This API freak likes to try new languages and APIs all the time. He has built many integrations for Slack and Amazon Echo. He runs a good number of meetups in Barcelona about APIs, Meteor, and entrepreneurship.

When he isn't working, you have a good chance of finding him hacking side projects or enjoying a good craft beer. And, of course, as he is French, frogs and snails are part of his daily diet!

I want to thank Steven Willmott, the CEO of 3scale, and the entire 3scale team for giving me the inspiration and time to hack interesting projects and technology.

I also want to thank my parents and family for the positive learning environment they've built, letting me explore my passion and curiosity for technology.

www.PacktPub.com

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

Chat bots have become big talking points in the world of business and software development. On the forefront of team communications is Slack, a platform for talking to colleagues and friends about absolutely anything. The engineers at Slack saw the potential and have designed a system that allows anyone to build their own Slack bots for productivity, ease of use, or just plain entertainment.

This book will teach you how to use a myriad of tools to build the very best bots for the Slack platform. Whether you are a programming beginner or a seasoned veteran, by the end of this book, you will be able to create high-quality bots whose only limit is the your imagination. You might also pick up a few tricks along the way.

What this book covers

Chapter 1, Getting Started with Slack, shows you what is Slack and why we should care about Slack bots.

Chapter 2, Your First Bot, takes you through building your first bot and explains how it works.

Chapter 3, Adding Complexity, helps us expand our first bot with new and useful functionalities.

Chapter 4, Using Data, teaches you how to use persistent data with your Slack bots.

Chapter 5, Understanding and Responding to Natural Language, teaches you about natural language processing and how to develop a bot that can comprehend and respond in natural language.

Chapter 6, Webhooks and Slash Commands, takes us through the uses of webhooks and Slash commands in a Slack setting.

Chapter 7, Publishing Your App, teaches you how to publish your app or bot so that it can be used by others outside your company.

What you need for this book

You should have an intermediate understanding of JavaScript and programming concepts in general. For this book, we will be using Node.js version 5.0.0. This means that the JavaScript code samples contained within will use ECMAScript 2015 (ES2015, more commonly known as ES6) features, which have been enabled in Node v5.0.0. For a full list of ES6 features enabled in Node.js version 5 and up, visit the Node.js website (https://nodejs.org/en/docs/es6/).

This book, its techniques, and the code samples within are OS-agnostic, although for debugging purposes, either the Google Chrome or Opera browser is required.

Who this book is for

This is a book for software developers who want to build Slack bots for their own company's use or for customers.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Save the file and then run the code via iron-node in your terminal."

A block of code is set as follows:

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

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

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

Any command-line input or output is written as follows:

npm install -g iron-node

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Either click on the Step over button in the top-right corner, symbolized by an arrow curving around a dot, or hit F10 to step over to the next line."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Building-Slack-Bots. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Getting Started with Slack

This book will enable a beginner to create their own Slack bot either for amusement or professional purposes.

The ultimate goal of this book is for you to think of Slack as a development platform with great potential, rather than simply a chat client. As Slack continues its meteoric rise in popularity in the developer community, the possibilities and opportunities contained in Slack apps will prove to be a valuable tool in any developer's toolbox.

In this chapter, we introduce you to Slack and its possibilities. We will cover:

An introduction to SlackSlack as a platformThe end goal

Introduction to Slack

Launched in August 2013, Slack started as an internal communication tool utilized by small teams but has been rapidly morphing into a versatile communications platform used by many parties, including the open source community and large businesses.

Slack is a real-time messaging application that specializes in team communication. In a crowded space of productivity applications, Slack sets itself apart by providing extensive integrations with popular third-party apps and provides users with the platform to build their own integrations.

As of the beginning of 2016, Slack is used by approximately 2 million users daily, and spread across 60,000 teams that send 800 million messages per month (http://expandedramblings.com/index.php/slack-statistics/). Some of the more well known companies who use Slack include Airbnb, LinkedIn, and The New York Times. This service has become so popular, largely thanks to its impressive uptime rate of over 99.9 percent. What sets Slack apart from competition such as HipChat or Skype for Business is the determination of the company to open its platform for third-party developers in the form of an application program interface (API). To spur the growth of their service as a platform, in December 2015 Slack pledged to invest $80 million into software projects that use its technology (http://fortune.com/2015/12/15/slack-app-investment-fund/). Added to the more than $320 million raised in funding for the company, it's safe to say that Slack will continue to be a driving force in the team productivity space in the years to come.

Slack as a platform

What many users perhaps don't know about Slack is that underneath the messaging client, a highly extensible platform exists that can be used to create apps and business tools that can simplify the development cycle, perform complex tasks, or just be downright silly.

Slack's UI with its own Slack bot in action

This platform or API can be utilized to integrate third-party services into Slack's platform and leverage their extensive reach and user friendly interface. The said third-party applications can send data into Slack via incoming webhooks, execute actions outside of Slack with commands, or respond to commands as a bot user. The bot user or bot is the most interesting; they are so named as they can mimic human users by performing the same actions that any human can.

Note

Slack bots are software applications that run on the Slack Real Time Messaging (RTM) platform. Bots can be used to interact with external applications or your custom code in a conversational manner.

Some of the more popular bots include GitHub's multitasking Hubot (https://hubot.github.com/) and Meekan's scheduling bot (http://meekan.com/slack/), but many more of varying complexity are developed each day.

The most obvious and well known bot is Slack's own Slack bot, used for built-in Slack functions such as:

Sending feedback to SlackScheduling remindersPrinting a list of all users in a channel

Another widely popular bot is Hubot. Originally developed by GitHub and ported to Slack by Slack themselves, Hubot can provide useful functionality such as GitHub activity tracking, which can keep you up to date with GitHub repositories.

GitHub integration showing branch and pull request activity

You can also add infrastructure monitoring through Jenkins:

Jenkins integration bot showing build automation logs in Slack

Bots can transform Slack from a simple messaging client to an important business tool, benefitting any company that uses custom bots unique to their workflow. The beauty of the Slack platform is that anyone can create a functional bot in a few simple steps.

The end goal

Upon completing this book, the reader will be able to build a complex Slack bot that can perform the following tasks, amongst other things:

Receive and send message sent in SlackRespond to user commandsProcess natural languagePerform useful tasks on command (for example, fetch data from external sources)Insert custom data into Slack via webhooks and slash commands

Summary

This chapter gave you an overview on what Slack is, why it is noteworthy, and how its platform can be leveraged to create a myriad of useful apps. The next chapter will show you how to build your first simple Slack bot.

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 environmentCreating a Slack API tokenConnecting your botJoining a channelSending a message to a channelBasic responsesSending a direct messageRestricting accessDebugging 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 teamSays hello to all the members of a channel after successfully connecting, distinguishing between real users and bot usersResponds to users saying helloSends a direct message to users who ask for the total amount of time the bot has been running (also known as uptime)Ensures that only administrative users can request the bot's 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 features of ECMAScript 2015 (better known as ES2015 or ES6). Whenever an ES6 feature is used in this book for the first time, look for the accompanying code comment for a brief explanation on the feature.

Note

Although many are implemented, not all ES6 features are currently available in Node and some are only available in strict mode. For more information, please visit the Node ES6 guide: https://nodejs.org/en/docs/es6/.

This section will briefly explain how to install Node.js and the Slack API on your development machine.

Installing Node.js

To install Node.js, head to the official Node website, https://nodejs.org/, download a v5 version and follow the onscreen instructions.

To test whether the installation succeeded, open up a terminal, type the following, and then hit Enter:

node

If node installed correctly, you should be able to type JavaScript commands and see the result: