Outgoing webhooks

Receive your server's events on your URL: format, headers, HMAC signature verification (Python, Node.js, Java, PHP), retries and the delivery log.

On this page Create a webhook Which URLs are accepted? What you receive Verify the signature PythonNode.jsJavaPHP Answering, retries and disabling Test and follow deliveries Best practices

An outgoing webhook makes Robert call your URL with a signed JSON POST for every event you care about (member joins, sanction, ticket, giveaway end…). It is the most economical option for an always-on site or service: no read request, so no quota consumed.

Not to be confused with the bot's Webhooks module (which posts to URLs of your choice from Robert's modules): here we mean the developer platform webhooks, signed, managed by API key or from the Developers → Webhooks page.

Create a webhook

Developers → Webhooks → New webhook page, or through the API (key with the bridges scope, see the reference):

curl -s -X POST "https://robert-bot.com/api/v1/public-api/guilds/987654321098765432/webhooks" \
  -H "Authorization: Bearer $ROBERT_KEY" -H "Content-Type: application/json" \
  -d '{"name": "My site", "url": "https://example.com/hooks/robert", "types": ["member.join", "case.create"]}'
Field Description
url Public HTTPS URL (see below)
types Wanted event types. Empty: all
name Display name, optional
secret Optional: your own secret (16 to 128 visible ASCII characters). Otherwise Robert generates one (whsec_…)

The secret is shown only once, at creation. To get a new one: PATCH with "regenerate_secret": true (or the dashboard button).

Which URLs are accepted?

So that a webhook cannot be used to attack an internal network, Robert refuses:

  • anything that is not https://;
  • URLs with credentials (https://user:pass@…);
  • localhost, names ending in .local, .internal, .lan, .home, .corp, .intranet;
  • private, local, reserved or metadata IP addresses (the name is resolved before every send, and the connection is pinned to the verified address);
  • ports below 1024, except 443.

Robert follows no redirect. To develop locally, expose your machine with an HTTPS tunnel.

What you receive

POST /hooks/robert HTTP/1.1
Host: example.com
Content-Type: application/json
User-Agent: Robert-Webhooks/0.3.0
X-Robert-Event: member.join
X-Robert-Delivery: e_4f9a0c2b7d1e3a5c8b60
X-Robert-Timestamp: 1791370000
X-Robert-Signature: sha256=210f99b0148143fa644450a2542c9cef4b43fc8d4aaf3092ea8bc125174d4fb5
X-Robert-Attempt: 1

{"id":"e_4f9a0c2b7d1e3a5c8b60","type":"member.join","guild_id":"987654321098765432","created_at":1791370000,"data":{"user":{"id":"123456789012345678","name":"Steve","bot":false}}}
Header Content
X-Robert-Event The event type (or ping for a test)
X-Robert-Delivery The event ID: identical on every retry, use it to ignore duplicates
X-Robert-Timestamp Unix timestamp of this send (changes on every attempt)
X-Robert-Signature sha256= followed by the hexadecimal signature
X-Robert-Attempt Attempt number (1 to 4)

The body is the event: id, type, guild_id, created_at and data (see Events).

Verify the signature

Always verify the signature before trusting the content: anyone can send a POST to your URL.

The signature is an HMAC-SHA256, with your secret as the key, of the string:

<X-Robert-Timestamp>.<raw body>

Three rules:

  1. Use the raw body as received (the exact bytes), never JSON that was parsed and written back: one space of difference changes the signature.
  2. Compare with a constant-time comparison (hmac.compare_digest, timingSafeEqual, hash_equals…), not with ==.
  3. Reject sends that are too old: if X-Robert-Timestamp is more than 5 minutes away from your clock, reject (anti-replay).

Test your implementation

With the secret whsec_exemple_0123456789abcdef, the timestamp 1791370000 and exactly the body of the example above, the expected signature is sha256=210f99b0148143fa644450a2542c9cef4b43fc8d4aaf3092ea8bc125174d4fb5.

Python

import hashlib, hmac, json, os, time
from flask import Flask, abort, request

SECRET = os.environ["ROBERT_WEBHOOK_SECRET"]
TOLERANCE = 300  # seconds
app = Flask(__name__)

def verify(secret, raw_body: bytes, timestamp: str, signature: str) -> bool:
    try:
        if abs(time.time() - int(timestamp)) > TOLERANCE:
            return False
    except ValueError:
        return False
    expected = "sha256=" + hmac.new(
        secret.encode(), timestamp.encode() + b"." + raw_body, hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(expected, signature)

@app.post("/hooks/robert")
def robert_hook():
    raw = request.get_data()                      # raw body
    if not verify(SECRET, raw, request.headers.get("X-Robert-Timestamp", ""),
                  request.headers.get("X-Robert-Signature", "")):
        abort(401)
    event = json.loads(raw)
    print(event["type"], event["data"])
    return "", 204                                 # answer fast, with a 2xx

With the standard library alone, or the SDK: construct_webhook_event(raw_body, headers, SECRET).

Node.js

import crypto from "node:crypto";
import express from "express";

const SECRET = process.env.ROBERT_WEBHOOK_SECRET;
const TOLERANCE = 300; // seconds
const app = express();

function verify(secret, rawBody, timestamp, signature) {
  if (!timestamp || !signature) return false;
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE) return false;
  const expected = "sha256=" + crypto.createHmac("sha256", secret)
    .update(`${timestamp}.`).update(rawBody).digest("hex");
  const a = Buffer.from(expected), b = Buffer.from(signature);
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

// express.raw: keep the raw body (Buffer), do not parse it before verifying
app.post("/hooks/robert", express.raw({ type: "application/json" }), (req, res) => {
  if (!verify(SECRET, req.body, req.get("X-Robert-Timestamp"), req.get("X-Robert-Signature"))) {
    return res.sendStatus(401);
  }
  const event = JSON.parse(req.body.toString("utf8"));
  console.log(event.type, event.data);
  res.sendStatus(204);
});

app.listen(3000);

With the SDK: constructWebhookEvent(rawBody, req.headers, SECRET).

Java

import com.sun.net.httpserver.HttpServer;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;

public class RobertWebhook {
    static final String SECRET = System.getenv("ROBERT_WEBHOOK_SECRET");
    static final long TOLERANCE = 300; // seconds

    static boolean verify(String secret, byte[] rawBody, String timestamp, String signature) throws Exception {
        if (timestamp == null || signature == null) return false;
        long ts;
        try { ts = Long.parseLong(timestamp.trim()); } catch (NumberFormatException e) { return false; }
        if (Math.abs(System.currentTimeMillis() / 1000 - ts) > TOLERANCE) return false;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        mac.update((timestamp.trim() + ".").getBytes(StandardCharsets.UTF_8));
        String expected = "sha256=" + HexFormat.of().formatHex(mac.doFinal(rawBody));
        return MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8),
                                     signature.getBytes(StandardCharsets.UTF_8)); // constant time
    }

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(3000), 0);
        server.createContext("/hooks/robert", exchange -> {
            try {
                byte[] raw = exchange.getRequestBody().readAllBytes();   // raw body
                boolean ok = verify(SECRET, raw,
                        exchange.getRequestHeaders().getFirst("X-Robert-Timestamp"),
                        exchange.getRequestHeaders().getFirst("X-Robert-Signature"));
                if (!ok) { exchange.sendResponseHeaders(401, -1); return; }
                System.out.println(new String(raw, StandardCharsets.UTF_8));
                exchange.sendResponseHeaders(204, -1);
            } catch (Exception e) {
                exchange.sendResponseHeaders(500, -1);
            } finally {
                exchange.close();
            }
        });
        server.start();
    }
}

HexFormat requires Java 17 or later.

PHP

<?php
const TOLERANCE = 300; // seconds
$secret = getenv('ROBERT_WEBHOOK_SECRET');

function verify(string $secret, string $rawBody, ?string $timestamp, ?string $signature): bool {
    if ($timestamp === null || $signature === null || !ctype_digit($timestamp)) return false;
    if (abs(time() - (int) $timestamp) > TOLERANCE) return false;
    $expected = 'sha256=' . hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
    return hash_equals($expected, $signature);          // constant time
}

$raw = file_get_contents('php://input');                // raw body
if (!verify($secret, $raw, $_SERVER['HTTP_X_ROBERT_TIMESTAMP'] ?? null, $_SERVER['HTTP_X_ROBERT_SIGNATURE'] ?? null)) {
    http_response_code(401);
    exit;
}

$event = json_decode($raw, true);
error_log($event['type'] . ' ' . json_encode($event['data']));
http_response_code(204);

Answering, retries and disabling

  • Answer with a 2xx quickly (Robert waits 8 seconds at most). Do the long work after answering.
  • Any other response (or a timeout, a network error) triggers retries: after 10 seconds, 1 minute then 10 minutes (4 attempts in all). Each attempt is signed with a new timestamp.
  • Events can therefore arrive several times and out of order: deduplicate with X-Robert-Delivery (or id).
  • After 50 consecutive final failures (4 failed attempts count as one), the webhook is disabled: the dashboard shows the reason. Fix the problem then re-enable it ("enabled": true), which resets the counter.

Test and follow deliveries

  • Test: the dashboard's "Test" button, or POST /webhooks/{id}/test, sends a ping event right away (a single attempt) and returns the result.
{ "id": 812, "event_id": "e_91c0…", "type": "ping", "status": "ok", "attempt": 1, "http_status": 204, "error": null, "duration_ms": 87 }
  • Log: GET /webhooks/{id}/deliveries (or the dashboard tab) lists the last 100 deliveries: status (pending, ok, failed), attempt, http_status, error, the start of your server's response, duration.

Best practices

  • Keep the secret in an environment variable and regenerate it if it may have leaked.
  • Run nothing sensitive without verifying the signature and the timestamp.
  • Answer first, process afterwards (internal queue).
  • Plan for idempotency: the same event may be delivered more than once.
  • Limit the types to the events you need: less traffic, less risk.