Skip to main content

Overview

TikTokLive provides a comprehensive error hierarchy to help you handle different failure scenarios when connecting to and interacting with TikTok LIVE streams.

Error Hierarchy

All TikTokLive errors inherit from the base TikTokLiveError class:
TikTokLiveError (RuntimeError)
├── AlreadyConnectedError
├── UserOfflineError
├── UserNotFoundError
├── AgeRestrictedError
├── InitialCursorMissingError
├── WebsocketURLMissingError
├── WebcastBlocked200Error
└── SignAPIError
    ├── SignatureRateLimitError
    ├── UnexpectedSignatureError
    ├── SignatureMissingTokensError
    ├── PremiumEndpointError
    └── AuthenticatedWebSocketConnectionError

Base Error

TikTokLiveError

Inherits from: RuntimeError Base error class for all TikTokLive errors. All error messages are automatically prefixed with the package version.
from TikTokLive.client.errors import TikTokLiveError

try:
    # Your code here
    pass
except TikTokLiveError as e:
    print(f"TikTokLive error occurred: {e}")

Connection Errors

AlreadyConnectedError

Inherits from: TikTokLiveError Raised when: Attempting to connect to a user that is already connected to.
from TikTokLive import TikTokLiveClient
from TikTokLive.client.errors import AlreadyConnectedError

client = TikTokLiveClient(unique_id="@username")

try:
    await client.start()
    await client.start()  # This will raise AlreadyConnectedError
except AlreadyConnectedError:
    print("Already connected to this user!")

UserOfflineError

Inherits from: TikTokLiveError Raised when: The requested streamer is offline.
from TikTokLive import TikTokLiveClient
from TikTokLive.client.errors import UserOfflineError

client = TikTokLiveClient(unique_id="@username")

try:
    await client.start()
except UserOfflineError:
    print("This user is not currently live.")

UserNotFoundError

Inherits from: TikTokLiveError Raised when: The user does not have a livestream account (e.g., accounts with less than 1,000 followers). Attributes:
  • unique_id (str): The unique ID of the user that was not found
from TikTokLive import TikTokLiveClient
from TikTokLive.client.errors import UserNotFoundError

client = TikTokLiveClient(unique_id="@username")

try:
    await client.start()
except UserNotFoundError as e:
    print(f"User '{e.unique_id}' not found or doesn't have LIVE access.")

AgeRestrictedError

Inherits from: TikTokLiveError Raised when: A LIVE stream is age-restricted. Solution: Pass a valid sessionid cookie to bypass age restrictions.
from TikTokLive import TikTokLiveClient
from TikTokLive.client.errors import AgeRestrictedError

client = TikTokLiveClient(unique_id="@username")

try:
    await client.start()
except AgeRestrictedError:
    print("This LIVE is age-restricted. Please provide a sessionid cookie.")
    # Reconnect with sessionid
    client_with_auth = TikTokLiveClient(
        unique_id="@username",
        sessionid="your_session_id_here"
    )
    await client_with_auth.start()

Blocking & Detection Errors

InitialCursorMissingError

Inherits from: TikTokLiveError Raised when: The cursor for connecting to TikTok is missing, indicating that you may be blocked.
from TikTokLive.client.errors import InitialCursorMissingError

try:
    await client.start()
except InitialCursorMissingError:
    print("Connection blocked: Initial cursor missing.")

WebsocketURLMissingError

Inherits from: TikTokLiveError Raised when: The websocket URL to connect to TikTok is missing, indicating that you may be blocked.
from TikTokLive.client.errors import WebsocketURLMissingError

try:
    await client.start()
except WebsocketURLMissingError:
    print("Connection blocked: WebSocket URL missing.")

WebcastBlocked200Error

Inherits from: TikTokLiveError Raised when: The webcast is blocked by TikTok with a 200 status code (detected connection).
from TikTokLive.client.errors import WebcastBlocked200Error

try:
    await client.start()
except WebcastBlocked200Error:
    print("Connection detected and blocked by TikTok.")

Sign API Errors

SignAPIError

Inherits from: TikTokLiveError Raised when: A fetch to the Sign API fails. Attributes:
  • reason (ErrorReason): The specific reason for the failure
  • response (httpx.Response | None): The HTTP response object from the Sign API
  • log_id (str | None): The log ID from the response headers
  • agent_id (str | None): The agent ID from the response headers
Error Reasons:
  • RATE_LIMIT: Sign API rate limit exceeded
  • CONNECT_ERROR: Connection error to Sign API
  • EMPTY_PAYLOAD: Empty payload received from Sign API
  • SIGN_NOT_200: Sign API returned non-200 status code
  • EMPTY_COOKIES: Empty cookies received from Sign API
  • PREMIUM_ENDPOINT: Premium endpoint access required
  • AUTHENTICATED_WS: Authenticated WebSocket connection error
from TikTokLive.client.errors import SignAPIError

try:
    await client.start()
except SignAPIError as e:
    print(f"Sign API error: {e.reason.name}")
    if e.response:
        print(f"Log ID: {e.log_id}")
        print(f"Agent ID: {e.agent_id}")

SignatureRateLimitError

Inherits from: SignAPIError Raised when: You hit the Sign API rate limit. Attributes:
  • retry_after (int): Number of seconds to wait before retrying
  • reset_time (int): Unix timestamp when the rate limit resets
from TikTokLive.client.errors import SignatureRateLimitError
import asyncio

try:
    await client.start()
except SignatureRateLimitError as e:
    print(f"Rate limited! Retry after {e.retry_after} seconds.")
    print(f"Reset time: {e.reset_time}")
    await asyncio.sleep(e.retry_after)
    await client.start()  # Retry after waiting

UnexpectedSignatureError

Inherits from: SignAPIError Raised when: The Sign API returns an unexpected response (non-200 status code).
from TikTokLive.client.errors import UnexpectedSignatureError

try:
    await client.start()
except UnexpectedSignatureError as e:
    print(f"Unexpected signature response: {e}")

SignatureMissingTokensError

Inherits from: SignAPIError Raised when: The Sign API returns an empty payload (missing tokens).
from TikTokLive.client.errors import SignatureMissingTokensError

try:
    await client.start()
except SignatureMissingTokensError:
    print("Sign API returned empty payload.")

PremiumEndpointError

Inherits from: SignAPIError Raised when: Attempting to access a premium endpoint without proper authorization.
from TikTokLive.client.errors import PremiumEndpointError

try:
    await client.start()
except PremiumEndpointError as e:
    print(f"Premium endpoint access required: {e}")

AuthenticatedWebSocketConnectionError

Inherits from: SignAPIError Raised when: Sending a session ID to the sign server. This is a risky operation that could lead to account bans.
from TikTokLive.client.errors import AuthenticatedWebSocketConnectionError

try:
    await client.start()
except AuthenticatedWebSocketConnectionError:
    print("Authenticated WebSocket connection blocked for security.")

Complete Error Handling Example

from TikTokLive import TikTokLiveClient
from TikTokLive.client.errors import (
    TikTokLiveError,
    AlreadyConnectedError,
    UserOfflineError,
    UserNotFoundError,
    AgeRestrictedError,
    InitialCursorMissingError,
    WebsocketURLMissingError,
    WebcastBlocked200Error,
    SignatureRateLimitError,
    SignAPIError
)
import asyncio

async def connect_to_stream(unique_id: str, sessionid: str = None):
    client = TikTokLiveClient(
        unique_id=unique_id,
        sessionid=sessionid
    )
    
    try:
        await client.start()
        print(f"Successfully connected to @{unique_id}")
        
    except AlreadyConnectedError:
        print("Already connected to this stream.")
        
    except UserOfflineError:
        print(f"@{unique_id} is not currently live.")
        
    except UserNotFoundError as e:
        print(f"User @{e.unique_id} not found or lacks LIVE access.")
        
    except AgeRestrictedError:
        if not sessionid:
            print("Stream is age-restricted. Please provide sessionid.")
            # Retry with authentication
            sessionid = input("Enter your sessionid: ")
            await connect_to_stream(unique_id, sessionid)
        else:
            print("Still age-restricted despite providing sessionid.")
            
    except (InitialCursorMissingError, WebsocketURLMissingError, WebcastBlocked200Error) as e:
        print(f"Connection blocked by TikTok: {type(e).__name__}")
        
    except SignatureRateLimitError as e:
        print(f"Rate limited! Waiting {e.retry_after} seconds...")
        await asyncio.sleep(e.retry_after)
        await connect_to_stream(unique_id, sessionid)
        
    except SignAPIError as e:
        print(f"Sign API error ({e.reason.name}): {e}")
        
    except TikTokLiveError as e:
        print(f"TikTokLive error: {e}")
        
    except Exception as e:
        print(f"Unexpected error: {e}")

# Run the client
await connect_to_stream("username")

Best Practices

  1. Always catch specific errors first: Handle specific error types before catching the base TikTokLiveError.
  2. Respect rate limits: When catching SignatureRateLimitError, always wait for retry_after seconds before retrying.
  3. Handle blocking gracefully: Blocking errors (InitialCursorMissingError, WebsocketURLMissingError, WebcastBlocked200Error) indicate TikTok has detected your connection. Implement exponential backoff or switch to a different connection method.
  4. Use sessionid for age-restricted streams: Always provide a valid sessionid cookie when connecting to age-restricted content.
  5. Log error details: For SignAPIError instances, log the log_id and agent_id for debugging purposes.
  6. Don’t ignore errors: Each error type provides important information about why the connection failed. Use this information to improve your connection strategy.

Build docs developers (and LLMs) love