/** * Type definitions for TikTok LIVE API events. * * These types provide IDE autocompletion and type safety * when handling events from {@link TikTokLive} and {@link TikTokCaptions}. * * @packageDocumentation */ /** User profile attached to most LIVE events. */ interface TikTokUser { userId: string; uniqueId: string; nickname: string; profilePictureUrl: string; followRole: number; isSubscriber: boolean; } /** Payload for `chat` events. */ interface ChatEvent { user: TikTokUser; comment: string; emotes: Array<{ emoteId: string; image: string; }>; /** Present only for starred (paid highlighted) chat messages. */ starred?: { claps: number; score: number; }; } /** Payload for `gift` events. */ interface GiftEvent { user: TikTokUser; giftId: number; giftName: string; diamondCount: number; repeatCount: number; repeatEnd: boolean; } /** Payload for `like` events. */ interface LikeEvent { user: TikTokUser; likeCount: number; totalLikes: number; } /** Payload for `member` (viewer join) events. */ interface MemberEvent { user: TikTokUser; actionId: number; } /** Payload for `follow` and `share` events. */ interface SocialEvent { user: TikTokUser; eventType: string; } /** Payload for `roomUserSeq` (viewer count) events. */ interface RoomUserSeqEvent { viewerCount: number; topViewers: TikTokUser[]; } /** Payload for `battle` events (PK start / end / countdown). */ interface BattleEvent { type: string; battleId: string; /** 1=ACTIVE, 2=STARTING, 3=ENDED, 4=PREPARING */ status: number; battleDuration: number; teams: Array>; scores: number[]; } /** One host on a battle side - present per-host in multi-guest PK. */ interface BattleHost { hostUserId: string; teamTotalScore: number; teamIdx: number; /** Sorted MVP first (highest score → lowest). */ contributors: BattleContributor[]; } interface BattleContributor { userId: string; score: number; nickname: string; } /** Payload for `battleArmies` events - score updates during PK. */ interface BattleArmiesEvent { battleId: string; /** 1=ACTIVE, 2=STARTING, 3=ENDED, 4=PREPARING */ status: number; teams: Array>; matchId?: string; sessionId?: string; startedAtMs?: number; serverTsMs?: number; sessionTag?: string; durationSec?: number; secsRemaining?: number; /** Per-host breakdown with MVP contributors. */ hosts?: BattleHost[]; } /** Payload for `battleItemCard` events - multipliers (x2/x3), gloves, mist, etc. */ interface BattleItemCardEvent { battleId: string; cardType: number; /** 'gloves' | 'mist' | 'booster_x2' | 'booster_x3' | 'match_guide' | * 'thunder' | 'extra_time' | raw resource key. */ effect: string; effectKey: string; /** 2 or 3 for booster_x2/x3, otherwise 0. */ multiplier: number; senderUserId: string; senderNickname: string; senderUniqueId: string; senderAvatarUrl: string; activatedAtSec: number; durationSec: number; endsAtSec: number; commentTemplate: string; /** Full TikTok CDN URL for the card art (webp/jpeg). */ iconUrl: string; /** Short identifier e.g. 'card_mist_v3' / 'card_crit_v3' / 'top3_buffer'. */ iconKey: string; /** Hex e.g. '#BCD9E0' (mist blue), '#E0D4BC' (gloves tan). */ accentColor: string; } /** Payload for `roomPin` (starred/pinned message) events. */ interface RoomPinEvent { /** User who wrote the pinned message. */ user: TikTokUser; /** The pinned comment text. */ comment: string; /** Pin action: 1 = pin, 2 = unpin. */ action: number; /** How long the message stays pinned (seconds). */ durationSeconds: number; /** Timestamp when the message was pinned (ms). */ pinnedAt: number; /** Original message type (e.g. "WebcastChatMessage"). */ originalMsgType: string; /** Original message ID that was pinned. */ originalMsgId: string; /** User ID of the operator who pinned the message. */ operatorUserId: string; } /** Payload for `caption` events from {@link TikTokCaptions}. */ interface CaptionEvent { text: string; speaker: string; isFinal: boolean; language: string; } /** Payload for `translation` events from {@link TikTokCaptions}. */ interface TranslationEvent { text: string; sourceLanguage: string; targetLanguage: string; } /** Payload for `credits` events from {@link TikTokCaptions}. */ interface CreditsEvent { total: number; used: number; remaining: number; } /** Connection event payload. */ interface ConnectedEvent { uniqueId: string; } /** Disconnection event payload. */ interface DisconnectedEvent { uniqueId: string; /** WebSocket close code (e.g. 4404 not live, 4005 stream ended). */ code?: number; } /** Error event payload. */ interface ErrorEvent { error: string; } /** * Map of event names to their payload types for {@link TikTokLive}. */ interface TikTokLiveEventMap { chat: ChatEvent; gift: GiftEvent; like: LikeEvent; follow: SocialEvent; share: SocialEvent; member: MemberEvent; subscribe: SocialEvent; roomUserSeq: RoomUserSeqEvent; battle: BattleEvent; battleArmies: BattleArmiesEvent; battleItemCard: BattleItemCardEvent; roomPin: RoomPinEvent; envelope: Record; streamEnd: Record; roomInfo: Record; connected: ConnectedEvent; disconnected: DisconnectedEvent; error: ErrorEvent; event: Record; } /** * Map of event names to their payload types for {@link TikTokCaptions}. */ interface TikTokCaptionsEventMap { caption: CaptionEvent; translation: TranslationEvent; credits: CreditsEvent; credits_low: CreditsEvent; status: Record; connected: ConnectedEvent; disconnected: DisconnectedEvent; error: ErrorEvent; } /** * TikTokLive - Connect to any TikTok LIVE stream via WebSocket. * * Receives real-time events: chat messages, gifts, likes, follows, * viewer counts, battles, and more. Powered by the TikTool managed API. * * @example * ```typescript * import { TikTokLive } from 'tiktok-live-api'; * * const client = new TikTokLive('streamer_username', { apiKey: 'YOUR_KEY' }); * * client.on('chat', (event) => { * console.log(`${event.user.uniqueId}: ${event.comment}`); * }); * * client.connect(); * ``` * * @packageDocumentation */ /** Options for {@link TikTokLive} constructor. */ interface TikTokLiveOptions { /** Your TikTool API key. Get one free at https://tik.tools */ apiKey?: string; /** Auto-reconnect on disconnect (default: true). */ autoReconnect?: boolean; /** Max reconnection attempts (default: 5). */ maxReconnectAttempts?: number; } type EventHandler$1 = (data: T) => void | Promise; /** * Connect to a TikTok LIVE stream and receive real-time events. * * @example * ```typescript * const client = new TikTokLive('username', { apiKey: 'KEY' }); * client.on('chat', (e) => console.log(e.comment)); * client.on('gift', (e) => console.log(`${e.giftName} worth ${e.diamondCount} 💎`)); * client.connect(); * ``` */ declare class TikTokLive { /** TikTok username (without @). */ readonly uniqueId: string; /** Your TikTool API key. */ readonly apiKey: string; /** Whether to auto-reconnect on disconnect. */ readonly autoReconnect: boolean; /** Maximum reconnection attempts. */ readonly maxReconnectAttempts: number; private _handlers; private _ws; private _connected; private _intentionalClose; private _reconnectAttempts; private _eventCount; /** * Create a new TikTokLive client. * * @param uniqueId - TikTok username (without @) * @param options - Configuration options * * @example * ```typescript * const client = new TikTokLive('streamer', { apiKey: 'YOUR_KEY' }); * ``` */ constructor(uniqueId: string, options?: TikTokLiveOptions); /** Whether the client is currently connected. */ get connected(): boolean; /** Total number of events received this session. */ get eventCount(): number; /** * Register an event handler. * * @param event - Event name (chat, gift, like, follow, etc.) * @param handler - Callback function * @returns this (for chaining) * * @example * ```typescript * client.on('chat', (event) => console.log(event.comment)); * client.on('gift', (event) => console.log(event.giftName)); * ``` */ on(event: K, handler: EventHandler$1): this; on(event: string, handler: EventHandler$1): this; /** * Remove an event handler. * * @param event - Event name * @param handler - The handler to remove */ off(event: string, handler: EventHandler$1): this; private _emit; /** * Connect to the TikTok LIVE stream. * * @returns Promise that resolves when connected, rejects on fatal error. * * @example * ```typescript * await client.connect(); * ``` */ connect(): Promise; /** * Disconnect from the stream. */ disconnect(): void; private _maybeReconnect; } /** * TikTool REST client - typed methods for every customer-facing tik.tools * REST endpoint. Pairs with the {@link TikTokLive} WebSocket client. * * @example * ```typescript * import { TikTool } from 'tiktok-live-api'; * * const api = new TikTool({ apiKey: 'YOUR_KEY' }); * * const live = await api.isLive('username'); * const board = await api.leaderboard({ region: 'US+' }); * const recruits = await api.eligibleCreators({ region: 'US+', limit: 50 }); * ``` * * Uses the global `fetch` (Node 18+ or any browser). */ interface TikToolOptions { apiKey: string; /** Override the API base URL. Defaults to https://api.tik.tools */ baseUrl?: string; } /** Thrown when an endpoint returns a non-2xx status. `body` holds the parsed error payload. */ declare class TikToolError extends Error { readonly status: number; readonly body: unknown; constructor(status: number, body: unknown); } type Query = Record; interface RequestOpts { method?: 'GET' | 'POST'; query?: Query; body?: unknown; } declare class TikTool { private readonly apiKey; private readonly baseUrl; constructor(options: TikToolOptions); /** Low-level request. Use the named methods below; this is exposed for endpoints not yet wrapped. */ request(path: string, opts?: RequestOpts): Promise; /** * Creator-identifier query params. The API is inconsistent about whether an * endpoint reads `unique_id`, `username`, or `uniqueId`, so we send all three; * unused ones are ignored server-side. */ private uid; signUrl(url: string): Promise; signWebsocket(body: Record): Promise; wsCredentials(uniqueId: string): Promise; connectionMode(uniqueId: string): Promise; checkAlive(uniqueId: string): Promise; rateLimits(): Promise; wsSessions(): Promise; jwt(body?: Record): Promise; isLive(uniqueId: string): Promise; liveStatus(uniqueId: string): Promise; bulkLiveCheck(usernames: string[]): Promise; liveCounts(region?: string): Promise; roomId(uniqueId: string): Promise; roomInfo(uniqueId: string): Promise; roomCover(uniqueId: string): Promise; roomVideo(uniqueId: string): Promise; rankings(query?: Query): Promise; ranklist(query?: Query): Promise; ranklistRegional(region: string): Promise; ranklistGaming(region: string): Promise; gamingMovers(region: string): Promise; regionMovers(region: string): Promise; leaderboard(query: { region: string; } & Query): Promise; eligibleCreators(query: { region?: string; page?: number; limit?: number; min_score?: number; } & Query): Promise; giftInfo(query?: Query): Promise; giftGallery(query?: Query): Promise; giftsByCountry(country: string): Promise; lookupUsername(uniqueId: string): Promise; profileInfo(uniqueId: string): Promise; resolveUserIds(usernames: string[]): Promise; userProfile(uniqueId: string): Promise; userVideos(uniqueId: string, query?: Query): Promise; userFollowers(uniqueId: string, query?: Query): Promise; userFollowing(uniqueId: string, query?: Query): Promise; userLikes(uniqueId: string, query?: Query): Promise; userEarnings(uniqueId: string): Promise; hashtagList(query?: Query): Promise; fetch(body: Record): Promise; feed(query?: Query): Promise; chat(uniqueId: string, query?: Query): Promise; analyticsVideoList(query?: Query): Promise; analyticsVideoDetail(query?: Query): Promise; analyticsUserInteractions(query?: Query): Promise; moderationMutes(uniqueId: string): Promise; moderationBans(uniqueId: string): Promise; solvePuzzle(body: Record): Promise; solveRotate(body: Record): Promise; solveShapes(body: Record): Promise; captionsCredits(): Promise; } /** * TikTokCaptions - Real-time AI speech-to-text for TikTok LIVE streams. * * Transcribe and translate any TikTok LIVE stream in real-time. * This feature is unique to TikTool Live - no other service offers it. * * @example * ```typescript * import { TikTokCaptions } from 'tiktok-live-api'; * * const captions = new TikTokCaptions('streamer', { * apiKey: 'YOUR_KEY', * translate: 'en', * diarization: true, * }); * * captions.on('caption', (event) => { * console.log(`[${event.speaker}] ${event.text}`); * }); * * captions.connect(); * ``` * * @packageDocumentation */ /** Options for {@link TikTokCaptions} constructor. */ interface TikTokCaptionsOptions { /** Your TikTool API key. Get one at https://tik.tools */ apiKey?: string; /** Target language code for real-time translation (e.g. "en", "es"). */ translate?: string; /** Enable speaker identification (default: true). */ diarization?: boolean; /** Auto-disconnect after N minutes (default: 60, max: 300). */ maxDurationMinutes?: number; } type EventHandler = (data: T) => void | Promise; /** * Real-time AI speech-to-text for TikTok LIVE streams. * * @example * ```typescript * const captions = new TikTokCaptions('streamer', { * apiKey: 'KEY', * translate: 'en', * }); * captions.on('caption', (e) => console.log(e.text)); * captions.on('translation', (e) => console.log(`→ ${e.text}`)); * captions.connect(); * ``` */ declare class TikTokCaptions { /** TikTok username (without @). */ readonly uniqueId: string; /** Your TikTool API key. */ readonly apiKey: string; /** Target translation language. */ readonly translate?: string; /** Whether speaker diarization is enabled. */ readonly diarization: boolean; /** Max session duration in minutes. */ readonly maxDurationMinutes?: number; private _handlers; private _ws; private _connected; private _intentionalClose; /** * Create a new TikTokCaptions client. * * @param uniqueId - TikTok username (without @) * @param options - Configuration options */ constructor(uniqueId: string, options?: TikTokCaptionsOptions); /** Whether currently connected and receiving captions. */ get connected(): boolean; /** * Register an event handler. * * @param event - Event name (caption, translation, credits, status, error) * @param handler - Callback function * * @example * ```typescript * captions.on('caption', (event) => { * const prefix = event.speaker ? `[${event.speaker}] ` : ''; * console.log(`${prefix}${event.text}${event.isFinal ? ' ✓' : '...'}`); * }); * ``` */ on(event: K, handler: EventHandler): this; on(event: string, handler: EventHandler): this; /** Remove an event handler. */ off(event: string, handler: EventHandler): this; private _emit; /** * Start receiving captions from the stream. * * @returns Promise that resolves when connected. */ connect(): Promise; /** Stop receiving captions. */ disconnect(): void; } export { type BattleEvent, type CaptionEvent, type ChatEvent, type ConnectedEvent, type CreditsEvent, type DisconnectedEvent, type ErrorEvent, type GiftEvent, type LikeEvent, type MemberEvent, type RoomUserSeqEvent, type SocialEvent, TikTokCaptions, type TikTokCaptionsEventMap, type TikTokCaptionsOptions, TikTokLive, type TikTokLiveEventMap, type TikTokLiveOptions, type TikTokUser, TikTool, TikToolError, type TikToolOptions, type TranslationEvent };