# Streaming donations: Python

This bot receives donations through the [live stream](https://developers.donatty.com/en/realtime.md) and prints those allowed by the [moderation rules](https://developers.donatty.com/en/structures/donation.md#moderation-and-display). It uses one file and the [centrifuge-python](https://github.com/centrifugal/centrifuge-python) library. Delivery time depends on payment processing and the [source conditions](https://developers.donatty.com/en/conditions/sources.md).

## What you need

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

## 1. Save the code

Save the code as `bot.py`.

> **Name and message are untrusted input.**
> Treat donor names and messages as untrusted input. Sanitize them before sending them to chat, an overlay or HTML. This example replaces control characters with a space to prevent messages from controlling the terminal.

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

from centrifuge import Client, ClientEventHandler

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
events = set()   # ids of events already handled: one event can arrive twice
shown = set()    # ids of donations already shown
waiting = {}     # id → donation moderation has not decided on
last = datetime.now(timezone.utc)  # time of the last event; before the first one, the launch moment
tasks = set()


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 show(d):
    shown.add(d["id"])
    amount = d["amount"]
    print(f'{clean(d["donorName"])} — {amount["value"]} {amount["currency"]}: {clean(d["message"])}', flush=True)


def donation(d, replay=False):
    status = d["moderation"]["status"]
    if status == "PENDING":
        waiting[d["id"]] = d  # shown after donation.moderated with the PASSED status
    elif status in SHOW and (replay or d["id"] not in shown):
        show(d)


def handle(event):
    global last
    if event["id"] in events:
        return
    events.add(event["id"])
    last = max(last, parse(event["time"]))
    kind, data = event["type"], event["data"]
    if kind == "donation.created":
        donation(data)
    elif kind == "donation.replayed":  # you pressed «Повторить на стриме» (Repeat on stream)
        donation(data, replay=True)
    elif kind == "donation.moderated":
        d = waiting.pop(data["id"], None)
        if d and data["moderation"]["status"] == "PASSED":
            show(d)


def get(url):
    req = urllib.request.Request(url, headers={"Authorization": f"Bearer {TOKEN}"})
    with urllib.request.urlopen(req, timeout=10) as res:
        return json.load(res)


# The channel history did not cover the gap: read the donations with regular requests.
async def catch_up():
    since = (last - timedelta(minutes=1)).isoformat().replace("+00:00", "Z")
    await asyncio.sleep(random.uniform(1, 10))  # so that all programs do not arrive in the same second after an outage
    items, cursor = [], None
    while True:
        url = f"{API}/v1/donations?limit=100&since={since}"
        if cursor:
            url += "&cursor=" + urllib.parse.quote(cursor, safe="")
        try:
            page = await asyncio.to_thread(get, url)
        except urllib.error.HTTPError as err:
            if err.code in (401, 403):
                sys.exit(f"{err.code}: the key does not work")
            await asyncio.sleep(int(err.headers.get("Retry-After", 5)))
            continue
        except (urllib.error.URLError, OSError, ValueError) as err:
            print(err, file=sys.stderr, flush=True)
            await asyncio.sleep(5)
            continue
        items += page["items"]
        cursor = page["nextCursor"]
        if not cursor:
            break
    for d in reversed(items):  # oldest first
        donation(d)


class Handler(ClientEventHandler):
    async def on_connecting(self, ctx):
        print(f"connecting: {ctx.code} {ctx.reason}", file=sys.stderr, flush=True)

    async def on_subscribed(self, ctx):
        if ctx.was_recovering and not ctx.recovered:
            task = asyncio.create_task(catch_up())  # not inside the handler: it holds up reading events
            tasks.add(task)
            task.add_done_callback(tasks.discard)

    async def on_publication(self, ctx):
        handle(ctx.pub.data)

    async def on_disconnected(self, ctx):  # final refusal: the library does not reconnect any more
        print(f"disconnected: {ctx.code} {ctx.reason}", file=sys.stderr, flush=True)
        stop.set()


async def main():
    global stop
    stop = asyncio.Event()
    client = Client(
        API.replace("http", "ws", 1) + "/v1/realtime/websocket",  # https → wss
        events=Handler(),
        headers={"Authorization": f"Bearer {TOKEN}"},
        data={"channels": ["donations"]},  # donations only; without data all the key's channels arrive
    )
    await client.connect()
    await stop.wait()
    sys.exit(1)


asyncio.run(main())
```

## 2. Run it

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


**macOS and Linux:**

```sh
python3 -m pip install centrifuge-python
python3 bot.py
```
**Windows (PowerShell):**

```powershell
py -m pip install centrifuge-python
py bot.py
```


The example was checked with centrifuge-python 0.7.0.

## What you'll see

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

```text
Alex — 500.00 RUB: Thanks for the stream!
```

To test the bot, press «Тест на стриме» (Test on stream) in your dashboard: the test donation arrives as an event.

## How it works

- The key is in the `headers=` parameter: the library sends it as a connection header, without including it in the URL.
- The bot asks for the donations channel only: `data={"channels": ["donations"]}`.
- The bot prints `NONE` and `PASSED` donations right away. It remembers a `PENDING` donation and prints it after `donation.moderated` with the `PASSED` status. It never prints `BLOCKED` or an unknown status: that is the [Moderation and display](https://developers.donatty.com/en/structures/donation.md#moderation-and-display) rule.
- `donation.replayed` arrives when you press «Повторить на стриме» (Repeat on stream): the donation is printed once more.
- The bot skips an event that arrived twice by its `id` ([repeats and order](https://developers.donatty.com/en/realtime/recovery.md#repeats-and-order)).
- After a drop the library reconnects by itself, and the server sends what was missed from the history. If the history did not cover the gap (`recovered` is `False`), the bot waits a random time from 1 to 10 seconds and reads the donations with the [Donations](https://developers.donatty.com/en/reference/donations.md) method: the steps are in the [Stream and catch-up](https://developers.donatty.com/en/examples/stream-recovery.md) example.
- If the server rejects the connection permanently, the bot prints the code and stops: [what the code means](https://developers.donatty.com/en/realtime/close-codes.md).
- The bot prints an amount as the `value` string with its currency code, without converting it to a number: [money](https://developers.donatty.com/en/data.md#formats).

## Example limitations

- After a restart, the bot reads new donations only. It does not keep a record of previously displayed donations.
- The bot does not show a donation that was waiting for moderation at the moment of the restart.
- To replace the key, set the new one in `DONATTY_TOKEN` and restart the bot.

## What to change

- Replace `print` with sending to chat or an overlay. Clean the name and message first.
- To receive goals too, remove `data` and handle the `goal.updated` event: the key needs the `goals:read` scope.
- This program does not handle Twitch and YouTube events. See [Stream channels](https://developers.donatty.com/en/realtime/channels.md) for channels, scopes and event types. To catch up on platform events, follow the [Stream and catch-up](https://developers.donatty.com/en/examples/stream-recovery.md) example.
