Streaming donations: Python
This bot receives donations through the live stream and prints those allowed by the moderation rules. It uses one file and the centrifuge-python library. Delivery time depends on payment processing and the source conditions.
What you need
Section titled “What you need”- Python 3.10 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.py.
import asyncio, json, os, random, re, sys, urllib.error, urllib.parse, urllib.requestfrom 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 → spaceevents = set() # ids of events already handled: one event can arrive twiceshown = set() # ids of donations already shownwaiting = {} # id → donation moderation has not decided onlast = datetime.now(timezone.utc) # time of the last event; before the first one, the launch momenttasks = 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
Section titled “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:
python3 -m pip install centrifuge-pythonpython3 bot.pypy -m pip install centrifuge-pythonpy bot.pyThe example was checked with centrifuge-python 0.7.0.
What you’ll see
Section titled “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:
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
Section titled “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
NONEandPASSEDdonations right away. It remembers aPENDINGdonation and prints it afterdonation.moderatedwith thePASSEDstatus. It never printsBLOCKEDor an unknown status: that is the Moderation and display rule. donation.replayedarrives 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). - 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 (
recoveredisFalse), the bot waits a random time from 1 to 10 seconds and reads the donations with the Donations method: the steps are in the Stream and catch-up example. - If the server rejects the connection permanently, the bot prints the code and stops: what the code means.
- The bot prints an amount as the
valuestring with its currency code, without converting it to a number: money.
Example limitations
Section titled “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_TOKENand restart the bot.
What to change
Section titled “What to change”- Replace
printwith sending to chat or an overlay. Clean the name and message first. - To receive goals too, remove
dataand handle thegoal.updatedevent: the key needs thegoals:readscope. - This program does not handle Twitch and YouTube events. See Stream channels for channels, scopes and event types. To catch up on platform events, follow the Stream and catch-up example.