How To Use Discord Webhooks to Get Notifications for Your Website Status on Ubuntu 18.04

The author selected the Apache Software Foundation to receive a donation as part of the Write for DOnations program.

Introduction

When you have critical websites you’ll want to know when they are experiencing any issues so you can fix them before there’s an impact on your users. One way to receive notifications is to set up alerts through a text-based chat system.

Discord is a hosted chat system similar to Slack. With Discord, you can set up a free messaging system that lets you communicate with text messages, images, audio, and video. While it offers premium features, you can sign up for free, and it has clients available for Windows, macOS, Linux, Android, and iOS.

In this tutorial, you will configure your own Discord server, create a Discord webhook, write a Bash script that will check the status of a list of websites, and test notifications from your server to your Discord channel.

Prerequisites

Before you begin this guide you’ll need the following:

Step 1 — Setting Up Your Discord Webhook

Once you have opened your Discord account you can create your own private Discord server.

First, log in to your Discord account in your browser or launch your Discord app and click on the Create a server button.

Create server or Join server Discord

Then pick a name for your server and click on the Create a server button.

Next, you will configure your Discord webhook. The webhooks are unique URLs that you can use to link services together. Discord’s webhooks allow you to automate your messages and send data updates to your Discord text channels.

In this tutorial, you will send a notification to your webhook when a specific service on your server goes down, and Discord will make sure that you get those messages on your channel.

To create a webhook you have to first click on your channel and then click on the Edit Channel button right next to your channel’s name.

Channel settings Discord

Then click on the Webhooks tab and click the Create Webhook button.

Create Webhook Button Discord

After that, pick a name for your webhook, in this tutorial we’ll use Alerts as this is what our Bash script will do—alert us in the case that one of our websites goes down.

Copy your webhook URL and save it for later. Finally, click the Save button.

Create webhook Discord

You now have your Discord account, server, and webhook. You can now move on to create a test file for your script to monitor.

Step 2 — Creating a Test File (Optional)

If you don’t have your own website to test already, complete this step to add a test file to check how your monitoring script will work. Make sure to run these commands on your apache-server.

First, create the test file with the following command:

  • nano /var/www/your_domain/test

Add some content to your file, so you can check it’s working:

test
test

Save and exit the file.

Now navigate to http://your_domain/test in your browser to make sure you can receive the text in the test file.

In the next step, you’ll start to build your monitoring script.

Step 3 — Creating Your Monitoring Script

Now that you’ve configured your webhook, you’ll go ahead and create your Bash script that will check the response code of your websites. In the event that any of the websites returns a status different from 200 OK, your script will send a request to the Discord webhook so you will receive a notification in your Discord channel.

Note: You could use any other programming language to build a script like this.

First SSH in to your monitor-server that you’re using to run your monitoring script.

Start by creating a file in your home folder. We’ll call the file check_status.sh in this tutorial.

With your favorite text editor open the file:

  • nano ~/check_status.sh

For the program loader to recognize this executable file as a Bash script, add the following line to the top of the file:

~/check_status.sh
#!/bin/bash

All lines starting with a # are a comment. The comments are optional, but having comments in your script will make it easier for other people to understand what the script does:

~/check_status.sh
#!/bin/bash

##
# Website status check script
# Author: Your Name
# Date: 01/01/2020
##
. . .

Next, specify your Discord webhook as a variable. Add the URL you copied earlier for your webhook:

~/check_status.sh
. . .
##
# Discord webhook
# Change the 'your_discord_webhook_name' with your actual Discord Webhook
##
url="your_discord_webhook_name"
. . .

As you’ll possibly use this script to check the status of multiple websites, make a variable called websites_list and store the domain names or IP addresses of the websites that you want to monitor. If you’re using the optional test file in this tutorial, make sure to add /test after your domain name or IP address:

~/check_status.sh
. . .
##
# List of websites to check
##
websites_list="your_domain/test"
. . .

In the case that you are monitoring more than one website, you can add more domain names or IP addresses to the websites_list variable and use space as a separator:

~/check_status.sh
. . .
websites_list="your_domain1/test your_domain2 your_domain3"
. . .

Now you’ll want to loop through the list of websites and check their status. To do so add the following for loop to your file:

~/check_status.sh
. . .
for website in ${websites_list} ; do
        status_code=$(curl --write-out %{http_code} --silent --output /dev/null -L ${website})
        echo $status_code
done
. . .

This for loop will go through each item in the websites_list variable and check the status of the website with the curl command.

The echo $status_code statement will print out the response status of the curl command. If the website is running as expected the curl command will return a response code 200 OK, meaning that the website is up and running. Otherwise you’ll receive another response code.

Inside the for loop, add an if statement to check if the response code is 200 or not. If the response code is 200 then this means that the website is running and you wouldn’t need a Discord notification. Add the following conditional block to your file:

~/check_status.sh
. . .
        if [[ "$status_code" -ne 200 ]] ; then
            # POST request to Discord Webhook with the domain name and the HTTP status code
        else
            echo "${website} is running!"
        fi
. . .

If there are any problems with the website then you’ll get a different response code, in this event you’ll want to receive a notification via your Discord webhook.

To send the notification you can use the curl command to submit a POST request to the Discord webhook URL.

Add the following curl request inside your if statement:

~/check_status.sh
. . .
        if [[ "$status_code" -ne 200 ]] ; then
            # POST request to Discord Webhook with the domain name and the HTTP status code
            curl -H "Content-Type: application/json" -X POST -d '{"content":"'"${domain} returned: ${status_code}"'"}'  $url
        else
            echo "${website} is running!"
        fi
. . .

Now let’s examine the different arguments:

  • -H: Tells curl that you want to add an extra header in your request.
  • "Content-Type: application/json": Defines the data type the webhook should expect (HTTP JSON).
  • -X POST: Specifies that you want to use a POST as the request method.
  • -d: Sends the specified JSON data to the Discord Webhook.

This will be the final version of your script:

~/check_status.sh
#!/bin/bash
##
# Website status check script
# Author: Your Name
# Date: 01/01/2020
##

##
# Discord webhook
# Change the 'your_discord_webhook_name' with your actual Discord Webhook
##
url="your_discord_webhook_name"

##
# List of websites to check
# To add more websites just use space as a separator, for example:
# websites_list="your_domain1 your_domain2 your_domain3"
##
websites_list="your_domain/test your_domain2"

for website in ${websites_list} ; do
        status_code=$(curl --write-out %{http_code} --silent --output /dev/null -L ${website})

        if [[ "$status_code" -ne 200 ]] ; then
            # POST request to Discord Webhook with the domain name and the HTTP status code
            curl -H "Content-Type: application/json" -X POST -d '{"content":"'"${domain} : ${status_code}"'"}'  $url
        else
            echo "${website} is running!"
        fi
done

The script will loop through this list and check the status for each website.

Run the script with the following command to make sure that it works as expected:

  • bash ~/check_status.sh

After running the script, you will receive the following output in your terminal confirming that your website is running:

Output
your_domain1 is running! your_domain2 is running!

Next, you’ll test your Discord notifications.

Step 4 — Testing Your Discord Notifications

Now it’s time to check if your webhooks are working as expected by using the test file.

On the apache-server run the following command to close down access permissions to this file:

  • sudo chmod 000 /var/www/your_domain/test

Next, return to your monitor-server and run the script:

  • bash check_status.sh

Move to your Discord app and check your alerts, you’ll receive a :403 error. This shows that you do not have the permissions set correctly and are forbidden from viewing the file.

Now, to test a different error, remove this file entirely from your apache-server:

  • sudo rm /var/www/your_domain/test

Next, return to your monitor-server and run the script:

  • bash check_status.sh

Move to your Discord app and check your alerts, you’ll receive a :404 error. This shows that the file is unavailable.

If you have Discord installed on your phone you’ll receive alerts there as well.

You now have a script that alerts you when your websites are experiencing any issues. Let’s next configure the script to run automatically every five minutes.

Step 5 — Automating the Process

One of the ways to automate the checks is to create a cron job that will run every 5 minutes or so.

First, go back to your monitor-server. Then before you can run the script automatically, you need to sort out your file permissions and make sure that the script is executable, otherwise, it will not run. To make the script executable run:

  • chmod u+x ~/check_status.sh

Run the following to edit your crontab:

  • crontab -e

Then add the following to the file:

*/5 * * * * /home/your_user/check_status.sh

Then save the crontab and your script will then execute every 5 minutes.

Conclusion

In this article, you configured your own Discord webhook and created a script to notify you in case a specific error occurs on your website. Now you can use your favorite programming language and write a more complex bot.

To learn more about setting up monitoring infrastructure, check out our Monitoring topic page.

And, if you are interested in learning more about shell scripting, check out our Introduction to Shell Scripting tutorial series.

To learn more about Discord webhooks, you can check the official Discord Webhooks documentation.

Originally posted on DigitalOcean Community Tutorials
Author: Bobby Iliev

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *