Go
Typed events over channels, with context-based cancellation.
Requirements
Go 1.23+.
Installation
go mod init example.com/live-reader
go get github.com/PirateTok/live-go
Save the quickstart as main.go and run go run ..
Quickstart
Replace username_here with the username of an account that is currently live.
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
golive "github.com/PirateTok/live-go"
"github.com/PirateTok/live-go/events"
pb "github.com/PirateTok/live-go/proto"
)
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
stream, err := golive.NewClient("username_here").Connect(ctx)
if err != nil { log.Fatal(err) }
for event := range stream {
if event.Type != events.EventChat { continue }
message, ok := event.Data.(*pb.WebcastChatMessage)
if !ok || message == nil { continue }
name := "?"
if message.User != nil { name = message.User.Nickname }
fmt.Printf("%s: %s\n", name, message.Content)
}
}
Connection lifecycle
Connect(ctx) resolves the room and returns an event channel. Consume the channel until it closes. Cancel the context to stop the background connection and retry loop.
Configuration
client := golive.NewClient("username_here").
CdnEU().
MaxRetries(10).
StaleTimeout(90 * time.Second)
| Method | Default | Description |
|---|---|---|
.CdnEU() |
global | Use the EU CDN endpoint |
.CdnUS() |
global | Use the US CDN endpoint |
.Cdn(host) |
"webcast-ws.tiktok.com" |
Custom CDN host |
.Timeout(d) |
10s |
HTTP timeout for API calls |
.HeartbeatInterval(d) |
10s |
Interval between WSS heartbeat frames (also sent as heartbeat_duration) |
.MaxRetries(n) |
5 |
Max consecutive failed attempts (reset after a 30s healthy session) |
.StaleTimeout(d) |
60s |
Close and reconnect after no data for this duration |
.UserAgent(ua) |
random pool | Override the random UA pool with a fixed UA |
.Cookies(cookies) |
none | Append session cookies alongside ttwid in the WSS cookie header |
.Language(lang) |
system locale | Override detected language (e.g. "pt", "ro") |
.Region(reg) |
system locale | Override detected region (e.g. "BR", "RO") |
.Proxy(url) |
env vars | HTTP/HTTPS/SOCKS5 proxy URL for all HTTP and WSS connections |
.Compress(enabled) |
true |
Disable gzip compression for WSS payloads (trades bandwidth for CPU) |
Room info (optional, separate call)
info, err := golive.FetchRoomInfo("ROOM_ID", 10*time.Second, "")
// 18+ rooms
info, err := golive.FetchRoomInfo("ROOM_ID", 10*time.Second, "sessionid=abc; sid_tt=abc")
Viewers
Every EventRoomUserSeq carries the counters and the top-viewers box — no cookies needed:
msg := evt.Data.(*pb.WebcastRoomUserSeqMessage)
msg.ViewerCount // in the room right now (goes up and down)
msg.TotalUser // unique viewers over the whole stream (only grows)
for _, c := range msg.TopViewers() { // usually top 3, sorted by rank
fmt.Println(c.Rank, c.GetUser().GetNickname(), 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 returns *tthttp.SessionRequiredError:
room, _ := golive.CheckOnline("username_here", 10*time.Second)
audience, err := golive.FetchRoomAudience(room.RoomID, room.AnchorID, 10*time.Second, "sessionid=abc; sid_tt=abc")
// audience.Total, audience.Anonymous, audience.Viewers (rank, score, username, follower count, ...)
Pass "" as the anchor ID to resolve it from room info (one extra request).
Reconnection
Connect returns once the room is resolved; the reconnect loop runs in the background until the
context is cancelled or MaxRetries consecutive attempts fail. The ttwid cookie is fetched with up to
8 retries (TikTok only sets it intermittently), then reused across reconnects together with the UA —
both rotate only on DEVICE_BLOCKED or a connection that died within 30s.
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