Rust
Typed protobuf events through an asynchronous stream.
Requirements
Rust 2021 edition · Tokio.
Installation
Add these dependencies to Cargo.toml:
[dependencies]
piratetok-live-rs = "0.5"
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
Put the quickstart in src/main.rs and run cargo run.
Quickstart
Replace username_here with the username of an account that is currently live.
use piratetok_live_rs::{TikTokLive, structs::TikTokLiveEvent};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut stream = TikTokLive::builder("username_here").connect().await?;
while let Ok(event) = stream.next_event().await {
match event {
TikTokLiveEvent::Chat(message) => {
let name = message.user.as_ref()
.map_or("?", |user| user.nickname.as_str());
println!("{name}: {}", message.comment);
}
TikTokLiveEvent::Disconnected => break,
_ => {}
}
}
Ok(())
}
Connection lifecycle
connect().await resolves the room and returns a stream. The connection supervisor runs in a background task; consume next_event().await to observe its events. Dropping the stream aborts that task. Room resolution alone does not establish that the WebSocket handshake has completed.
Configuration
use std::time::Duration;
use piratetok_live_rs::structs::config::CdnEndpoint;
TikTokLive::builder("username_here")
.cdn(CdnEndpoint::Eu) // EU / US / Global (default)
.timeout(Duration::from_secs(15))
.heartbeat_interval(Duration::from_secs(10)) // default 10s
.max_retries(10) // default 5, 0 to disable
.stale_timeout(Duration::from_secs(90)) // default 60s
.proxy("socks5://user:pass@127.0.0.1:1080") // http(s)://, socks5://, socks5h:// (+ user:pass) for HTTP and WSS
.user_agent("Mozilla/5.0 ...") // override random UA pool with a fixed UA
.cookies("sessionid=abc; sid_tt=abc") // session cookies appended alongside ttwid
.language("de") // override auto-detected language (default from system locale)
.region("DE") // override auto-detected region (default from system locale)
.compress(false) // disable gzip for WSS payloads (default true)
.connect()
.await
Room info (optional, separate call)
use piratetok_live_rs::http::api::{fetch_room_info, FetchParams};
// Normal rooms — no cookies needed
let info = fetch_room_info("ROOM_ID", FetchParams::default()).await?;
// 18+ rooms — pass session cookies from browser DevTools
let info = fetch_room_info("ROOM_ID", FetchParams {
cookies: Some("sessionid=abc; sid_tt=abc"), ..Default::default()
}).await?;
Who's watching (viewer names)
Two sources, matching what the web/phone app shows:
// 1. Top-viewers box (the top-3 next to the counter) — free with WSS, no cookies
TikTokLiveEvent::RoomUserSeq(msg) => {
for c in msg.top_viewers() {
if let Some(u) = &c.user {
println!("#{} {} score={}", c.rank, u.nickname, c.score);
}
}
}
// 2. Full roster (every named viewer in the room) — HTTP, login-gated
use piratetok_live_rs::http::api::{fetch_room_id, fetch_room_audience, AnchorId, FetchParams};
let room = fetch_room_id("username", FetchParams::default()).await?;
let audience = fetch_room_audience(&room.room_id, AnchorId::Known(&room.anchor_id), FetchParams {
cookies: Some("sessionid=abc; sid_tt=abc"), ..Default::default()
}).await?;
println!("{} in room ({} anonymous)", audience.total, audience.anonymous);
for v in &audience.viewers {
println!("#{} @{} ({}) score={}", v.rank, v.username, v.nickname, v.score);
}
The roster endpoint needs session cookies (TikTok gates it behind login) but no
signing — no msToken, no X-Bogus. Without cookies it returns
TikTokLiveError::SessionRequired.
Gift streaks
TikTokLiveEvent::Gift(gift) => {
if gift.is_combo_gift() {
if gift.is_streak_over() {
println!("x{} = {} diamonds", gift.repeat_count, gift.diamond_total());
}
} else {
println!("{} diamonds", gift.diamond_total());
}
}
Errors from fetch_room_id / connect
| Condition | Error |
|---|---|
statusCode 19881007 |
UserNotFound(username) |
| user exists, no active room / status ≠ 2 | HostNotOnline |
other non-zero statusCode |
ApiError(code) |
| HTTP 403/429, empty or non-JSON body | TikTokBlocked(reason) |
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