Pirate Tok
Library guidepiratetok_liveSource

Dart

Event callbacks with a Dart-native WebSocket implementation.

Requirements

Dart SDK 3+ · native runtime.

Installation

Shell
dart pub add piratetok_live

Save the quickstart as bin/reader.dart and run dart run bin/reader.dart. The library uses dart:io and requires a native runtime.

Quickstart

Replace username_here with the username of an account that is currently live.

Dart
import 'package:piratetok_live/piratetok_live.dart';

Future<void> main() async {
  final client = TikTokLiveClient('username_here');
  client.on(EventType.chat, (event) {
    final user = event.data?['user'];
    final name = user?['nickname'] ?? '?';
    print('$name: ${event.data?['content']}');
  });
  await client.connect();
}

Connection lifecycle

await client.connect() runs the session, including automatic reconnects. Register callbacks before connecting. Native I/O access is required; this is not a browser WebSocket client.

Configuration

Dart
final client = TikTokLiveClient("username_here")
    .cdnEu()                             // EU / US / Global (default)
    .timeout(Duration(seconds: 15))
    .heartbeatInterval(Duration(seconds: 10)) // default 10s, also sent as heartbeat_duration
    .maxRetries(10)                       // consecutive failures, default 5 (reset after a 30s healthy session)
    .staleTimeout(Duration(seconds: 90))  // default 60s
    .userAgent("custom UA string")        // default: random from pool
    .cookies("sessionid=xxx; sid_tt=xxx") // only for 18+ room info
    .language("en")                       // default: system locale
    .region("US")                         // default: system locale
    .compress(false)                      // disable gzip for WSS payloads (default true)
    .proxy("socks5://127.0.0.1:1080");

Room info (optional, separate call)

Dart
import 'package:piratetok_live/piratetok_live.dart';

// Check if user is live
final result = await checkOnline("username_here");
print('room_id: ${result.roomId} anchor_id: ${result.anchorId}');

// Fetch room metadata (title, viewers, stream URLs)
final info = await fetchRoomInfo(result.roomId);

// 18+ rooms -- pass session cookies from browser DevTools
final info18 = await fetchRoomInfo(result.roomId,
    cookies: "sessionid=abc; sid_tt=abc");

Viewers

Every roomUserSeq event carries the counters and the top-viewers box — no cookies needed:

Dart
client.on(EventType.roomUserSeq, (evt) {
  evt.data!['viewerCount']; // in the room right now (goes up and down)
  evt.data!['totalUser'];   // unique viewers over the whole stream (only grows)
  for (final c in topViewers(evt.data!)) { // usually top 3, sorted by rank
    print('#${c['rank']} ${(c['user'] as Map)['nickname']} (${c['score']})');
  }
});

The full audience roster is a separate call. TikTok gates it behind a login, so session cookies are required for this call only — without them it throws SessionRequiredError:

Dart
final room = await checkOnline("username_here");
final audience = await fetchRoomAudience(room.roomId,
    anchorId: room.anchorId, cookies: "sessionid=abc; sid_tt=abc");
// audience.total, audience.anonymous, audience.viewers (rank, score, username, followerCount, ...)

Omit anchorId to resolve it from room info (one extra request).

Helpers

Stateful helpers for common patterns. Exported from the main package, never imported by the core pipeline.

GiftStreakTracker

Computes per-event gift deltas from TikTok's running totals. Combo gifts fire multiple events during a streak with cumulative repeatCount values -- this helper tracks active streaks and gives you the delta.

Dart
final tracker = GiftStreakTracker();

client.on(EventType.gift, (evt) {
  final e = tracker.process(evt.data!);
  if (e.isFinal) {
    print('streak done: ${e.totalGiftCount} gifts, ${e.totalDiamondCount} diamonds');
  } else if (e.eventGiftCount > 0) {
    print('ongoing: +${e.eventGiftCount} (+${e.eventDiamondCount} diamonds)');
  }
});

LikeAccumulator

Monotonizes TikTok's inconsistent total field on like events. Different server shards send stale values causing backwards jumps -- this helper accumulates from the reliable per-event count field.

Dart
final likes = LikeAccumulator();

client.on(EventType.like, (evt) {
  final s = likes.process(evt.data!);
  print('${s.accumulatedCount} likes accumulated (server says ${s.totalLikeCount})');
});

ProfileCache

Wraps sigi profile scraping with TTL cache and automatic ttwid management. Fetches HD avatars, follower counts, bio, verified status.

Dart
final cache = ProfileCache(ttlMs: 300000); // 5 min TTL (default)
final profile = await cache.fetch('username');
print('${profile.nickname} — ${profile.followerCount} followers');

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.

Source and license

Public source and examples · 0BSD license