Slack Tutorial (2019)

Slack Integrations and Slack Definition

Slack Integrations Tutorial (2019)

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 processor 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.

  1. The source code for all hacks in this blog can be found in this blog’s Github repo.
  2. Keep track of Documents with Google Drive
  3. This app allows you to import Google Drive files by pasting a file’s URL into Slack.
  4. 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 shared message that points to the external reference. Doing this means:

  1. Other team members see the document’s title.
  2. You can easily spot links to Google drive documents within the conversation
  3. The file will be added to Slack and the document’s full text will be indexed for search.

 

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:

  1. When a Github issue is assigned to you, add a to-do that specifies the repository, issue, and link (recipe here).
  2. Add a to-do when a Trello card is assigned to you (recipe here).
  3. Log your work hours on your #calendar of choice (recipe here).
  4. 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 Keyboard app will take your use of Gifs to the next level. It makes it easy to search for a massive Gif collection, and you can also:

  1. Create custom GIFs by typing /gif “YOUR CAPTION HERE”
  2. Choose which GIF you want to send by typing /gifs
  3. 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.

  1. You can also add captions to your Gifs.
  2. You can combine the above and use /gifs cat "Schrodinger's cat" to select an image and put a caption on it.
  3. 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 a 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.

 

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 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):
  5. Command: /overflow
  6. URL: http://so.goel.io/overflow
  7. 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.

 

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:

  1. A hosted paid version that can be found at the Standup bot page.
  2. An open source version that you can host yourself.
  3. 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.

 

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. 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:

  1. title - A bolded title for the attachment.
  2. value - An unbolded field for the attachment.
  3. 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  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. 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.

 

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.

  1. Select Twitter for your this
  2. Click on this and search for Twitter. After typing a few letters, Twitter should be one of your choices
  3. 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”.

 

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.

 

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. 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:

  1. When a new channel is created, the API user who receives the channel_created event can react by joining that channel.
  2. 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:

  1. id: The new channel’s id
  2. name: The new channel’s name
  3. created: The new channel’s creation time
  4. 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.

  1. Why two kinds of APIs?
  2. 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 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.

 

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.

Recommend