Skip to content

Repository files navigation

Add TikTool Bot to Discord

Agency rank feeds in Discord: gaming ranks, creator ranks and 99+ movers across all 30 regions, copy-paste usernames for backstage. /ranks to start (Global Agency).

tiktok-live-api Python

TikTok LIVE API for Python

tiktok-live-api is the most complete, production-managed TikTok LIVE API for Python. Receive real-time chat, gifts, likes, viewers, follows, shares and battle events from any TikTok LIVE stream over a single WebSocket - plus AI live captions with 60+ language translation, an Unreal Engine plugin, and SDKs in multiple languages. Managed signing works out of the box: no third-party sign server, no keys to configure. Zero maintenance, zero breakages.

PyPI versionPyPI downloadsPythonStarsLicense: MIT

TikTok Live API Demo - real-time chat, gifts, and viewer events

99.9% uptime - Never breaks when TikTok updates. No protobuf, no reverse engineering, no maintenance required. Powered by the TikTool managed WebSocket API.


TikTool Logo

TikTool offers a fully managed TikTok LIVE API - real-time events, AI captions, CAPTCHA solving, and more. Free Community tier (forever). No credit card required.

🎤 Exclusive:Real-Time Live Captions - AI-powered speech-to-text with translation & speaker diarization. No other TikTok library offers this.

Why tik.tools

The premium managed alternative for TikTok LIVE data. What you get out of the box:

  • Managed signing infrastructure. Signing runs on our servers and works immediately - no third-party sign server to run, no separate key to configure.
  • AI live captions and translation. Real-time speech-to-text with 60+ language translation and speaker labels, available on no other TikTok LIVE library.
  • Unreal Engine plugin. Drive avatars, overlays and gameplay directly from live chat, gifts and battles.
  • Agency and leaderboard intelligence. Gifter leaderboards, gaming and creator ranks across regions, and eligible-creator discovery.
  • Multi-language SDKs. First-class Python and Node.js clients plus a plain WebSocket API for any language.
  • Free Sandbox tier. Start building for free, upgrade only when you need higher limits or unmasked data.

🚀 One-Command Quick Start

Instantly connect to a live TikTok stream and print real-time events to your terminal.

pip install tiktok-live-api
python -m tiktok_live_api

Or connect to a specific stream:python -m tiktok_live_api @username


Table of Contents


🆚 Why tiktok-live-api?

tiktok-live-apiTikTokLive (isaackogan)TikTok-Live-Connector (Node.js)
Stability✅ Managed API, 99.9% uptime❌ Breaks on TikTok updates❌ Breaks on TikTok updates
Setup✅ 3 lines of code❌ Protobuf + reverse engineering❌ Protobuf + signing server
Live Captions (AI STT)✅ Real-time speech-to-text❌ Not available❌ Not available
Translation✅ 50+ languages❌ Not available❌ Not available
CAPTCHA Solving✅ Built-in (Pro+)❌ Manual❌ Manual
Feed Discovery✅ See who's live❌ Not available❌ Not available
Maintenance✅ Zero - we handle everything❌ You fix breakages❌ You fix breakages
Multi-Language✅ Python, Node.js, Java, Go, C#Python onlyNode.js only
Free Tier✅ 5,000 req/day, 3 concurrent WS, 60 connects/hr, 2h per WS✅ Free (when it works)✅ Free (when it works)

⚡ Getting Started

1. Install

pip install tiktok-live-api

2. Get your free API key

Go to tik.tools → Sign up → Copy your API key. No credit card required.

3. Connect

fromtiktok_live_apiimportTikTokLiveclient=TikTokLive("streamer_username", api_key="YOUR_API_KEY")
@client.on("chat")defon_chat(event):
print(f"{event['user']['uniqueId']}: {event['comment']}")
@client.on("gift")defon_gift(event):
print(f"{event['user']['uniqueId']} sent {event['giftName']} ({event['diamondCount']} 💎)")
@client.on("roomUserSeq")defon_viewers(event):
print(f"Viewers: {event['viewerCount']}")
client.run()

That's it. No protobuf, no signing servers, no reverse engineering, no breakages.


🚀 Try It Now - Live Demo

Copy-paste, run, see real-time TikTok events in your terminal. Works on the free Community tier - 2h per WS, runs as long as the stream is live.

# demo.py - TikTok LIVE in real time# pip install tiktok-live-apifromtiktok_live_apiimportTikTokLiveAPI_KEY="YOUR_API_KEY"# Get free key → https://tik.toolsLIVE_USERNAME="tv_asahi_news"# Any live TikTok usernameclient=TikTokLive(LIVE_USERNAME, api_key=API_KEY)
events=0@client.on("connected")defon_connected(event):
print(f"\n✅ Connected to @{LIVE_USERNAME} - streaming events...\n")
@client.on("chat")defon_chat(event):
globalevents; events+=1print(f"💬 {event['user']['uniqueId']}: {event['comment']}")
@client.on("gift")defon_gift(event):
globalevents; events+=1print(f"🎁 {event['user']['uniqueId']} sent {event['giftName']} ({event.get('diamondCount', 0)}💎)")
@client.on("like")defon_like(event):
globalevents; events+=1print(f"❤️ {event['user']['uniqueId']} liked × {event.get('likeCount', 0)}")
@client.on("member")defon_member(event):
globalevents; events+=1print(f"👋 {event['user']['uniqueId']} joined")
@client.on("roomUserSeq")defon_viewers(event):
globalevents; events+=1print(f"👀 Viewers: {event['viewerCount']}")
@client.on("disconnected")defon_disconnect(event):
print(f"\n📊 Disconnected. Received {events} events.\n")
# Press Ctrl+C to stop. Community tier caps each WebSocket at 2 hours.client.run()
🔌 Pure WebSocket version (no SDK)
# ws-demo.py - Pure WebSocket, zero dependencies# pip install websocketsimportasyncio, websockets, jsonAPI_KEY="YOUR_API_KEY"LIVE_USERNAME="tv_asahi_news"asyncdeflisten():
url=f"wss://api.tik.tools?uniqueId={LIVE_USERNAME}&apiKey={API_KEY}"events=0asyncwithwebsockets.connect(url) asws:
print(f"\n✅ Connected to @{LIVE_USERNAME} - streaming events...\n")
asyncformessageinws:
msg=json.loads(message)
events+=1data=msg.get("data", {})
user=data.get("user", {}).get("uniqueId", "")
event=msg.get("event", "")
ifevent=="chat": print(f"💬 {user}: {data.get('comment', '')}")
elifevent=="gift": print(f"🎁 {user} sent {data.get('giftName', '')}")
elifevent=="like": print(f"❤️ {user} liked × {data.get('likeCount', 0)}")
elifevent=="member": print(f"👋 {user} joined")
elifevent=="roomUserSeq": print(f"👀 Viewers: {data.get('viewerCount', 0)}")
else: print(f"📦 {event}")
print(f"\n📊 Disconnected. Received {events} events.\n")
asyncio.run(listen())

REST API - leaderboards, recruiting, profiles, gifts

The WebSocket client streams live events. For everything else - leaderboards, gaming ranks, recruiting, live status, gift catalogs, profiles - use the TikTool REST client. Async, one method per endpoint, no extra dependencies.

importasynciofromtiktok_live_apiimportTikTool, TikToolErrorasyncdefmain():
api=TikTool(api_key="YOUR_KEY")
# Live status (single + bulk)awaitapi.live_status("charlidamelio")
awaitapi.bulk_live_check(["user1", "user2", "user3"])
# Leaderboards + rankingsawaitapi.leaderboard(region="US+")
awaitapi.ranklist_gaming("US+")
awaitapi.region_movers("US+") # entered top today, below cutoff now# Recruiting (Global Agency) - find eligible creatorsrecruits=awaitapi.eligible_creators(region="US+", limit=50, min_score=1000)
# Profiles + giftsawaitapi.profile_info("khaby.lame")
awaitapi.gifts_by_country("US")
asyncio.run(main())

Tier gating is enforced server-side: a call above your tier raises TikToolError with .status == 403. Any endpoint not yet wrapped is reachable via await api.request("/webcast/...", query={...}).

try:
awaitapi.eligible_creators(region="US+")
exceptTikToolErrorase:
ife.status==403:
print("Upgrade required:", e)

See the full endpoint + tier matrix.


📋 Events (54 v3 event types)

Every event is dispatched by name. Each event payload extends the BaseEvent shape (type, timestamp, msgId, optional protoVersion: 1 | 2 | 3).

Core live events

EventDescription
connectedWebSocket open.
disconnectedWebSocket close.
roomInfoOne-shot post-connect: { roomId, wsHost, clusterRegion, connectedAt }.
chatChat message. user, comment, emotes, optional starred. v3 adds language (auto-detected ISO 639-1) + messageUuid (moderation correlation).
giftVirtual gift. giftId, giftName, diamondCount, repeatCount, repeatEnd, giftType. v3 adds transactionId (dedup key), senderUserId, relationship (joinDayNumber, fromUser, toUser).
likeLike batch. likeCount, totalLikes.
memberViewer joined. v3 adds actionCode, entrySource ("homepage_hot-live_cell", "follow-tab", ...), entryAction ("draw"/"click"), entryType ("rec" = algorithmic).
socialFollow / share.
roomUserSeqPeriodic viewer count tick.
subscribeA viewer subscribed.

PK / battle events

EventDescription
battlePK lifecycle. status (1=ACTIVE, 2=STARTING, 3=ENDED, 4=PREPARING), battleDuration, teams. v3 adds extraHostUserIds, layoutSubtype.
battleArmiesPer-host MVP breakdown. hosts[].contributors[] sorted MVP first. v3 adds transactionId.
battleItemCardBooster card: x2/x3 multipliers, gloves (crit), mist, thunder, extra-time, match-guide. Carries TikTok CDN overlay assets.
battlePunishFinishLoser-side punishment screen ended.
battleNoticePK notice (version-mismatch toast, invite-failure).
battleGameplayPK mini-game state.
linkLayerPK / link-mic negotiation.
linkMicOpponentGiftPer-gift breakdown from the OPPONENT side of a PK.
linkScreenChangePK split-screen layout flip.
cohostLayoutUpdateCohost layout subtype change.
linkMic, linkMicLayoutState, linkGeneric link-mic envelopes.
competition, competitionContributorCross-stream competition + per-contributor breakdown.
guestShowdownGuest showdown lifecycle.

Native captions (v3)

EventDescription
captionNEW in v3. TikTok native auto-captions on the LIVE WebSocket. text, isFinal, startedAtMs, endsAtMs. Independent of the operator-managed TikTok Live Captions product.

Creator-side events

EventDescription
goalUpdateStream goal progress (subscriber / gift / watch-time goals).
commentTrayComment tray UI state change.
roomPinA chat got pinned by the host or a moderator.
hostBoardHost leaderboard board update.
privilegeAdvanceViewer privilege tier-up notification.
anchorToolModificationCreator modified a panel/widget.
inRoomBannerIn-room activity banner.
roomStickerRoom-wide sticker drop.
bottomMessageBottom-bar safety / risk notice.
accessRecall, roomVerifyContent-classification recheck events.
smbBoardSMB (small-business) board overlay.
streamStatusStream status flip.
shareRevenueNoticeShare-revenue subscriber count change.
capsuleTikTok service-plus pin reminder.
hotRoomTikTok promoted the room to a high-traffic slot.
linkMicAnchorGuideAnchor (creator) guide nudges.

Moderation / safety

EventDescription
imDeleteChat moderation delete. Correlate via chat.messageUuid (v3).
unauthorizedMemberUnauthorized viewer hit a gated feature.
barrageRaw barrage feed.
superFan, superFanJoin, superFanBoxSuper-fan lifecycle.
emoteChatInline emote message.

Gift catalog + ecommerce

EventDescription
giftPanelUpdateReal-time gift catalog change. Cache-bust your local catalog.
giftDynamicRestrictionPer-room gift availability flip / age-gating.
giftGalleryHost-side gift wall snapshot.
giftUnlockHost unlocked a gated gift.
viewerPicksUpdateTikTok-promoted viewer-pick gift highlights.
oecLiveShopping, oecLiveManager, oecLiveBillboardOEC live-shopping events.
ecShortItemRefreshLucky-bag drop refreshed.

Engagement + AI

EventDescription
aiSummaryTikTok AI summary of the room (entry-time recap, multi-language).
poll, shortTouchIn-stream poll lifecycle.
rankText, rankUpdate, hourlyRankRank events.
question, questionSelected, questionSlideDownQ&A round events.
pictionaryUpdate, pictionaryEnd, pictionaryExitDrawing-game round events.
fansEvent, fanTicketFan-club events.
envelope, envelopePortalRed-envelope drops + multi-room portal chain.
gameMoment, gameServerFeatureTikTok Gaming live integration.
groupLiveMemberNotifyGroup-live member join / leave.
perceptionPerception event (mute cancel, TikTok hint signal).
control, room, liveIntroStream control + room metadata.

Catch-all

  • event - Fires for every decoded event.
  • unknown - Fires when TikTok ships a method we don't yet model (forward-compat hook).

All events ship with full TypedDict annotations. Your IDE shows autocompletion for every field. See full per-event JSON examples + field tables.

Battle / PK example

fromtiktok_live_apiimportTikTokLiveclient=TikTokLive(unique_id="creator_username", api_key="tk_...")
@client.on("battle")defon_battle(e):
print(f"PK status={e['status']} id={e['battleId']} duration={e['battleDuration']}s")
@client.on("battleArmies")defon_armies(e):
print(f"Countdown: {e.get('secsRemaining')}s")
forhostine.get("hosts", []):
print(f" @{host['hostUserId']} total={host['teamTotalScore']}")
ifhost["contributors"]:
mvp=host["contributors"][0]
print(f" MVP {mvp['nickname']} score={mvp['score']}")
@client.on("battleItemCard")defon_card(e):
ife["multiplier"] >0:
print(f"x{e['multiplier']} booster from @{e['senderUniqueId']}")
else:
print(f"Effect {e['effect']} from @{e['senderUniqueId']} ({e['durationSec']}s)")
client.connect()

🎤 Live Captions (Speech-to-Text)

Transcribe and translate any TikTok LIVE stream in real-time. This feature is unique to TikTool - no other TikTok library offers it.

fromtiktok_live_apiimportTikTokCaptionscaptions=TikTokCaptions(
"streamer_username",
api_key="YOUR_API_KEY",
translate="en", # translate to English (50+ languages)diarization=True, # identify who is speaking
)
@captions.on("caption")defon_caption(event):
speaker=event.get("speaker", "")
text=event["text"]
is_final=event.get("isFinal", False)
print(f"[{speaker}] {text}{' ✓'ifis_finalelse'...'}")
@captions.on("translation")defon_translation(event):
print(f" → {event['text']}")
captions.run()

Caption Events

EventDescriptionKey Fields
captionReal-time caption texttext, speaker, isFinal, language
translationTranslated captiontext, sourceLanguage, targetLanguage
creditsCredit balance updatetotal, used, remaining

🔄 Async Usage

For integration with async frameworks (FastAPI, Django Channels, etc.):

importasynciofromtiktok_live_apiimportTikTokLiveasyncdefmain():
client=TikTokLive("streamer_username", api_key="YOUR_API_KEY")
@client.on("chat")asyncdefon_chat(event):
print(f"{event['user']['uniqueId']}: {event['comment']}")
awaitclient.connect()
asyncio.run(main())

🤖 Chat Bot Example

fromtiktok_live_apiimportTikTokLiveclient=TikTokLive("streamer_username", api_key="YOUR_API_KEY")
gift_leaderboard= {}
message_count=0@client.on("chat")defon_chat(event):
globalmessage_countmessage_count+=1msg=event["comment"].lower().strip()
user=event["user"]["uniqueId"]
ifmsg=="!hello":
print(f">> BOT: Welcome {user}! 👋")
elifmsg=="!stats":
print(f">> BOT: {message_count} messages, {len(gift_leaderboard)} gifters")
elifmsg=="!top":
top=sorted(gift_leaderboard.items(), key=lambdax: -x[1])[:5]
fori, (name, diamonds) inenumerate(top):
print(f" {i+1}. {name} - {diamonds} 💎")
@client.on("gift")defon_gift(event):
user=event["user"]["uniqueId"]
diamonds=event.get("diamondCount", 0)
gift_leaderboard[user] =gift_leaderboard.get(user, 0) +diamondsclient.run()

🌐 Other Languages

TikTool Live is available in every major language:

LanguagePackageInstall
Pythontiktok-live-apipip install tiktok-live-api
Node.js / TypeScript@tiktool/livenpm install @tiktool/live
Any LanguageWebSocket APIwss://api.tik.tools?uniqueId=USERNAME&apiKey=KEY

Full documentation with examples in Java, Go, C#, cURLtik.tools/docs


Environment Variable

Instead of passing api_key directly, set it as an environment variable:

# Linux / macOSexport TIKTOOL_API_KEY=your_api_key_here
# Windows (PowerShell)$env:TIKTOOL_API_KEY="your_api_key_here"
fromtiktok_live_apiimportTikTokLive# Automatically reads TIKTOOL_API_KEY from environmentclient=TikTokLive("streamer_username")
client.on("chat", lambdae: print(e["comment"]))
client.run()

Pricing and limits (USD)

TierWeeklyMonthlyRequests / dayConcurrent WSConnects / hour
Sandbox / CommunityFreeFree5,000360
Basic$7$1910,00020Unlimited
Pro$15$4975,00050Unlimited
Ultra$45$149300,000250Unlimited
Global Agency$119$3991,000,000500Unlimited

Full pricing + checkout: https://tik.tools/pricing

Tiers

Tier ladder (each includes everything below it): Sandbox -> Basic -> Pro -> Ultra -> Global Agency. Sandbox is free with reduced rate limits + masked identifiers on intelligence endpoints; paid tiers raise limits and unmask data. Outgoing webhooks need Basic+. The agency intelligence endpoints (gaming ranks, movers, eligible-creator finder, gifter intel) need Global Agency.

TierHeadline features
Sandbox / CommunityAll core webcast + signing endpoints, real-time WS events (chat, gifts, viewers, battles, 18+ types), masked identifiers on intelligence endpoints. Development + evaluation only.
BasicEverything in Sandbox, plus outgoing webhooks and chat send. Higher rate limits and more concurrent WS.
ProFull unmasked Leaderboard API, Feed Discovery, user profiles, built-in CAPTCHA solving, priority chat.
UltraEverything in Pro, plus Gift Catalog, unmasked League Rankings, and peak-viewer / high-value-gift webhook events.
Global AgencyEverything in Ultra, plus Gaming Ranks (all regions), Live Gifter Firehose WS, unmasked Gifter Leaderboard, CRM + watchlist, follower-milestone webhooks, and IP allowlist.

Endpoints and required tier

EndpointMin tier
POST /webcast/sign_urlSandbox
POST /webcast/sign_websocketSandbox
GET /webcast/ws_credentialsSandbox
GET /webcast/fetchSandbox
GET /webcast/room_idSandbox
GET /webcast/room_infoSandbox
GET /webcast/room_videoSandbox
GET /webcast/room_coverSandbox
GET /webcast/check_aliveSandbox
POST /webcast/bulk_live_checkSandbox
GET /webcast/live_statusSandbox
GET /webcast/live-countsSandbox
POST /webcast/resolve_user_idsSandbox
GET /webcast/rankingsSandbox
GET /webcast/leaderboardSandbox
GET /webcast/leaderboard/leagueSandbox
GET /webcast/leaderboard/leaguesSandbox
GET /webcast/gift_infoSandbox
GET /webcast/gift_gallerySandbox
GET /webcast/hashtag_listSandbox
GET /webcast/user_earningsSandbox
GET /webcast/live_analytics/video_listSandbox
GET /webcast/live_analytics/video_detailSandbox
GET /webcast/live_analytics/user_interactionsSandbox
GET /webcast/rate_limitsSandbox
POST /authentication/jwtSandbox
GET /api/live/connectSandbox
POST /chat-sendBasic
GET/POST /api/webhooksBasic
POST /api/webhooks/{id}/testBasic
GET /ws/sweepBasic
GET /webcast/feedPro
POST /webcast/ranklist/regionalPro
GET /webcast/user_profilePro
GET /api/leaderboards/country/:slugPro
GET /webcast/gifts_by_countryUltra
GET /api/leaderboards/leagues/:regionUltra
GET /api/leaderboards/league/:region/:classTypeUltra
GET /webcast/ranklist/gamingGlobal Agency
GET /webcast/ranklist/gaming_moversGlobal Agency
GET /webcast/ranklist/region_moversGlobal Agency
GET /webcast/eligible_creatorsGlobal Agency
GET /api/gifters/topGlobal Agency
GET /api/gifters/leaderboardGlobal Agency
GET /api/gifters/profileGlobal Agency

Full docs with request/response shapes and examples: https://tik.tools/docs

What you get

Creators: real-time live events (gifts, chat, viewers), your own live status + room info, earnings + analytics, signed CDN/stream URLs that do not expire. Developers: drop-in signing (works as a tiktok-live-connector backend - point the sign base at api.tik.tools), one-WebSocket fan-out (your IP never touches TikTok), bulk live checks, leaderboards, webhooks (HMAC-signed live.start/live.end and more), SDKs across languages. Agencies (Global Agency): TikTok LIVE gaming ranks + creator ranks + 99+ movers across all 30 regions, eligible-creator recruiting finder, gifter intelligence (top gifters, profiles, leaderboards), and the Discord bot that posts copy-paste username batches for backstage.

Live Gifter Firehose - Global Agency

Real-time gift event stream. Filter by region, league, or globally; cap by minimum diamond threshold.

importasyncio, json, websocketsAPI_KEY="tk_..."URL=f"wss://api.tik.tools/firehose/gifters?apiKey={API_KEY}&mode=region&region=US%2B&min_diamonds=1000"asyncdefmain():
asyncwithwebsockets.connect(URL) asws:
asyncforrawinws:
evt=json.loads(raw)
# evt: { type:'gifter_alert', ts, gifter:{username,displayName,isAnonymous},# creator:{uniqueId}, gift:{name,totalDiamonds}, region }print(evt)
asyncio.run(main())

Modes: global (all regions), region (single region code), league (region + league class, e.g. B2). Update the filter mid-stream by sending {"type":"update_filter","mode":"global","min_diamonds":5000} - no reconnect needed.

Get your free API key → tik.tools


Star History

If this project helps you, please consider giving it a ⭐ - it helps others discover it!

Star History Chart


Links


License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributors

See also the full list of contributors who have participated in this project.

About

TikTok LIVE API for Python - Real-time chat, gifts, viewers, battles & AI live captions. Managed WebSocket, 99.9% uptime, zero maintenance.

Topics

Resources

Stars

5 stars

Watchers

2 watching

Forks

Contributors

Languages