> ## Documentation Index
> Fetch the complete documentation index at: https://docs.usequotable.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Slack alerts from webhooks

> Receive tracking.run.finalized webhooks, verify them, and post a daily visibility update to Slack.

This recipe builds a small receiver that turns Quotable webhooks into Slack messages. Every day, when a brand's tracking is scored, it posts the visibility score, the change from the previous tracked day and the mention rate.

It verifies every signature, ignores duplicates and answers within the 10-second limit.

## What you need

| Requirement | Value |
| - | - |
| Webhook events | `tracking.run.finalized` |
| API scopes | `read:projects`, `read:visibility` (to look up the brand name and the previous score) |
| Slack | An [incoming webhook](https://api.slack.com/messaging/webhooks) URL for the channel |
| Hosting | Any server or serverless platform with a public HTTPS URL |
| Environment | `QUOTABLE_WEBHOOK_SECRET`, `QUOTABLE_API_KEY`, `SLACK_WEBHOOK_URL`, `PORT` (optional) |

## Set it up

**1. Create a Slack incoming webhook**

In Slack, create an app with **Incoming Webhooks** turned on, add a webhook to the channel you want, and copy its URL. It starts with `https://hooks.slack.com/services/`.

**2. Create an API key**

In **Settings → API keys**, create a key for the brands you want alerts for. It needs the `read:projects` and `read:visibility` scopes, which new keys include. See [Authentication](https://docs.usequotable.com/api-reference/authentication.md).

**3. Deploy the receiver**

Deploy the code below to a host with a public HTTPS URL, and set the environment variables. For example, the receiver's URL might be `https://alerts.example.com/hooks/quotable`.

**4. Add the webhook endpoint**

In **Settings → Webhooks**, select **Add endpoint**, enter the receiver's URL, keep **Tracking run finalized** checked, and select **Add endpoint**. Copy the signing secret into `QUOTABLE_WEBHOOK_SECRET` and restart the receiver. See [Manage endpoints](https://docs.usequotable.com/webhooks/manage-endpoints.md).

## Code

```javascript slack-alerts.mjs theme={"system"}
// Node.js 20+, no dependencies. Run: node slack-alerts.mjs
import { createServer } from "node:http";
import { createHmac, timingSafeEqual } from "node:crypto";

const SECRET = process.env.QUOTABLE_WEBHOOK_SECRET;
const API_KEY = process.env.QUOTABLE_API_KEY;
const SLACK_URL = process.env.SLACK_WEBHOOK_URL;
const API = "https://app.usequotable.com/api/v1";
const MAX_BODY_BYTES = 256 * 1024;

// --- Signature verification (see /webhooks/verify-signatures) ---
function verify(rawBody, signatureHeader, timestampHeader) {
  if (!signatureHeader || !timestampHeader) return false;
  const timestamp = Number(timestampHeader);
  if (!Number.isInteger(timestamp) || Math.abs(Date.now() / 1000 - timestamp) > 300) return false;
  const expected = createHmac("sha256", SECRET).update(`${timestamp}.`).update(rawBody).digest();
  return signatureHeader
    .split(",")
    .map((part) => part.trim())
    .filter((part) => part.startsWith("v1="))
    .some((part) => {
      const offered = Buffer.from(part.slice(3), "hex");
      return offered.length === expected.length && timingSafeEqual(offered, expected);
    });
}

// --- Deduplication. In production, use your database with a unique index on the event id. ---
const seen = new Set();

async function api(path) {
  const res = await fetch(path.startsWith("http") ? path : `${API}${path}`, {
    headers: { Authorization: `Bearer ${API_KEY}` },
  });
  if (!res.ok) throw new Error(`Quotable API ${res.status}: ${await res.text()}`);
  return res.json();
}

async function postToSlack(text) {
  const res = await fetch(SLACK_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ text }),
  });
  if (!res.ok) throw new Error(`Slack ${res.status}: ${await res.text()}`);
}

function shiftDay(day, days) {
  const date = new Date(`${day}T00:00:00Z`);
  date.setUTCDate(date.getUTCDate() + days);
  return date.toISOString().slice(0, 10);
}

async function handle(event) {
  if (event.type === "tracking.run.finalized") {
    const { run_date, score, mention_rate, answers_scored } = event.data;
    const brand = await api(event.resource.href); // GET /projects/{project_id}
    const series = await api(
      `/projects/${event.project_id}/visibility?from=${shiftDay(run_date, -14)}&to=${run_date}`,
    );
    const previous = series.data.filter((p) => p.date < run_date).at(-1);
    const change = previous
      ? ` (${score - previous.score >= 0 ? "+" : ""}${(score - previous.score).toFixed(1)} vs ${previous.date})`
      : "";
    await postToSlack(
      `:bar_chart: *${brand.name}* visibility for ${run_date}: *${score.toFixed(1)}*${change}\n` +
        `Mentioned in ${Math.round(mention_rate * 100)}% of ${answers_scored} AI answers.`,
    );
  }
}

createServer((req, res) => {
  if (req.method !== "POST" || req.url !== "/hooks/quotable") {
    res.writeHead(404).end();
    return;
  }
  const chunks = [];
  let size = 0;
  req.on("data", (chunk) => {
    size += chunk.length;
    if (size > MAX_BODY_BYTES) req.destroy();
    else chunks.push(chunk);
  });
  req.on("end", () => {
    const rawBody = Buffer.concat(chunks);
    if (!verify(rawBody, req.headers["x-quotable-signature"], req.headers["x-quotable-timestamp"])) {
      res.writeHead(401).end("invalid signature");
      return;
    }
    const event = JSON.parse(rawBody.toString("utf8"));

    // Answer first, work after: Quotable needs a 2xx within 10 seconds.
    res.writeHead(204).end();
    if (seen.has(event.id)) return;
    seen.add(event.id);

    handle(event).catch((error) => {
      seen.delete(event.id); // a redelivery from Settings can try again
      console.error(`Failed to handle ${event.type} ${event.id}:`, error);
    });
  });
}).listen(Number(process.env.PORT ?? 3000), () => {
  console.log(`Listening on :${process.env.PORT ?? 3000}/hooks/quotable`);
});
```

```python slack_alerts.py theme={"system"}
# Python 3.10+, pip install flask requests. Run: python slack_alerts.py
import hashlib
import hmac
import json
import os
import threading
import time
from datetime import date, timedelta

import requests
from flask import Flask, request

SECRET = os.environ["QUOTABLE_WEBHOOK_SECRET"]
SLACK_URL = os.environ["SLACK_WEBHOOK_URL"]
API = "https://app.usequotable.com/api/v1"

api_session = requests.Session()
api_session.headers["Authorization"] = f"Bearer {os.environ['QUOTABLE_API_KEY']}"

app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 256 * 1024

# Deduplication. In production, use your database with a unique index on the event id.
seen: set[str] = set()

def verify(raw_body: bytes, signature_header: str | None, timestamp_header: str | None) -> bool:
    if not signature_header or not timestamp_header:
        return False
    try:
        timestamp = int(timestamp_header)
    except ValueError:
        return False
    if abs(time.time() - timestamp) > 300:
        return False
    expected = hmac.new(SECRET.encode(), f"{timestamp}.".encode() + raw_body, hashlib.sha256).hexdigest()
    offered = [p.strip()[3:] for p in signature_header.split(",") if p.strip().startswith("v1=")]
    return any(hmac.compare_digest(sig, expected) for sig in offered)

def api(path: str):
    url = path if path.startswith("http") else f"{API}{path}"
    res = api_session.get(url, timeout=30)
    res.raise_for_status()
    return res.json()

def post_to_slack(text: str):
    requests.post(SLACK_URL, json={"text": text}, timeout=10).raise_for_status()

def handle(event: dict):
    data = event["data"]
    if event["type"] == "tracking.run.finalized":
        run_date = data["run_date"]
        brand = api(event["resource"]["href"])  # GET /projects/{project_id}
        start = (date.fromisoformat(run_date) - timedelta(days=14)).isoformat()
        series = api(f"/projects/{event['project_id']}/visibility?from={start}&to={run_date}")
        earlier = [p for p in series["data"] if p["date"] < run_date]
        change = ""
        if earlier:
            prev = earlier[-1]
            change = f" ({data['score'] - prev['score']:+.1f} vs {prev['date']})"
        post_to_slack(
            f":bar_chart: *{brand['name']}* visibility for {run_date}: *{data['score']:.1f}*{change}\n"
            f"Mentioned in {round(data['mention_rate'] * 100)}% of {data['answers_scored']} AI answers."
        )

def handle_safely(event: dict):
    try:
        handle(event)
    except Exception as error:  # a redelivery from Settings can try again
        seen.discard(event["id"])
        print(f"Failed to handle {event['type']} {event['id']}: {error}")

@app.post("/hooks/quotable")
def quotable_webhook():
    raw_body = request.get_data()
    if not verify(raw_body, request.headers.get("X-Quotable-Signature"), request.headers.get("X-Quotable-Timestamp")):
        return "invalid signature", 401
    event = json.loads(raw_body)
    if event["id"] not in seen:
        seen.add(event["id"])
        # Answer first, work after: Quotable needs a 2xx within 10 seconds.
        threading.Thread(target=handle_safely, args=(event,), daemon=True).start()
    return "", 204

if __name__ == "__main__":
    app.run(port=int(os.environ.get("PORT", "3000")))
```

## Test it locally

Quotable only delivers to public HTTPS URLs, but you can test the receiver on your machine by signing a sample event yourself. Start the receiver, then run this script with the same `QUOTABLE_WEBHOOK_SECRET`:

```javascript send-test-event.mjs theme={"system"}
// Node.js 20+. Run: node send-test-event.mjs <project_id>
import { createHmac, randomUUID } from "node:crypto";

const projectId = process.argv[2];
const body = JSON.stringify({
  id: randomUUID(),
  type: "tracking.run.finalized",
  schema_version: 1,
  occurred_at: new Date().toISOString(),
  org_id: "00000000-0000-0000-0000-000000000000",
  project_id: projectId,
  resource: {
    type: "project",
    id: projectId,
    href: `https://app.usequotable.com/api/v1/projects/${projectId}`,
  },
  data: { run_date: new Date().toISOString().slice(0, 10), score: 43.8, mention_rate: 0.6111, answers_scored: 36 },
});
const timestamp = Math.floor(Date.now() / 1000);
const signature = createHmac("sha256", process.env.QUOTABLE_WEBHOOK_SECRET)
  .update(`${timestamp}.${body}`)
  .digest("hex");

const res = await fetch("http://localhost:3000/hooks/quotable", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "X-Quotable-Timestamp": String(timestamp),
    "X-Quotable-Signature": `v1=${signature}`,
  },
  body,
});
console.log(res.status); // 204
```

Use the id of a real brand your API key can read, so the receiver's API calls succeed.

## Expected output

After each day's tracking is scored, the receiver posts this message text. Slack shows `:bar_chart:` as an emoji and text between asterisks in bold.

```text theme={"system"}
:bar_chart: *Acme Analytics* visibility for 2026-10-01: *43.8* (+2.6 vs 2026-09-30)
Mentioned in 61% of 36 AI answers.
```

## Make it production-ready

* **Persist deduplication.** The in-memory set forgets everything on restart. Store event ids in your database with a unique index, and insert before you process.
* **Use a queue for the work.** Hand the event to a job queue instead of processing it in the request process, so a crash doesn't lose it.
* **Expect re-scored days.** A day can be scored more than once. Each `tracking.run.finalized` carries the latest score, so post an update, or edit the earlier message, rather than treating it as a new day.
* **Watch the delivery log.** If the receiver is down for more than about a day and a half, deliveries go dead. Redeliver them from **Settings → Webhooks** once it's back. See [Delivery and retries](https://docs.usequotable.com/webhooks/delivery-and-retries.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.