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

> ## Agent Instructions
> Every page is listed in https://docs.keenable.ai/llms.txt. To pick a product for a job, read https://docs.keenable.ai/choose.md
> Setup steps for agents, covering the SDKs, the MCP server and the CLI: https://docs.keenable.ai/skill.md
> Keenable search and fetch work without an API key. To add them to code, use the official SDK for the project's language: https://docs.keenable.ai/sdks.md
> Without a key, call POST https://api.keenable.ai/v1/search/public or GET https://api.keenable.ai/v1/fetch/public with an X-Keenable-Title header that names your app.
> With a key, send it in the X-API-Key header and read it from the KEENABLE_API_KEY environment variable. Never ask a user to paste a key into chat. Every access method: https://docs.keenable.ai/auth.md
> To get an API key without the console, use device login: https://docs.keenable.ai/authentication.md#device-login
> MCP server: https://api.keenable.ai/mcp (no key, or X-API-Key; keyless Codex uses https://api.keenable.ai/mcp-public), or https://api.keenable.ai/mcp-oauth for OAuth sign-in. These docs are an MCP server at https://docs.keenable.ai/mcp and the OpenAPI spec is at https://docs.keenable.ai/api-reference/openapi.json
> Keenable searches and fetches public web pages. If a question needs no web information, skip the call.
> On 402 with an API key (code insufficient_credits), stop and ask a human to add credits; don't retry. On 429, wait the number of seconds in Retry-After, then retry. Before you ship, follow https://docs.keenable.ai/production.md
> Every error, with its cause and fix, is in https://docs.keenable.ai/errors.md and moving from another search API is covered in https://docs.keenable.ai/migrate.md
> Before you compare Keenable with another search API, read https://docs.keenable.ai/guides/evaluate-search-apis.md

# Send Keenable Monitors news to a Slack channel

> Post each new page a Keenable monitor finds to Slack: verify the monitor.result.found webhook, then forward the title, link and summary to an incoming webhook.

Get a Slack message in a channel minutes after a page about your topic is published and crawled. A Keenable monitor sends each new page to your handler as a signed `monitor.result.found` event. The handler checks the signature and posts the page to a Slack incoming webhook.

## Recipe prompt

Paste this into your coding agent to have it build the recipe in your project:

```text Recipe prompt theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
Read https://docs.keenable.ai/recipes/news-monitor-to-slack.md and build the webhook handler in this project's language with the official Keenable SDK, version 0.2.0 or later. Read KEENABLE_WEBHOOK_SECRET and SLACK_WEBHOOK_URL from the environment, verify every delivery on the raw body before parsing it, and drop repeated event ids. Then show me the curl command that creates the monitor with my handler's public URL. Don't create the monitor yourself and never print the secrets.
```

## What you build

| Piece | What it does |
| - | - |
| A monitor | Watches the web for your topic. Its `webhook.events` lists `monitor.result.found`, so each accepted page is sent as soon as it's found. |
| A webhook handler | Verifies the delivery with `verify_webhook`, keeps `monitor.result.found` events and answers `204`. |
| A Slack incoming webhook | Receives `{"text": "..."}` and posts it to the channel you picked when you created it. |

You need a Keenable [API key](https://docs.keenable.ai/api-keys.md), a Slack [incoming webhook URL](https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks) and a public HTTPS address for your handler.

## When it runs

On every `monitor.result.found` event: minutes after Keenable crawls a page that reports something new about the topic. A monitor matches only pages crawled after you create it, so the first message can take minutes to hours. It sends each story once, with the first page that carries it.

## Code

This handler verifies each delivery and posts every `monitor.result.found` page to Slack. The curl tab checks the Slack webhook, then creates the monitor that points at your handler. Replace `https://hooks.example.com/keenable` with your handler's public address:

```typescript TypeScript theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
// Needs keenable 0.2.0 or later on npm.
import { verifyWebhook, WebhookVerificationError } from "keenable";

const secret = process.env.KEENABLE_WEBHOOK_SECRET ?? "";
const slackUrl = process.env.SLACK_WEBHOOK_URL ?? "";
if (!secret || !slackUrl) throw new Error("Set KEENABLE_WEBHOOK_SECRET and SLACK_WEBHOOK_URL");

// Page text can hold Slack formatting such as <!channel>: escape it
const esc = (s: string) => s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");

export async function POST(request: Request): Promise<Response> {
  const body = await request.text();
  let event;
  try {
    event = await verifyWebhook(body, request.headers, secret);
  } catch (err) {
    if (err instanceof WebhookVerificationError) return new Response(null, { status: 400 });
    throw err;
  }
  const result = event.data.result;
  if (event.type === "monitor.result.found" && result) {
    const text = `*<${esc(result.url)}|${esc(result.title ?? result.url)}>* (importance ${result.importance ?? 0})\n${esc(result.summary ?? "")}`;
    const slack = await fetch(slackUrl, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ text }),
    });
    if (!slack.ok) return new Response(null, { status: 502 });
  }
  return new Response(null, { status: 204 });
}
```

```python Python theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
# Needs keenable 0.2.0 or later on PyPI.
import os

import httpx
from flask import Flask, request
from keenable import WebhookVerificationError, verify_webhook

SECRET = os.environ.get("KEENABLE_WEBHOOK_SECRET", "")
SLACK_URL = os.environ.get("SLACK_WEBHOOK_URL", "")
if not SECRET or not SLACK_URL:
    raise SystemExit("Set KEENABLE_WEBHOOK_SECRET and SLACK_WEBHOOK_URL")

app = Flask(__name__)


def esc(s: str) -> str:
    # Page text can hold Slack formatting such as <!channel>: escape it
    return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")


@app.post("/keenable")
def keenable_webhook():
    try:
        event = verify_webhook(request.get_data(), request.headers, SECRET)
    except WebhookVerificationError:
        return "", 400
    result = event.data.result
    if event.type == "monitor.result.found" and result is not None:
        text = f"*<{esc(result.url)}|{esc(result.title or result.url)}>* (importance {result.importance or 0})\n{esc(result.summary or '')}"
        httpx.post(SLACK_URL, json={"text": text}, timeout=10).raise_for_status()
    return "", 204
```

```go Go theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strings"

	"github.com/keenableai/keenable-sdk/go"
)

// Page text can hold Slack formatting such as <!channel>: escape it
var esc = strings.NewReplacer("&", "&amp;", "<", "&lt;", ">", "&gt;").Replace

func main() {
	secret := os.Getenv("KEENABLE_WEBHOOK_SECRET")
	slackURL := os.Getenv("SLACK_WEBHOOK_URL")
	if secret == "" || slackURL == "" {
		log.Fatal("set KEENABLE_WEBHOOK_SECRET and SLACK_WEBHOOK_URL")
	}
	http.HandleFunc("/keenable", func(w http.ResponseWriter, r *http.Request) {
		body, err := io.ReadAll(r.Body)
		if err != nil {
			http.Error(w, "", http.StatusBadRequest)
			return
		}
		event, err := keenable.VerifyWebhook(body, r.Header, secret, nil)
		var refused *keenable.WebhookVerificationError
		if errors.As(err, &refused) {
			http.Error(w, "", http.StatusBadRequest)
			return
		} else if err != nil {
			http.Error(w, "", http.StatusInternalServerError)
			return
		}
		result := event.Data.Result
		if event.Type == "monitor.result.found" && result != nil {
			title, summary, importance := result.URL, "", 0
			if result.Title != nil {
				title = *result.Title
			}
			if result.Summary != nil {
				summary = *result.Summary
			}
			if result.Importance != nil {
				importance = *result.Importance
			}
			text := fmt.Sprintf("*<%s|%s>* (importance %d)\n%s", esc(result.URL), esc(title), importance, esc(summary))
			payload, _ := json.Marshal(map[string]string{"text": text})
			resp, err := http.Post(slackURL, "application/json", bytes.NewReader(payload))
			if err != nil {
				http.Error(w, "", http.StatusBadGateway)
				return
			}
			resp.Body.Close()
			if resp.StatusCode != http.StatusOK {
				http.Error(w, "", http.StatusBadGateway)
				return
			}
		}
		w.WriteHeader(http.StatusNoContent)
	})
	log.Fatal(http.ListenAndServe(":8080", nil))
}
```

```rust Rust theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
// Needs keenable 0.2.0 or later, plus axum, tokio and serde_json in Cargo.toml.
use std::sync::Arc;

use axum::{
    body::Bytes,
    extract::State,
    http::{HeaderMap, StatusCode},
    routing::post,
    Router,
};

struct Config {
    secret: String,
    slack_url: String,
    http: keenable::reqwest::Client,
}

// Page text can hold Slack formatting such as <!channel>: escape it
fn esc(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

async fn keenable_webhook(
    State(config): State<Arc<Config>>,
    headers: HeaderMap,
    body: Bytes,
) -> StatusCode {
    let event = match keenable::verify_webhook(&body, &headers, &config.secret) {
        Ok(event) => event,
        Err(keenable::Error::WebhookVerification(_)) => return StatusCode::BAD_REQUEST,
        Err(_) => return StatusCode::INTERNAL_SERVER_ERROR,
    };
    if let (true, Some(result)) = (event.event_type == "monitor.result.found", event.data.result) {
        let text = format!(
            "*<{}|{}>* (importance {})\n{}",
            esc(&result.url),
            esc(result.title.as_deref().unwrap_or(&result.url)),
            result.importance.unwrap_or(0),
            esc(result.summary.as_deref().unwrap_or(""))
        );
        let sent = config
            .http
            .post(&config.slack_url)
            .header("Content-Type", "application/json")
            .body(serde_json::json!({ "text": text }).to_string())
            .send()
            .await;
        if !matches!(sent, Ok(ref resp) if resp.status().is_success()) {
            return StatusCode::BAD_GATEWAY;
        }
    }
    StatusCode::NO_CONTENT
}

#[tokio::main]
async fn main() {
    let var = |name: &str| {
        std::env::var(name)
            .ok()
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| panic!("set {name}"))
    };
    let config = Arc::new(Config {
        secret: var("KEENABLE_WEBHOOK_SECRET"),
        slack_url: var("SLACK_WEBHOOK_URL"),
        http: keenable::reqwest::Client::new(),
    });
    let app = Router::new()
        .route("/keenable", post(keenable_webhook))
        .with_state(config);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
```

```bash curl theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
# 1. Check that the Slack incoming webhook posts to your channel
curl -X POST "$SLACK_WEBHOOK_URL" \
  -H "Content-Type: application/json" \
  -d '{"text": "Keenable monitor connected"}'

# 2. Create the monitor and point its monitor.result.found events at your handler
curl -X POST https://api.keenable.ai/v1/monitors \
  -H "X-API-Key: $KEENABLE_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: eu-ai-act-to-slack" \
  -d '{
    "name": "EU AI Act enforcement to Slack",
    "search": {"query": "EU AI Act enforcement actions and fines"},
    "webhook": {
      "url": "https://hooks.example.com/keenable",
      "events": ["monitor.result.found", "monitor.disabled"]
    }
  }'
```

Set `KEENABLE_WEBHOOK_SECRET` to the `webhook.secret` from the create response. Only the create response carries it. Each handler stops at startup if either variable is missing, and answers `400` to a delivery whose signature doesn't match.

## Example output

Each new page arrives in Slack as one message: the title as a link and the importance from 3 to 5, then the result's one-line `summary` on the second line. With the page from the [Monitors](https://docs.keenable.ai/products/monitors#read-the-results) example, the first line of the message text is:

```text Slack message text theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
*<https://example.com/news/example-70b|Example Labs releases a 70B open-weights model>* (importance 4)
```

Slack answers `200` with the body `ok`. The handler then answers Keenable with `204`.

## Production notes

| Situation | What happens | What to do |
| - | - | - |
| Slow handler | Keenable waits 15 seconds for a `2xx`, then retries with backoff for up to 12 attempts over about 15 hours. | Answer fast. If Slack is slow, queue the message and answer `204` first. |
| Retried delivery | An event keeps its `id` across retries, so Slack can get the same page twice. | Store the `id` of each event you posted and skip repeats. |
| Slack rejects the post | Slack answers with an error such as `invalid_payload` or `channel_is_archived`. | The handler answers with a `5xx` status, so Keenable retries the delivery. Fix the Slack side, or check [List deliveries](https://docs.keenable.ai/api-reference/monitors/deliveries.md) for the last error. |
| Titles with `<`, `>` or `&` | Slack reads them as formatting, so a page could post a mention such as `<!channel>`. | The samples replace `&` with `&amp;` first, then `<` with `&lt;` and `>` with `&gt;`, in the URL, title and summary. Keep that step if you change the message. |
| Too many messages | The topic is broad. | Narrow the query, or post only results with `importance` of 4 or 5. |
| No delivery succeeds for 3 days | Keenable disables the monitor and sends `monitor.disabled`. | Fix the handler, then set the status back to `active`. See [Statuses](https://docs.keenable.ai/products/monitors#statuses). |
| `429` from the Monitors API | Over 120 requests per minute per organization, or more than 10 of them creating monitors. | Wait, then retry. Limits on active monitors are on the [Monitors](https://docs.keenable.ai/products/monitors#limits) page. |

## Next steps

* [Competitor watch](https://docs.keenable.ai/recipes/competitor-watch.md): a scheduled digest from a competitor's own sites instead of one message per page.
* [Verify a webhook](https://docs.keenable.ai/products/monitors#verify-a-webhook): verify without the SDK.
* [Webhook events](https://docs.keenable.ai/products/monitors#webhook-events): every event type and its `data`.
* [Recipes](https://docs.keenable.ai/recipes.md): every recipe on one page.


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