Skip to content

Instantly share code, notes, and snippets.

@mchangrh
Created March 3, 2025 02:20
Show Gist options
  • Select an option

  • Save mchangrh/89ea53bbf15ac81cac30cf95f3795c57 to your computer and use it in GitHub Desktop.

Select an option

Save mchangrh/89ea53bbf15ac81cac30cf95f3795c57 to your computer and use it in GitHub Desktop.
vnstat parsing and discord webhook
#!/bin/bash
DEBUG=FALSE
WEBHOOK_URL="https://discord.com/api/webhooks/"
parse_unit() {
amount=$1
unit=$2
if [ "$unit" == "TiB" ]; then
amount=$(echo "scale=2; $amount*1024" | bc)
fi
echo "$amount"
}
parse_day () {
IFS="|"; read -ra arr_day <<< "$1"; unset IFS;
# shellcheck disable=SC2086
rx=$(parse_unit ${arr_day[0]})
# shellcheck disable=SC2086
tx=$(parse_unit ${arr_day[1]})
# shellcheck disable=SC2086
total=$(parse_unit ${arr_day[2]})
echo "$rx $tx $total"
}
target_date=$(date -d "$(date +'%Y-%m-12') -1 month" +"%Y-%m-%d")
stats=$(vnstat --days -b "$target_date" | tail -n+6 | head -n-2 | cut -b 19-56)
readarray -t dayarray <<< "$(echo -e "${stats}")"
total_rx=0
total_tx=0
total_total=0
for day in "${dayarray[@]}"; do
# shellcheck disable=SC2207
totals=($(parse_day "$day"))
total_rx=$(echo "scale=2; $total_rx + ${totals[0]}" | bc)
total_tx=$(echo "scale=2; $total_tx + ${totals[1]}" | bc)
total_total=$(echo "scale=2; $total_total + ${totals[2]}" | bc)
done
if [ "$DEBUG" == "TRUE" ] ; then
echo "Traffic Since: ${target_date}"
echo "In: $total_rx GiB"
echo "Out: $total_tx GiB"
echo "Total: $total_total GiB"
else
BODY="{\"embeds\": [{ \"title\": \"Traffic Since: ${target_date}\", \"fields\":[{\"name\":\"In\",\"value\":\"${total_rx} GiB\"},{\"name\":\"Out\",\"value\":\"${total_tx} GiB\"},{\"name\":\"Total\",\"value\":\"${total_total} GiB\"}]}]}"
curl \
-H "Content-Type: application/json" \
-d "$BODY" \
$WEBHOOK_URL
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment