# Node.js bot

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

## What you need

- Node.js 18 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.mjs`.

> **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.

```js title="bot.mjs"
const API = "https://api.donatty.com";
const TOKEN = process.env.DONATTY_TOKEN;
if (!TOKEN) {
  console.error("Set DONATTY_TOKEN: a secret key with the donations:read scope");
  process.exit(1);
}

const SHOW = new Set(["NONE", "PASSED"]);
const clean = text => String(text ?? "").replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, " ");  // untrusted input: control characters → space
const shown = new Set();    // ids of donations already shown
const waiting = new Map();  // id → createdAt of donations moderation has not decided on
let boundary = new Date();  // read donations created since launch
let failures = 0;

async function get(url) {
  const res = await fetch(url, { headers: { Authorization: `Bearer ${TOKEN}` } });
  if (res.ok) return res.json();
  const problem = await res.json().catch(() => ({}));
  if (res.status === 401 || res.status === 403) {
    console.error(res.status, problem.code, problem.type);
    process.exit(1);
  }
  const error = new Error(`${res.status} ${problem.code ?? ""}`.trim());
  error.retryAfter = res.status === 429 ? Number(res.headers.get("Retry-After") ?? 5) : null;
  throw error;
}

// One pass: all pages of the window with the same parameters.
async function readWindow() {
  const items = [];
  let cursor = null;
  do {
    const url = `${API}/v1/donations?limit=100&since=${boundary.toISOString()}`
      + (cursor ? `&cursor=${encodeURIComponent(cursor)}` : "");
    const page = await get(url);
    items.push(...page.items);
    cursor = page.nextCursor;
  } while (cursor);
  return items;
}

function handle(items) {
  const seen = new Set();
  for (const d of items.reverse()) {  // oldest first
    seen.add(d.id);
    if (d.moderation.status === "PENDING") {
      waiting.set(d.id, d.createdAt);
      continue;
    }
    waiting.delete(d.id);
    if (SHOW.has(d.moderation.status) && !shown.has(d.id)) {
      shown.add(d.id);
      const fee = d.feeCompensation ? ` (+${d.feeCompensation.value} ${d.feeCompensation.currency} fee covered)` : "";
      console.log(`${clean(d.donorName)} — ${d.amount.value} ${d.amount.currency}${fee}: ${clean(d.message)}`);
    }
  }
  for (const id of waiting.keys()) if (!seen.has(id)) waiting.delete(id);
  if (items.length > 0) {
    const newest = Math.max(...items.map(d => Date.parse(d.createdAt))) - 60_000;
    const oldestWaiting = Math.min(Infinity, ...[...waiting.values()].map(Date.parse));
    boundary = new Date(Math.max(boundary, Math.min(newest, oldestWaiting)));
  }
}

while (true) {
  let pause = 5;
  try {
    handle(await readWindow());
    failures = 0;
  } catch (error) {
    failures += 1;
    pause = error.retryAfter ?? Math.min(2 ** failures, 60);
    console.error(error.message);
  }
  await new Promise(resolve => setTimeout(resolve, pause * 1000));
}
```

## 2. Run it

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

```sh
node bot.mjs
```

## 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 `console.log` 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).
