Pirate Tok
Docs/Library guides/PowerShell
Library guidePirateTok.LiveSource

PowerShell

Cmdlets for polling, event callbacks and room metadata.

Requirements

PowerShell 5.1 or PowerShell 7+.

Installation

Install directly from the public source and import the module manifest:

Powershell
git clone https://github.com/PirateTok/live-ps1.git
Import-Module ./live-ps1/PirateTok.Live.psd1

Run the quickstart in the same PowerShell session. This installation does not use PowerShell Gallery.

Quickstart

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

Powershell
Import-Module ./live-ps1/PirateTok.Live.psd1

$client = Connect-TikTokLive "username_here"
try {
    Start-TikTokLive $client -OnEvent {
        param($event)
        if ($event.Type -eq 'Chat') {
            Write-Host "$($event.Data.user.nickname): $($event.Data.comment)"
        }
    }
}
finally {
    Disconnect-TikTokLive $client
}

Connection lifecycle

Connect-TikTokLive creates the connection; Start-TikTokLive runs the callback loop. Use Receive-TikTokEvent for manual polling. Always finish with Disconnect-TikTokLive, preferably in a finally block.

Configuration

Powershell
$options = @{
    Cdn = 'eu'
    TimeoutSec = 15
    HeartbeatInterval = 10
    StaleTimeout = 90
    MaxRetries = 10
    Language = 'en'
    Region = 'US'
}
$client = Connect-TikTokLive 'username_here' @options

Proxies: HTTP CONNECT proxies only, with optional Basic auth (http://user:pass@host:port). SOCKS4/5 is not supported — a socks5:// proxy is rejected with InvalidUrl instead of being silently bypassed.

Cookies are only required for room metadata on 18+ rooms (Get-TikTokRoomInfo) and the audience roster (Get-TikTokRoomAudience). They are not required for connecting or streaming events.

Reconnection

Stale/dropped connections reconnect automatically with backoff 2s → 4s → 8s → 16s → 30s cap. The ttwid + user agent are fetched once and reused across reconnects; they rotate only on DEVICE_BLOCKED (2 s retry) or when a session died within 30 s. MaxRetries counts consecutive failures — a session that stayed up 30 s resets the counter. A ttwid fetch failure is a failed attempt (Reconnecting fires), never an abort. Disconnected fires only when retries run out or you call Disconnect-TikTokLive.

Cmdlet reference

Cmdlet Description
Get-TikTokRoomId check_online — RoomId + AnchorId (streamer user id)
Connect-TikTokLive Resolve the room and open the event stream; returns a client
Receive-TikTokEvent Poll the client (heartbeats, stale detection, acks, reconnects handled inside)
Start-TikTokLive Blocking loop running -OnEvent until the client disconnects
Disconnect-TikTokLive Close the stream and stop reconnecting
Get-TikTokRoomInfo Optional room metadata: title, viewers, likes, FLV stream URLs
Get-TikTokRoomAudience Optional full viewer roster (login-gated)
Get-TikTokTtwid Fetch a ttwid cookie (retried while TikTok omits it)
ConvertTo-TikTokEvents Decode one wire message into events
Get-TikTokTopViewers Top-viewers box from a RoomUserSeq event
Test-TikTokComboGift / Test-TikTokStreakOver / Get-TikTokDiamondTotal Gift helpers
New-TikTokGiftStreakTracker / New-TikTokLikeAccumulator / New-TikTokProfileCache / Get-TikTokProfile Stateful helpers
Get-TikTokRandomUserAgent / Get-TikTokSystemTimezone / Get-TikTokSystemLocale UA pool + locale detection

Events

Every event is [pscustomobject]@{ Type; Method; Data; RawPayload }. Data is the decoded protobuf as a hashtable with snake_case field names ($e.Data.user.nickname, $e.Data.comment, …).

  • 64 typed message types (Tier A + Tier B) — Chat, Gift, Like, Member, Social, RoomUserSeq, Control, LiveIntro, RoomMessage, Caption, GoalUpdate, ImDelete, RankUpdate, Poll, Envelope, RoomPin, LinkMicBattle, EmoteChat, SubNotify, … (the Type names match the other PirateTok libs).
  • Sub-routed convenience events fire alongside the raw event: Follow / Share (Social action 1 / 2–5), Join (Member action 1), LiveEnded (Control action 3).
  • Unknown — any other message type: Method + RawPayload bytes, nothing lost.
  • Lifecycle — Connected (room_id, anchor_id), RoomEntered, Reconnecting (attempt, max_retries, delay_secs, reason, device_blocked), Disconnected (reason), Error (undecodable frame).

user objects carry the enriched fields: id, unique_id, display_id, nickname, verified, follow_info (follower/following counts, follow status), fans_club.data (club name + level), badge_list (badge_scene: 1 moderator, 6 top gifter, 8 gifter level, 10 member level; level in log_extra.level), is_follower, is_following, is_subscribe, pay_score, fan_ticket_count, top_vip_no.

Top viewers (WSS, no cookies)

Powershell
'RoomUserSeq' { Get-TikTokTopViewers $e.Data | ForEach-Object { "$($_.rank) $($_.user.nickname) $($_.score)" } }

RoomUserSeq carries viewer_count, total_user, anonymous, pop_str, ranks_list, seats_list.

Room info (optional)

Powershell
$live = Get-TikTokRoomId "username_here"
$info = Get-TikTokRoomInfo $live.RoomId                                     # normal rooms
$info = Get-TikTokRoomInfo $live.RoomId -Cookies "sessionid=xxx; sid_tt=xxx" # 18+ rooms
$info.Title; $info.Viewers; $info.StreamUrl.FlvOrigin                         # FlvOrigin/FlvHd/FlvSd/FlvLd/FlvAo

Audience roster (optional, login-gated)

The full viewer list behind the web viewer panel. Session cookies are required for this call only — without them you get SessionRequired.

Powershell
$aud = Get-TikTokRoomAudience $live.RoomId -AnchorId $live.AnchorId -Cookies "sessionid=xxx; sid_tt=xxx"
$aud.Total; $aud.Anonymous; $aud.Viewers | Format-Table Rank, Username, Nickname, Score

Omit -AnchorId to resolve it via room info (one extra request).

Helpers

Powershell
$tracker = New-TikTokGiftStreakTracker   # $tracker.Process($e.Data) -> EventGiftCount, TotalDiamondCount, IsFinal
$likes   = New-TikTokLikeAccumulator     # $likes.Process($e.Data)   -> TotalLikeCount (monotonic), AccumulatedCount
$cache   = New-TikTokProfileCache        # $cache.Fetch('username')  -> cached SIGI profile (5 min TTL)

Errors

All errors throw [PirateTok.Live.TikTokLiveException] with .ErrorKind (and .Code where TikTok sent one):

ErrorKind Meaning
UserNotFound Username does not exist on TikTok
HostNotOnline User exists but is not currently live
ApiError Other TikTok API status code (.Code)
TikTokBlocked HTTP 403/429, or an empty / non-JSON response
AgeRestricted 18+ room — pass session cookies to Get-TikTokRoomInfo
SessionRequired Audience roster needs session cookies
DeviceBlocked WSS handshake returned DEVICE_BLOCKED (handled by reconnect)
InvalidResponse Malformed or unexpected response
HttpError / WebSocketError Transport failure
ProfilePrivate / ProfileNotFound / ProfileError / ProfileScrape Profile lookup
Powershell
try { $live = Get-TikTokRoomId "username_here" }
catch [PirateTok.Live.TikTokLiveException] {
    switch ($_.Exception.ErrorKind) {
        'HostNotOnline' { 'offline' }
        'UserNotFound'  { 'no such user' }
        default         { "[$($_.Exception.ErrorKind)] $($_.Exception.Message)" }
    }
}

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