Discord Alerts for Cron Jobs: Webhook Scripts and Heartbeat Monitoring
There are two ways to send cron job alerts to Discord. You can wrap each cron command in a small script that posts to a Discord channel webhook when the command exits non-zero, or you can have the job ping a heartbeat monitor that posts to Discord when the job fails or goes overdue. The webhook script needs no outside service, but it only runs when the job itself runs. If the server powers off, cron stops, a crontab edit drops the line, or the job hangs forever, the script never executes and your Discord channel stays silent. A heartbeat monitor catches both crashes and silent missed runs.
Two ways to send cron alerts to Discord
1. The job posts to Discord itself. A wrapper runs your command, captures stdout and stderr, checks the exit code, and posts a JSON embed to a Discord webhook URL on failure. That catches errors when the process actually runs and returns non-zero (such as a failed backup or expired API token).
2. An external monitor posts to Discord for the job. The job sends a quick HTTPS ping to Watchgoose when it finishes (or pings /fail if it errors). Watchgoose tracks the schedule from outside your host, and if the expected ping does not arrive before the grace period ends, Watchgoose posts the alert to your Discord channel.
Approach 1 stays completely silent when:
- the server or container is offline, or the wrapper itself is killed by OOM (if only a child command is OOM-killed with exit 137, a surviving wrapper can still report it)
- the cron daemon stopped or a deployment overwrote the crontab
- the job hung on a database lock or network call without a timeout
- a dependency the wrapper needs (
jq,curl, DNS) broke on the host
Create a Discord channel webhook
A Discord webhook is a secret HTTPS URL bound to one text channel. Creating one takes four clicks:
- Open your Discord server, hover over the target channel (for example
#ops-alerts), and click Edit Channel (gear icon). - Open Integrations and click Webhooks (or Create Webhook).
- Click New Webhook, give it a name such as
Cron Alerts, and confirm the channel. - Click Copy Webhook URL. It looks like
https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz....
Discord allows up to 15 webhooks per channel (creating a 16th returns API error 30007). Keep one webhook for your ops alerts rather than creating one per cron job.
Keep the webhook URL secret
Anyone with a Discord webhook URL can post messages directly into your channel. Do not paste it into your crontab or commit it to Git. Store it in a chmod 600 environment file:
mkdir -p -m 700 "$HOME/.config"
(umask 077; touch "$HOME/.config/cron-discord.env")
chmod 600 "$HOME/.config/cron-discord.env"
Put this line inside ~/.config/cron-discord.env:
export DISCORD_WEBHOOK_URL='https://discord.com/api/webhooks/123456789012345678/replace-with-token'
Verify it works from your shell (Discord returns HTTP 204 No Content on success by default):
. ~/.config/cron-discord.env
curl -fsS -H 'Content-Type: application/json' \
--data '{"content":"Test alert from cron","allowed_mentions":{"parse":[]}}' \
--config /dev/fd/3 3<<EOF
url = "$DISCORD_WEBHOOK_URL"
EOF
Passing url = ... on file descriptor 3 keeps the secret webhook token out of ps process listings.
A bash wrapper that posts failures and recoveries to Discord
Save this script as /usr/local/bin/discord-on-fail.sh and run chmod +x /usr/local/bin/discord-on-fail.sh. It requires curl and jq, stores a small failure state file so a broken every-5-minute job does not flood your Discord channel, posts a green recovery embed when the job passes again, and disables @everyone/@here mentions inside job logs.
#!/usr/bin/env bash
# Run a command and alert Discord on failure and recovery.
# Usage: discord-on-fail.sh JOB_NAME COMMAND [ARGS...]
set -u
if [ "$#" -lt 2 ]; then
printf '%s\n' 'Usage: discord-on-fail.sh JOB_NAME COMMAND [ARGS...]' >&2
exit 64
fi
job="$1"; shift
log="$(mktemp)" || exec "$@"
trap 'rm -f "$log"' EXIT
"$@" >"$log" 2>&1
rc=$?
cat "$log"
ENV_FILE="${DISCORD_ENV_FILE:-$HOME/.config/cron-discord.env}"
[ -r "$ENV_FILE" ] && . "$ENV_FILE"
state_dir="${XDG_STATE_HOME:-$HOME/.local/state}/cron-discord"
mkdir -p "$state_dir" 2>/dev/null || true
safe_job="$(printf '%s' "$job" | tr -c 'A-Za-z0-9._-' '_')"
state_file="${state_dir}/${safe_job}.failed"
post_discord() {
local title="$1"
local color="$2"
local output="$3"
if [ -z "${DISCORD_WEBHOOK_URL:-}" ]; then
printf '%s\n' 'discord-on-fail: DISCORD_WEBHOOK_URL is not set' >&2
return 1
fi
# Truncate output to fit safely inside Discord's 4096-char embed description limit.
local trimmed
trimmed="$(printf '%s' "$output" | tail -c 3500)"
local desc=""
if [ -n "$trimmed" ]; then
local tick='`'
local fence="${tick}${tick}${tick}"
desc="$(printf '%s\n%s\n%s' "$fence" "$trimmed" "$fence")"
fi
local payload
payload="$(jq -cn \
--arg title "$title" \
--arg desc "$desc" \
--arg host "$(hostname -s 2>/dev/null || hostname)" \
--argjson color "$color" \
'{
allowed_mentions: { parse: [] },
embeds: [{
title: $title,
description: $desc,
color: $color,
footer: { text: ("host: " + $host) }
}]
}')" || return 1
printf '%s' "$payload" | curl --disable --silent --show-error --fail --globoff \
--connect-timeout 3 --max-time 10 --retry 3 --retry-max-time 20 \
-H 'Content-Type: application/json' \
--data-binary @- --output /dev/null --config /dev/fd/3 3<<EOF 2>/dev/null || true
url = "$DISCORD_WEBHOOK_URL"
EOF
}
if [ "$rc" -ne 0 ]; then
if [ ! -f "$state_file" ]; then
post_discord "Cron FAILED: ${job} (exit ${rc})" 15158332 "$(cat "$log")"
touch "$state_file" 2>/dev/null || true
fi
elif [ -f "$state_file" ]; then
post_discord "Cron RECOVERED: ${job}" 3066993 ""
rm -f "$state_file"
fi
exit "$rc"
Call it from crontab like this:
0 2 * * * /usr/local/bin/discord-on-fail.sh nightly-backup /usr/local/bin/run-backup.sh
Because alerting is best-effort and the script ends with exit "$rc", your backup still runs even if Discord is unreachable, and cron still sees the real exit status.
The same wrapper in Python
If your host does not have jq or you prefer Python (standard library only, Python 3.9+), save this as /usr/local/bin/discord-on-fail.py:
#!/usr/bin/env python3
"""Run a command and send Discord alerts on failure and recovery."""
import json
import os
import socket
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
def post_discord(webhook_url: str, title: str, color: int, output: str) -> None:
fence = "`" * 3
desc = f"{fence}\n{output[-3500:]}\n{fence}" if output else ""
body = json.dumps(
{
"allowed_mentions": {"parse": []},
"embeds": [
{
"title": title[:256],
"description": desc,
"color": color,
"footer": {"text": f"host: {socket.gethostname()}"},
}
],
}
).encode("utf-8")
req = urllib.request.Request(
webhook_url,
data=body,
method="POST",
headers={
"Content-Type": "application/json",
"User-Agent": "cron-discord-wrapper/1.0",
},
)
for attempt in range(3):
try:
with urllib.request.urlopen(req, timeout=10):
return
except urllib.error.HTTPError as exc:
if exc.code == 429 and attempt < 2:
retry_after = exc.headers.get("Retry-After", "2")
try:
delay = min(float(retry_after), 10.0)
except ValueError:
delay = 2.0
time.sleep(delay)
continue
return
except (urllib.error.URLError, TimeoutError, OSError):
if attempt < 2:
time.sleep(2**attempt)
def main() -> int:
if len(sys.argv) < 3:
print("Usage: discord-on-fail.py JOB_NAME COMMAND [ARGS...]", file=sys.stderr)
return 64
job_name = sys.argv[1]
command = sys.argv[2:]
proc = subprocess.run(command, capture_output=True, text=True)
combined = (proc.stdout or "") + (proc.stderr or "")
if combined:
sys.stdout.write(combined)
webhook_url = os.environ.get("DISCORD_WEBHOOK_URL", "").strip()
state_dir = Path(os.environ.get("XDG_STATE_HOME", Path.home() / ".local/state")) / "cron-discord"
state_dir.mkdir(parents=True, exist_ok=True)
safe_name = "".join(c if c.isalnum() or c in "._-" else "_" for c in job_name)
state_file = state_dir / f"{safe_name}.failed"
if proc.returncode != 0:
if webhook_url and not state_file.exists():
post_discord(
webhook_url,
f"Cron FAILED: {job_name} (exit {proc.returncode})",
0xE74C3C,
combined.strip(),
)
state_file.touch()
elif state_file.exists():
if webhook_url:
post_discord(webhook_url, f"Cron RECOVERED: {job_name}", 0x2ECC71, "")
state_file.unlink(missing_ok=True)
return proc.returncode
if __name__ == "__main__":
sys.exit(main())
Notice the custom User-Agent header in the Python version. Discord's edge proxy (Cloudflare) often blocks requests sent with Python's default Python-urllib/* user agent (HTTP 403).
Discord payload limits, mentions, and rate limits
Four Discord rules trip up hand-rolled cron scripts:
- Disable mention parsing on untrusted output. Setting
"allowed_mentions": {"parse": []}prevents stray@everyone,@here, or<@&role>strings in stdout/stderr from accidentally pinging every member in your Discord server. - Embed size ceilings. Discord rejects payloads over 2,000 characters in
content, over 256 characters in an embedtitle, over 4,096 characters in an embeddescription, or over 6,000 characters across all embeds combined (HTTP400). Truncate job logs before serializing JSON. - Webhook rate limits. Discord enforces dynamic per-webhook rate-limit buckets communicated via
X-RateLimit-Remaining,X-RateLimit-Reset-After, andRetry-AfteronHTTP 429. State-file deduplication stops a failing 1-minute job from trippingHTTP 429or muting real incidents under noise. - Backtick escaping. If a command's stderr contains three consecutive backticks, it can break formatting inside a Discord code block. Keep log excerpts short and avoid dumping sensitive environment variables or SQL queries into a shared chat channel.
Webhook script vs heartbeat monitor
Scroll horizontally to see all columns.
| Scenario | Discord webhook wrapper | Watchgoose + Discord integration |
|---|---|---|
| Job runs and exits non-zero | Alerts Discord with log excerpt | Immediate Down alert in Discord (with exit code and optional log) |
| Server down, cron stopped, or crontab deleted | Silent (wrapper never runs) | Alerts Discord after grace window ends |
| Job hangs indefinitely | Silent (command never exits) | Alerts Discord when /start grace or schedule deadline expires |
| Alert routing across Slack, Teams, PagerDuty, or email | Must maintain extra scripts | Add channels in Watchgoose without changing cron scripts |
| Webhook secret management across 20 servers | Copy webhook URL to every host | Discord OAuth lives in Watchgoose; hosts only ping their check URL |
Missed-run alerts in Watchgoose arm after the check receives its first successful ping. Explicit /fail pings and /start timeouts can alert before that.
Monitor cron jobs and alert Discord with Watchgoose
Instead of copying your Discord webhook token onto every server and hoping cron stays alive, connect Discord once inside Watchgoose:
- Create a free Watchgoose account (includes up to 10 checks, no credit card required).
- Open your project's Integrations page, choose Discord, and click Connect Discord. Authorize Watchgoose to create a webhook in your chosen server and channel (Discord's OAuth flow grants
webhook.incomingfor that single channel only; Watchgoose cannot read your Discord messages). - Create a check matching your cron schedule and confirm the Discord integration is enabled for it.
Then store the check's ping URL in a chmod 600 curl config file (~/.config/watchgoose/backup.curl containing url = "https://watchgoose.com/ping/<your-check-uuid>") so the secret never appears in ps output, and ping Watchgoose when your job succeeds:
0 2 * * * /usr/local/bin/backup.sh && curl --disable -fsS -m 10 --retry 3 -o /dev/null --config "$HOME/.config/watchgoose/backup.curl"
For full exit-code and runtime reporting without exposing the URL on the command line, use the POSIX /dev/fd/3 wrapper in our rclone guide. Need Slack or Teams too? See our Slack alerts for cron jobs and Microsoft Teams alerts for cron jobs guides.
Frequently asked questions
Why does my Python Discord webhook script return HTTP 403 Forbidden?
Discord's Cloudflare front-end frequently rejects requests that use Python's default Python-urllib/* User-Agent header. Set an explicit User-Agent header (such as cron-discord-wrapper/1.0) on your urllib.request.Request to fix HTTP 403 errors.
How do I stop cron logs from pinging @everyone in Discord?
Include "allowed_mentions": {"parse": []} in the top-level JSON body sent to the Discord webhook. Discord will still display the literal text in the message, but it will not trigger push notifications for @everyone, @here, users, or roles.
Can Watchgoose read messages in my Discord server when I connect it?
No. Watchgoose requests only Discord's webhook.incoming OAuth scope, which creates a single write-only webhook for the one channel you select. Watchgoose cannot read channel history, member lists, or messages in your server.
What happens if my Discord channel already has 15 webhooks?
Discord enforces a maximum of 15 webhooks per text channel and rejects additional creations with error code 30007. Delete an unused webhook under Channel Settings > Integrations > Webhooks before connecting Watchgoose or creating a new script webhook.
Will Discord alerts fire if my server crashes before the cron job starts?
A local webhook wrapper script cannot alert when the server is down because the script never executes. A heartbeat monitor like Watchgoose tracks the job's schedule externally and posts a Down alert to Discord as soon as the expected run passes its grace window.