Slack Integrations and Definition (40+ New Slack Hacks 2019)

Slack Integrations and Slack Definition

Slack Integrations and Slack Definition

Slack is much more than IRC on steroids. It contains emojis, gravatars, statistics, and a powerful search engine. It is a platform where you can take advantage of public and private channels, which provide instant communication for effectively engaging with all types of groups and teams.

 

You can also implement to-do lists and use notifications to help prioritize levels of communication so you can work smarter.

 

Slack is a great tool for increasing team communication and transparency in your business or organization. The real power of Slack comes from the ways in which you can extend it. Integrations in Slack allow you to add-in most any type of app or feature, whether that is Google Drive, Github or your favorite CRM platform.

 

In order to get the most out of Slack, you need to learn about Webhooks, which allow you to push notifications and actions in and out of Slack.

 

To extend Slack even further, you can tap into the Slack APIs with almost any programming language and even create your own Slack bots that you can then use to carry out a myriad of tasks, such as having a bot get sandwich orders from your team or schedule a meeting that fits with everyone’s schedules.

 

Once you adopt Slack and begin using it in these types of ways, you will discover how much more effective it is for you to work, communicate and even have fun via Slack. The hacks in this blog will not only provide many Slack solutions, they will also give you ideas for extending these solutions or creating your own.

 

Slack Apps and Simple Webhooks

Apps are a great way to extend Slack to improve your workflow, monitor external services, and coordinate your team’s efforts across devices, locations, and functional groups. 

 

One such app is Google Calendar, which allows you to get reminders before an event starts, get summaries of the current day’s and week’s events, and get updates when an event is changed.

 

The real power of Slack comes from its ability to become your communication center. Slack apps can be bi-directional, not just receiving notifications from other services, but also sending commands to other services. With Slack, you can also have a bot listen to your conversations and act according to this content.

 

You don’t have to be a programmer in order to activate apps. Once you add them, you will wonder how you ever managed without them. Slack has ready-made apps with most of today’s popular online services. The setup process for each app is a bit different, but once you learn how to integrate one service, the rest is easy.

 

Applications vs. integrations

A Slack App can be found at App Directory page, is packaged from a third party, and has a User Interface (UI). 

 

An integration, on the other hand, is comprised of Custom Webhooks, bots and slash commands. In other words, it is a piece of software that integrates with Slack and can be installed from the Custom Integrations page.

 

Webhooks are a great way of creating your own simple integrations without having to integrate with the Slack API. Slack provides both Incoming and Outgoing Webhooks, so let’s examine them both.

 

Incoming Webhooks

Incoming Webhooks let you push notifications into Slack from any service or application. Using Incoming Webhooks is a great way to make Slack act as a central spot where you can be notified of events coming from external systems. 

 

For example, adding Incoming Webhooks to the beginning or end of a script allows a progress, success, or error report to be posted directly to Slack, so you don’t have to constantly check manually.

 

Incoming Webhook scripts don’t need to be hosted on a publicly accessible server or computer, but they do need to be hosted somewhere that has access to the Internet in order to post to Slack.

 

Outgoing Webhooks

Outgoing Webhooks allow you to trigger a script or action from within Slack using a predefined keyword or phrase. 

 

These are handy if you want to allow anyone on your team (regardless of whether they have any coding experience) to initiate a process or script without having to leave Slack. For example, you can trigger a code to deploy or have a script that can reboot a server.

 

Unlike Incoming Webhooks, an Outgoing Webhook requires the process or script you want triggered to be accessible to Slack’s servers. That’s because there are several parameters passed in a payload when the Webhook is fired, which includes a security token for authentication.

 

The hacks in this blog provide examples of some Slack apps. In addition to some simple Slack Apps, one hack requires you to create a new slash command, while another hack shows how to install a bot into your team. Slash commands are shortcuts for sending an HTTP request to a server. The user just types /_command name* and some arguments, and Slack returns the answer from the server.

 

Let’s get started with some simple Apps.

Source code for the blog

  • The source code for all hacks in this blog can be found in this blog’s Github repo.
  • Keep track of Documents with Google Drive
  • This app allows you to import Google Drive files by pasting a file’s URL into Slack.
  • Go to the Google Drive app page and click the install button, then follow the on-screen instructions.

 

After you’ve done that, when a link is pasted into Slack, the message containing the link will be changed into a share message that points to the external reference. Doing this means:

Other team members see the document’s title.

You can easily spot links to Google drive documents within the conversation

The file will be added to Slack and the document’s full text will be indexed for search (Slack will keep the preview of the document up-to-date if it gets updated on Google Drive).

 

Add the Dropbox App

The Dropbox app provides you with the same capabilities for Dropbox as the Google Drive app described above. To install this app, go to the Dropbox app page and click the install button, and then follow the on-screen instructions. From now on, when you paste a link to a Dropbox file in Slack, you will have a preview of that file.

 

Easily Have Video Chats with Google Hangouts

The Google Hangouts app allows you to enter the /hang out slash command in any channel. You will be given a link from which you can start the Hangout with a handy Slack control panel.

 

From that panel, you can invite other Slack team members to the Hangout. To add this app, go to the Google Hangouts app page and click the install button, then follow the on-screen instructions.

 

This app is extremely useful if you have remote co-workers in your team and use Google Hangouts to have face-to-face conversations. Being able to set up a Hangout and share the link without leaving Slack means it’s easy to set up a quick call

 

Start Skype Calls

If you prefer Skype over Google Hangouts, there is a Skype app available. Navigate to Skype app page and click the “Visit site to install” link. Click the “Add to Slack” button and select a channel. Now you can type/skype to start a video call

 

Add an Email App

This app works a bit different from the previous ones. It assigns an email address for the channel you choose. Visit the Email app page to install it.

 

On the setup page that appears, choose the channel that you want the emails to be posted to. On the next page, you will get an email address. All email sent to this address will appear in the selected channel 

 

This app is great for subscribing to email newsletters because every-one in the channel can see the email without each user needing to subscribe.

 

Keep up-to-date with Github Activity

This app posts activity on GitHub issues to a channel in Slack. Navigate to the GitHub app page and choose which channel the events will appear in, and which repositories to report on.

 

From now on you will have a channel with a stream of all the changes in your repositories so anyone can get a quick overview of what’s going on. This app posts messages about commits pull requests, comments, and issues.

 

The messages include links to these events so you can click on them and go directly to Github. The Git‐ Hub channel can serve as the pulse for your team’s development progress

 

Increase productivity with Kyber

Kyber adds several productivity tools to Slack with one app. It provides project management tools, a team calendar, to-do lists and reminders, and other apps including IFTTT. Navigate to Kyber Slack page and click the Add to Slack button, and then follow the on-screen instructions.

 

Once you’ve installed the app, go to the #general channel on Slack and type /kyber to get started. You will be presented with a list of common Kyber commands. In addition to the commands Kyber lists for you, the app comes with IFTTT integration, and here are just some of those actions that you can tap into:

  • When a Github issue is assigned to you, add a to-do that specifies the repository, issue, and link (recipe here).
  • Add a to-do when a Trello card is assigned to you (recipe here).
  • Log your work hours on your #calendar of choice (recipe here).
  • Create a to-do with Amazon Alexa and add it to Slack (recipe here).

 

Send Quick Gifs with the Gif Keyboard

Gifs are the de-facto self-expression tool on the Internet (a picture is worth a thousand words). The Gif Key‐ board app will take your use of Gifs to the next level. It makes it easy to search a massive Gif collection, and you can also:

  • Create custom GIFs by typing /gif “YOUR CAPTION HERE”
  • Choose which GIF you want to send by typing /gifs
  • Add personal GIFs of your company and coworkers

 

Navigate to the Gif Keyboard app page and click Visit site to install button. Then click the Add to Slack button, and follow the on-screen instructions. 

 

Now you can select a Gif from a few options and not settle for the one that the app chooses for you. For example, you can issue /gifs cat and pick the one you wish to share from the various choices displayed 

 

These choices are only visible to you, not your team members. To pick one, just type /gif 2, for example, and Gif number 2 will be selected and posted on the channel.

  • You can also add captions to your Gifs.
  • You can combine the above and use /gifs cat "Schrodinger's cat" to select an image and put a caption on it.
  • You can even save a Gif for a later by typing: /gif save [alias]

 

Make Scheduling Easy with Meekan

Everybody hates scheduling meetings with multiple participants—finding a time when everyone is available is tough. The Meekan bot comes to your rescue. The bot scans the participant’s calendars and comes up with one or more options that you can vote on.

 

To install it, navigate to the Meekan Scheduling Assistant page and click the Visit site to install button. On the next page click the Install it now button and then select the Add to Slack button. Finally, on the next page, click Authorize.

 

In Slack, you can now invite Meekan to a channel by typing /invite meek. The next step is to connect your calendar to Meekan by typing meek a connect me or connect all the channel members’ calendars by issuing meek an connect @channel.

 

The bot will send you a direct message with a link for connecting your calendar, and after authorizing this you will be good to go. You can now enjoy the power of the bot. For example:

 

Issue meekan we want to have lunch next week, and the robot will check everyone’s calendar for a free lunch spot next week, and reply with a list of possible options.

Set up a meeting with specific people (as opposed to everyone on the channel) by typing meek a schedule lunch with @john and @amy

Ask Meekan to find an available room for your meeting: meekan schedule a meeting next week, and please add a room

 

This should give you a good idea of the types of useful apps that you can add to Slack.

Search for flights, car, or hotels

Search Flights, Hotels & Rental Cars | KAYAK lets you find the best prices on flights, hotel rooms, and rental cars. They have developed a Slack app that lets you do this research from within Slack using a slash command along with natural language.

 

Installation

To add Kayak to your Slack team, head to the Kayak Slack App page and click the Add to Slack button. This takes you to an authorization page, which (once complete) will add a new kayak slash command that lets you perform travel-related queries.

 

Usage

One cool feature of the Kayak app is that you can write your queries in natural language. For example, if you’re looking for flights from San Francisco to Chicago on July 26th, just type this command:

  • /kayak flights from San Francisco to Chicago on July 26th
  • It will also work if you type this:
  • /kayak flights from San Francisco to Chicago on the 26th of July
  • You can use a relative time, like tomorrow, or next Friday:
  • /kayak flights from San Francisco to Chicago tomorrow
  • /kayak flights from San Francisco to Chicago next Friday
  • You can even use a duration. If you have to plan a one-week trip, it’s as easy as this:
  • /kayak flights from San Francisco to Chicago next Friday for one week
  • You can replace for one week by for 7 days or for 7 days, too. If you want to be very specific, you can:
  • /kayak direct flights in business class from San Francisco to Chicago on the day after July 26th for three weeks for two adults and one child
  • The same kind of requests can be done for rental cars or hotels:
  • /kayak cars in Miami tomorrow for the day
  • /kayak hotels around las vegas on next Saturday for the weekend

 

For every request, a summary of four answers (with prices, schedules, and ratings) will be displayed with a link to Kayak’s website to see the details. What if you don’t want to share your results?

 

The Kayak app’s default behavior is to show its results to everyone in the channel where you run it. So if you wish to do a private search (or not bother everyone else), then just run this app in your own direct message channel. Why query in Slack?

 

You may wonder why you should bother using Slack to do such queries? There are several good reasons:

 

You can star the answers to retrieve them quickly You can share them with other users You don’t need to open a browser for the query—the summary gives you an idea of what to expect You won’t see any ads in Slack By integrating Kayak with your Slack channel, you can easily have all sorts of travel information returned right in Slack.

 

Add Lytespark videoconferencing

Slack is designed to be an asynchronous chat system, but you will often find yourself chatting with one or more users at once, and such conversations can take some time. What if you could switch from this mode to a video conference in which you simply speak to chat and where you can share your screen?

 

Lytespark is a web-based video conferencing tool that has all of these features, and it can be integrated to Slack.

Head to the Lytepark Slack page and click “Add to Slack”. Simply authorize the app, and then you can start using it.

 

The Lytespark extension adds two components:

A slash command (/lytespark) for triggering a video chat

A new bot that suggests when it might be a good time to open a video chat. To achieve this, it reads the channel activity and when there’s a lot of discussion in a short amount of time the bot gives a link to continue the discussion using video chat.

 

Clicking the link opens a web page asking you for a name (no need to have an account) to enter the room

Then you can resume your discussion, using the video chat. Screen sharing is available using a Google Chrome extension, plus you can take notes and even draw on a virtual board.

 

Add Stack Overflow search

StackOverflow is a programmer’s best friend. By adding the following slash command you can access Stack Overflow from the comfort of your favorite Slack channel:

1. Click on the channel selector window (upper left corner in Slack).

2. Click Configure Apps.

3. Select the Make a Custom Integration button.

4. Click the Slash Commands button, and then enter these settings (the rest are default settings):

  • Command: /overflow
  • URL: http://so.goel.io/overflow
  • Method: POST

 

5. For the Autocomplete help text, turn on the “Show this command in the autocomplete list” checkbox. This will enable the following two options (type in the description and hint):

Description: A programmer's best friend, now in Slack.

Usage hint: [search terms]

 

6. Now, add the label:

Descriptive Label: Search StackOverflow

7. The final step is to select the Save Integration button.

 

The StackOverflow integration is now complete. Click on any channel and type /overflow with a space followed by whatever search term you are looking for on StackOverflow, such as /overflow slack integration. The top five results (if there are at least that many) will be returned in the channel for you to click on.

 

Have a Bot host your Standup meetings

The Standup bot will let you run a virtual standup meeting within your Slack team by asking each team member what they did yesterday, what they plan to do tomorrow, and if anything is blocking them from carrying out their work.

 

The Standup bot will run the meeting. Once the standup is complete, a report will be generated and, if desired, emailed to team members. This bot comes in two flavors:

A hosted paid version that can be found at the Standup bot page.

An open source version that you can host yourself.

If you would like to run the open source version, there are detailed instructions about how to deploy it to Heroku on the project’s Github page.

 

Send a Simple Message to Slack Using Incoming Webhooks

In this hack, you will learn how to post to a Slack channel using a PHP script. In the first part of this hack, we will post a simple, hard-coded message to a Slack channel whenever a script is called. In the second part, we will post a formatted message every time a Git commit is done on your repository.

 

Unlike Outgoing Webhooks, Incoming Webhooks do not need to be hosted externally - they just require an Internet connection. This allows you to host them on a local server (with your Git repository) and communicate with locally installed packages and sites.

 

Add Incoming Webhooks

The first step is to add Incoming Webhooks to your Slack team. To get started, navigate to the Incoming Webhooks App page and click install next to your team. You will then be asked to select a channel to post to.

 

(This setting can be overridden when sending the message.) The selection you make here determines the default channel if one isn’t specified in your code. Pick one and click Add Incoming Webhook.

 

You will then be presented with a Webhook URL. Take note of this URL, since you will need it later. This URL is private and should not be posted anywhere public (as it allows anyone to post to any channel). If the URL becomes compromised, you can generate a new URL at the bottom of this page.

 

You can also customize the default icon and the name of your Incoming Webhook bot. (Like the default channel you selected, this can be overridden when posting the text.)

 

Run a PHP script

To begin, create a PHP file on a server that has Internet access. This can be on your computer if you have a local server running, or on a remote server accessed via the web.

 

To ensure that you have the file in an executable place, create a simple Hello World example and then trigger the file.

<?php

echo ‘Hello World’;

We’re running this through the command line, so to run the script, the command is:

$ php file.php

 

Post the simple message

Having a script return to you isn’t of much help, since you want to post to Slack. Using cURL, you can POST to the Incoming Webhook URL to send a message. Replace [WEBHOOK URL] in the example below with the URL you were given when you set up the Webhook:

><?php // Your webhook URL $webhook='[WEBHOOK URL]'; // Encode the data $data='payload=' . json_encode(array( 'text'=> 'Hello World'
));
// PHP cURL POST request
$ch = curl_init($webhook);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch); curl_close($ch);
echo $result;

 

Slack expects the data to be in json format, encoded with the key payload. This is what gets created at the beginning of the script. The text key is what is output into Slack. The last part of the script is the convoluted PHP cURL request required to POST data from a PHP script. 

 

Wherever you run this script, it should return an ok if everything went well. (If it didn’t, check your Webhook URL and make sure that your message isn’t malformed.) In Slack, you should see your message posted to your designated channel

 

Customize the Bot Name and Avatar

The next step in creating your Incoming Webhook bot is to customize its look and name (and change the channel if required). All customizations are passed into the payload array, parallel to the text key:

 

name - The name needs to be plain text (emojis can be used but must be inserted directly in the script, rather than the :cactus: a style that you can use inside Slack).

 

channel - This is the channel the hook posts to. This can either be a public channel with the # (such as #general) or a private message with a user by using an @ (such as @user).

 

icon_url - Using the icon_url you can specify your bot’s avatar, which needs to be a URL to a web-hosted image. You can also use an icon_emoji instead.

icon_emoji - This takes a standard emoji code to use as the icon for your messages, such as rocket:. (If both the icon_url and icon_emoji are specified, the emoji takes precedence.)

 

Update the payload data to the following:

 // Encode the data
$data = 'payload=' . json_encode(array( 'username' => 'Incoming Bot', 'channel' => '#general', 'icon_emoji' => ':rocket:',
'text' => 'A customised message'
));

 

Add Message Attachments and Formatting

Slack Incoming Webhooks have the ability to have custom styled messages, featuring various data formatted with a bold title and a value. Called Attachments, these styled messages allow you to pass in several bits of information in one message while keeping the message readable.

 

You can have as many attachments as you wish, but consider readability and your team’s sanity before you go too overboard.

Along with attachments, you can also pass additional message texts to precede the extra data. There is also a fallback value required for Slack clients that don’t support attachments (like APIs).

 

To make attachments work, there are several extra fields you can pass in. Most of them are optional:

fallback - This text should be a summary of the attachments and is used in the event that the client doesn’t support attachments. This is required but will not show in the default Slack clients.

pretext - This text appears before the attachment. This is not required but allows you to give an introduction to the extra data.

text - This text appears inside the attachment (colored bar) but above any of the titled sections.

color - This color appears on the left-hand side of the attachment section of the message. This is useful if you want to add some visual context to your messages (such as a red border if something goes wrong, or green if something goes right).

 

fields - This is the meat of the Webhook and contains the extra data. It is a multidimensional array, meaning it is an array of arrays. Each array inside the fields array is equal to an extra attachment. The attachments themselves have several fields you can use that are all optional:

 

  • — title - A bolded title for the attachment.
  • — value - An unbolded field for the attachment.
  • — short - A boolean value (True or false); by default this is false. This field allows the other fields to be half width and means you can have two short fields next to each other, side by side in Slack. Using this, you can simulate a key/value pair reading left to right.

 

Here’s a simple example of using the field's key to create several attachments for your Webhook:

$data = 'payload=' . json_encode(array( 'username' => 'Incoming Bot', 'icon_emoji' => ':rocket:',
'fallback' => 'This is the fallback text', 'pretext' => 'This is the pretext field value', 'color' => '#0066ff',
'fields' => array( array(
'title' => 'First attachment title',
'value' => 'First attachment value can be some long text \ as it goes full width'
),
array(
'title' => 'Second attachment title', 'value' => 'Second attachment value', 'short' => true
),
array(
'title' => 'Third attachment title', 'value' => 'Third attachment value', 'short' => true
),
array(
'title' => 'Fourth attachment title which can be long too', 'value' => 'The value of the fourth attachment',
'short' => false
),
array(
'title' => 'This is actually the fifth array title', 'short' => true
),
array(
'value' => 'And the sixth array value', 'short' => true
)
)
));

 

On the fourth attachment, you can see short has a value of false. Although this is the default, you can make your code more verbose by specifying this default value.  You now know how to use an Incoming Webhook to post to a Slack channel with a PHP script.

 

Post a Message from Git

Now that you can send messages to Slack, let’s build up a payload programmatically. The payload we are going to build up includes a correctly formatted $_POST request to a specified URL provided by Slack.

 

We are going to use hooks within Git (the popular version control system). If you are unfamiliar with Git hooks, we recommend reading up on them before you get started.

 

Essentially, they are scripts that can be triggered at certain points before or after a commit, push, branch checkout, and more. This allows you to extend and automate several Git tasks.

 

Using a Git hook, we are going to send a Slack message every time a commit is made on a certain repository. This might not be a practical real-world example (as it would annoy everyone in the team), but it will get you used to Incoming Webhooks and will also expose you to Git hooks and their uses.

 

To build and test this script, you will want to create a new repository that you can commit to regularly without any repercussions, such as a test repo.

 

Make Your Git Hook

The first step is to create a simple Git hook to fire whenever you make a commit. Hooks are stored inside the .git folder located at the root of your repository. Inside that folder is a folder called hooks. It contains some sample files. You can copy a sample file, rename it, and then customize it to make your own hook.

 

For this hack, make sure you title your hook post-commit (with no extension). If, however, you decide to create your file from scratch, you must enable execution rights on the file by entering the following command on the command line:

chmod +x .git/hooks/post-commit

 

The post-commit hook will get triggered whenever you make a commit. Similar to what we did earlier, output a simple “Hello” whenever you commit to double check it’s working:

#!/usr/bin/php

<?php

echo "** Hello ** \n";

 

The #! at the top of the file is called a shebang and instructs the system on how it should process the file. The one we included tells the system that the following file is PHP. The next step is outputting the word “Hello” followed by a new line. If you make a commitment you should see this output in your terminal.

 

Now that we’ve verified that the post-commit hook runs once committed, we can trigger it manually without having to commit code every time. You’ll need to do this via the command line:

./.git/hooks/post-commit

 

Get the last commit

In order to post our latest commit message to Slack, we first need to get it from the log. PHP can run commands using the built-in exec function. Using the -1 flag on git log we are able to retrieve only the last commit.

#!/usr/bin/php
<?php
exec('git log -1', $output, $class='lazy' data-src);
var_dump($output);

 

Running this should output your last commit in an array, with each line as a new string. This information is not very handy and it would be hard to extract anything useful from it to post to Slack. 

 

As a way of customizing the log output, Git allows you to pass the -- format flag, enabling you to customize the output using placeholders.

Take the following example: git log -1 --format=%h%n%an%n%ae%n%ar%n%s%n%b

 

Although the format looks like gibberish, there is some logic too it. Each value is followed by a new line placeholder (%n). Removing those leaves us with the following:

%h - abbreviated commit hash
%an - author name
%ae - author email
%ar - author-date, relative to now
%s - subject (this is the subject of the commit message)
%b - The commit body (If the body is spread over multiple lines, this will appear as multiple strings when `var_dump`ed.
This git log command can be added to our post-commit - add the following to your file:
// Get the last commit
exec('git log -1 --format=%h%n%an%n%ae%n%ar%n%s%n%b', $output);

 

Extract the Relevant Data

Now that we have specified the format of the commit message, we are able to know exactly what value the first five keys of the $output array will be.

 

Because the commit body can be as long as it wants, we are going to assign the known values and remove them from the array. This leaves $output with just the body message of the commit message. To do this, assign the values to humanly readable variables, and then unset() them from the $ouput array.

$hash = $output[0];
$name = $output[1];
$email = $output[2];
$time = $output[3];
$subject = $output[4];
// Remove the keys from the array
unset($output[0], $output[1], $output[2], $output[3], $output[4]);

 

The last variable we need is the commit body. This can be obtained by gluing the remaining $output array together with a new line between each value. You do this using the implode() PHP function.

// Glue the array back together as a string

$body = implode("\n", $output);

Make sure this is placed after the unset() function.

 

Build Your Message with Attachments

Using the code from the previous hack (#14), build up the correctly formatted payload to send off to Slack. 

 

One last thing is that you can generate links in Slack Webhooks using a <|> syntax, allowing you to pass in <http:// Google|Google> (note the pipe character in the middle).

 

This will produce a link to Google with the text “Google.” Using this technique, you can create an email link to your author by passing in the two variables:

<mailto:' . $email . '|' . $name . '>'
You now have the following code:
#!/usr/bin/php
<?php // Your webhook URL $webhook='[WEBHOOK URL]'; // Get the last commit exec('git log -1 --format=%h%n%an%n%ae%n%ar%n%s%n%b', $output); // Assign the variables we know $hash=$output[0]; $name=$output[1]; $email=$output[2]; $time=$output[3]; $subject=$output[4]; // Remove the keys from the array unset($output[0], $output[1], $output[2], $output[3], $output[4]); // Glue the array back together as a string $body=implode("\n", $output); // Encode the data $data='payload=' . json_encode(array( 'username'=> 'Git Bot', 'icon_emoji' => ':robot_face:',
'fallback' => 'The latest git commit', 'pretext' => 'There has been a new commit', 'color' => '#0066ff',
'fields' => array( array(
'value' => 'Commit Hash:', 'short' => true
),
array(
'title' => '#' . $hash, 'short' => true
),
array(
'title' => $hash
),
array(
'value' => '<mailto:' . $email . '|' . $name . '>', 'short' => true
),
array(
'value' => $time, 'short' => true
),
array(
'title' => $subject, 'value' => $body
)
)
));
// PHP cURL POST request
$ch = curl_init($webhook);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch); curl_close($ch);
echo $result;

Notice that for the commit hash, we have used two short fields to put the title and value next to each other. This gives the hash a title without taking up more vertical space.

 

Send a snippet of code from Jetbrain’s IDE to Slack

Slack Storm is a free plugin available on most of the Jet‐ brain’s software (such as IntelliJ and PHPStorm) whose purpose is to let you quickly send a snippet of code to a Slack channel by just selecting the code in the IDE and right-clicking it

 

Here are the simple steps for configuring Slack Storm:

Install the plugin in your IDE (choose File > Settings > plugins, enter “Slack Storm” in the plugin name field, and click on “Search in repositories”).

 

Setup an Incoming Webhook on your Slack team, as outlined at the beginning of this blog.

 

In the IDE go to Tools > Slack Settings > Add Slack Channel, and then insert the channel details: A channel description, the Incoming Webhook you just created, the username the bot will use to post the snippet, and an emoji to use as the bot user’s avatar.

 

Slack meets IFTTT and Zapier

While there is a huge selection of integrations available for Slack, sometimes the features you need to connect Slack to just aren’t available. You can always write your own Webhook integration, but there are a couple of popular options for the non-developer, namely IFTTT (If This Then That) and Zapier.

 

While both of these platforms offer similar capabilities, IFTTT offers more integrations for personal use and IoT devices, while Zapier is geared more toward integrating business applications. Our recommendation is to check out both services and use the one that best supports your needs.

 

At this time, IFTTT is a completely free service, while Zapier offers a limited free plan as well as multiple paid plans. The source code for all hacks in this blog can be found in this blog’s Github repo.

 

IFTTT

IFTTT is a web-based service that allows you to chain together simple “recipes” that are triggered when one of your Internet-connected devices or applications do something.

 

Whether you want to hack Slack to display who’s in the office by leveraging your Samsung SmartThings sensors, or you want to automatically post your daily Fitbit activity to your fitness channel, IFTTT can help you accomplish it.

 

The one major limitation to what IFTTT can achieve with Slack is that IFTTT can only post to Slack, and thus you cannot (without a little bit of hacking—see Hack #21) use it to trigger an action from within Slack.

 

Getting started with IFTTT

In order to get IFTTT integrated with Slack, you first need to create an account at IFTTT helps your apps and devices work together. Once you’ve signed up. Follow the onscreen tutorial to create your first recipe, and once you’re done, follow along in Hack #17 to create your first Slack- integrated recipe.

 

Create an IFTTT Slack-integrated Weather recipe

On the IFTTT website, clicking the My Recipes menu item will present you with a screen that allows you to create custom recipes.

 

Go ahead and click on “Create a recipe,” and you’ll be presented with the “If this then that” screen. We’re going to start with a simple integration to get weather information into Slack, and then we’ll tie into some more exciting applications.

 

Click on this and search for “weather.” In the search results, click on “weather”, and you’ll see a screen asking you to connect with The Weather Channel. Clicking the button registers the integration into your IFTTT account.

 

Clicking Connect will take you to a screen where you can search for the location you want weather information to come from.

 

Once you’ve clicked “Connect,” continue to the next step and choose “Today’s weather report.” This will scroll you down to select a “time” for this event to be triggered. Select any time in the near future because you’ll want to see this data flow into Slack soon. 

 

Click “that” and you’ll be presented with the “search” screen. Type “slack” into the search box, and you’ll see “Slack” as one of your results 

 

Select Slack and connect it as you did with The Weather Channel. If you’re currently signed into your team(s) in your browser, you’ll see them listed. If not, sign into the team you want to integrate by selecting “sign into another team.” Once you’ve selected your team, continue by authorizing IFTTT to post messages to your team

 

After authorizing, continue on until you’re able to “Choose an Action” for Slack. (As mentioned earlier, currently IFTTT only supports the posting a message to a channel action.) The list of actions available varies from channel to channel. They consist of actions IFTTT can perform. 

 

The fields in this form allow you to customize what the output of the Slack messages look like. The field text consists of fixed text and variables. The variables have a gray background when you’re just viewing the form and switch to being encased in brackets {{ }} when you click into a field to edit.

 

When you click into a field, a flask icon will appear in the top right that allows you to view the available variables (a.k.a. ingredients).

 

If you wish to change the text by adding more ingredients, click the flask to reveal a drop-down where you can choose from available options. These will change depending on the action you have chosen.

 

Once you’re happy with your message and text fields click “Create Action,” name your recipe, then click “Create Recipe” and voila, you have a Slack app! Once the time you’ve set has passed (if you set a time, that is)

 

Monitor your Twitter followers with IFTTT

Twitter is a great social network, but as you get more and more followers, it’s easy to miss notifications when somebody @mentions you or follows you. IFTTT and Slack can really help in this regard. By leveraging IFTTT, you can be notified when any of these events occur, and you can stream them into a #social channel.

 

Create a new recipe

To get started, head to IFTTT helps your apps and devices work together, Click My Recipes and then click the Create a recipe button.

  • Select Twitter for your this
  • Click on this and search for Twitter. After typing a few letters, Twitter should be one of your choices
  • Connect your Twitter account to IFTTT

 

If you’ve never used Twitter in this IFTTT account, you’ll be prompted to connect. Go ahead and click the “Connect” button, and Twitter will prompt you to authorize IFTTT to access your account (after you’ve logged in). IFTTT asks for a lot of permissions so that it can be used as both the this and the that in IFTTT.

Once you’ve authorized access, continue to the next step in IFTTT.

 

Choosing a trigger

IFTTT’s Twitter integration offers a lot of triggers. For this example, we’ll choose “New follower”. This means that any time somebody new follows your account on Twitter, this recipe will be initiated. Since this is a very simple trigger, you won’t need to provide any additional settings. When prompted, click “Create Trigger”.

 

Selecting Slack for your that

Whenever you get a new follower, you want to have IFTTT post to a Slack channel of your choosing. Since you’ve already integrated Slack with IFTTT, this should be a breeze.

 

You’ll notice that there are a lot of different options On the Complete Action Fields screen. Clicking inside of any of the text boxes will present you with the flask icon you saw earlier in this blog. Click it to see a list of all the “ingredients” that are available to use in this action.

 

Customize the message as you wish, adding/removing ingredients as you see fit, and then click Create Action. You will now receive a message in Slack whenever somebody new follows you on Twitter.

 

Triggering IFTTT from Slack

Since IFTTT doesn’t allow you to trigger recipes based on what happens in Slack, we are limited by what we can easily achieve. Luckily, we have a trick up our sleeves that will allow us to get information out of Slack, and into another service (or even back into Slack).

 

The trick involves using Maker (which allows you to connect IFTTT to any service that can make or receive web requests) with IFTTT; see Hack #21 for details. Some other great examples of what IFTTT can be used for include:

 

Reminding the team about an upcoming meeting

Posting a message when you enter or exit an area, such as “Alan has arrived at the New York office” (this requires the IFTTT Android or iPhone app)

Posting an image of the day

 

The IFTTT website includes a bunch of prebuilt recipes that you can install. You should browse the existing recipes to get some ideas!

 

Tweet from inside of Slack with Zapier

Zapier is a powerful tool that serves a similar role as IFTTT, but it allows you to accomplish a lot more with Slack. One of the big advantages of using Zapier is that it allows you to get data out of Slack, not just put data into it. This means you can monitor public channels for certain words, and trigger an event to happen when it detects those words.

 

The free Zapier offering is quite limited at this time because it only allows you to use a single action in any given Zap.

 

A Zap is what Zapier calls a recipe, but unlike IFTTT, Zapier allows you to filter, transform, and chain actions together, which makes it well worth the price to achieve great Slack solutions with little to no development work.

 

Getting started with Zapier

In order to get Zapier integrated with Slack, you first need to create a Zapier account by going to Zapier Once you’ve signed up. In this hack, we are going to create a Zap that allows you to tweet from inside of Slack. This requires either a paid version of Zapier or a trial of the Basic plan.

 

Create a new Zap

Go to Zapier and click “Make a Zap!” This will take you to a screen where you can select your “Trigger App.”

 

Select Slack as your Trigger App

Underneath your name, you’ll see that there are two prominent sections: “Trigger” and “Action.” The trigger is the event that causes a Zap to happen, and an action is the result (or results, in more complex cases) of the aforementioned trigger.

 

You should see that “Choose App” is already selected for the trigger, and in the main section of the screen you will be presented with a search box and some “Popular Apps.” If you see Slack, click it; if you don’t see it, search for it by typing Slack into the search box

 

Select Your Trigger

The trigger is up to you, so feel free to adapt it to your needs. To make sure the Zap gets picked up anywhere in Slack, select “New Message Posted Anywhere.”

 

Saving and continuing will prompt you to choose an associated Slack account, or to associate a new Slack account if you haven’t done so. Authorizing your account is pretty straightforward, and eventually, you’ll be presented with a screen asking you to post a “brand new message.”

 

Post a Slack message that will be sent to Twitter

In Slack, head to a public channel (we recommend #random) and type “Twitter: My first Tweet from #slack!” Navigating back to your Zapier screen should show you a “Test successful” message.

 

Validate your message

Click “View your message” in Zapier in order to verify that the right message was received. The text of the message should be what you typed into Slack.

 

Create a filter

The purpose of this hack is to allow you (but not another team member) to type a message in a Slack channel that is automatically posted to your Twitter account. To do this you must create a filter in Zapier.

 

Click on the + sign in the left-hand navigation (above action), and then select the “Filter” button to create a filter

 

Select “Only continue if ” and continue. Using the drop-down boxes, build up two filters with the following options (Replace [your username] with your actual username):

1. Text / (Text) Starts with / Twitter:

2. User Name / (Text) Exactly matches / [your username]

 

Once these filters are set up, you can test your filter on the Zapier website by clicking continue. You should see the filter results high‐ lighted in green on the next page in Zapier.

 

Create an action: Code

For your action, search for “Code by Zapier.” This will let you choose to write logic in either Python or JavaScript. Select the “Run Javascript” option.

 

Edit your Code template

First off, you need to create an Input that maps the Text “Twitter: My first Tweet from #slack!” into a variable called data. 

 

In the Code section, type the following, which removes the Twitter: a portion of your Text and creates an output called message, which will be used in subsequent steps in this Zap:

output = {

message: input.data.substring(9).trim()

}

Click continue and the next page of the zap should show the “My first Tweet from #slack!” message. Now let’s add another action.

 

Create a Tweet action

Let’s now add a second Action to your zap (remember, you need to have a paid Zapier membership—or at least a trial of one—in order to create multi-step Zaps). 

 

In the zap window, select Twitter as your next action, choose “Create Tweet” as your Twitter action and, if you haven’t already connected Zapier and your Twitter account, do that now.

 

Edit your Twitter template

Your next step in this zap is to “Set up Twitter Tweet.” Go to “For your Message,” in the zap window and select the Message output. Using the drop-down, select “Step1 Test.”

 

You can also choose to have Zapier shorten any URLs you type, which is a great feature. You then select the Continue button and this multi-step zap is complete. You can access the zap in the Zapier dashboard and be sure to turn on the zap.

 

To test this zap, go into one of your Slack channels and type “Twitter:” followed by a message. Whatever you type as your message (anything after Twitter:) will automatically be posted as a tweet in your Twitter account.

 

Create a screenshot of any URL

In this hack, we are going to create a Zapier Zap that allows you to generate a screenshot of a website from inside of Slack.

 

We’re going to accomplish this by lever‐ aging a service called CloudConvert (http://vert.com). This service has a free tier and is capable of so much more than what we’re using it for, so feel free to play around with it.

 

Create a new Zap

Go to Zapier | The easiest way to automate your work and click “Make a Zap!” This will take you to a screen where you can select your “Trigger App.”

 

Select Slack as your Trigger App

There are a lot of choices for trigger apps, but we’re interested in Slack. This integration provides a lot of flexibility and will enable you to trigger Zaps without the need for slash commands. Go ahead and type Slack into the search box, and then select it in the results.

 

Select Your Trigger

The trigger is up to you, so feel free to adapt it to your needs. For this example, select “New Message Posted Anywhere.”

 

Saving and continuing will prompt you to choose an associated Slack account, or to associate a new Slack account if you haven’t already done so. If you haven’t authorized your Slack account yet, be sure to do that.

 

Post your first message in Slack to generate a screenshot

In Slack, head to a public channel (we recommend #random) and type “screenshot: Google”. If you head back to Zapier, you should see a “Test successful” screen.

 

Validate your message

Make sure the message Zapier got was the correct one. You can vali‐ date this by expanding the “view your message” portion of the zap window.

 

Create a filter

Like in Hack #19, we want this action to be specific to you in Slack (meaning no other Slack users can use it), so we need to add a filter in Zapier.

 

Click on the + sign in the sidebar to create a filter. The filter will need to have the following two settings (Replace [your username] with your actual username):

1. Text / (Text) Starts with / screenshot:

2. User Name / (Text) Exactly matches / [your username]

 

Once this is set up you can test your filter on the Zapier website by clicking continue. You should see the filter results highlighted in green on the page that appears in the zap window.

 

Create an action: Code

The next step in the zap is the action, so you’ll want to select “Code by Zapier.” This will let you choose to write logic in either Python or JavaScript. For this example, we will use JavaScript.

 

Edit your Code template

Proceed with the zap by creating an Input that maps the Text into a variable called data. In the Code section of the zap window, you need to type the follow‐ ing code snippet. This code removes the screenshot: a portion of your message, and creates an output called message that will be used later in this zap:

output = {

url: input.data.substring(11).trim().split('|')[0]

};

 

Continuing and testing your new action allows you to see the output of this step. The message that is output should be http:// Google. You’ll notice that Slack has taken care of adding in the http:// portion of the URL, which will be useful later on when we run this hack, since CloudConvert will be accessing that URL.

 

Create a CloudConvert action

Next, you’ll add a second Action to Slack (as you know, you need to have a paid Zapier membership in order to create multi-step Zaps).

 

Select CloudConvert as your next Zapier action, choose “Save Website” as your CloudConvert action and provide CloudConvert access to Zapier.

 

Of course, if you haven’t set up a CloudConvert account, you will need to do so (it doesn’t cost anything).

 

Edit your CloudConvert template

In the Edit Template field in the zap window select the “Step 3 URL” option in the drop-down as the Website URL option.

 

For the Output Format, you can choose whatever you’d like, but we will go with JPG. At the bottom of the screen, you’ll see an option for Save Output. Set this to yes, so that the JPGs are individually saved on CloudConvert.

 

Create a Slack Action

At this point in the zap we have a JPG in CloudConvert, but we need to get it inserted into the Slack channel via an action. In the zap window, add a new Action, and pick Slack.

 

You’ll notice there are a lot of new options (since this isn’t a trigger). Choose “Send Channel Message.” This allows you to post the JPG from CloudConvert back into the Slack channel you initiated this zap from.

 

Edit your Slack Channel Message template

It is now time to Edit the Template of our message in the zap window. For the “Channel” option, choose “Use a Custom Value”.

 

This will let you specify a channel based on a previous step in the zap. For the “Customs Value for Channel Name” choose the “Step 1, Channel Name” from the drop-down.

 

For the Message Text, you can mix text and values from previous steps, such as: “Generating a JPG of” followed by the “Step3:Url” option. For “Attach image by URL”, choose “Step 4, OutputURL.”

 

If you don’t want to expand the URL in the Message Text, you can disable this behavior by changing Auto-expand links to No.

Select the “Testing this Step” in the zap window to have your message sent to Slack. The Image will automatically be attached to your post.

 

Congratulations, you have completed this Hack! Now, in a Slack channel type “Screenshot:” followed by a URL, and an actual JPG of that website will be returned to Slack.

 

Prebuilt Zaps

Similar to IFTTT, Zapier has plenty of prebuilt zaps that you can install. These range from ones that let you get data from YouTube, MailChimp, Email, Google Drive, Sales Force (and plenty of other services) to ones that let you post data to Trello, Twitter, Google Tasks, and Wrike, among others! Head over to the Slack Zap blog to get some idea of what Zapier can do.

 

Trigger IFTTT using Slack

At the beginning of this blog, we said that it wasn’t possible to trigger an action from Slack using IFTTT without a little bit of hacking. Now, it’s time to create a hack that allows Slack to trigger IFTTT.

 

Using the Maker trigger channel

This channel allows you to trigger an event each time a specific GET or POST HTTP request is done on a specific URI. Here’s the URI format:

https://maker.ifttt.com/trigger/{event}/with/key/{secret_key}

 

You can pass up to three parameters, either using JSON content if you do a POST request or as request params for a GET request. You can find all of this information on the Maker channel of IFTTT. The Maker channel allows you to connect IFTTT to any service that can make or receive web requests.

 

The first step of this hack is to get the secret key, which you do by navigating to IFTTT and clicking on connect. As long as you have an IFTTT account, you will be given a secret key. Now that you have a key, you can proceed with the rest of the steps in this hack.

 

Linking the Maker trigger to a Slack event

On the Slack side, we use the Slack RTM API, with the goal of notifying a specific user or a channel about any Slack events. 

 

For this hack we will build a small Slack bot written in Java by using the Simple Slack API library, which provides an easy way to get notified of events coming from the Slack RTM API.

 

The following code snippet connects to a Slack team and has a listener listening to incoming messages:

public static void main(String[] args) throws Exception {
//creating the session
SlackSession session = SlackSessionFactory.createWebSocketSlackSession(TOKEN);
//adding a message listener to the session
session.addMessagePostedListener(SlackIFTTTTrigger::listenToIFTTTCommand);
//connecting the session to the Slack team
session.connect();
//delegating all the event management to the session
Thread.sleep(Long.MAX_VALUE);
}
This next code snippet then connects to the Slack RTM API and adds a listener that is notified for each posted message:
private static void listenToIFTTTCommand(SlackMessagePosted event,
SlackSession session) {
if (!event.getChannel().isDirect() || event.getSender().isBot()) {
return;
}
if (!event.getMessageContent().trim().startsWith("!IFTTT")) {
return;
}
String [] splitCommand = event.getMessageContent().trim().split(" ");
if (splitCommand.length<2) { session.sendMessage(event.getChannel(),
"You have to provide an IFTTT event to trigger," +
" using the following syntax: !IFTTT {event_name})");
return;
}
notifyIFTTT(event, session, splitCommand[1]);
}

 

The listener filters the event it receives to keep only messages, and the content is followed by an event name sent as a direct message to the Slack bot. If the event is not filtered out, then IFTTT is triggered, as you can see here:

private static void notifyIFTTT(SlackMessagePosted event,
SlackSession session, String iftttEvent) { HttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet("IFTTT" +
iftttEvent + "/with/key/" + IFTTT_SECRET_KEY);
try {
HttpResponse response = client.execute(get); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() >= 400) { session.sendMessage(event.getChannel(),
"An error occured while triggering IFTTT : " + statusLine.getReasonPhrase());
}
} catch (IOException e) {
session.sendMessage(event.getChannel(),
"An error occured while triggering IFTTT : " + e.getMessage());
}
}

 

Using the code in this hack, we performed a GET HTTP call matching the required template, which then passed the IFTTT secret key and IFTTT event name as an argument.

 

The end result is that you can use this code to trigger IFTTT remote-controlled software or objects with a simple Slack command. Just build the recipe with the appropriate Maker trigger and you will be set.

 

There are so many projects that take advantage of this IFTTT recipe, from pool temperature monitors to Darth Vader’s command center. Go to IFTTT projects for a long list of examples.

 

Simple Slack API

Don’t panic if you don’t understand all of the implementation details about the Simple Slack API library (registering listener, events, sending messages and so on). The point of this hack was to work around the fact that IFTTT can’t be triggered using Slack. 

 

Develop Your Own App

In this blog, you will learn how to directly integrate with the Slack API by writing and deploying apps and slash commands for Slack.

 

 The hacks described in this blog cover specific applications, directly calling the Slack web API by manually performing HTTP calls to remote methods. You will become familiar with the API by seeing all of the interactions between the applications and the Slack server.

 

Slack API overview

Slack provides a powerful API for developers and admins to interact with. This API allows scripts to read and write to channels and conversations, and interact with users by means of bots and slash commands. 

 

When the API is used, it transforms Slack from a normal chat client into a powerful central hub for your company. For example, scripts can provide you with regular updates on sales, or you can interact with your on-site live chat widget.

 

The Slack API is divided into two parts:

The Slack Web API: This API is used to act on a Slack team, to post a message, to create a channel, or to browse a channel history.

The Slack RTM (Real Time Messaging) API: This API is mostly used to get notified on what’s happening in a Slack team.

We’ll discuss both of these parts in detail in the following sections.

Curious why Slack has two APIs? Jump ahead to “Why two kinds of APIs?” for an explanation.

 

Authentication

Whichever part of the API you use (you might use both), you will have to perform authentication using a token. This token can be provided through an OAuth flow, or it can be tapped directly and given by Slack if it’s a bot access token.

 

Slack Web API

This API is a set of methods that are called remotely using HTTP (GET or POST) calls. There’s a method for every action you can perform on Slack: Sending a message, modifying it, subscribing to a channel, leaving a channel, browsing the channel list, and more. You will find a matching method in the Web API for all of these actions.

 

On each method call, you have to provide the token you received for authentication in order to identify what is calling the method and to see if it has the right to call the method.

 

The response to the call will be in JSON format and will give you some information about the way the command you sent was handled (whether it succeeded or failed).

 

And, if you post a new message, the response will also provide you with the message’s timestamp. This timestamp is useful since it serves as the message identifier. You will have to provide this timestamp if you want to later modify or delete the message.

 

For example, say we call the chat. the postMessage method which uses the following arguments to post a message on a channel:

  • token: your authentication token
  • channel: #general
  • text: hello from the API

 

This provides us with the following answer:

{
"ok": true,
"channel": "C1CFWD0PP",
"ts": "1466844677.000002",
"message": {
"text": "hello from the API", "username": "testuser", "bot_id": "B1L8V9SU9",
"type": "message", "subtype": "bot_message", "ts": "1466844677.000002"
}
}

 

You can see here the ok field is true, indicating the command was successful, along with a full description of the message that you sent. We won’t describe every field, because the official documentation is quite thorough, but we will find the message timestamp stored in the ts field within the message. As mentioned earlier, you need this timestamp to modify or delete the message.

 

If you make a mistake and send a message on a channel that doesn’t exist, for instance, you’ll get this result:

{

"ok": false,

"error": "channel_not_found"

}

All of the Web API’s methods are described in the official Slack documentation.

 

Slack RTM API

The Slack Real Time Messaging (RTM) API is WebSocket-based. It lets you receive events from Slack in real time, so you can send messages as a user. Slack Bots can also use this API to interact with users.

 

In order to use this API to listen to Slack events, you first need to make a call to rtm.start method | Slack. This call returns a full description of the team as seen by the caller:

Users in the team and their profiles (including avatar links)

 

Public channels

Private channels on which the third party application is a member of (other private channels won’t be listed). In addition to this full description, you’ll be provided with a unique URL to open a secure web socket connection.

 

This connection, once established, allows for a bi-directional dialog between your application and the Slack servers. This dialog is in JSON format.

 

The ping command

The RTM API does not provide a wide set of message types to send over the web socket, but there’s one you should know: ping. The purpose of this message is to ask Slack to send you a pong response.

 

Sending this message at a regular rate allows you to detect disconnections and to take appropriate measures. To use ping send the following JSON message:

{
"id": 1,
"type": "ping"
}
Slack will answer you with this pong response:
{
"id": 1,
"type": "pong"
}

 

The id field allows you to match the pong, so you’ll have to change it for each request to be able to pair each ping you send with a pong you receive sometime later. The best way to do that is to start at 1 and to progressively increment the value.

 

Slack team events

The main reason to use the RTM API is to listen for team events through the web socket connection. There can be hundreds of events each second on big Slack teams. Events are just a way to indicate to a user that something happened on the team in such a manner that this user can react to the event. For example:

When a new channel is created, the API user who receives the channel_created event can react by joining that channel.

When a message is sent, the API user might want to respond to it depending on its content.

 

Here is an example of an event you can receive if a message is posted in a Slack channel that you are a member of:

{
"type": "message",
"channel": "C123456",
"user": "U123456",
"text": "Hello world",
"ts": "1466844677.000002"
}

type: This is the event identifier - in this example, it’s a “message” event

channel: The id of the channel the message was posted on

text: The text content

ts: The timestamp of the message that serves as a unique identifier within the channel it was posted in (so the channel’s id and this timestamp are a unique key for a message in the Slack team)

 

The following event is sent whenever a new channel is created:

>{
"type": "channel_created",
"channel": {
"id": "C123456",
"name": "new channel", "created": 1462821547, "creator": "U123456"
}
}

type: As above, this is the event identifier

channel: This is a JSON object containing details about the channel just created:

— id: The new channel’s id

— name: The new channel’s name

— created: The new channel’s creation time (This is a simple epoch timestamp and, unlike the info in a ts field, can’t be used to identify channels)

— creator: The user id of the user who created this new channel

 

There’s a lot of different events you can receive through the RTM API. You can find a complete list here.

Why two kinds of APIs?

Slack made two APIs for a simple reason: they separated the APIs’ duties.

 

The RTM API, using a WebSocket to keep a permanent connection, is a convenient way to quickly receive notifications. You don’t have to poll a server at a regular rate to get notified, and the notifications are pushed through the WebSocket each time an event happens.

 

The web API, on the other hand, doesn’t require a permanent connection, but it’s well suited for performing some remote procedure calls and for acting on a server. A drawback of this kind of call is that it adds some latency due to the fact you have to establish a connection to the HTTP server for each call.

 

The fact that web sockets are bi-directional doesn’t make the web API useless: Slack could have provided a bigger RTM API with which you could call every command by sending JSON objects.

 

But that would have been painful for people developing third-party applications whose only purpose was to call methods on the Slack server without having to take care of the team events.

 

That situation would have forced app developers either to maintain a WebSocket connection or to establish a new one each time they needed to call a remote method.

 

Slack engineers knew about these impediments because they are using these APIs to build the official clients. If you have a look at the network activity of your Slack web page, you will easily see the calls to the Web API. 

 

It shows two steps: * A call to channels.join: Despite its name (which is rather deceiving), this method creates a channel if the name of the channel you try to join doesn’t exist. * A call to channels.history:

 

The client is calling this method to fetch the message history of the newly created channel to retrieve the only message existing in a new channel, which is the initial message indicating that the creator joined the channel. The client needs this message to display the channel content.

 

You can’t easily observe the message going through a WebSocket, but of course, the official clients are using it.

 

That’s how they can be aware of new messages posted that they have to display, and how they know about channel topic changes, new channel members, new users, and everything that makes the client responsive to the changes to the team that should be displayed to the user.

 

An interesting point to note is that you won’t see any web API calls when you publish some messages. This is because the RTM API allows you to publish messages with no attachments, which is a quick way to bypass the latency of HTTP calls on messages that must be pushed as fast as possible (adding attachments to messages is not something users are doing frequently and so it is less latency sensitive).

 

This behavior lightens the load on Slack’s HTTP servers, since sending messages is the most common activity of a user. Feel free to have a closer look at the network traffic of the official client, because it contains a lot of useful info for understanding how Slack APIs can be used in your own bots or integrations.

 

API Language neutrality

You will see later in this blog that the Slack APIs can be used by a wide variety of languages. The fact that the APIs are built upon HTTP, WebSockets and JSON structures make them language neutral.

 

Any programming language that allows you to do HTTP requests and a bit of JSON parsing/formatting can be used with the APIs. Taking a look at Community | Slack will give you an idea of the range of languages that can rely on these APIs (and the list is constantly growing).

 

Slack Bots

Bots are where Slack and its integrations really come alive. They allow you to build advanced functionality right into a chat application, giving sometimes complex code an easy-to-use and familiar interface.

 

Bots appear in Slack as users in the team directory. They have the ability to read and write to conversations, they can be invited to channels and private groups, and you can interact with them via direct messages.

 

 The most popular bots include Errbot and Hubot. These bots run independently of Slack and can be extended and customized to cater to the needs of a team.

 

For example, Errbot can organize tournaments for your team or generate graphs in conversations. Hubert can interact with Trello or return Google PageSpeed results.

 

Let’s get started with some hacks that tap into the Slack APIs.

Source code for the blog

The source code for all hacks in this blog can be found in this blog’s Github repo.

 

Use Google Cloud Functions as a slash command endpoint

Slash commands in Slack are shortcuts that users can type to send an HTTP request to a server. The users don’t need to know all of the details about which server to call and how to pass parameters, they just type /commandName with some arguments and Slack does the rest, returning the answer from the server.

 

In this hack, you will learn how to host a slash command endpoint using Google Cloud Functions and integrate it with your Slack team. Google Cloud Functions is a feature available in the Google Cloud Platform, a cloud hosting solution offered by Google (https:// Google Cloud including GCP & G Suite — Try Free  |  Google Cloud).

 

Using the Google Cloud Platform allows you to integrate your hosted projects seamlessly with Google’s API. This is done using Google Maps’ features like generating a custom map image or fetching a YouTube video stream. Google Cloud Functions are a very simple way to deploy a slack slash command endpoint on the web.

 

If you don’t have yet a Google Cloud Platform account, you will have to create one for free using the URL given above. On the project you will create to host the endpoint, you will need to enable the Google Cloud Billing API (this is covered in the Quickstart step below).

 

Since Google Cloud Functions is still in alpha stage, you must perform the following steps to enable its use on your project.

1. First, perform the five first steps of the cloud.google.com/functions/quickstart
 

2. At the time of writing, cloud functions are pretty new, so you’ll have to go to the API manager to activate the API.

3. Then use gcloud init to authenticate and select the project on which you want to deploy your function.

4. Functions at this point are in alpha, so you can add them to gcloud by typing: gcloud components install alpha. 

 

For the latest full release notes, please visit: https://cloud.google.com/sdk/release_notes

Do you want to continue (Y/n)?

 

Once you’ve performed those steps, create a working directory:

$ mkdir ~/slack-function

$ cd ~/slack-function

 

And then create a bucket to store your code. The name of the bucket needs to be globally unique:

$ gsutil mb gs://[BUCKET_NAME]

 

Now that your function is ready, you can deploy it to be triggered via HTTP:

$ gcloud alpha functions deploy slackhello --bucket [BUCKET_NAME] \

--trigger-http

Copying http://file:///tmp/tmpbr_Zen/fun.zip [Content-Type=application/zip]... Uploading ...ns/us-central1-slackhello-nojdajqvmusi.zip: 689 B/689 B Waiting for the operation to finish...|

 

Carefully note the given URL (it should be something like https:// [PROJECT].http://cloudfunctions.net/slackhello). If you lose it, you can get it back querying the fucntion like this: $ gcloud alpha function describe slackhello

 

Now, try your function to see if it is ready before trying it with Slack:

$ curl -X POST <HTTP_URL> --data '{"message":"Hello World!"}'

 

You are now ready to hook your function up to Slack! In your channel, click on the gear and then choose “Add an app or integration.” Then in the search box type “command” and select Slash Commands

 

Next, name your slash command so you can assign it to your Google Cloud function

Then hook your slash command up to the URL of your Cloud Function via the URL field of the slash command settings. Be sure to fill in the Autocomplete help text field in the settings to add your slash command in the autocomplete list.

 

Use an AWS Lambda to host a slash command endpoint

Amazon Web Services’ Lambda is a nice alternative to Google Cloud Functions. It hosts your code on Amazon’s cloud so you can focus on your code and delegate the hosting duty to Amazon Web Services.

 

Using Lambda is a simple way to host a Slack slash command endpoint. Amazon has even provided a blueprint for doing so. (Blueprints are pre-built samples that Amazon makes available.) In your AWS console, go to the Lambdas section and create a new Lambda from the slack-echo-command-python blueprint.

 

Then replace the template version with this simpler version:

import logging
logger = logging.getLogger() logger.setLevel(logging.info -&nbspThis website is for sale! -&nbspLogging Resources and Information.)
def lambda_handler(event, context): user = event['user_name'] command = event['command'] channel = event['channel_name'] command_text = event['text']
return "%s invoked %s in %s with the following text: %s" % \ (user, command, channel, command_text)

 

On the lambda endpoint, select “POST” as the method and set security to “Open”

Next, click on the API endpoint to go to the API gateway

 

Once the API gateway screen appears, click on the lambda, then the API endpoint, then POST to show the method execution

At the bottom of the method-execution diagram screen, click “add mapping template.”

 

On the screen that, appears set the content type to application/x-www-form-urlencoded, and copy the content available on this Github gist ryanray’s gists 668022ad2432e38493df into the body.

 

This transformation is the magic behind the lambda code that transforms the POST data content encoded in application/x-www- form-urlencoded into JSON structured data, which is easier to manipulate. 

 

Now that you’ve set up your endpoint on Amazon Web Services’ Lambda, you can create a slash command in Slack using the process described in Hack #22, and then copy and paste the API endpoint into the URL field

 

Make a calculator with Google App Engine

Google App Engine is a platform-as-a-service (PAAS) that simplifies greatly the deployment and maintenance of a web-based service (Like Heroku or Amazon Web Services). This is exactly what we need for a Slack bot. In this hack, we will show you how to make a simple calculator with a Slack Slash command in Go. 

 

Make a new application on App Engine

You’ll need to open an account on the Google Cloud Platform and start a project. You can use the GCP free trial: https://cloud.google.com/free-trial/.

 

Once you have created a project ID, write its name down, since it will be useful later. You can also see the project ID in the drop-down menu on the top right of Google Cloud Platform. 

 

Next, you need to install the Go language App Engine SDK from https://cloud.google.com/appengine/downloads. You can check whether your SDK is correctly installed by typing app version.

 

Configure the slash command in Slack

Now let’s configure a Slash command in Slack to handle our little calculator using techniques similar to the ones we used in Hacks #22 and #23. Enter the following in the Integrations Setting screen

  • Command: /calc.
  • URL: https://fizz-buzz-314.appspot.com/
  • Method: POST
  • Token: This will be generated for you
  • Customize Name: calculator
  • Autocomplete help text: Select /feedback, turn on the “Show this command in the autocomplete list” checkbox.
  • For the autocomplete description, we used “Calculate some-thing” and our usage hint is “/calc 2+3*(5-7)”.

 

Code and structure

You need to create the following files and directory structure:

├── app.yaml

└── calc

└── cmd.go

The app.yaml file is an App Engine descriptor that sets up the run-time and serving parameters for your application. You can find the official documentation for this file here: cloud.google.com/

Enter the following code in app.yaml:

application: slashcalc version: 1

runtime: go api_version: go1

handlers: - url: /.* script: _go_app

 

Next, we are going to define the logic of our command. The entry point is a handler, which will be called every time an HTTP request lands on your application.

 

The slash command will post a form with parameters like “text” that we will use to get the parameters the user gave to the command in the Slack chat box. The remaining code is pretty standard with some formatting and error handling.

 

Security

In order to keep the example simple, it doesn’t deal with any security. For example, we recommend that you match the security token you define in your Slack command from the handler function to be sure the request comes from Slack and not any third party on the Internet.

 

Here’s the Go code of the calculator we will deploy on Google App Engine:

package calc
import (
"fmt"
"http://github.com/ryandao/go-calculator/lib" "net/http"
)
func init() {
http.HandleFunc("/", handler)
}
const PAYLOAD string = `
{
"response_type": "in_channel", "text": "= %s"
}`
// Strip trailing zeros from a float
func formatFloat(num float64) string { str := fmt.Sprintf("%.9f", num) truncate := len(str)
for i := len(str) - 1; i >= 0; i-- {
if str[i] == '0' {
truncate = i
}
}
if truncate > 0 && str[truncate-1] == '.' { truncate--
}
return str[0:truncate]
}
func handler(w http.ResponseWriter, r *http.Request) { args := r.FormValue("text")
lexer := lib.Lexer(args)
interpreter := lib.Interpreter(&lexer) result, err := interpreter.Result()
if err == nil {
w.Header().Set("Content-Type", "application/json") fmt.Fprintf(w, PAYLOAD, formatFloat(result))
} else {
fmt.Fprintf(w, "ERROR %s [%s]", err, args)
}
}

For this example, we used a pre-built calculator parser library that you can find at ryandao/go-calculator. In order to install this library so App Engine can deploy it, you simply run the following command:$ goapp get http://github.com/ryandao/go-calculator/lib

 

Testing locally

Before deploying your application, you can use App Engine’s dev app server feature to test it locally. To start a little local server with your code deployed on it, you can use soap serve from the root of your application (where app.yaml is):

$ goapp serve

INFO 2016-06-07 06:08:40,109 http://devappserver2.py:769]

 

Skipping SDK update check.

  • INFO 2016-06-07 06:08:40,173 api_server.py:205]
  • Starting API server at: http://localhost:45511 INFO 2016-06-07 06:08:40,175 http://dispatcher.py:197]
  • Starting module "default" running at: http://localhost:8080 INFO 2016-06-07 06:08:40,176 admin_server.py:116]
  • Starting admin server at: http://localhost:8000
  • To test your application, give it an expression within the URL, such as http://localhost:8080/?text=3*2

 

URL encoded format for + symbol

The text parameter needs to be URL encoded and + is a character used in the encoding grammar, so if you want to try out + you will need to use %2B instead.

For example, for 2+3, use http://local host:8080/?text=3%2B2.

 

Deploying on App Engine

This is where you’ll need your project ID from the cloud console. We used fizz-buzz-314 here, but you’ll need to replace that with your actual ID. Use this command to deploy the application:

$ goapp deploy -application fizz-buzz-314 app.yaml [...]

Once it is deployed, you can test the application independently from Slack with https://fizz-buzz-314.appspot.com/?text=3*2. Notice that the URL includes both https and the name of your project

 

You can then try your application in Slack

You can use this example as a base for your own project or by analogy for any other language available on the App Engine (Java, PHP, Python).

 

Host a poker bot with Heroku

Heroku is an easy to use platform-as-a-service, and hosting a Slack bot on it is really simple. As an example, in this hack, we will see how to use it to run the poker bot from https://github.com/CharlieHess/slack-poker-bot. This hack requires a Heroku Slack bot using Node.js.

 

Create a bot integration

First, create a bot user for your team via https://TEAM.slack.com/ services/new/bot, where TEAM is the name of your Slack team.

Then fill in the API Token, Customize Name, and optionally upload a Customize Icon field on that web page

 

Install a local Heroku environment

Next, follow the toolbelt installation instructions at https://devcen http://ter.heroku.com/articles/getting-started-with-nodejs#set-up. In a nut-shell, if you want to install the toolbelt on your account on Linux do the following:

$ cd
$ wget https://s3.amazonaws.com/assets.heroku.com/\ heroku-client/heroku-client.tgz
$ taz xzvf heroku-client.tgz [...]
$ mv heroku-client heroku

 

Then add the ~/heroku/bin to your latex-math:[$PATH environment variable in your /.bashrc or /.zshrc by adding the line export PATH=$]\{HOME}/heroku/bin:$PATH.

 

You can then use the following command to log in to your Heroku account (if you don’t already have one, create one on http://heroku.com):

$ heroku login

heroku-cli: Installing CLI. 22.7MB/22.7MBB

 

Enter your Heroku credentials. Email: gbin@domain.tld

Password (typing will be hidden):

Logged in as gbin@domain.tld

Deploy the project on Heroku

First, clone the code repository:

$ git clone https://github.com/CharlieHess/slack-poker-bot
$ cd slack-poker-bot
Then create a Heroku App from the root of this Git repository:
$ heroku create
Creating app... done, ⬢ mighty-tundra-99867 https://mighty-tundra-99867.herokuapp.com/ | \
https://git.heroku.com/mighty-tundra-99867.git
If you run git remote -v, you’ll see that heroku create effectively added a new remote to your local Git clone:
$ git remote -v [...]
heroku https://git.heroku.com/mighty-tundra-99867.git (fetch) heroku https://git.heroku.com/mighty-tundra-99867.git (push) [...]
Then set your bot’s API token:
$ heroku config:set SLACK_POKER_BOT_TOKEN=\
xoxb-48370906999-nF40aVh2hM76Ub0LWCtiripm Setting SLACK_POKER_BOT_TOKEN and restarting ⬢ \
mighty-tundra-99867... done, v3
SLACK_POKER_BOT_TOKEN: xoxb-48370906999-nF40aVh2hM76Ub0LWCtiripm
You can now deploy your bot like so (note that this may take a while).
$ git push heroku master Counting objects: 1211, done.
Delta compression using up to 4 threads. Compressing objects: 100% (465/465), done.
Writing objects: 100% (1211/1211), 5.43 MiB | 88.00 KiB/s, done. Total 1211 (delta 733), reused 1211 (delta 733)
remote: Compressing source files... done. remote: Building source:
remote:
remote: ----> Node.js app detected remote:
remote: ----> Creating runtime environment remote:
remote: NPM_CONFIG_LOGLEVEL=error
remote: NPM_CONFIG_PRODUCTION=true remote: NODE_ENV=production
remote: NODE_MODULES_CACHE=true [...]
remote: Verifying deploy. done.

To https://git.heroku.com/mighty-tundra-99867.git * [new branch] master -> master

 

Invite and use the bot

At the top right of your Slack window, click the gear icon and choose “Invite team members to join…”

Select the newly created team member that should be online by then

 

You can now ask the dealer (or whatever name you gave it) to deal by typing @dealer: deal; after that, all of the players wanting to play need to respond yes. Once they’ve done so, the game can get started, and the bot will message you in private about your hand. You may now have some ideas for creating and hosting your own games on Heroku!

 

Create a bot to randomly select someone for a task

In this hack, we’ll build a PHP script which, when called, will pick a random person who is both a member of the Slack channel from which it was called and is currently online. The purpose of this particular script is to randomly select someone to make tea, but the same tool can be used to distribute other tasks around the office.

 

In this hack, you’ll learn the basic mechanism for triggering scripts and targeting specific members of a channel. Once you know how to do that, you can let your imagination run free and create all sorts of solutions.

 

Hosting this hack

Consider hosting your PHP script on Google App Engine or on Heroku. The steps for this script, which can be found on Github are:

1. Trigger from a channel

2. Get the members in that channel

3. Filter out the offline members

4. Filter out any from the exclusion list

5. Select a random online team member for tea making

The first step is to get Slack to call your script and to return something. To do this, you need to add an outgoing webhook to your team.

 

Add an Outgoing Webhook for the !tea command

1. Go to the Outgoing Webhooks page and click “install for your team”.

2. Click “Add Outgoing Webhooks Integration”.

3. Fill in the fields as follows:

  • Channel: Any (or your dedicated Tea channel).
  • Trigger Word(s): !tea.
  • URL(s): The URL where your script will be (make sure it is a PHP file and publicly accessible).
  • Descriptive Label: Whatever you want.
  • Customize Name: Tea Bot.
  • Customize Icon: Click “Choose an emoji” and select the tea icon

4. Click Save.

 

It Started with Hello

Now that you’ve created the Outgoing Webhook, verify that the script is working. Outgoing Webhooks print whatever the script returns, as long as it is valid JSON that matches what is expected.

 

The string to send to the Outgoing Webhook has to match the following JSON syntax in order to have the text successfully printed in the channel:

{
"text": "text to print"
}
So, here’s the PHP script for creating such a JSON string to print
Hello world:
<?php header('Content-Type: application/json'); echo json_encode(array( 'text'=> 'Hello world'
));

 

Using the trigger word we set up earlier (!tea), the above script will print Hello World in the channel that it was called from by your named bot. This script has to be called from a public channel—it doesn’t work private channels or conversations.

 

Slack payload data

When using Outgoing Webhooks, Slack sends several bits of useful information to your page in the payload using some key/value pairs:

* channel_name: the name of the channel from which the outgoing webhook was triggered * channel_id: the id of this same channel * user_name: the Slack username of the person who triggered the Outgoing Webhook * user_id: this same user’s Slack ID * text: the text line which triggered the Outgoing Webhook (including the trigger word)

 

Along with the trigger word, you can pass additional text to your script. Returning to the tea example, you can ask for a specific tea flavor by passing the flavor after the trigger word by running !tea Earl Grey (if you set !tea as your trigger word, that is).

 

This PHP script extracts the payload data passed after the keyword! tea for further use to build the bot response:

// Specify your trigger word
$trigger_word = '!tea';
// Remove our keyword and proceeding space from the
// text to extract name to exclude
$text = str_replace($trigger_word . ' ', '', $_POST['text']);

 

Using this script, you should now have all of the information that was passed after !tea. A simple example would be to echo what the user entered. Here’s a complete example echoing what a user is passing after a keyword:

 style="margin:0;height:67px;width:941px"><?php // Specify your trigger word $trigger_word='!echo'; // Remove our keyword from the text to extract name to exclude $text=str_replace($trigger_word . ' ', '', $_POST['text']); // Return a random response header('Content-Type: application/json'); echo json_encode(array( 'text'=> $text
));

In the example above, the user types:

  • !echo hello everybody
  • And the bot replies
  • hello everybody

 

Text passed to the script can be used as a parameter to finely control what the script output will be. In the tea maker example, you can pass names to exclude from the next round of tea duty (very helpful for getting out of the next round). 

 

From here, the possibilities of what your script can do are endless. Next up, we will connect to the Slack API, get channel and user data, and ultimately pick a tea maker!

 

Access Slack data using the API and Outgoing Webhooks

Now it is time to use the Slack PHP API to access channel and user data. Using the API we’re going to connect to Slack, work out who is in a channel, who is online, and who should make the tea.

 

To do this, you can communicate directly with the API, but to make it even easier, let’s use this Slack API PHP Wrapper. You’ll need to download the script and place it in the same folder as your webhook script.

 

Before proceeding, you must generate an oAuth token. This allows Slack to verify that we are in fact the ones communicating with it, and that we’re allowed to do that. If you are a member of multiple teams, then you’ll need multiple oAuth tokens. To generate one, follow these steps:

1. Go to https://api.slack.com/web.

2. Scroll down to “Generate test tokens”.

3. If you have previously generated a token, there will be one near the end of the “Test token generator” section, with the team name on the left. If not, click the “Create token” button.

4. Make a note of the token.

 

What Channel are you on?

Slack sends a lot of information when triggering a script. One piece of this is the ID of the channel it was triggered from. This is stored in the $_POST['channel_id] key.

 

Here’s how to connect to the Slack Web API, get the requested channel information and display it:

<?php // Replace AUTH TOKEN with your auth token $auth_token='AUTH TOKEN'; // Include slack library from // https://github.com/10w042/slack-api include 'Slack.php'; // Connect to Slack // Use authentication token found here: https://api.slack.com/ $Slack=new Slack($auth_token); // Get the info for the channel requested from $data=$Slack->call('http://channels.info', array( 'channel' => $_POST['channel_id']
));
header('Content-Type: application/json');
echo json_encode(array(
'text' => json_encode($data)
));

 

This code snippet connects to the Slack API using the library mentioned previously (using the Slack() class). Make sure your include path is correct. 

 

The next part(following the definition of $Slack variable) gets the channel info using the channel_id found in the $_POST information. $data now contains all of the information about the current channel. This info is then passed back to Slack to post.

 

In JSON data returned by Slack when calling the http://channels.info method, you should notice channel information such as the latest event, the channel purpose, and the created timestamp. The key we’re interested in is members, which lists the IDs for every member in the channel.

 

Picking an active user

To select a random user to prepare the tea, we need to select one among all the users that are active in the channel the command was sent on.

 

Through its Web API, Slack provides a method for getting information about a channel: http://channels.info. (You can see a detailed description of this method on the official Slack Web API documentation). Among this information is the channel members, so you can call it to get a list of the members’ IDs.

 

To convert IDs to names, use another Web API method that gives you information about a user from an ID: http://users.info. From this call, we will be able to get the username in order to determine who should be excluded from the tea making duty.

 

Finally, we will need to determine each user’s presence by using the users.getPresence Slack API method and filter out the inactive users. The active member users will then be added to a new $teaMak ers array.

 

From this array, a random team member can then be picked to make the tea using the pickOne function whose purpose is to pick a random element from an array of elements.

 

Here’s the script that performs all of these tasks:

// Get the info for the channel requested from
$data = $Slack->call('http://channels.info',
array('channel' => $_POST['channel_id']));
$teaMakers = array();
// Loop through channel members
foreach ($data['channel']['members'] as $m) {
// Get user data
$userData = $Slack->call('http://users.info', array('user' => $m));
// Check to see whether the user is online before adding
// them to list of brewers
$presence = $Slack->call('users.getPresence',
array('user' => $m));
$user = $userData['user'];
// If there is an exclude, check to see if it matches
// a user's real name (lowercase)
// If it doesn't, add it to the $teaMakers array
if($presence['presence'] == 'active')
$teaMakers[] = $user;
}
function pickOne($array) { shuffle($array);
return $array[rand(0, (count($array) - 1))];
}
$user = pickOne($teaMakers); header('Content-Type: application/json');
echo json_encode(array( 'text' => $user['id']
));

 

This script returns a user ID, which isn’t very helpful to anyone. To fix that, instead of returning $user['id'] in json_encode, you can return $user['name']. This tells you whose turn it is in human-readable form. 

 

The other option is to return the ID as a link to the user. This approach then, not only returns the username but also notifies the user of their duty.

 

To build a link to a user in Slack, add a <@ in front of the

$user['id'] and a > after it; for example:
header('Content-Type: application/json');
echo json_encode(array(
'text' => '<@' . $user['name'] . '>'
));

 

Allow exclusions

The last step in building the tea bot is to allow exclusions to be passed in. Using the $_POST['text'] key, you can exclude the trigger word and exclude the correct users. 

 

Once you’ve isolated the exclusion text, you need to check to see whether the user matches the exclusion string; here’s the code that does that:

if($presence['presence'] == 'active')
if($exclude) {
if(!(strpos(strtolower($user['real_name']), strtolower($exclude)) !== false))
$teaMakers[] = $user;
} else {
$teaMakers[] = $user;
}

 

If the exclusion string is present, but the user doesn’t match the exclusion string, you still add them to the teaMakers array. You also convert everything to lower case when comparing, to remove any capital discrepancies.

 

 Your script should now pick a random, online member to get up and put the kettle on. Remember, everyone can see what you type and input into the webhook, so you won’t be able to get away with always excluding yourself!

 

Add a greeting to the tea bot

Now that the script is complete, you can add a nice greeting.

Being able to pick a random index from an array lets the bot make decisions; this will allow it to pick both the user and the response to use.

 

The following PHP script is the part of the tea bot that specifies an array at the top of the script and then, using a custom function, picks a random response:

<?php // Specify an array of responses $responses=array( 'Hello!', 'How are you?' 'How is your day going?' 'What do you call a chicken on roller skates? 'Poultry in motion!' ' ); // Random picking function function pickOne($array) { shuffle($array); return $array[rand(0, (count($array) - 1))]; } // Return a random response header('Content-Type: application/json'); echo json_encode(array( 'text'=> pickOne($responses)
));

 

This code snippet specifies responses in a simple PHP array, which is used for our tea bot (see this blog’s Github repo for the bot’s full source code).

 

Add some personality to the tea bot

An extra, optional step is to give your tea bot a little bit of personality. The following bit of code creates an array of random responses with a {{USER}} marker. Upon picking a victim, the tea bot uses this code to choose a response and substitute the marker with the selected marker.

 

First, create your array. For each entry, make sure the marker

{{USER}} is present. Then assign it to the variable $responses, like so:
$responses = array(
"It's about time {{USER}} put the kettle on - off you trot!",
"Pop the kettle on {{USER}} - it's your turn to make a cuppa",
"Who wants a drink? {{USER}} is heading to the kitchen to make one",
"Coffee? Tea? Sugar? Peppermint Tea? Green Tea? Get your orders in as {{USER}} is making a round",
"That's very nice of {{USER}} to make a round of tea!", "Mine is milk 2 sugars please {{USER}} - what about
everyone else?",
"The tea maker is... {{USER}}! Get brewing."
);

From this array, we can use the pickOne function to choose a random response, replace the marker with the actual user, and return the response using str_replace.

str_replace is a built in PHP function that has three parameters:
str_replace($what_to_search_for,
$what_to_replace_it_with, and $what_to_search_in). More details can be found on the PHP website.

 

Here’s the script choosing a random user and substituting {{USER}} for the designated user (the tea but will now be able to share random responses in Slack):

// Get a random user from the array

$user = pickOne($teaMakers);

// SEND OUT THE JSON!! Enjoy your brew header('Content-Type: application/json'); echo json_encode(array(

'text' => str_replace('{{USER}}', '<@' . $user['id'] . '>', pickOne($responses))

));

 

You have now successfully created your tea bot. Enjoy! Create a Slash command for posting anonymous messages to a channel

 

In this hack, you will learn how to implement a slash command in Golang and deploy it using Docker. When you activate the slash command /anon Who am I ?, a message will be posted to a pre-selected channel.

 

The message will have a randomly selected avatar along with a quote. The avatar makes the user who sent the slash command anonymous since his message is posted without his name and avatar.

 

This hack can be a source of fun if several people use this slash command since multiple avatars can be created by multiple Slack users to send random messages, as detailed in the Loading the avatars section below.

 

 This hack is purely for fun, although as you will see, there’s a lot going on behind the scenes. The source code for this slash command can be found on Github.

 

Add a Slash command

  • To create this slash command:
  • 1. Go to the Slash Commands page and click Add Configuration.
  • 2. Click “Add Outgoing Webhooks Integration”.
  • 3. On the page that appears, fill in the command name, e.g. /anon, and then click “Add Slash Command Integration”
  • 4. Leave the URL field empty.
  • 5. Set the method to POST.
  • 6. Write down the content of the Token field.
  • 7. In the Description field write “Send anonymous messages”.
  • 8. Click “Save Integration”.
  • 9. Go to the Incoming webhooks page.
  • 10. Click “Add Configuration” and copy the webhook URL
  • 11. Click “Save Settings”.

 

Setting up a server

In order for Slack to respond to your new slash command, you need to set up web servers that will accept the request from Slack after someone enters the command. In Go, each source file can define its own init function to set up whatever state is required. (Each file can actually have multiple init functions.)

 

This means init is called after all of the variable declarations in the package have evaluated their initializers, and those are evaluated only after all the imported packages have been initialized. In our init function we will set the HTTP server port to 5000.

 

In the main function, we initialize a random number generator (we will use it later in order to select an avatar). We will get from the environment two variables:

  • The channel that we would like to post to.
  • The Slack token in order to validate requests.

 

The next step is to load the avatars from a JSON file. Once the loading is complete we will set up a handler function (readAnonymous‐ Message) for the / path, and then the HTTP server will start.

 

Here’s the Go code that performs the steps we just described:

func main() {
rand.Seed(time.Now().UnixNano()) channel = os.Getenv("SLACK_CHANNEL_ID")
token = os.Getenv(tokenConfig) getAvatars()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { result := readAnonymousMessage(r)
fmt.Fprintf(w, result)
})
http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}
func init() {
//Init the web server port 5000
flag.IntVar(&port, "port", 5000, "HTTP server port") flag.Parse()
}

 

Loading the Avatars

Avatars are loaded from a JSON file, avatars.json, which is located at the same directory as our binary. We have defined The JSON object structure for an avatar as follows:

  • username - The user from which the message will be sent
  • default_text - A text that appears next to the avatar’s name
  • icon_url - The user avatar url

 

Here’s an example for a given avatar using this JSON structure:

[
{
"username": "Archer",
"default_text": "Phrasing!",
"icon_url": "http://i.imgur.com/CyIgnqi.png"
}
]
The following code does two things:
1. It reads the JSON file.
2. It then populates three global arrays with the data from the file.
func getAvatars() []Avatar {
raw, err := ioutil.ReadFile("./avatars.json")
if err != nil { fmt.Println(err.Error()) os.Exit(1)
}
var c []Avatar
json.Unmarshal(raw, &c)
for _, p := range c {
avatars = append(avatars, p.Username) avatarIcon = append(avatarIcon, p.IconURL) avatarText = append(avatarText, p.DefaultText)
}
return c
}

Getting a message from Slack

When users issue the /anon slash command, the Slack server will perform a POST request to our server. We will handle this request in the readAnonymousMessage function.

 

First, we will try to parse the data that we received. We will compare the token that we received to the one from the environment variable in order to make sure that the request is legit. The next validation is to make sure that there is an actual text to send. Finally, we will trim spaces and send an anonymous message.

 

Here’s the code that performs these tasks:

func readAnonymousMessage(r *http.Request) string { err := r.ParseForm()
if err != nil {
return string(err.Error())
}
if len(r.Form[keyToken]) == 0 || r.Form[keyToken][0] != token {
return "Config error."
}
if len(r.Form[keyText]) == 0 {
return "Slack bug; inform the team."
}
msg := strings.TrimSpace(r.Form[keyText][0])
err = sendAnonymousMessage(msg)
if err != nil {
return "Failed to send message."
}
return fmt.Sprintf("Anonymously sent [%s] ", msg)
}

 

Sending the anonymous message

To send the anonymous message, the code has to perform these steps:

1. Get the Slack webhook from the environment variable using os.Getenv function.

2. Generate a random avatar ID using the rand.Intn function.

3. Construct the message payload in JSON. The JSON structure for posting a message on a channel is available on the official Slack API documentation.

 

Here’s the Go code that performs these steps:

func sendAnonymousMessage(message string) error { url := os.Getenv(webhookConfig)
avatarID := rand.Intn(len(avatars)) payload, err := json.Marshal(slackMsg{
Text: message, Channel: channel, AsUser: "False",
IconURL: avatarIcon[avatarID], LinkNames: "1",
Username: fmt.Sprintf("%s : %s", avatars[avatarID],
avatarText[avatarID]),
})
if err != nil {
return err
}
_, err = http.Post(url, "application/json", bytes.NewBuffer(payload))
return err
}

We are now ready to send the anonymous message via the webhook URL.

 

Deploying

Now, you can run the server inside a Docker container that can be deployed to your favorite cloud provider. A prebuilt binary Docker image can be found at Docker Hub. You can pull it by running the following command: docker pull rounds/10m-annona. Here is the Dockerfile used to build this Docker image:

FROM rounds/10m-build-go RUN apt-get update && \ apt-get install wget
RUN go get http://github.com/rounds/annona
EXPOSE 5000
RUN wget -O /root/go/bin/avatars.json \
https://raw.githubusercontent.com/rounds/annona/master/avatars.json
CMD cd /root/go/bin/ && ./annona

 

The preceding code starts with a minimal base image. Then, we make sure that all packages are up to date and we use the standard go toolchain to fetch and build our Annona binary with go get. After downloading the necessary avatars file using wget, we finally run the binary. You now can run Docker and pass in the following three environment variables:

INCOMING_SLACK_WEBHOOK - SLACK_CHANNEL_ID - INCOMING_SLACK_TOKEN

 

Here’s the command line to do so :

docker run -e INCOMING_SLACK_WEBHOOK='<your webhook URL>' \
-e SLACK_CHANNEL_ID='<channel id where to post messages>' \
-e INCOMING_SLACK_TOKEN='<Slack token obtained when configuring the slas -p 5000\ <your_image_name>

Make sure to map the Docker port (5000) to a port at the host with the -p flag to Docker. After you deploy, make sure you go back to the URL at the slash command configuration page, and fill in your server address and port. You have now seen some simple, custom-made applications you can integrate into Slack. In the next blog, we cover how to integrate Slack into your business.

Recommend