On August 26, 2018 In Blog, Tech, Tutorials

Sending Linux Variables to Discord Webhook from Linux Bash Shell Script

Sending Linux Variables to Discord Webhook from Linux Bash Shell Script

Discord provides an API where you can send messages/notifications via their webhook using curl . Which is all very helpful, except the code provided on their website only allows plain text, you can’t pass $variables onto it

Having started playing with Linux Bash scripts, it may seem natural or easy to the Linux veterans, definitely not for me

So after some research over at StackOverflow and self-test. Here is the code that will work when $variables are passed to it

#!/bin/bash
message="$1"
## format to parse to curl
## echo Sending message: $message
msg_content=\"$message\"

## discord webhook
url='https://replace-your-full-discord-webhoook-url-here'
curl -H "Content-Type: application/json" -X POST -d "{\"content\": $msg_content}" $url

How to use

Assuming you already know the basics of basics in Linux bash scripting, you will need to save that code above in a “.sh” file. Eg: discord-notify.sh

Anyhow, for users of all experience ranging from complete beginners to somewhat experienced Linux users

Here are the complete steps:

  1. SSH/Login/Open your Linux Terminal
  2. We will save the discord-notify.sh onto your user $HOME folder
    cd $HOME
    nano discord-notify.sh
  3. Paste in the code above, modify and paste your Discord webhook URL for $url variable
  4. Save the file by pressing Ctrl+X, answer the questions when asked
  5. Make discord-notify.sh executable
    chmod +x discord-notify.sh
  6. Prepare a variable for testing
    testdate="Text with whitespace and variable $(date +%T)"
  7. Test send a notification to your Discord Server/Channel
    ./discord-notify.sh "$testdate"

    Make sure you have the double quotes around your variable that you wish to send

And that’s it.

discord-notify.sh

discord-notify.sh

Note if you don’t double quote your $testdate variable, only “Text” get’s sent as shown on screenshot above

I’ll leave it to you on how you want to modify the code above to become a function to use in your scripts, or just call the discord-notify.sh script from another script

Eg:

#!/bin/bash
## This is "changetheworld-super-script.sh" Your almighty script
# Make a call to the discord-notify.sh script located in $HOME
$HOME/discord-notify.sh "$heal_the_world"

As there is no one “correct” way to program/script, appreciate it if you could share your version of code that worked for you, or share something even better!

Leave a comment if it helped 🙂

Scroll Up