diff --git a/README.md b/README.md index 7f825d8..98fe52d 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,47 @@ jobs: To sync other repositories, list them in `repos` and pass a token that can edit their labels as the `token` secret. +## Discord posts + +[actions/discord-post](actions/discord-post) posts one embed to a Discord webhook. Keep the webhook URL in a secret. Without one, the step posts nothing and passes. + +- `kind: release` or `kind: issue` fills the title, link and text from the event that started the workflow. +- `kind: custom` posts your own `title`, `url` and `description`. +- Mentions are off. `ping-role` pings one role by ID. `everyone: true` pings @everyone, only when you ask. +- Rate limits and Discord outages are retried, then end in a warning. A deleted webhook fails the step. + +```yaml +# .github/workflows/discord.yml +name: Discord +on: + release: + types: [published] + issues: + types: [opened] +permissions: + contents: read +jobs: + post: + runs-on: ubuntu-latest + steps: + - uses: Horrible-Dev/toolkit/actions/discord-post@v0 + with: + webhook: ${{ secrets.DISCORD_WEBHOOK }} + kind: ${{ github.event_name == 'release' && 'release' || 'issue' }} +``` + +A message of your own: + +```yaml + - uses: Horrible-Dev/toolkit/actions/discord-post@v0 + with: + webhook: ${{ secrets.DISCORD_WEBHOOK }} + title: Nightly build + url: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + description: A new nightly build is up. + color: "3066993" +``` + ## Credits Parts of the toolkit are adapted from ChupathingyCE's release and housekeeping tools. diff --git a/actions/discord-post/action.yml b/actions/discord-post/action.yml new file mode 100644 index 0000000..d01e4d0 --- /dev/null +++ b/actions/discord-post/action.yml @@ -0,0 +1,52 @@ +name: Discord post +description: Post an embed to a Discord webhook, for a release, an issue or a message of your own. + +inputs: + webhook: + description: "The webhook URL, from a secret. Empty: nothing is posted." + required: false + default: "" + kind: + description: "release, issue or custom. release and issue fill the post from the triggering event." + required: false + default: custom + title: + description: "The embed's title (overrides the event's)" + required: false + default: "" + url: + description: "The link on the title (overrides the event's)" + required: false + default: "" + description: + description: "The embed's text (overrides the event's). Cut to Discord's 4096 characters." + required: false + default: "" + color: + description: "The embed's color, as a decimal number" + required: false + default: "5793266" + ping-role: + description: "A role ID to mention. Only that role is pinged." + required: false + default: "" + everyone: + description: "true to mention @everyone. Mentions are off otherwise." + required: false + default: "false" + +runs: + using: composite + steps: + - name: Post to Discord + shell: bash + env: + WEBHOOK: ${{ inputs.webhook }} + KIND: ${{ inputs.kind }} + TITLE: ${{ inputs.title }} + URL: ${{ inputs.url }} + DESCRIPTION: ${{ inputs.description }} + COLOR: ${{ inputs.color }} + PING_ROLE: ${{ inputs.ping-role }} + EVERYONE: ${{ inputs.everyone }} + run: "$GITHUB_ACTION_PATH/post.sh" diff --git a/actions/discord-post/post.sh b/actions/discord-post/post.sh new file mode 100755 index 0000000..a0e8de5 --- /dev/null +++ b/actions/discord-post/post.sh @@ -0,0 +1,106 @@ +#!/bin/sh +# Posts one embed to a Discord webhook. Everything comes from the environment: +# WEBHOOK the webhook URL; empty: nothing is posted +# KIND release, issue or custom; release and issue read the event +# file (GITHUB_EVENT_PATH) for the title, link and text +# TITLE, URL, DESCRIPTION, COLOR override what the event gives +# PING_ROLE a role ID to mention (only that role) +# EVERYONE true to mention @everyone; otherwise no mentions at all +# Rate limits (HTTP 429) and server errors are retried a few times; still +# failing, that's a warning, not a failed run. Any other answer (a deleted +# webhook, a bad request) fails. +set -eu + +if [ -z "${WEBHOOK:-}" ]; then + echo "No webhook given: nothing to post." + exit 0 +fi + +KIND=${KIND:-custom} +event=${GITHUB_EVENT_PATH:-} +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +from_event() { + if [ -n "$event" ] && [ -f "$event" ]; then + jq -r "$1 // \"\"" "$event" + fi +} + +case "$KIND" in +release) + repo=$(from_event '.repository.name') + tag=$(from_event '.release.tag_name') + name=$(from_event '.release.name') + default_title="$repo ${name:-$tag}" + default_url=$(from_event '.release.html_url') + default_description=$(from_event '.release.body') + ;; +issue) + number=$(from_event '.issue.number') + default_title="#$number $(from_event '.issue.title')" + default_url=$(from_event '.issue.html_url') + default_description=$(from_event '.issue.body') + ;; +custom) + default_title="" default_url="" default_description="" + ;; +*) + echo "::error::kind must be release, issue or custom, not '$KIND'" + exit 1 + ;; +esac + +title=${TITLE:-$default_title} +url=${URL:-$default_url} +description=${DESCRIPTION:-$default_description} +if [ -z "$title" ] && [ -z "$description" ]; then + echo "::error::Nothing to post: give a title or a description" + exit 1 +fi + +jq -n \ + --arg title "$title" \ + --arg url "$url" \ + --arg description "$description" \ + --arg color "${COLOR:-5793266}" \ + --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ + --arg ping "${PING_ROLE:-}" \ + --arg everyone "${EVERYONE:-false}" \ + 'def cut($n): if length > $n then .[0:$n - 1] + "…" else . end; + {embeds: [{title: ($title | cut(256)), color: ($color | tonumber), + description: ($description | cut(4096)), timestamp: $timestamp} + + (if $url == "" then {} else {url: $url} end)]} + + if $everyone == "true" then {content: "@everyone", allowed_mentions: {parse: ["everyone"]}} + elif $ping != "" then {content: "<@&\($ping)>", allowed_mentions: {parse: [], roles: [$ping]}} + else {allowed_mentions: {parse: []}} end' \ + >"$work/payload.json" + +code=000 +for attempt in 1 2 3 4 5; do + code=$(curl -sS --max-time 15 -o "$work/response.json" -w '%{http_code}' \ + -H "Content-Type: application/json" -d @"$work/payload.json" "$WEBHOOK") || code=000 + case "$code" in + 2??) + echo "Posted to Discord." + exit 0 + ;; + 429) + wait=$(jq -r '.retry_after // 5' "$work/response.json" 2>/dev/null || echo 5) + wait=$(awk -v w="$wait" 'BEGIN { w += 0; if (w < 1) w = 1; if (w > 30) w = 30; printf "%d", w + 0.999 }') + echo "Discord is rate limiting the webhook; trying again in ${wait}s (attempt $attempt of 5)" + ;; + 000 | 5??) + wait=${RETRY_WAIT:-5} + echo "Discord answered HTTP $code; trying again in ${wait}s (attempt $attempt of 5)" + ;; + *) + echo "::error::Discord answered HTTP $code: $(head -c 300 "$work/response.json" 2>/dev/null)" + exit 1 + ;; + esac + if [ "$attempt" -lt 5 ]; then + sleep "$wait" + fi +done +echo "::warning::The Discord post did not go through after 5 attempts (HTTP $code)" diff --git a/tests/test_discord_post.py b/tests/test_discord_post.py new file mode 100644 index 0000000..66911b0 --- /dev/null +++ b/tests/test_discord_post.py @@ -0,0 +1,141 @@ +import json +import os +import subprocess +import threading +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path + +import pytest + +SCRIPT = Path(__file__).resolve().parent.parent / "actions" / "discord-post" / "post.sh" + + +class Webhook: + """A local stand-in for a Discord webhook: answers with the given codes + in turn and keeps every payload.""" + + def __init__(self, codes): + self.codes = list(codes) + self.payloads = [] + webhook = self + + class Handler(BaseHTTPRequestHandler): + def do_POST(self): + length = int(self.headers["Content-Length"]) + webhook.payloads.append(json.loads(self.rfile.read(length))) + code = webhook.codes.pop(0) if webhook.codes else 204 + body = b'{"retry_after": 0.1}' if code == 429 else b"{}" + self.send_response(code) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *arguments): + pass + + self.server = HTTPServer(("127.0.0.1", 0), Handler) + self.url = f"http://127.0.0.1:{self.server.server_port}/hook" + threading.Thread(target=self.server.serve_forever, daemon=True).start() + + def close(self): + self.server.shutdown() + + +@pytest.fixture +def webhook(): + hooks = [] + + def make(codes=()): + hook = Webhook(codes) + hooks.append(hook) + return hook + + yield make + for hook in hooks: + hook.close() + + +def run(environment, tmp_path): + env = {"PATH": os.environ["PATH"], "RETRY_WAIT": "0", **environment} + return subprocess.run([str(SCRIPT)], env=env, capture_output=True, text=True, cwd=tmp_path) + + +def test_no_webhook_posts_nothing(tmp_path): + result = run({"TITLE": "Hello"}, tmp_path) + assert result.returncode == 0 + assert "nothing to post" in result.stdout + + +def test_custom_post_has_no_mentions(webhook, tmp_path): + hook = webhook() + result = run({"WEBHOOK": hook.url, "TITLE": "Weekly", "DESCRIPTION": "@everyone look", "URL": "https://example.com"}, + tmp_path) + assert result.returncode == 0, result.stdout + result.stderr + payload = hook.payloads[0] + assert payload["allowed_mentions"] == {"parse": []} + assert "content" not in payload + assert payload["embeds"][0]["title"] == "Weekly" + assert payload["embeds"][0]["url"] == "https://example.com" + + +def test_role_ping_mentions_only_that_role(webhook, tmp_path): + hook = webhook() + run({"WEBHOOK": hook.url, "TITLE": "Out now", "PING_ROLE": "123"}, tmp_path) + payload = hook.payloads[0] + assert payload["content"] == "<@&123>" + assert payload["allowed_mentions"] == {"parse": [], "roles": ["123"]} + + +def test_everyone_only_when_asked(webhook, tmp_path): + hook = webhook() + run({"WEBHOOK": hook.url, "TITLE": "Out now", "EVERYONE": "true"}, tmp_path) + assert hook.payloads[0]["allowed_mentions"] == {"parse": ["everyone"]} + + +def test_release_kind_reads_the_event(webhook, tmp_path): + event = tmp_path / "event.json" + event.write_text(json.dumps({"repository": {"name": "demo"}, + "release": {"tag_name": "v1.0.0", "name": "", "html_url": "https://example.com/r", + "body": "x" * 5000}})) + hook = webhook() + result = run({"WEBHOOK": hook.url, "KIND": "release", "GITHUB_EVENT_PATH": str(event)}, tmp_path) + assert result.returncode == 0, result.stdout + result.stderr + embed = hook.payloads[0]["embeds"][0] + assert embed["title"] == "demo v1.0.0" + assert embed["url"] == "https://example.com/r" + assert len(embed["description"]) == 4096 + + +def test_issue_kind_reads_the_event(webhook, tmp_path): + event = tmp_path / "event.json" + event.write_text(json.dumps({"issue": {"number": 7, "title": "Crash", "html_url": "https://example.com/7", + "body": None}})) + hook = webhook() + run({"WEBHOOK": hook.url, "KIND": "issue", "GITHUB_EVENT_PATH": str(event)}, tmp_path) + assert hook.payloads[0]["embeds"][0]["title"] == "#7 Crash" + + +def test_rate_limit_is_retried(webhook, tmp_path): + hook = webhook([429, 204]) + result = run({"WEBHOOK": hook.url, "TITLE": "Again"}, tmp_path) + assert result.returncode == 0 + assert len(hook.payloads) == 2 + + +def test_server_errors_end_in_a_warning(webhook, tmp_path): + hook = webhook([500] * 5) + result = run({"WEBHOOK": hook.url, "TITLE": "Down"}, tmp_path) + assert result.returncode == 0 + assert "::warning::" in result.stdout + + +def test_a_deleted_webhook_fails(webhook, tmp_path): + hook = webhook([404]) + result = run({"WEBHOOK": hook.url, "TITLE": "Gone"}, tmp_path) + assert result.returncode == 1 + assert "HTTP 404" in result.stdout + + +def test_unknown_kind_fails(tmp_path): + result = run({"WEBHOOK": "http://127.0.0.1:9/", "KIND": "push", "TITLE": "x"}, tmp_path) + assert result.returncode == 1