# Build a chat bot

Chat with your tool: your message arrives by webhook, the answer goes out through the send call.

In a channel with replies, you write with your tool, for example with your own AI agent. There's hardly anything new to learn: your message arrives as a webhook event, and the reply is a perfectly normal message.

**You need:** [Send a message](https://packlets.app/en/docs/senden.md) and a [webhook](https://packlets.app/en/docs/webhook.md).

## How a conversation works

1. You write in the app. Your message appears immediately on the right in the history.
2. Packlets sends it to your webhook as a `message` event.
3. Your tool replies with `POST /v1/push`. The reply appears on the left in the history and as a push.

## 1. Turn on replies

In the app, create a new packlet, choose **Messages** and turn on **Allow replies**. Enter your tool's webhook URL right away. Without it, your messages won't reach your tool.

You turn an existing channel into a chat the same way: in the packlet's settings, turn on **Allow replies**. If you turn it off, the input field disappears again; the history stays.

## 2. Receive messages

When you write in the channel, your webhook gets this event:

```json
{
  "type": "message",
  "packlet_id": "9d2f7c10-3a5b-4c8e-9f21-6b7d8e9f0a12",
  "message_id": "c41e8a77-0d1f-4e6a-b2c3-91a4d5e6f708",
  "text": "Is the shop back up?",
  "sent_at": "2026-11-10T08:15:00.000Z"
}
```

`text` holds what you wrote, up to 4,000 characters.

## 3. Reply

The reply is the same call as for any message. The key makes sure it lands in the right channel:

```bash
curl https://api.packlets.app/v1/push \
  -H "Authorization: Bearer $PACKLETS_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text": "Yes. All servers have been responding since 9:52 AM."}'
```

Everything a message can do works here too: [formatting](https://packlets.app/en/docs/senden.md#formatting), [buttons](https://packlets.app/en/docs/knoepfe.md) and [elements](https://packlets.app/en/docs/nachrichten-elemente.md). You usually leave out the title in replies.

## A complete bot

This bot checks the signature and replies to every message:

```python
import hashlib, hmac, os, requests
from flask import Flask, request

app = Flask(__name__)
PACKLETS_KEY = os.environ["PACKLETS_KEY"]
SECRET = hashlib.sha256(PACKLETS_KEY.encode()).hexdigest().encode()

def reply(text):
    requests.post("https://api.packlets.app/v1/push", timeout=10,
                  headers={"Authorization": f"Bearer {PACKLETS_KEY}"},
                  json={"text": text}).raise_for_status()

@app.post("/packlets")
def packlets_webhook():
    expected = "sha256=" + hmac.new(SECRET, request.get_data(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, request.headers.get("X-Packlets-Signature", "")):
        return "", 401
    event = request.get_json()
    if event["type"] == "message":
        reply(f"You wrote: {event['text']}")
    return "", 204

app.run(port=8080)
```

```typescript
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";

const PACKLETS_KEY = process.env.PACKLETS_KEY ?? "";
const secret = createHash("sha256").update(PACKLETS_KEY).digest("hex");

async function reply(text: string) {
  const res = await fetch("https://api.packlets.app/v1/push", {
    method: "POST",
    headers: { Authorization: `Bearer ${PACKLETS_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({ text }),
  });
  if (!res.ok) throw new Error(`Packlets ${res.status}: ${await res.text()}`);
}

createServer(async (req, res) => {
  let body = "";
  for await (const chunk of req) body += chunk;
  const expected = Buffer.from("sha256=" + createHmac("sha256", secret).update(body, "utf8").digest("hex"));
  const given = Buffer.from(String(req.headers["x-packlets-signature"] ?? ""));
  if (expected.length !== given.length || !timingSafeEqual(expected, given)) {
    res.writeHead(401).end();
    return;
  }
  const event = JSON.parse(body) as { type: string; text?: string };
  res.writeHead(204).end(); // respond first, then work
  if (event.type === "message") await reply(`You wrote: ${event.text}`);
}).listen(8080);
```

## When the reply takes longer

Packlets waits only 10 seconds for the webhook's response. An AI often needs longer. So separate the two:

1. Acknowledge the webhook right away with a `2xx` status.
2. Let the reply be produced in the background.
3. Send it with `POST /v1/push` as soon as it's ready.

If you acknowledge too late, Packlets sends the same event again, and your bot replies twice. So remember the `message_id` of the messages you're already handling. More on this under [Duplicate events](https://packlets.app/en/docs/webhook.md#duplicate-events).

## Good to know

- **Writing on its own** is something your tool can do at any time, for example a reminder. It doesn't have to wait for a message.
- **The history** isn't sent to your tool. Every event contains only the one new message. If your bot needs a memory, it stores the messages itself.
- **Your texts are input from outside.** Don't run them as commands without checking, see [Keys and security](https://packlets.app/en/docs/sicherheit.md).
