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
Section titled “What you need”- Node.js 18 or newer.
- A secret key with
donations:readin theDONATTY_TOKENvariable: how to save it.
1. Save the code
Section titled “1. Save the code”Save the code as 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 → spaceconst shown = new Set(); // ids of donations already shownconst waiting = new Map(); // id → createdAt of donations moderation has not decided onlet boundary = new Date(); // read donations created since launchlet 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
Section titled “2. Run it”In the same terminal window where you saved the key, go to the folder with the file and run:
node bot.mjsWhat you’ll see
Section titled “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:
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
Section titled “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
PENDINGones and reads them again until moderation decides. - Only
NONEandPASSEDare printed. The bot never showsBLOCKEDor an unknown status. - The bot reads every page until
nextCursorisnull. It starts the next pass from the earlier of two moments: when the oldestPENDINGdonation was created, or when the newest donation was created minus one minute. It skips donations it has already shown byid. - After
429the bot waits forRetry-After. On401and403the 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
valuestring plus a currency code. Do not turn it into a floating-point number. feeCompensationis the extra paid to cover the fee, in the same format and currency, ornull;amountremains the base amount.
Example limitations
Section titled “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
Section titled “What to change”- Replace
console.logwith 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.