Skip to main content

TikTok Live Python Client

Project description

TikTokLive

The definitive Python library to connect to TikTok LIVE.

Connections Downloads Stars Forks Issues

TikTokLive is a Python library designed to connect to TikTok LIVE and receive realtime events such as comments, gifts, and likes through a websocket connection to TikTok's internal Webcast service. This library allows you to connect directly to TikTok with just a username (@unique_id). No credentials are required to use TikTokLive.

Join the TikTokLive discord and visit the #py-support channel for questions, contributions and ideas.

Consider Donating <3

I'm a 2nd-year Biology student in university who likes to program for fun. Please consider supporting development through a small donation at https://www.buymeacoffee.com/isaackogan. Anything you can offer will go towards school & development costs for TikTokLive, which has taken hundreds of hours of time to build.

Other Languages

TikTokLive is available in several alternate programming languages:

Table of Contents

Getting Started

  1. Install the module via pip from the PyPi repository
$ pip install TikTokLive
  1. Create your first chat connection
from TikTokLive import TikTokLiveClient
from TikTokLive.events import ConnectEvent, CommentEvent

# Create the client
client: TikTokLiveClient = TikTokLiveClient(unique_id="@isaackogz")


# Listen to an event with a decorator!
@client.on(ConnectEvent)
async def on_connect(event: ConnectEvent):
    print(f"Connected to @{event.unique_id} (Room ID: {client.room_id}")


# Or, add it manually via "client.add_listener()"
async def on_comment(event: CommentEvent) -> None:
    print(f"{event.user.nickname} -> {event.comment}")


client.add_listener(CommentEvent, on_comment)

if __name__ == '__main__':
    # Run the client and block the main thread
    # await client.start() to run non-blocking
    client.run()

For more quickstart examples, see the examples folder provided in the source tree.

Parameters

Param Name Required Default Description
unique_id Yes N/A The unique username of the broadcaster. You can find this name in the URL of the user. For example, the unique_id for https://www.tiktok.com/@isaackogz would be isaackogz.
web_proxy No None TikTokLive supports proxying HTTP requests. This parameter accepts an httpx.Proxy. Note that if you do use a proxy you may be subject to reduced connection limits at times of high load.
ws_proxy No None TikTokLive supports proxying the websocket connection. This parameter accepts an httpx.Proxy. Using this proxy will never be subject to reduced connection limits.
web_kwargs No {} Under the scenes, the TikTokLive HTTP client uses the httpx library. Arguments passed to web_kwargs will be forward the the underlying HTTP client.
ws_kwargs No {} Under the scenes, TikTokLive uses the websockets library to connect to TikTok. Arguments passed to ws_kwargs will be forwarded to the underlying WebSocket client.

Methods

A TikTokLiveClient object contains the following important methods:

Method Name Notes Description
run N/A Connect to the livestream and block the main thread. This is best for small scripts.
add_listener N/A Adds an asynchronous listener function (or, you can decorate a function with @client.on("<event>")) and takes two parameters, an event name and the payload, an AbstractEvent
connect async Connects to the tiktok live chat while blocking the current future. When the connection ends (e.g. livestream is over), the future is released.
start async Connects to the live chat without blocking the main thread. This returns an asyncio.Task object with the client loop.
disconnect async Disconnects the client from the websocket gracefully, processing remaining events before ending the client loop.

Properties

A TikTokLiveClient object contains the following important properties:

Attribute Name Description
room_id The Room ID of the livestream room the client is currently connected to.
web The TikTok HTTP client. This client has a lot of useful routes you should explore!
connected Whether you are currently connected to the livestream.
logger The internal logger used by TikTokLive. You can use client.logger.setLevel(...) method to enable client debug.
room_info Room information that is retrieved from TikTok when you use a connection method (e.g. client.connect) with the keyword argument fetch_room_info=True .
gift_info Extra gift information that is retrieved from TikTok when you use a connection method (e.g. client.run) with the keyword argument fetch_gift_info=True.

WebDefaults

TikTokLive has a series of global defaults used to create the HTTP client which you can customize. For info on how to set these parameters, see the web_defaults.py example.

Parameter Type Description
tiktok_app_url str The TikTok app URL (https://www.tiktok.com) used to scrape the room.
tiktok_sign_url str The signature server used to generate tokens to connect to TikTokLive.
tiktok_webcast_url str The TikTok livestream URL (https://webcast.tiktok.com) where livestreams can be accessed from.
client_params dict The URL parameters added on to TikTok requests from the HTTP client.
client_headers dict The headers added on to TikTok requests from the HTTP client.
tiktok_sign_api_key str A global way of setting the sign_api_key parameter.

Events

Events can be listened to using a decorator or non-decorator method call. The following examples illustrate how you can listen to an event:

@client.on(LikeEvent)
async def on_like(event: LikeEvent) -> None:
    ...

async def on_comment(event: CommentEvent) -> None:
    ...

client.add_listener(CommentEvent, on_comment)

There are two types of events, CustomEvent events and ProtoEvent events. Both belong to the TikTokLive Event type and can be listened to. The following events are available:

Custom Events

  • ConnectEvent - Triggered when the Webcast connection is initiated
  • DisconnectEvent - Triggered when the Webcast connection closes (including the livestream ending)
  • LiveEndEvent - Triggered when the livestream ends
  • LivePauseEvent - Triggered when the livestream is paused
  • LiveUnpauseEvent - Triggered when the livestream is unpaused
  • FollowEvent - Triggered when a user in the livestream follows the streamer
  • ShareEvent - Triggered when a user shares the livestream
  • WebsocketResponseEvent - Triggered when any event is received (contains the event)
  • UnknownEvent - An instance of WebsocketResponseEvent thrown whenever an event does not have an existing definition, useful for debugging

Proto Events

If you know what an event does, make a pull request and add the description.

  • GiftEvent - Triggered when a gift is sent to the streamer
  • GoalUpdateEvent - Triggered when the subscriber goal is updated
  • ControlEvent - Triggered when a stream action occurs (e.g. Livestream start, end)
  • LikeEvent - Triggered when the stream receives a like
  • SubscribeEvent - Triggered when someone subscribes to the TikTok creator
  • PollEvent - Triggered when the creator launches a new poll
  • CommentEvent - Triggered when a comment is sent in the stream
  • RoomEvent - Messages broadcasted to all users in the room (e.g. "Welcome to TikTok LIVE!")
  • EmoteChatEvent - Triggered when a custom emote is sent in the chat
  • EnvelopeEvent - Triggered every time someone sends a treasure chest
  • SocialEvent - Triggered when a user shares the stream or follows the host
  • QuestionNewEvent - Triggered every time someone asks a new question via the question feature.
  • LiveIntroEvent - Triggered when a live intro message appears
  • LinkMicArmiesEvent - Triggered when a TikTok battle user receives points
  • LinkMicBattleEvent - Triggered when a TikTok battle is started
  • JoinEvent - Triggered when a user joins the livestream
  • LinkMicFanTicketMethodEvent
  • LinkMicMethodEvent
  • BarrageEvent
  • CaptionEvent
  • ImDeleteEvent
  • RoomUserSeqEvent
  • RankUpdateEvent
  • RankTextEvent
  • HourlyRankEvent
  • UnauthorizedMemberEvent
  • MessageDetectEvent
  • OecLiveShoppingEvent
  • RoomPinEvent
  • SystemEvent
  • LinkEvent
  • LinkLayerEvent

Special Events

GiftEvent

Triggered every time a gift arrives. Extra information can be gleamed from the available_gifts client attribute.

NOTE: Users have the capability to send gifts in a streak. This increases the event.gift.repeat_count value until the user terminates the streak. During this time new gift events are triggered again and again with an increased event.gift.repeat_count value. It should be noted that after the end of a streak, a final gift event is triggered, which signals the end of the streak with event.repeat_end:1. The following handlers show how you can deal with this in your code.

Using the low-level direct proto:

@client.on(GiftEvent)
async def on_gift(event: GiftEvent):
    # If it's type 1 and the streak is over
    if event.gift.info.type == 1:
        if event.gift.is_repeating == 1:
            print(f"{event.user.unique_id} sent {event.gift.count}x \"{event.gift.info.name}\"")

    # It's not type 1, which means it can't have a streak & is automatically over
    elif event.gift.info.type != 1:
        print(f"{event.user.unique_id} sent \"{event.gift.info.name}\"")

Using the TikTokLive extended proto:

@client.on("gift")
async def on_gift(event: GiftEvent):
    # Streakable gift & streak is over
    if event.gift.streakable and not event.streaking:
        print(f"{event.user.unique_id} sent {event.gift.count}x \"{event.gift.info.name}\"")

    # Non-streakable gift
    elif not event.gift.streakable:
        print(f"{event.user.unique_id} sent \"{event.gift.info.name}\"")

SubscribeEvent

This event will only fire when a session ID (account login) is passed to the HTTP client before connecting to TikTok LIVE. You can set the session ID with client.web.set_session_id(...).

Contributors

  • Isaac Kogan - Creator, Primary Maintainer, and Reverse-Engineering - isaackogan
  • Zerody - Initial Reverse-Engineering Protobuf & Support - Zerody
  • Davincible - Reverse-Engineering Stream Downloads - davincible
  • David Teather - TikTokLive Introduction Tutorial - davidteather

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

License

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

TikTokLive-6.0.0rc1.tar.gz (72.6 kB view details)

Uploaded Source

Built Distribution

TikTokLive-6.0.0rc1-py3-none-any.whl (79.3 kB view details)

Uploaded Python 3

File details

Details for the file TikTokLive-6.0.0rc1.tar.gz.

File metadata

  • Download URL: TikTokLive-6.0.0rc1.tar.gz
  • Upload date:
  • Size: 72.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.9.13

File hashes

Hashes for TikTokLive-6.0.0rc1.tar.gz
Algorithm Hash digest
SHA256 550b58dcc7b378f9536a44cc90794ec7c274edfef448818d9bcffab2770bfa4e
MD5 c721ddb8f6273d074a0fdd8493811601
BLAKE2b-256 8825453a1de240c4a738c1a0ca9d5457e38720da2980f11d1f4b23c85047fe22

See more details on using hashes here.

Provenance

File details

Details for the file TikTokLive-6.0.0rc1-py3-none-any.whl.

File metadata

File hashes

Hashes for TikTokLive-6.0.0rc1-py3-none-any.whl
Algorithm Hash digest
SHA256 f76cefbc651f435228462ce2c4d54513d5efdf73ec4170efe3c48fffe7e3e00a
MD5 e4321e8e6d1e8117d15a5b3117d44a5e
BLAKE2b-256 f53120df65344563b9ae8cec49b6418c052bee2db6129012ca8193c835d74937

See more details on using hashes here.

Provenance

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page