Using Discord as a Notification System: Sending Notifications with Curl

2023-03-25

Discord is a popular communication platform that is popular with gamers, but has gained a lot of traction among homelab users and software engineers in recent years. It offers a variety of features, including voice and video calls, chat rooms, and the ability to integrate with other applications. One of the most useful features of Discord is the ability to send notifications for important events, such as server downtime, software updates, or log errors via webhooks. Discord’s webhooks provide an easy, low-effort way to send messages to Discord channels without adding a bot user or authentication.

I have setup a discord server for my homelab and have been leveraging Discord’s webhooks for years now. Discord’s webhooks have given me an easy way to get alearts from various scripts and monitoring process that are running in my lab.

In this blog post, we’ll explore how to send notifications to Discord using the command-line tool curl, later we’ll extend what we can post with curl with JSON. If you’re not familiar with these tools, don’t worry - we’ll explain everything step by step. By the end of this post, you’ll be able to send customized notifications to your Discord channels and integrate them with your homelab or other software projects. We will not be covering how to set up a Discord server in this post or how to create a Discord account.

So, whether you’re a homelab enthusiast looking to automate your notifications, or a software engineer building integrations with Discord, read on to learn how to send notifications to Discord using curl!

1. Setting up a Discord Webhook

The first step to using Discord as a notification system is setting up a webhook. A webhook is a way for an application to send data to a third-party application. In this case, we’ll use a webhook to send notifications to Discord. Here’s how to set up a Discord webhook:

  • Open Discord and go to the server or channel where you want to receive notifications.
  • Click on the server or channel settings and select Integrations.
  • Click on the “Create Webhook” button.
  • Give your webhook a name and select the channel you want to receive notifications in.
  • Copy the webhook URL.

Note: If you are not able to create webhooks for the channel or server, you might not have permissions for it in discord. I am an admin in both servers that I tested these in.

2. Sending Notifications to Discord with Curl

What is Curl?

Curl is a command-line tool that allows you to send HTTP requests and receive responses from web servers. It’s a powerful tool that can be used for a variety of tasks, such as testing APIs, downloading files, and sending notifications. Curl comes preinstalled with some Linux distributions, you can check that it is installed by running curl --version. If it’s not installed you can install it from your package manager, apt isntall curl, dnf insatll curl or yum install curl for example. For more info, have a look at curl’s man page

Sending Notifications to Discord

Now that we have a webhook URL, we can start sending notifications to Discord. To send a notification to a Discord channel using curl, we need to use the webhook URL we created earlier. In case you’ve forgotten or didn’t make note of it. You can always retreive your webhook url, from the same place you created it.

Here’s an example of a simple curl command to send a message to a Discord channel:

  • Open your terminal or command prompt.
  • Type the following command, replacing “YOUR_WEBHOOK_URL” with the webhook URL we created earlier:

NOTE:
For testing sake, you can export your YOUR_WEBHOOK_URL so you don’t have to retype or paste the whole thing each time. export WEB_HOOK_URL="https://discord.com/api/webhooks/<WEBHOOK_ID>/<WEBHOOK_TOKEN>", to reuse, in curl change YOUR_WEBHOOK_URL to $YOUR_WEBHOOK_URL This will only remain until you sign out of your terminal session. Baeldung has a fair write up on export here. If you’re new to bash, I started with the bash guide for beginners from The Linux Documentation Project. It is dated, but served as a good starting ground for me. This is just a helpful hint! Not a requirement, the remainder of this post will show the full webook url as https://discord.com/api/webhooks/<WEBHOOK_ID>/<WEBHOOK_TOKEN>

curl -X POST -H "Content-Type: application/json" -d '{"content": "Hello, world!"}' https://discord.com/api/webhooks/<WEBHOOK_ID>/<WEBHOOK_TOKEN>

Here, curl sends a POST request to the Discord API with the message “Hello, world!” as the content. The <WEBHOOK_ID> and <WEBHOOK_TOKEN> parameters are specific to your Discord channel and webhook. You can find these parameters by going to your Discord channel settings and creating a new webhook.

Try it out!

NOTE: When learning new code, it’s always better to type it out rather than copy and paste!

Type out the above curl command in your terminal and press enter. Within a few moments you should see your hello world alert in Discord!

  • If you don’t see your alert, double check YOUR_WEBHOOK_URL or try adding -v to curl for more verbose output.

Congratulations! You’ve just sent a notification to Discord with curl. That is just a basic example, lets see about customizing our notifications.

3. Customizing Our Notifications

The notification we just send was a simple message that said “Hello, world!” Just enough to prove to us that it we have a basic workign concept. Now that we know how to send a basic Discord notification using curl, let’s take a look at some ways we can customize our notification.

Here are some options that you can add to your curl command to customize your notification:

  • username: Sets the username that will appear as the sender of the message.
  • avatar_url: Sets the avatar that will appear next to the username.
  • embeds: Allows you to send a rich embed with additional information, such as a title, description, and thumbnail image.

Here’s an example of a curl command that includes these options:

curl -X POST -H "Content-Type: application/json" -d '{
    "content": "Hello, world!",
    "username": "My Bot",
    "avatar_url": "https://example.com/avatar.png",
    "embeds": [
        {
            "title": "New Message",
            "description": "There's a new message in the chat room!",
            "color": 16711680 // Colors are in decimal format
        }
    ]
}' https://discord.com/api/webhooks/<WEBHOOK_ID>/<WEBHOOK_TOKEN>

This command sends a notification with a customized username, avatar, and embed. The embeds parameter is an array of embed objects, each of which can include a title, description, color, and other options. A full list of embed parameters can be found on Discord’s Developer Documentation

Try it out!

Now that we’ve learned how to send a basic Discord notification using curl and how to customize it, it’s time to try it out for yourself!

Follow these steps to send a test notification to your Discord channel:

  • Create a new webhook in your Discord channel settings.
  • Copy the webhook URL and replace <WEBHOOK_ID> and <WEBHOOK_TOKEN> in the curl command with the corresponding values.
  • Open a terminal window and type out the curl command.
  • Press enter and check your Discord channel for the notification.

Congratulations, you’ve just sent your second Discord notification with curl! In the next section, we’ll take a look at how to send notifications using JSON, which will allow us to send more complex data to Discord.

Section 4: Notifications with external JSON file

The previous notifications work well as a one off alert, but what if we want to extend up those? Maybe our app already outputs errors in JSON format, or maybe we want our curl commands to look less ugly. Using an external JSON file allows for more customizations in our notification post.

What is JSON?

JSON, which stands for JavaScript Object Notation, is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It’s commonly used for data exchange between web servers and client applications. I like to think of it as an array of key value pairs.

Sending a Notification Discord with Curl and an External JSON file

Sending a JSON payload to Discord with curl is useful for sending notifications with more complex data. However, writing the JSON payload directly into the curl command can become unwieldy and difficult to read. To simplify the process, we can use an external JSON file and pass it as an argument to the curl command.

To start, create a JSON file with the content you want to send as the notification. For example, we will create a file called notification.json with the following content:

{
    "username": "John Doe",
    "avatar_url": "https://example.com/avatar.jpg",
    "content": "This is a notification sent from a JSON file!"
}
  • Save this file to your home or current working directory
  • Open your terminal and run thefollowing command:
curl -X POST -H "Content-Type: application/json" -d @./notifications.json https://discord.com/api/webhooks/<WEBHOOK_ID>/<WEBHOOK_TOKEN>

This command sends a notification with the username “My Bot” and the message “Hello, world!” to the specified webhook.

The -d parameter specifies that we’re sending data with the curl command, and the @ symbol indicates that we’re passing a file as the data. The ./ before the file name specifies the path to the file, in this case, the current working directory.

By using an external JSON file as the payload, you can easily update the content of the notification without having to modify the curl command every time. Additionally, this approach can be useful when you have more complex JSON payloads that are easier to manage in a separate file. Plus we can make our notifications look pretty with images and colors!

Parameters for the JSON Payload

Here are some parameters that you can include in your JSON payload to customize your Discord notification:

  • content (required): The content of the notification. This can be a string or an embed object (see below for more information on embeds).
  • username: The username of the bot or user sending the notification.
  • avatar_url: The URL of the image to use as the avatar of the bot or user sending the notification.
  • tts: A boolean value indicating whether the notification should be sent as text-to-speech.
  • embeds: An array of embed objects. Embeds allow you to send richer content with more customization options, such as titles, descriptions, images, and more. You can include up to 10 embeds in a single webhook request.

Here’s an example JSON payload that includes all of these options:

{
    "content": "This is a notification with an embed!",
    "username": "MyBot",
    "avatar_url": "https://example.com/mybot-avatar.jpg",
    "tts": false,
    "embeds": [
        {
            "title": "My Embed Title",
            "description": "This is my embed description.",
            "url": "https://example.com",
            "color": 16711680, // hex color code in decimal format
            "author": {
                "name": "Author Name",
                "url": "https://example.com/author",
                "icon_url": "https://example.com/author-icon.jpg"
            },
            "fields": [
                {
                    "name": "Field Name",
                    "value": "Field Value",
                    "inline": true
                },
                {
                    "name": "Another Field",
                    "value": "Another Value",
                    "inline": false
                }
            ],
            "image": {
                "url": "https://example.com/image.jpg"
            },
            "thumbnail": {
                "url": "https://example.com/thumbnail.jpg"
            },
            "footer": {
                "text": "My Embed Footer"
            },
            "timestamp": "2023-03-25T12:34:56.000Z"
        }
    ]
}

Note that some of these options are optional and can be omitted if not needed. Also, some options have specific formats or limitations, such as the color option for embeds which must be a decimal representation of a hex color code.

Try it out!

Now that we’ve learned how to send a notification with curl and a JSON file, it’s time to try it out for yourself!

Follow these steps to send a test notification to your Discord channel:

  • Create a new webhook in your Discord channel settings.
  • Copy the webhook URL and replace <WEBHOOK_ID> and <WEBHOOK_TOKEN> in the curl command with the corresponding values.
  • Open a text editor and create a new file with the JSON payload.
  • Save the file as notifications.json in your home or current working directory.
  • Open a terminal window and type out the curl command.
  • Press enter and check your Discord channel for the notification.

Congratulations, you’ve just sent a Discord notification using curl and a JSON file!

5. Wrapping Up

In this tutorial, we’ve covered how to use Discord as a notification system and send notifications to Discord with curl. By setting up a webhook and using curl to send requests, you can easily integrate Discord into your workflow and receive notifications in real-time. We’ve learned how to create a JSON payload file with customized parameters, and pass it as an argument to the curl command. By using an external file, we can simplify the process of sending notifications with complex data. With the ability to customize your notifications, you can tailor them to your specific needs and make the most of this powerful notification platform.

Overall, the Discord API provides a flexible and easy-to-use way to integrate notifications into your homelab or software engineering projects. By leveraging the power of curl and JSON, you can quickly and easily send notifications to Discord, keeping you informed and in control. For further reading on Discord’s webhooks, Discord has some great documentation.


Enter your instance's address


More posts like this

Homelab

2023-03-15 | #blog #homelab #linux #personal

Motivation My primary motivation for starting a homelab was to back up photo’s from my wife’s and my phones. We each had our photo’s already set to back up to google drive, but our 15Gb of free storage quickly ran out.

Continue reading 