Despite the fact that bots have existed since the dawn of the internet (and have also been universally hated since their inception), for some reason chat-bots are all the rage among nerds right now. In true opportunistic fashion, I saw it fit the take advantage of this new hype train by putting out a quick tutorial of my own on how to actually create one of these little apps on my favourite platform.
Today I will be showing you how to create a simple bot we will be calling ‘Jokebot’. Jokebot searches the rustiest parts of the internet for the worst possible jokes, then spits them out to any user mentioning its name in true evil robot fashion.
note: All of the code for this tutorial can be found on my Github repository.
Setting up a Bot on Slack
The first step to creating a slackbot is to add a new bot user to your team. There are instructions on how to do this on the Slack website, however I personally found that the easiest way is to go to https://api.slack.com/custom-integrations, and click the ‘Set up a bot user’ button.
If you do not currently have any running bots, you are going to be asked to ‘add configuration’ (for your bot), and will then be taken to a page where you give your bot a username. For our purposes however, we will give it the name ‘jokebot’.
After this, simply click ‘Add bot integration’ button, then copy the API Token you are provided with for storage in a safe location. My recommendation is to send it out in a tweet. That way you can always find it in your Twitter history.
You can also give your jokebot a name and an avatar if you care about that kind of stuff.
Ok, now that we have gone through all of the pomp and circumstance, we can finally move on to actually creating our app
Creating our App
Assuming that you already have Node and NPM installed, the first thing we need to do is initialize out project with NPM.
In your command line navigate to an empty folder and type ‘npm init’. Fill in all of the usual details asked of you (or if you are like me, simply spam the enter button). After this, we are going to create an ‘index.js’ file, and a ‘lib’ folder. Inside the lib folder, we are going to create a jokebot.js file.
At this point in time, you project should look like this.
Using the Slackbots Library
Thankfully a guy called Mikhail Mokrushin has already developed a package called slackbots that pretty much handles all of the heavy lifting for us, and also does a great job of abstracting away all of the complexities of interacting with Slacks RTM API.
We are going to use this package in our project, so the next step it is install ‘slackbots’ by typing the command ‘npm install –save slackbots’ in our terminal/command line.
We are also going to use the request package to make http request to a ‘joke’ API to get the random jokes for out bot.
Run ‘npm install –save request’ in your terminal/command line.
Creating our Jokebot Class
In the file libs>jokebot.js we are going to create a class that will actually inherit from the Slackbots object. In our constructor, we will pass on the settings needed for the slackbots package, using ‘super()’ to call out parent class.
We are also going to initialise two class properties; settings and user.
The slackbots package gives us access to the ‘start’ and ‘message’ events. The start event fires when the slack RTM API is initialized, and the ‘message’ event is fired anytime something happens in a slack channel/chat/team that your bot is active in.
We will now create an initialize method that handles both of these events. Remember, our goal is to listen out for any message that mentions our bot ‘@jokebot’, and respond with a randomly generated corny joke.
Writing our _onStart Method
The first thing we will do is confirm that our bot has actually connected to Slack’s RTM API by printing a simple message in our console.
The next thing we want to do is to immediately populate our ‘user’ attribute with our jokebot user.
Note: To anyone who is confused, the slackbots object, once initialized, comes with a ‘users’ property that holds an array of users. In the code above, we are searching this array for a user whose ‘name’ property matches the name property in our settings object and passing this value to our ‘user’ attribute.
Writing the _onMessage Method
You will notice that the onMessage method is passed an event object. We will use this objects to perform a series of checks to ensure that we only send back a message when the event matches what we are looking for. If all the criteria are met, we will send back a random joke using a sendMessage method that we will define later.
Now that we have a method that only gets fired when our bot is mentioned in a chat, the only things we have left to do is generate the random joke, and respond to the message in our sendMessage method.
Generating a random Joke Message
After scouring the internet for a few minutes, I managed to find tambalAPI, a free (of-course) open source API created by Kia Faith that provides us jokes with an adequate amount of randomness and corniness for our bot.
To make use of this API, we will create a generateJokeMessage method. All we have to do in this method is make a simple get request to the tanbalApi, and return a promise that resolves with a random joke string once our request has completed successfully.
Sending Back Our Joke Message
Finally, now that we have everything else in place, all we need to do is implement our sendMessage method.
The first thing we will do is call the generateJokeMesage method we just implemented and get a random joke string. After this, we need to store the channel in which our bot was mentioned in a variable, allowing us to later post a response to that same channel.
Now that we have both the channel and the message, all we need to do now is call the postMessageToChannel method provided by the slackbots object.
At this point, all we now need to do is initialize Jokebot in our index.js file.
To test your new bot, sign in to a slack channel where your bot is active, and send it a message.
This post was inspired by simpleprogrammer.com