"""TikPlays developer API — the smallest possible example.

Connects to your live TikTok event stream and prints everything that happens.

    pip install websocket-client
    python 01_print_events.py YOUR_DEV_KEY

Create a developer key on the dashboard, under Documentation. It starts with
"tik_dev_" and is NOT the same as your normal API key.
"""
import json
import sys

import websocket

DEV_KEY = (sys.argv[1] if len(sys.argv) > 1 else "").strip() or "PASTE_YOUR_DEV_KEY"
URL = f"wss://tiktok.shibalabs.live/ws/events?k={DEV_KEY}"

ws = websocket.create_connection(URL)
print("connected — waiting for events (Ctrl+C to stop)\n")

while True:
    frame = json.loads(ws.recv())

    # "keepalive" arrives every ~20s when nothing is happening. "ready" arrives once.
    if frame["type"] != "events":
        continue

    for event in frame["events"]:
        who = event["user"]["nick"] or event["user"]["uid"]

        if event["kind"] == "gift":
            gift = event["gift"]
            print(f"{who} sent {event['count']}x {gift['name']} "
                  f"({gift['value']} coins)")
        elif event["kind"] == "comment":
            print(f"{who}: {event['message']}")
        elif event["kind"] == "like":
            print(f"{who} liked x{event['count']}")
        else:
            print(f"{who} — {event['kind']}")
