Python
Async sessions with decorator-based event handlers.
Requirements
Python 3.11+.
Installation
python -m pip install piratetok-live-py
Save the quickstart as reader.py and run python reader.py.
Quickstart
Replace username_here with the username of an account that is currently live.
import asyncio
from piratetok_live import TikTokLiveClient, EventType
async def main():
client = TikTokLiveClient("username_here")
@client.on(EventType.chat)
def on_chat(event):
user = event.data.get("user") or {}
print(f"{user.get('nickname', '?')}: {event.data.get('content', '')}")
try:
await client.connect()
finally:
client.disconnect()
asyncio.run(main())
Connection lifecycle
await client.connect() runs the session until disconnection or the retry budget is exhausted. Use asyncio.create_task(client.connect()) when the application must do other asynchronous work. Call client.disconnect() to stop.
Configuration
client = (TikTokLiveClient("username_here")
.cdn_eu()
.timeout(15)
.max_retries(10)
.stale_timeout(90)
.heartbeat_interval(10)
.proxy("socks5://127.0.0.1:1080")
.user_agent("Mozilla/5.0 ...")
.cookies("sessionid=abc; sid_tt=abc")
.language("pt")
.region("BR")
.compress(False))
| Method | Default | Description |
|---|---|---|
.cdn_eu() / .cdn_us() / .cdn(host) |
Global CDN | WebSocket CDN endpoint |
.timeout(seconds) |
10 |
HTTP request timeout in seconds |
.max_retries(n) |
5 |
Consecutive failed reconnects before giving up (a 30 s+ session resets the count) |
.stale_timeout(seconds) |
60 |
Seconds without data before triggering a reconnect |
.heartbeat_interval(seconds) |
10 |
WSS heartbeat interval (also sent as heartbeat_duration) |
.proxy(url) |
None | HTTP/HTTPS/SOCKS5 proxy for all HTTP + WSS traffic |
.user_agent(ua) |
Random from pool | Override the user agent (rotated automatically on reconnect by default) |
.cookies(cookies) |
None | Append session cookies alongside ttwid in the WSS cookie header |
.language(lang) |
System detected | Override the language sent in WSS params (e.g. "pt", "ro") |
.region(reg) |
System detected | Override the region sent in WSS params (e.g. "BR", "RO") |
.compress(enabled) |
True |
Disable gzip compression for WSS payloads (trades bandwidth for CPU) |
Room info (optional, separate call)
from piratetok_live import check_online, fetch_room_info
result = check_online("username_here")
info = fetch_room_info(result.room_id)
# 18+ rooms
info = fetch_room_info(result.room_id, cookies="sessionid=abc; sid_tt=abc")
Viewers
The top-viewers box (usually top 3) rides the WSS feed — no cookies:
from piratetok_live import top_viewers
@client.on(EventType.room_user_seq)
def on_seq(evt):
for c in top_viewers(evt.data):
print(c["rank"], c["user"].get("nickname"), c["score"])
The full roster (the web viewer panel) is a separate HTTP call. TikTok requires session
cookies for this one call — without them it raises SessionRequiredError:
from piratetok_live import check_online, fetch_room_audience
room = check_online("username_here")
audience = fetch_room_audience(room.room_id, room.anchor_id, cookies="sessionid=abc; sid_tt=abc")
# audience.total, audience.anonymous, audience.viewers[i].username / nickname / rank / ...
Pass anchor_id=None to resolve it from room info (one extra request).
Protocol reference
The basic LIVE connection uses an anonymous ttwid cookie. Session cookies may be needed for restricted room metadata or the full audience roster. These are separate calls from the event stream.
- WebSocket contract
- Room metadata
- Audience endpoint
- Authentication and connection lifecycle
- Troubleshooting
Source and license
Public source and examples · 0BSD license