# Ready-made code

Building blocks to copy: client for Python and TypeScript, webhook receiver and shell.

Building blocks to copy. All of them read the key from the environment variable `PACKLETS_KEY`.

## Client for Python

A file `packlets.py` with two functions: send a message and set an app's page.

```python
import os, requests  # pip install requests

API = "https://api.packlets.app"
HEADERS = {"Authorization": f"Bearer {os.environ['PACKLETS_KEY']}"}

def _call(method, path, body):
    res = requests.request(method, API + path, headers=HEADERS, json=body, timeout=10)
    if not res.ok:
        raise RuntimeError(f"Packlets {res.status_code}: {res.text}")
    return res.json()

def push(text, title=None, url=None, image=None, buttons=None, elements=None, priority="normal"):
    """Send a message. Returns the message_id."""
    body = {"text": text, "title": title, "url": url, "image": image,
            "buttons": buttons or [], "elements": elements or [], "priority": priority}
    return _call("POST", "/v1/push", body)["message_id"]

def set_page(page):
    """App: set the page the app shows (https address)."""
    return _call("PUT", "/v1/ui", {"page": page})
```

Here's how you use it:

```python
from packlets import push, set_page

push("Last night's backup is done.", title="Backup", priority="silent")

push("shop-api hasn't responded since 9:38 AM.", title="Server down", priority="high",
     buttons=[{"id": "restart", "label": "Restart"}])

push("23 orders, 1,204 in revenue.", title="Daily report", elements=[
    {"type": "chart", "id": "umsatz", "label": "Revenue this week", "unit": "€",
     "points": [{"label": "Mon", "value": 860}, {"label": "Tue", "value": 1204}]},
])

set_page("https://your-server.example/invoices")  # only for a packlet of the app kind
```

## Client for TypeScript

A file `packlets.ts`, runs on Node.js 18 or newer without further packages.

```typescript
const API = "https://api.packlets.app";

async function call<T>(method: string, path: string, body: unknown): Promise<T> {
  const res = await fetch(API + path, {
    method,
    headers: { Authorization: `Bearer ${process.env.PACKLETS_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });
  if (!res.ok) throw new Error(`Packlets ${res.status}: ${await res.text()}`);
  return (await res.json()) as T;
}

/** Send a message. Returns the message_id. */
export async function push(message: PackletsMessage): Promise<string> {
  return (await call<{ message_id: string }>("POST", "/v1/push", message)).message_id;
}

/** App: set the page the app shows (https address) */
export const setPage = (page: string) => call<{ ok: true; page: string }>("PUT", "/v1/ui", { page });
```

## Types for TypeScript

These go in the same file. They let your editor check as you type whether messages, elements and events are correct.

```typescript
export type PackletsMessage = {
  text: string;
  title?: string;
  url?: string;
  image?: string;
  buttons?: { id: string; label: string; url?: string }[];
  elements?: PackletsElement[];
  priority?: "normal" | "high" | "silent";
};

type Layout = {
  /** Unique per message: letters, digits, _ and -, 1 to 40 characters */
  id: string;
  /** Columns in the grid, default 6 (full width) */
  width?: 1 | 2 | 3 | 4 | 5 | 6;
  /** Minimum height in points */
  height?: number;
};

export type PackletsElement =
  | (Omit<Layout, "height"> & { type: "text"; text: string; style?: "title" | "body" | "caption" })
  | (Layout & { type: "button"; label: string; style?: "primary" | "secondary" })
  | (Layout & { type: "toggle"; label: string; description?: string; value?: boolean })
  | (Layout & { type: "input"; label: string; placeholder?: string; button?: string; value?: string })
  | (Layout & {
      type: "chart";
      label: string;
      points?: { label: string; value: number }[];
      chart?: "bar" | "line";
      unit?: string;
      highlight?: number;
    })
  | (Layout & { type: "table"; columns: string[]; rows?: (string | number)[][]; label?: string });

/** Events at the webhook */
export type PackletsEvent =
  | { type: "button"; packlet_id: string; message_id: string; button_id: string; pressed_at: string }
  | { type: "message"; packlet_id: string; message_id: string; text: string; sent_at: string }
  | {
      type: "ui";
      packlet_id: string;
      /** The message the element belongs to */
      message_id: string;
      element_id: string;
      /** Toggle: true/false, input field: text, button: null */
      value: boolean | string | null;
      changed_at: string;
    };
```

## Webhook receiver

Checks the signature and dispatches the three events. The explanation is under [Set up a webhook](https://packlets.app/en/docs/webhook.md).

```python
import hashlib, hmac, os
from flask import Flask, request  # pip install flask

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

@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"] == "button":
        print("Button", event["button_id"], "in message", event["message_id"])
    elif event["type"] == "ui":
        print("Element", event["element_id"], "in message", event["message_id"], "is now", event["value"])
    elif event["type"] == "message":
        print("Chat:", event["text"])
    return "", 204

app.run(port=8080)
```

```typescript
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";
import type { PackletsEvent } from "./packlets.ts";

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

function isFromPacklets(rawBody: string, signature = ""): boolean {
  const expected = Buffer.from("sha256=" + createHmac("sha256", secret).update(rawBody, "utf8").digest("hex"));
  const given = Buffer.from(signature);
  return expected.length === given.length && timingSafeEqual(expected, given);
}

createServer(async (req, res) => {
  let body = "";
  for await (const chunk of req) body += chunk;
  if (!isFromPacklets(body, req.headers["x-packlets-signature"] as string | undefined)) {
    res.writeHead(401).end();
    return;
  }
  res.writeHead(204).end(); // respond first, then work

  const event = JSON.parse(body) as PackletsEvent;
  if (event.type === "button") console.log("Button", event.button_id, "in message", event.message_id);
  else if (event.type === "ui") console.log("Element", event.element_id, "in message", event.message_id, "is now", event.value);
  else if (event.type === "message") console.log("Chat:", event.text);
}).listen(8080);
```

## Shell

For cron jobs and scripts. The first version sends JSON, the second is the shortest that works:

```bash
curl -fsS https://api.packlets.app/v1/push \
  -H "Authorization: Bearer $PACKLETS_KEY" \
  -H "Content-Type: application/json" \
  -d '{"title":"Backup","text":"The nightly backup is done.","priority":"silent"}'
```

```bash
curl -fsS https://api.packlets.app/v1/push -H "Authorization: Bearer $PACKLETS_KEY" -d text="Backup done"
```

With `-f`, `curl` exits with a non-zero status on an error. That way your script notices when something didn't work.

A message only on failure:

```bash
./backup.sh || curl -fsS https://api.packlets.app/v1/push \
  -H "Authorization: Bearer $PACKLETS_KEY" \
  -d title="Backup" -d text="The backup failed." -d priority=high
```
