Book Image

Building Slack Bots

Book Image

Building Slack Bots

Overview of this book

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.
Table of Contents (14 chapters)

Mentions


To implement the second point, we need to revisit our Bot class and add mention functionality. In the Bot class' constructor, replace the RTM_CONNECTION_OPENED event listener block with the following:

this.slack.on(CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED, () => {
  let user = this.slack.dataStore.getUserById(this.slack.activeUserId)
  let team = this.slack.dataStore.getTeamById(this.slack.activeTeamId);

  this.name = user.name;
  this.id = user.id;

  console.log(`Connected to ${team.name} as ${user.name}`);
});

The only change here is the addition of the bot's id to the this object. This will help us later. Now, replace the respondTo function with this:

respondTo(opts, callback, start) {
  if (!this.id) {
    // if this.id doesn't exist, wait for slack to connect
    // before continuing
    this.slack.on(CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED, () => {
      createRegex(this.id, this.keywords);
    });  
  } else {
    createRegex(this.id, this.keywords);
  }
      
  function...