# Python bot

This bot checks for new donations every 5 seconds and prints the ones you can show on stream. One file, no extra libraries.

## What you need

- Python 3.9 or newer.
- A secret key with `donations:read` in the `DONATTY_TOKEN` variable: [how to save it](https://developers.donatty.com/en/quickstart/bot.md#2-save-the-key-in-a-variable).

## 1. Save the code

Save the code as `bot.py`.

> **Name and message are untrusted input.**
> A donor's message and name are untrusted input: sanitize them before printing to chat, an overlay or HTML. The example replaces control characters with a space so a donor cannot control your terminal.

```python title="bot.py"
import json, os, re, sys, time, urllib.error, urllib.parse, urllib.request
from datetime import datetime, timedelta, timezone

API = "https://api.donatty.com"
TOKEN = os.environ.get("DONATTY_TOKEN") or sys.exit(
    "Set DONATTY_TOKEN: a secret key with the donations:read scope")

SHOW = {"NONE", "PASSED"}
CONTROL = re.compile(r"[\x00-\x1f\x7f-\x9f\u2028\u2029\u202a-\u202e\u2066-\u2069]")  # untrusted input: control characters → space
shown = set()                        # ids of donations already shown
waiting = {}                         # id → createdAt of donations moderation has not decided on
boundary = datetime.now(timezone.utc)  # read donations created since launch
failures = 0


class Retry(Exception):
    def __init__(self, message, after=None):
        super().__init__(message)
        self.after = after


def clean(text):
    return CONTROL.sub(" ", str(text))


def parse(ts):
    return datetime.fromisoformat(re.sub(r"(\.\d{6})\d+", r"\1", ts).replace("Z", "+00:00"))


def get(url):
    req = urllib.request.Request(url, headers={"Authorization": f"Bearer {TOKEN}"})
    try:
        with urllib.request.urlopen(req, timeout=10) as res:
            return json.load(res)
    except urllib.error.HTTPError as err:
        try:
            problem = json.load(err)
        except ValueError:
            problem = {}
        if err.code in (401, 403):
            sys.exit(f"{err.code} {problem.get('code')} {problem.get('type')}")
        after = int(err.headers.get("Retry-After", 5)) if err.code == 429 else None
        raise Retry(f"{err.code} {problem.get('code', '')}".strip(), after)
    except (urllib.error.URLError, OSError, ValueError) as err:
        raise Retry(str(err))


# One pass: all pages of the window with the same parameters.
def read_window():
    items, cursor = [], None
    while True:
        url = f"{API}/v1/donations?limit=100&since={boundary.isoformat().replace('+00:00', 'Z')}"
        if cursor:
            url += "&cursor=" + urllib.parse.quote(cursor, safe="")
        page = get(url)
        items += page["items"]
        cursor = page["nextCursor"]
        if not cursor:
            return items


def handle(items):
    global boundary
    seen = set()
    for d in reversed(items):  # oldest first
        seen.add(d["id"])
        status = d["moderation"]["status"]
        if status == "PENDING":
            waiting[d["id"]] = d["createdAt"]
            continue
        waiting.pop(d["id"], None)
        if status in SHOW and d["id"] not in shown:
            shown.add(d["id"])
            amount = d["amount"]
            fee = d.get("feeCompensation")
            extra = f' (+{fee["value"]} {fee["currency"]} fee covered)' if fee else ""
            print(f'{clean(d["donorName"])} — {amount["value"]} {amount["currency"]}{extra}: {clean(d["message"])}', flush=True)
    for stale in [key for key in waiting if key not in seen]:
        del waiting[stale]
    if items:
        newest = max(parse(d["createdAt"]) for d in items) - timedelta(minutes=1)
        boundary = max(boundary, min([newest, *map(parse, waiting.values())]))


while True:
    pause = 5
    try:
        handle(read_window())
        failures = 0
    except Retry as error:
        failures += 1
        pause = error.after if error.after is not None else min(2 ** failures, 60)
        print(error, file=sys.stderr, flush=True)
    time.sleep(pause)
```

## 2. Run it

In the same terminal window where you saved the key, go to the folder with the file and run:


**macOS and Linux:**

```sh
python3 bot.py
```
**Windows (PowerShell):**

```powershell
py bot.py
```


## What you'll see

The bot shows donations that arrive after it starts, so the terminal is empty at first. Every new donation you can show on stream appears as a line:

```text
Alex — 500.00 RUB (+27.00 RUB fee covered): Thanks for the stream!
```

If the donor paid extra to cover the fee, the extra is shown in parentheses; otherwise there are no parentheses.

You can only test the bot with a real donation: «Тест на стриме» (Test on stream) in your dashboard shows an alert but creates no donation, so the API does not return it.

## How it works

- The bot reads donations without a moderation filter, so a donation that first waited for a decision and passed later is not lost. It remembers `PENDING` ones and reads them again until moderation decides.
- Only `NONE` and `PASSED` are printed. The bot never shows `BLOCKED` or an unknown status.
- The bot reads every page until `nextCursor` is `null`. It starts the next pass from the earlier of two moments: when the oldest `PENDING` donation was created, or when the newest donation was created minus one minute. It skips donations it has already shown by `id`.
- After `429` the bot waits for `Retry-After`. On `401` and `403` the bot stops and prints the error code with a link to its page, which says what to do with the key. On 5xx and network errors it retries with a pause of 2, 4, 8… seconds, up to a minute.
- An amount is the `value` string plus a currency code. Do not turn it into a floating-point number.
- `feeCompensation` is the extra paid to cover the fee, in the same format and currency, or `null`; `amount` remains the base amount.

## Example limitations

- After a restart the bot starts from the current moment: it does not remember what it showed before.
- The bot misses a donation that appears in the list more than a minute after it was created. This happens with Donation Alerts donations after a connection drop.
- The bot also misses an old rejected donation that you bring back with «Повторить на стриме» (Repeat on stream).

## What to change

- Replace `print` with sending to chat or an overlay. Clean the name and message first.
- While there are fewer than 100 new donations, one pass is one request. Each extra page is one more request towards the [rate limit](https://developers.donatty.com/en/rate-limits.md).
