One place for hosting & domains

      Discord

      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:

      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:

      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:

      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:

      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:

      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.



      Source link

      How To Build a Discord Bot with Node.js


      The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Discord is a chat application that allows millions of users across the globe to message and voice chat online in communities called guilds or servers. Discord also provides an extensive API that developers can use to build powerful Discord bots. Bots can perform various actions such as sending messages to servers, DM-ing users, moderating servers, and playing audio in voice chats. This allows developers to craft powerful bots that include advanced, complex features like moderation tools or even games. For example, the utility bot Dyno serves millions of guilds and contains useful features such as spam protection, a music player, and other utility functions. Learning how to create Discord bots allows you to implement many possibilities, which thousands of people could interact with every day.

      In this tutorial, you will build a Discord bot from scratch, using Node.js and the Discord.js library, which allows users to directly interact with the Discord API. You’ll set up a profile for a Discord bot, get authentication tokens for the bot, and program the bot with the ability to process commands, with arguments, from users.

      Prerequisites

      Before you get started, you will need the following:

      Step 1 — Setting Up a Discord Bot

      In this step, you’ll use the Discord developers GUI to set up a Discord bot and get the bot’s token, which you will pass into your program.

      In order to register a bot on the Discord platform, use the Discord application dashboard. Here developers can create Discord applications including Discord bots.

      Image of the Discord application dashboard after first visiting https://discord.com/developers/applications

      To get started, click New Application. Discord will ask you to enter a name for your new application. Then click Create to create the application.

      Image of the prompt to create an application, with

      Note: The name for your application is independent from the name of the bot, and the bot doesn’t have to have the same name as the application.

      Now open up your application dashboard. To add a bot to the application, navigate to the Bot tab on the navigation bar to the left.

      Image of the bot tab of the application dashboard

      Click the Add Bot button to add a bot to the application. Click the Yes, do it! button when it prompts you for confirmation. You will then be on a dashboard containing details of your bot’s name, authentication token, and profile picture.

      Dashboard containing details of your bot

      You can modify your bot’s name or profile picture here on the dashboard. You also need to copy the bot’s authentication token by clicking Click to Reveal Token and copying the token that appears.

      Warning: Never share or upload your bot token as it allows anyone to log in to your bot.

      Now you need to create an invite that allows you to add the bot Discord guilds where you can test the bot. First, navigate to the OAuth2 tab of the application dashboard. To create an invite, scroll down and select bot under scopes. You must also set permissions to control what actions your bot can perform in guilds. For the purposes of this tutorial, select Administrator, which will give your bot permission to perform nearly all actions in guilds. Copy the link with the Copy button.

      OAuth2 tab, with scope set to

      Next, add the bot to a server. Follow the invite link you just created. You can add the bot to any server you own, or have administrator permissions in, from the drop-down menu.

      Page from following the invite link, allowing users to add the bot to servers

      Now click Continue. Ensure you have the tickbox next to Administrator ticked—this will grant the bot administrator permissions. Then click Authorize. Discord will ask you to solve a CAPTCHA before the bot joins the server. You’ll now have the Discord bot on the members list in the server you added the bot to under offline.

      Members list of a Discord server with the newly created bot under the

      You’ve successfully created a Discord bot and added it to a server. Next, you will write a program to log in to the bot.

      Step 2 — Creating Your Project

      In this step, you’ll set up the basic coding environment where you will build your bot and log in to the bot programmatically.

      First, you need to set up a project folder and necessary project files for the bot.

      Create your project folder:

      Move into the project folder you just created:

      Next, use your text editor to create a file named config.json to store your bot’s authentication token:

      Then add the following code to the config file, replacing the highlighted text with your bot’s authentication token:

      config.json

      {
          "BOT_TOKEN": "YOUR BOT TOKEN"
      }
      

      Save and exit the file.

      Next you’ll create a package.json file, which will store details of your project and information about the dependencies you’ll use for the project. You’ll create a package.json file by running the following npm command:

      npm will ask you for various details about your project. If you would like guidance on completing these prompts, you can read about them in How To Use Node.js Modules with npm and package.json.

      You’ll now install the discord.js package that you will use to interact with the Discord API. You can install discord.js through npm with the following command:

      Now you’ve set up the configuration file and installed the necessary dependency, you’re ready to begin building your bot. In a real-world application, a large bot would be split across many files, but for the purposes of this tutorial, the code for your bot will be in one file.

      First, create a file named index.js in the discord-bot folder for the code:

      Begin coding the bot by requiring the discord.js dependency and the config file with the bot’s token:

      index.js

      const Discord = require("discord.js");
      const config = require("./config.json");
      

      Following this, add the next two lines of code:

      index.js

      ...
      const client = new Discord.Client();
      
      client.login(config.BOT_TOKEN);
      

      Save and exit your file.

      The first line of code creates a new Discord.Client and assigns it to the constant client. This client is partly how you will interact with the Discord API and how Discord will notify you of events such as new messages. The client, in effect, represents the Discord bot.

      The second line of code uses the login method on the client to log in to the Discord bot you created, using the token in the config.json file as a password. The token lets the Discord API know which bot the program is for and that you’re authenticated to use the bot.

      Now, execute the index.js file using Node:

      Your bot’s status will change to online in the Discord server you added it to.

      Image of the bot online

      You’ve successfully set up a coding environment and created the basic code for logging in to a Discord bot. In the next step you’ll handle user commands and get your bot to perform actions, such as sending messages.

      Step 3 — Handling Your First User Command

      In this step, you will create a bot that can handle user commands. You will implement your first command ping, which will respond with "pong" and the time taken to respond to the command.

      First, you need to detect and receive any messages users send so you can process any commands. Using the on method on the Discord client, Discord will send you a notification about new events. The on method takes two arguments: the name of an event to wait for and a function to run every time that event occurs. With this method you can wait for the event message—this will occur every time a message is sent to a guild where the bot has permission to view messages. Therefore let’s create a function, which runs every time a message is sent, to process commands.

      First open your file:

      Add the following code to your file:

      index.js

      ...
      const client = new Discord.Client();
      
      
      client.on("message", function(message) { 
                                               
      });                                      
      
      client.login(config.BOT_TOKEN);
      

      This function, which runs on the message event, takes message as a parameter. message will have the value of a Discord.js message instance, which contains information about the sent message and methods to help the bot respond.

      Now add the following line of code to your command-handling function:

      index.js

      ...
      client.on("message", function(message) {
        if (message.author.bot) return;
      });
      ...
      

      This line checks if the author of the message is a bot, and if so, stops processing the command. This is important as generally you don’t want to process, or respond to, bots’ messages. Bots usually don’t need to, or want to, be using our bot, so ignoring their messages saves processing power and helps prevent accidental replies.

      Now you’ll write a command handler. To accomplish this, it’s good to understand the usual format of a Discord command. Typically, the structure of a Discord command contains three parts in the following order: a prefix, a command name, and (sometimes) command arguments.

      An image of a typical Discord command reading

      • Prefix: the prefix can be anything, but is typically a piece of punctuation or abstract phrase that wouldn’t normally be at the start of a message. This means that when you include the prefix at the start of the message, the bot will know that the intention for this command is for a bot to process it.

      • Command name: The name of the command the user wants to use. This means the bot can support multiple commands with different functionality and allow users to choose between them by supplying a different command name.

      • Arguments: Sometimes if the command requires or uses extra information from the user, the user can supply arguments after the command name, with each argument separated by a space.

      Note: There is no enforced command structure and bots can process commands how they like, but the structure presented here is an efficient structure that the vast majority of bots use.

      To begin creating a command parser that handles this format, add the following lines of code to the message handling function:

      index.js

      ...
      const prefix = "!";
      
      client.on("message", function(message) {
        if (message.author.bot) return;
        if (!message.content.startsWith(prefix)) return;
      });
      ...
      

      You add the first line of code to assign the value "!" to the constant prefix, which you will use as the bot’s prefix.

      The second line of code you add checks if the content of the message the bot is processing begins with the prefix you set, and if it doesn’t, stops the message from continuing to process.

      Now you must convert the rest of the message into a command name and any arguments that may exist in the message. Add the following highlighted lines:

      index.js

      ...
      client.on("message", function(message) {
        if (message.author.bot) return;
        if (!message.content.startsWith(prefix)) return;
      
        const commandBody = message.content.slice(prefix.length);
        const args = commandBody.split(' ');
        const command = args.shift().toLowerCase();
      });
      ...
      

      You use the first line here to remove the prefix from the message content and assign the result to the constant commandBody. This is necessary as you don’t want to include the prefix in the parsed command name.

      The second line takes the message with the removed prefix and uses the split method on it, with a space as the separator. This splits it into an array of sub-strings, making a split wherever there is a space. This results in an array containing the command name then, if included in the message, any arguments. You assign this array to the constant args.

      The third line removes the first element from the args array (which will be the command name provided), converts it to lowercase, and then assigns it to the constant command. This allows you to isolate the command name and leave only arguments in the array. You also use the method toLowerCase as commands are typically case insensitive in Discord bots.

      You’ve completed building a command parser, implementing a required prefix, and getting the command name and any arguments from messages. You will now implement and create the code for the specific commands.

      Add the following code to start implementing the ping command:

      index.js

      ...
        const args = commandBody.split(' ');
        const command = args.shift().toLowerCase();
      
        if (command === "ping") {
                                 
        }                        
      });
      ...
      

      This if statement checks if the command name you parsed (assigned to the constant command) matches "ping". If it does, that indicates the user wants to use the "ping" command. You will nest the code for the specific command inside the if statement block. You will repeat this pattern for other commands you want to implement.

      Now, you can implement the code for the "ping" command:

      index.js

      ...
        if (command === "ping") {
          const timeTaken = Date.now() - message.createdTimestamp;
          message.reply(`Pong! This message had a latency of ${timeTaken}ms.`);
        }
      ...
      

      Save and exit your file.

      You add the "ping" command block that calculates the difference between the current time—found using the now method on the Date object—and the timestamp when the message was created in milliseconds. This calculates how long the message took to process and the "ping" of the bot.

      The second line responds to user’s command using the reply method on the message constant. The reply method pings (which notifies the user and highlights the message for the specified user) the user who invoked the command, followed by the content provided as the first argument to the method. You provide a template literal containing a message and the calculated ping as the response that the reply method will use.

      This concludes implementing the "ping" command.

      Run your bot using the following command (in the same folder as index.js):

      You can now use the command "!ping" in any channel the bot can view and message in, resulting in a response.

      Image of bot replying in Discord to

      You have successfully created a bot that can handle user commands and you have implemented your first command. In the next step, you will continue developing your bot by implementing a sum command.

      Step 4 — Implementing the Sum Command

      Now you will extend your program by implementing the "!sum" command. The command will take any number of arguments and add them together, before returning the sum of all the arguments to the user.

      If your Discord bot is still running, you can stop its process with CTRL + C.

      Open your index.js file again:

      To begin implementing the "!sum" command you will use an else-if block. After checking for the ping command name, it will check if the command name is equal to "sum". We use an else-if block since only one command will process at a time, so if the program matches the command name "ping", it doesn’t have to check for the "sum" command. Add the following highlighted lines to your file:

      index.js

      ...
        if (command === "ping") {
          const timeTaken = Date.now() - message.createdTimestamp;
          message.reply(`Ping! This message had a latency of ${timeTaken}ms.`);
        }
      
        else if (command === "sum") {
                                     
        }                            
      });
      ...
      

      You can begin implementing the code for the "sum" command. The code for the "sum" command will go inside the else-if block you just created. Now, add the following code:

      index.js

      ...
        else if (command === "sum") {
          const numArgs = args.map(x => parseFloat(x));
          const sum = numArgs.reduce((counter, x) => counter += x);
          message.reply(`The sum of all the arguments you provided is ${sum}!`);
        }
      ...
      

      You use the map method on the arguments list to create a new list by using the parseFloat function on each item in the args array. This creates a new array (assigned to the constant numArgs) in which all of the items are numbers instead of strings. This means later you can successfully find the sum of the numbers by adding them together.

      The second line uses the reduce method on the constant numArgs providing a function that totals all the elements in the list. You assign the sum of all the elements in numArgs to the constant sum.

      You then use the reply method on the message object to reply to the user’s command with a template literal, which contains the sum of all the arguments the user sends to the bot.

      This concludes implementing the "sum" command. Now run the bot using the following command (in the same folder as index.js):

      You can now use the "!sum" command in any channel the bot can view and message in.

      Image of bot replying

      The following is a completed version of the index.js bot script:

      index.js

      const Discord = require("discord.js");
      const config = require("./config.json");
      
      const client = new Discord.Client();
      
      const prefix = "!";
      
      client.on("message", function(message) {
        if (message.author.bot) return;
        if (!message.content.startsWith(prefix)) return;
      
        const commandBody = message.content.slice(prefix.length);
        const args = commandBody.split(' ');
        const command = args.shift().toLowerCase();
      
        if (command === "ping") {
          const timeTaken = Date.now() - message.createdTimestamp;
          message.reply(`Pong! This message had a latency of ${timeTaken}ms.`);
        }
      
        else if (command === "sum") {
          const numArgs = args.map(x => parseFloat(x));
          const sum = numArgs.reduce((counter, x) => counter += x);
          message.reply(`The sum of all the arguments you provided is ${sum}!`);
        }
      });
      
      client.login(config.BOT_TOKEN);
      

      In this step, you have further developed your Discord bot by implementing the sum command.

      Conclusion

      You have successfully implemented a Discord bot that can handle multiple, different user commands and command arguments. If you want to expand on your bot, you could possibly implement more commands or try out more parts of the Discord API to craft a powerful Discord bot. You can review the Discord.js documentation or the Discord API documentation to expand your knowledge of the Discord API.

      While creating Discord bots, you must always keep in mind the Discord API terms of service, which outlines how developers must use the Discord API. You could also read this set of guidelines on how to best implement a Discord bot and provides tips on how to design Discord bots. If you would like learn more about Node.js check out our How To Code in Node.js series.



      Source link