Skip to content

Instantly share code, notes, and snippets.

@foooomio
Last active September 2, 2021 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foooomio/892523799a4bc29bb2e4dc202ceed9ed to your computer and use it in GitHub Desktop.
Save foooomio/892523799a4bc29bb2e4dc202ceed9ed to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
set -euo pipefail
run_speedtest() {
speedtest -f json
}
to_slack_message() {
jq -c --argjson threshold "$1" '
if .type == "result" then . else halt end | {
ping: (.ping.latency + 0.5) | floor,
download: (.download.bandwidth / 125000) | floor,
upload: (.upload.bandwidth / 125000) | floor,
server: .server,
url: .result.url
} | {
text: [
if .download < $threshold then
"<!channel> :rotating_light: *Slow connection*"
else
empty
end,
"*Ping* \(.ping) ms *↓* \(.download) Mbps *↑* \(.upload) Mbps",
"*Server* \(.server.name) - \(.server.location)",
.url
] | join("\n")
}
'
}
send_message() {
curl \
-fsSL \
-X POST \
-H 'Content-Type: application/json' \
-d "$1" \
"$SLACK_WEBHOOK_URL"
}
check_args() {
if [[ "${1:-}" =~ [^0-9] ]]; then
echo "Error: The threshold must be a positive integer." >&2
exit 1
elif [[ ! "${SLACK_WEBHOOK_URL:-}" =~ ^https?:// ]]; then
echo "Error: The environment variable SLACK_WEBHOOK_URL must be a URL." >&2
exit 1
fi
}
main() {
check_args "$@"
local body
body="$(run_speedtest | to_slack_message "${1:-0}")"
send_message "$body"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment