Slack is a powerful tool for teams to communicate together, but it can also be the perfect platform to set up alerts. Learn to make your first Slackbot with their great API.

Slack is a common communication platform used for businesses, most offices have these set up. It stands for Searchable Log (of) All Communication (and) Knowledge.

But it's not just for communication, it's a vastly underused platform and with the addition of some of it's Apps and simple (yet powerful) API you can set up custom alerts and messages for all members of your team.

Some of the cooler uses of Slack come from linking your websites data to set up custom alerts. In this article we will be taking a look at the Slack API to code a very simple script in PHP that checks the HTTP status of our website and sends an alert to a slack channel if there's an issue. This could be very easily modified to send an alert for almost anything.

What is an API?

An API (application programming interface) is a piece of code that allows you to use the features of another platform. It describes you one platform can communicate with another as well as the rules and mechanisms that allow that to happen. They allow software to software and usually do not include any kind of user interface, all instructions sent over to slack today will be done through code.

In this case we can imagine that we have two islands, the first island is us and the second island is Slack.

An API can be seen as a bridge that allows us to send things over from our island to the island of slack. Lots of platforms have API's, they can be used to extend what certain platforms do as well as customise them to suit your businesses needs much better.

There are lots of types of API, but usually the platform you're working with will have documentation to show you how to use their platform. Slacks documentation can be found here.

What are we going to build?

We are going to build a slack bot which tells us if there is a problem with one of our websites. It will do this through CURL requests.

This will be built in PHP, it will be a small script we host on the web which you can set up run through a cron job as often as you need.

It's a very simple tutorial that will help you get familar with some of the lesser known features of Slack, as well as API's/Web Hooks as a beginner.

How do I set up Slack Bots with PHP?

Step 1: Set up a slack App.

To dot his please go to here and log into your work space. Click the green "Create An App" button and fill in the data you see in the pop up form.

Give your app a name, and select your work space. Click "Create App"

Step 2:Setting up web hooks.

On the next screen we're given a bunch of options of permissions we can give the app, to do what we need to do all we need is web hooks so select this box.

We will then be taken here, we need to activate our web hooks as well as add a new web hook to the workspace. See the image below for where you need to click.

When you add your new web hook it's going to ask you where you want the alert messages to be posted to, you can choose between any user or channel in your slack group.

Just for the tutorial I will be posting into #general, you might want to set up an invite only channel so you can add only those who need to see the alerts. This avoids annoying people.

Next up you're going to be taken back to the previous screen and you should have a webhook registered, leave this open for now. We will come back to it soon.

Step 3: We have our hook set up and ready to go, now we need something to send it.

Boot up your favourite code editor, it's time we do the fun stuff.

We're going to do 3 things.

List the website(s) we want to check Check the HTTP status of these websites Send a message to Slack

We will need two functions, an array for our websites and a foreach loop.

Set up your php file (name it anything you like) like so:

<?php //Sends message to slack function slack($domain){ } //Get HTTP status of each domain function getstatus($domain){ } //List of domains we are going to check $domains = array( "mywebsite.com", "mywebsite.info", "mywebsite.us" ) //foreach loop to check each domain foreach($domains as $domain){ } ?>

Step 4: Get the HTTP Status of our websites

Before we send anything, we need something to send. Let's start with building out the for each loop.

Before we go further it might be a good idea to quickly cover what a HTTP status code is. HTTP status codes are standard response codes given by web site servers on the internet. The codes help identify the cause of the problem when a web page or other resource does not load properly.

You may be familar with 404 pages, 301 redirects or 200 OK statuses if you have done any kind of server management. This is what we are looking for.

To start with let's take a look here:

foreach($domains as $domain){ //send domain to getstatus() function and assign result to $status $status = getstatus($domain); //check status for errors if (($status != 200) && ($status != 301) && ($status != 302)){ //if there is an error, send to our slack function slack($domain); } }

It's a very simple loop that takes the list of domains from our $domain array.

It checks the domain through our getstatus() function (we are yet to write) and assigns the returned value to $status.

Next, we are going to check the status in a very simple IF statement. We are checking that the domain is:

NOT status 200 - Status 200 means everything is fine.

- Status 200 means everything is fine. NOT status 301 - If our domains are set up to usewww.domain.com or https://domain.com instead of domain.com a 301 will be returned.

- If our domains are set up to usewww.domain.com or https://domain.com instead of domain.com a 301 will be returned. NOT status 302 - If our domains are set up to usewww.domain.com instead of domain.com a 302 could be returned.

I know through the set up of our websites, anything other than these status codes is a problem which should trigger an alert. If you want to add more or less status codes you can find a complete list of HTTP status codes here and add whatever you need.

Step 5: Getting the HTTP Status of our domains

We now need to build our our getstatus() function.

We are passing in the domain, we need to perform a HTTP status check and return the HTTP code.

There are a number of ways to do this, but we're going to use CURL. Another option could be the get_headers() function in PHP but we're going to be using CURL a little later on for the Slack web hook so it's best we learn about it.

What is CURL?

CURL (or Client URL) is a software library that lets us transfer data is various protocols. It's used in PHP for sending and receiving files through URL syntax.

Here is the completed function, we will talk about it below.

function getstatus($domain){ $curlHandle = curl_init(); curl_setopt($curlHandle, CURLOPT_URL, $domain); //set our $domain as the url curl_setopt($curlHandle, CURLOPT_HEADER, true); //we want header data curl_setopt($curlHandle, CURLOPT_NOBODY , true); // we don't need body curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); //return the raw transfer curl_exec($curlHandle); //execute cURL $response = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE); //get http status from response, set to $response curl_close($curlHandle); // Don't forget to close the connection //return http status return $response; }

I've commented everything going on the best I can, but just to show you what's going on let's take a look line by line.

When using CURL, we need to initialise the session. This is done with this line, which we set to $curlHandle for ease of use later on.

$curlHandle = curl_init();

Next we need to set our options up for the CURL session, this is done in the next 4 lines of code.

curl_setopt($curlHandle, CURLOPT_URL, $domain); curl_setopt($curlHandle, CURLOPT_HEADER, true); curl_setopt($curlHandle, CURLOPT_NOBODY , true); curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);

CURL Options set up what we are going to do in our CURL session. These are set with the curl_setopt() function and your options are passed in as arguments.

Each option we set up coresponds to the point below:

CURLOPT_URL : This lets us set the URL of the CURL session, we use our $domain variable here.

: This lets us set the URL of the CURL session, we use our $domain variable here. CURLOPT_HEADER : This sets the option of returning header data, this is where our HTTP status will be.

: This sets the option of returning header data, this is where our HTTP status will be. CURLOPT_NOBODY : No body tells the CURL request we are not interested in the body of the response, our HTTP status data is in the header.

: No body tells the CURL request we are not interested in the body of the response, our HTTP status data is in the header. CURLOPT_RETURNTRANSFER: This sets the option of returning the raw response data.

When all your CURL options are set and everything is ready, it's time to execute. This is done with this line:

curl_exec($curlHandle);

From the response we can get our HTTP Status.

Thankfully CURL makes this easy, we have a function we cal use called curl_getinfo(). To use this we pass in our CURL Session ($curlHandle) and the option for what we need. This is pretty easy.

$response = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE); //get http status from response, set to $response

We set this to the variable $response so we can turn it to the foreach loop.

Next up we close the CURL session. In this case it would not break anything but it's best practice.

curl_close($curlHandle);

And finally, we return the status for the domain.

return $response;

Step 6: Let's communicate to Slack

Now we have something to check, and possible issues to report we should think about sending them to Slack. Let's build out our slack() function.

The easiest way to do this is again with CURL, Slack will give you a piece of code as an example which actually uses CURL.

curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/***YOUR HOOK HERE***

If you add your slack hook URL and run this through a CLI you will be able to post "Hello, World!" into the slack channel you picked earlier. Unfortunately we're not going to do use a CLI, we're going with PHP.

To do this in PHP the way to go would be sending our message through POST data using CURL.

We should think about what we need to send to Slack:

Includes our message

Sent to our correct web hook URL

The user it's sent from

All of this needs to be be built into a JSON string, in the correct format for Slack to accept it.

Again, here is the complete function. We will break it down below:

function slack($domain){ $msg = "Website Alert: <".$domain."|".$domain."> might be down."; $url = "https://hooks.slack.com/YOUR-COMPLETE-HOOK-URL-HERE"; $payload = 'payload={"username": "Problem Alert!", "text": "'.$msg.'", "icon_emoji": ":rotating_light:"}'; $curlHandle = curl_init(); curl_setopt($curlHandle, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"); //set our user agent curl_setopt($curlHandle, CURLOPT_POST, TRUE); //set data transfer as POST curl_setopt($curlHandle, CURLOPT_URL, $url); //set the url we want to use curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $payload); curl_exec($curlHandle); //execute and get the results curl_close($curlHandle); // Don't forget to close the connection }

Slack accepts Web Hook data in JSON format. For an example of a complete web hook which it expects you can read the Slack web hook page.

Slack gives you the option to pass in a lot of information, but to keep this tutorial fairly easy we are only going to send:

A username for the alert.

An emoji for the alert

The message for the alert

Slack contains a whole host of extra options you may want to include, simply add in the JSON fields and information to the above code and you will be rocking.

The first part of our code is all about building the data we need to POST to our Slack Hook.

$msg is the message we want to send as the alert. Links in Slack are formatted with <URL|link text>.

$url is your Slack URL, which should not be shared. Add yours in place of the place holder URL in the example code. This is where we are going to POST to later on. You can find this in your web hooks page that I said to leave open earlier.

The next variable is $payload, here we are just passing in the $msg contents into the part of the JSON data that handles our message.

If you wish, this is also where you can edit the username of the bot, as well as the emoji for the bots profile. In my case I have name it "Problem Alert!" and used the :rotating_light: emoji.

Now we have the data/message we need to send as well as the URL location to POST to, we will use CURL to complete the function.This is done in the next block of code and is much the same process (with some slight changes) as we completed in step 5.

$curlHandle = curl_init(); curl_setopt($curlHandle, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"); //set our user agent curl_setopt($curlHandle, CURLOPT_POST, TRUE); //set how many paramaters to post curl_setopt($curlHandle, CURLOPT_URL, $url); //set the url we want to use curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $payload); curl_exec($curlHandle); //execute and get the results curl_close($curlHandle); // Don't forget to close the connection

As normal, we start with curl_init() to initialise the session, this is assigned to $curlHandle to make it easy later on.

We next need to set up our CURL options for the session. First we set a useragent. This is done as some servers will reject requests where no useragent is set. We use a standard Mozilla/windows useragent but anything could be set here.

As we need to send the via with POST, we set POST to true.

The URL we are going to use for the session will be our Slack Web Hook, we set this earlier to $url so this is what we will use.

The contents of our POST is set with CURLOPT_POSTFIELDS, we pass this into the option with $payload.

Finally, we execute the CURL session and close our connection.

We are done.

Step 7: Upload and set up CRON job.

Now all you need to do is upload this to a server and set up your CRON job. This will run the completed PHP file for every period of time you set for the CRON.

This is something you will have to figure out on your own, CRON settings varie depending on web host and server set up. Although on most web hosts this is fairly easy and your host should provide documents on how to do this.

To test the file you can either break your website, change the != to == in the if statement inside the foreach loop or add a domain which does not exist to your $domains array.

The output of the Slack bot should look like this.





Conclusion:

Hopefully we have learned two things:

Slack is super powerful and can be extended to do a lot more than share cat videos with each other in the office. API's really arn't as hard to play with as they first seem.

I hope you go and use the code and extend it further to include more and more information. If you code something cool feel free to share it in the comments below!

Here is the completed code:

<?php function slack($domain){ $msg = "Website Alert: <".$domain."|".$domain."> might be down."; $url = "https://hooks.slack.com/YOUR-COMPLETE-HOOK-URL-HERE"; $payload = 'payload={"username": "Problem Alert!", "text": "'.$msg.'", "icon_emoji": ":rotating_light:"}'; $curlHandle = curl_init(); curl_setopt($curlHandle, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"); //set our user agent curl_setopt($curlHandle, CURLOPT_POST, TRUE); //set how many paramaters to post curl_setopt($curlHandle, CURLOPT_URL, $url); //set the url we want to use curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $payload); curl_exec($curlHandle); //execute and get the results curl_close($curlHandle); // Don't forget to close the connection } function getstatus($domain){ $curlHandle = curl_init(); curl_setopt($curlHandle, CURLOPT_URL, $domain); //set our $domain as the url curl_setopt($curlHandle, CURLOPT_HEADER, true); //we want header data curl_setopt($curlHandle, CURLOPT_NOBODY , true); // we don't need body curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); //return the raw transfer curl_exec($curlHandle); //execute cURL $response = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE); //get http status from response, set to $response curl_close($curlHandle); // Don't forget to close the connection //return http status return $response; } $domains = array( "mywebsite.com" ); foreach($domains as $domain){ //send domain to getstatus() function and assign result to $status $status = getstatus($domain); //check status for errors if (($status != 200) && ($status != 301) && ($status != 302)){ //if there is an error, send to our slack function slack($domain); } } ?>

Share This Post

Users Who Have Downloaded More RAM:

August R. Garcia (1 year ago)

Huevos Rancheros (1 year ago) 🐏 ⨉ 2 Posted by Hash Brown 1 year ago 🕓 Posted at 09 December, 2018 01:16 AM PST

Read More: