Coder Social home page Coder Social logo

fieu / discord.sh Goto Github PK

View Code? Open in Web Editor NEW
487.0 14.0 70.0 205 KB

Write-only command-line Discord webhooks integration written in 100% Bash script

License: GNU General Public License v3.0

Shell 98.40% Makefile 1.60%
bash discord discord-webhook shell discord-webhooks webhook webhooks discord-bash discord-shell

discord.sh's Introduction

GitHub stars

Write-only command-line integration for Discord webhooks, written in 100% Bash script. Influenced heavily by slack-cli.

Table of Contents

Features

  • Create and send very customizable and beautiful Discord messages 🎉 ✨
  • Less than 400 lines of pure Bash 😎
  • Extremely lightweight ⚡ 🚀
  • Only requires curl and jq to run 🔥

Dependencies

  • bash (GNU Bourne-Again SHell)
  • bats (tests)
  • curl (http requests)
  • jq (JSON parsing)
  • base64 (webhook avatar modification)
  • file (MIME type retrieval for webhook avatar modification)

Usage

1. Setting up a Discord webhook.

  1. Setup a webhook in the desired Discord text channel
  2. Download (or clone) a copy of discord.sh
  3. Point discord.sh at a webhook endpoint (see below)
  4. Go nuts.

2. Specifying a Webhook URL within discord.sh

There are three ways to point discord.sh at a webhook endpoint, in order of priority that discord.sh takes:

  1. Pass the webhook URL as an argument to discord.sh using --webhook-url
  2. Set an environment variable called $DISCORD_WEBHOOK
  3. Create a file called .webhook in the same directory as discord.sh, containing only the webhook URL

3. Using the script

Simple chat example

$ ./discord.sh --webhook-url="$WEBHOOK" --text "Hello, world!"

Simple chat example with custom username and avatar

$ ./discord.sh \
  --webhook-url="$WEBHOOK" \
  --username "NotificationBot" \
  --avatar "https://i.imgur.com/12jyR5Q.png" \
  --text "Hello, world!"

Advanced chat example using an embed (using all possible options)

$ ./discord.sh \
  --webhook-url="$WEBHOOK" \
  --username "NotificationBot" \
  --avatar "https://i.imgur.com/12jyR5Q.png" \
  --text "Check out this embed!" \
  --title "New Notification!" \
  --description "This is a description\nPretty cool huh?" \
  --color "0xFFFFFF" \
  --url "https://github.com/fieu/discord.sh" \
  --author "discord.sh" \
  --author-url "https://github.com/fieu/discord.sh" \
  --author-icon "https://i.imgur.com/12jyR5Q.png" \
  --image "https://i.imgur.com/12jyR5Q.png" \
  --thumbnail "https://i.imgur.com/12jyR5Q.png" \
  --field "Author;ChaoticWeg" \
  --field "Author;fieu" \
  --footer "discord.sh" \
  --footer-icon "https://i.imgur.com/12jyR5Q.png" \
  --timestamp

Sending a file (up to 8MB, per Discord limitations)

Note: per the Discord webhook API, posts cannot contain embeds and file attachments. Therefore, discord.sh will bail out when trying to build a message with embeds and files. The best practice is to send the message with embeds before sending a file.

$ ./discord.sh \
  --webhook-url="$WEBHOOK" \
  --file README.md \
  --username "Notification Bot" \
  --text "Check out this README.md file!"

Options

--webhook-url <url>

This should be set to your Discord webhook URL. You may alternatively set the environment variable DISCORD_WEBHOOK to your Discord webhook URL and that way you don't have to pass in the webhook URL inline.

--text <string>

This is basic text like shown below.

--username <string>

You can override the username of the webhook "bot" with this flag.

--avatar <url>

You can override the avatar of the webhook "bot" with this flag.

--modify

You can permanently change the username and avatar of the webhook. The following options are valid: --username and --modify

Warning No other options may be passed, including those for sending messages.

Example

$ ./discord.sh \
  --modify \
  --username "NotifBot" \
  --avatar "https://i.imgur.com/12jyR5Q.png" 

Once executed, all other webhook messages by default will contain the username and avatar set.

Advanced Options

Now we're going to look at how to setup a custom embed message.

--title <string>

This option allows you to set the title of the embed.

--description <string>

This option allows you to set the description of the embed.

--color <string>

This option allows you to set color on the left of the embed.

Input Syntax 1: 0x + COLOR HEX

Input Syntax 2: COLOR DEC

Input Example 1: --color 0xFFFFFF

Input Example 2: --color 16777215

--url <url>

This option allows you to set the URL of the --title flag within the embed.

--author <string>

This option allows you to set the author name of the embed.

--author-url <url>

This option allows you to set the author URL of the --author flag within the embed.

--author-icon <url>

This option allows you to set the author icon that sits to the left of the --author flag within the embed.

--image <url>

This option allows you to set the image that sits within the embed.

--thumbnail <url>

This option allows you to set the thumbnail that sits to the right within the embed.

--field <name;value;inline>

This option allows you to add fields to your embed. You may use this option multiple times up to 25 times. Example usage:

$ ./discord.sh \
  --webhook-url="$WEBHOOK" \
  --username "System Status" \
  --description "Here are your system stats!" \
  --field "Hostname;localhost;false" \
  --field "CPU;95%" \
  --field "Disk Usage;120/512GB"

--footer <string>

This option allows you to set the thumbnail that sits to the right within the embed.

--footer-icon <url>

This option allows you to set the footer icon that sites to the right of the --footer flag within the embed.

--timestamp

This option allows you to define whether the timestamp is displayed on the embed message or not.

Tips

Proper character escaping

If you want to show the output of a file or stdin via discord.sh, and your file includes special characters such as backticks (`) and ", then you can't simply cat filename. You will need to properly escape special characters.

One of the easiest methods to output properly escaped text from a file is to use jq, cut, and rev

Prerequisites

  • jq - Character escaping
  • cut - Cut characters from string (part of coreutils, included by default on most systems)
  • rev - Reversing of characters (part of util-linux, included by default on most systems)

Usage (contents of file)

  1. Simply pass filename to the following command to escape the file contents to stdout:
jq -Rs . <filename | cut -c 2- | rev | cut -c 2- | rev

Usage (contents of stdin)

  1. Simply pipe stdin to the beginning of the following command to escape the contents to stdout:
cat `filename` | jq -Rs . | cut -c 2- | rev | cut -c 2- | rev

  1. Assuming filename or stdin contains the following contents when viewed in an editor such as vim or nano:
    ```php
    <?php echo "Hello, world!" ?>
    ```

    :smile:

    Bobs your uncle. !@#$%^&*()_}{":?><,./;'[]-=
  1. If you ran the command, the output would be:
```php\n<?php echo \"Hello, world!\" ?>\n```\n\n:smile:\n\nBobs your uncle. !@#$%^&*()_}{\":?><,./;'[]-=\n
  1. In order to use it in discord.sh, all we have to do is pass that command within a subshell.

  1. Usage (contents of file)
./discord.sh --webhook-url "$WEBHOOK_URL" --text "$(jq -Rs . <filename | cut -c 2- | rev | cut -c 2- | rev)"

  1. Usage (contents of stdin)
./discord.sh --webhook-url "$WEBHOOK_URL" --text "$(cat filename | jq -Rs . | cut -c 2- | rev | cut -c 2- | rev)"
  1. Result:

Screenshot

Usage (contents of stdin)

Simply pass filename to the following command to escape the file to stdout:

jq -Rs . <filename | cut -c 2- | rev | cut -c 2- | rev

Explanation

jq takes the file in as stdin then escapes it. We then pipe it to cut to remove the first 2 "indexes" meaning the first character which is a " that jq adds. We then pip that into rev to reverse the text as a whole, then pipe that into cut to remove the first 2 "indexes" or first (last) character which is once again a " that jq adds. Finally we re-reverse the text back to the standard order. The command will output to stdout

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

GPL-3.0

Made with 💖 by ChaoticWeg & fieu || Documentation and design by fieu and Matt

discord.sh's People

Contributors

chaoticweg avatar dayne avatar dependabot[bot] avatar dozn avatar fieu avatar keevan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

discord.sh's Issues

Include version number as comment in header

I think it would be a good idea to include the version number in the header in a comment.

A possible use-case would be that you have set up the script some time ago and now don't know which version it was or when it was done. This would then be helpful in case you want to update (which basically amounts to just downloading from the github releases but to know which version you had run is still important in case there are some breaking changes etc).

Another option might be to rename the release file to discord-X.Y.Z.sh.
Or introduce a --version CLI flag? (But the version can also be shown in the --help message.)

bash should be added as a dependency, for now

https://github.com/ChaoticWeg/discord.sh/blob/2f2c0f4c14b48474a6a360eb401c040016cfbedb/README.md?plain=1#L32-L36

I've tried running this on sh and there were a few bash specific things that stopped this from getting very far, namely

discord.sh: line 6: shopt: not found
discord.sh: line 7: shopt: not found
discord.sh: line 31: syntax error: bad substitution

There's probably many more that it hasn't reached yet but it might be easier to set the requirements to include bash.

Need usage guidelines webpage

  • Add a gh-pages branch with usage information, etc
  • Set it as the website for this repo (should end up being https://chaoticweg.cc/discord.sh)

Unable to add extra JSON values when attaching file

cURL doesn't correctly package and send the JSON payload when attaching a file.

Input

./discord.sh --file foo.txt \
    --username "FileBot" \
    --text "Here's a file!"

Expected

  • Content-Type: multipart/form-data
  • Username: FileBot
  • Text: Here's a file!
  • Attached file: foo.txt

Actual

  • Content-Type: multipart/form-data
  • Attached file: foo.txt

The url-encoded JSON passed to cURL gets lost in transit somehow.

Problems with --color

When trying to use --color with either hex or decimal I get the following error on. Is there a required argument when using --color?

My test argument
error! {
"embeds": [
"0"
]
}
attempted to send: {
"wait": true,
"content": "My test argument",
"avatar_url": "https://i.imgur.com/12jyR5Q.png",
"embeds": [
{
"": "",
"color": 16711682,
"timestamp": "2022-04-07T21:25:51+00:00",
"author": {
"": ""
},
"thumbnail": {},
"image": {
"": ""
},
"footer": {
"": ""
}
}
]
}

fatal: curl failed with code 3

Just tested your discord script and am getting an error code on curl.

This happens when using your example simple text.

Any suggestions?
Using your latest release.

Data Input factor on shell script

/opt/vc/bin/vcgencmd measure_temp >> /tmp/temp.log

tmp = /opt/vc/bin/vcgencmd measure_temp

./data/discord.sh-1.5/discord.sh --webhook-url="" --text tmp

Not able to send the temperature of the device -- tried tmp, "tmp", "$tmp" still not working please help

[Suggestion] Minified version

Make a version with single-line, minified code. This will allow you to make a function in your script instead of calling a separate script.

Problems to use discord.sh behind a proxy squid version 3.5

I cant send anything using this script behind a proxy squid with version superior than 3.1 (probably)
To solve, i have to remove, this header from curl comand:

-H 'Expect: application/json'

There are the problem:
curl -H 'Content-Type: application/json' -H 'Expect: application/json' -X POST https://discord.com/api/webhooks/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -d '{ "wait": true, "content": "gohorse" }'
curl: (56) Received HTTP code 417 from proxy after CONNECT

There are the solution:
curl -H 'Content-Type: application/json' -X POST https://discord.com/api/webhooks/844929124527243264/VER83fwol8pWU9Yyp9z6CnDvzz09gOix1aWDvX5UhiHYcISKkYt__52RdTTgZV3TgJay -d '{ "wait": true, "content": "gohorse" }'
No error after that.

Seems had a explanation (or workarround) in squid doc, but it's no more supported by newer versions of squid:
http://www.squid-cache.org/Doc/config/ignore_expect_100/

I hope it's help someone.

thx

Create thread message

It is possible to create thread discussion ? Ex: I use your script to create a message of the day and post the message with a cron job. It is possible to create a thread message linked to this message of the day?

shopt: lastpipe: invalid shell option name

Getting the following error on macos

discord.sh-1.3/discord.sh: line 6: shopt: lastpipe: invalid shell option name

with an invocation something like this:

discord.sh-1.3/discord.sh --webhook-url $webhook --title "title text" --text "$tags cat $filename"

date: illegal option on FreeBSD

Hi,

I use discord.sh on FreeBSD, everything if fine except when --timestamp is called.

The FreeBSD date program does not understand the --iso-8601 argument and returns this to the console:

# date -u --iso-8601=seconds
date: illegal option -- -
usage: date [-jnRu] [-d dst] [-r seconds|file] [-t west] [-v[+|-]val[ymwdHMS]]
            [-I[date | hours | minutes | seconds]]
            [-f fmt date | [[[[[cc]yy]mm]dd]HH]MM[.ss]] [+format]

Quick fix for FreeBSD's users

Get the line:

get_ts() { date -u --iso-8601=seconds; };

Replace with this:

get_ts() { date -u -Iseconds; };

Best regards,
al.

Unescaped control characters fire an error in jq

Control characters in the inclusive range U+0000 to U+001F are invalid JSON per section 7 of RFC 7159, and jq handles this by firing off a slightly difficult-to-debug error (in our use case). Because of this, passing any unescaped control characters including CR, LF, and tabs causes discord.sh to fail to send the message (specifically, Discord rejects the message with "cannot send an empty message" since jq bails out).

As of now, this will not be fixed. It will be up to the end user to escape desired control characters using sed and/or tr.

Reasons:

  • Escaping and/or removing control characters inside discord.sh requires us to add dependencies, specifically sed and/or tr. This breaks the goal of maximum portability.

Sources:

Workaround examples:

Do you have an example of a workaround you came up with? Comment it here.

curl runs even without username or text

When build_message bails out due to lack of username or text, send_message fails to recognize this and still attempts to run curl. This is likely caused by incorrect detection of the exit code in the command substitution used to capture the output of build_message.

Sending a bash string as description results in invalid JSON error

So when I have a message like:
message="${user} is not following the rules as set in ${rules}"

and then sending it like:
discord.sh --webhook-url https://blabla.com/xyz --title "Hello world" --description "${message}"

I then get:

error! {
  "code": 50109,
  "message": "The request body contains invalid JSON."
}

text under the --image ?

Hello, would there be a way to put text below the image when we use the --image argument? Or even place the text of the --description argument below the image?

Custom text + content of file?

Hello, i am trying to send a custom text + the content of a file:

./discord.sh --webhook-url "$WEBHOOK_URL" --text "$(cat filename | jq -Rs . | cut -c 2- | rev | cut -c 2- | rev)" this sends the content of a file

and i want to send it like this:

./discord.sh --webhook-url "$WEBHOOK_URL" --text " customtxtHere ``` $(cat filename | jq -Rs . | cut -c 2- | rev | cut -c 2- | rev) (now this quote x3 `)"

i want to add the ` so it is in a nicer format when printing it in discord.

Modify a webhook

Is it possible to add an option to modify/delete a Webhook by giving its id to an argument ?

Any way for debugging?

Hello,

I am always recieving this error:
parse error: Invalid string: control characters from U+0000 through U+001F must be escaped at line 6, column 25

and I would like to know how I can debug that or if there is a way to enable debug output

in case embeds: timestamp not shown

not sure why, but this command does not show the timestamp:

./discord.sh \ --webhook-url="$WEBHOOK" \ --username "System Status" \ --description "Here are your system stats!" \ --field "Hostname;localhost;false" \ --field "CPU;95%" \ --field "Disk Usage;120/512GB" --timestamp

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.