Tutorial

TikTok LIVE API Guida Python

Collegati a qualsiasi LIVE di TikTok da Python con l'API WebSocket di TikTools. Ricevi in tempo reale messaggi in chat, regali, numero di spettatori e molto altro: pronto per la produzione, completamente gestito.

Perché usare TikTools con Python?

Il client Python TikTokLive, con licenza MIT, si collega direttamente al protocollo di trasmissione di TikTok e delega la firma a un backend gestito (quello predefinito è Euler Stream, che ha un suo piano gratuito e piani a pagamento). È un modello con client in self-hosting + firma gestita, mantenuto dal team di Euler Stream.

TikTools è un servizio API gestito indipendente con una propria infrastruttura di firma. Gestisce i cambi di protocollo lato server, dichiara un obiettivo di uptime del 99,9% e funziona con qualsiasi linguaggio tramite WebSocket standard. Nessuna gestione del protocollo: ti colleghi e ricevi gli eventi. Scegli il modello più adatto al tuo team.

Modello di hosting✓ Completamente gestito - uptime 99,9%~ Client in self-hosting + firma gestita
Configurazione✓ pip install websockets~ pip install TikTokLive
Manutenzione✓ Zero - gestita lato server~ Aggiornamenti di client + backend di firma

Requisiti

  • Python 3.8+ installato
  • Una chiave API TikTools gratuita: ottienila qui

Opzione 1: asyncio + websockets

L'approccio più semplice: usa la libreria standard websockets per collegarti all'API WebSocket di TikTools:

pip install websockets
import asyncio
import websockets
import json
import os

API_KEY = os.environ.get("TIKTOOL_API_KEY", "YOUR_API_KEY")
STREAMER = "tv_asahi_news"  # TikTok username (without @)

async def connect():
    uri = f"wss://api.tik.tools?uniqueId={STREAMER}&apiKey={API_KEY}"

    async with websockets.connect(uri) as ws:
        print(f"✅ Connected to @{STREAMER}")

        async for message in ws:
            event = json.loads(message)
            event_type = event.get("event", "")
            data = event.get("data", {})

            if event_type == "chat":
                user = data.get("user", {}).get("uniqueId", "?")
                comment = data.get("comment", "")
                print(f"[CHAT] {user}: {comment}")

            elif event_type == "gift":
                user = data.get("user", {}).get("uniqueId", "?")
                gift = data.get("giftName", "?")
                diamonds = data.get("diamondCount", 0)
                print(f"[GIFT] {user} sent {gift} ({diamonds} 💎)")

            elif event_type == "member":
                user = data.get("user", {}).get("uniqueId", "?")
                print(f"[JOIN] {user} joined")

            elif event_type == "roomUserSeq":
                viewers = data.get("viewerCount", 0)
                print(f"[VIEWERS] {viewers} watching")

asyncio.run(connect())

Opzione 2: API REST con requests

Per recuperi di dati occasionali (info sulla stanza, profili utente), usa l'API REST:

pip install requests
import requests

API_KEY = "YOUR_API_KEY"
BASE = "https://api.tik.tools"

# Get room info for a streamer
resp = requests.get(f"{BASE}/webcast/room_info/", params={
    "uniqueId": "tv_asahi_news",
    "apiKey": API_KEY,
})
data = resp.json()
print(f"Title: {data.get('title', 'N/A')}")
print(f"Viewers: {data.get('viewer_count', 0)}")
print(f"Status: {'LIVE' if data.get('alive') else 'OFFLINE'}")

Eseguire gli script

# Set your API key as environment variable
export TIKTOOL_API_KEY=your_api_key_here

# Run the WebSocket example
python tiktok_live.py

Output previsto

✅ Connected to @tv_asahi_news
[VIEWERS] 1,234 watching
[CHAT] viewer42: Hello everyone!
[GIFT] big_fan sent Rose (1 💎)
[CHAT] news_watcher: Great coverage
[JOIN] new_viewer joined
[VIEWERS] 1,237 watching

Prossimi passi

  • Salva gli eventi in un database: invia gli eventi a PostgreSQL, MongoDB o SQLite
  • Crea una dashboard: usa Flask o FastAPI per creare una dashboard web in tempo reale
  • Analisi con AI: passa i messaggi della chat a GPT/Claude per l'analisi del sentiment
  • Più dirette: monitora più dirette contemporaneamente (piano Pro: 50 connessioni)