Python script: send a message to a Discord channel from any script, using a webhook

You do not need a bot to post into Discord. A webhook is an address, and whatever you POST to it shows up in the channel. This is a tiny command line tool for that, so backup jobs, monitors and installers can report in.

Create the webhook under Channel settings, Integrations, Webhooks, and copy its address. Anyone who has that address can post in the channel, so keep it out of public code.

#!/usr/bin/env python3
"""Post a message to a Discord channel through a webhook.

usage:  discord_notify.py "text"
        some_command | discord_notify.py
env:    DISCORD_WEBHOOK   the webhook address
"""
import json
import os
import sys
import time
import urllib.error
import urllib.request

LIMIT = 2000  # Discord refuses longer messages


def chunks(text):
    text = text.strip()
    while text:
        if len(text) <= LIMIT:
            yield text
            return
        cut = text.rfind("\n", 0, LIMIT)
        if cut < LIMIT // 2:
            cut = LIMIT
        yield text[:cut]
        text = text[cut:].lstrip("\n")


def post(webhook, content):
    body = json.dumps({"content": content}).encode()
    req = urllib.request.Request(
        webhook,
        data=body,
        headers={"Content-Type": "application/json", "User-Agent": "notify-script/1.0"},
    )
    for _ in range(3):
        try:
            urllib.request.urlopen(req, timeout=15).read()
            return True
        except urllib.error.HTTPError as err:
            if err.code == 429:
                wait = float(err.headers.get("Retry-After", "2"))
                time.sleep(min(wait, 30))
                continue
            print(f"discord answered {err.code}", file=sys.stderr)
            return False
        except OSError as err:
            print(f"network error: {err}", file=sys.stderr)
            time.sleep(2)
    return False


def main():
    args = [a for a in sys.argv[1:] if a != "--dry-run"]
    dry_run = "--dry-run" in sys.argv
    text = " ".join(args) if args else sys.stdin.read()
    if not text.strip():
        print("nothing to send", file=sys.stderr)
        return 64
    webhook = os.environ.get("DISCORD_WEBHOOK", "")
    if not webhook and not dry_run:
        print("set DISCORD_WEBHOOK", file=sys.stderr)
        return 78
    ok = True
    for part in chunks(text):
        if dry_run:
            print(f"[would send {len(part)} chars]\n{part}\n")
        else:
            ok = post(webhook, part) and ok
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main())

Using it

export DISCORD_WEBHOOK="..."
./discord_notify.py "backup finished"
df -h | ./discord_notify.py
./cert_check.sh hosts.txt | grep -v '^OK' | ./discord_notify.py

Add --dry-run to see what would be sent without sending.

Why it looks the way it does

2000 characters. Discord rejects anything longer, so long input is split, at a line break where possible.

The User-Agent header. Requests with Python’s default one get refused with a 403. Any normal looking value works.

429. Webhooks are rate limited. The answer says how long to wait, and the script waits that long and tries again, three times at most.

Formatting. Wrap output in three backticks inside your text if you want it shown as a code block. Plain df -h output is unreadable otherwise.

No third-party packages, so it runs anywhere Python 3 does.