TikTok-Live-Java

repository·master·Indexed 42 days ago

https://github.com/jwdeveloper/tiktoklivejava

A Java library for connecting to TikTok LIVE streams in real-time by reverse-engineering TikTok's WebCast push service. It allows developers to listen for events such as comments, gifts, follows, and room information. The library includes extensions for collecting live data into MongoDB via extension-collector and recording streams to .flv files using extension-recorder with ffmpeg.

Tokens
9K
Snippets
19
Records
28
Agent score
52%

What's inside TikTok-Live-Java

  1. Explore the project module structure

    master

    The project is divided into several modules:

    API Module

    Contains all public interfaces and data classes intended for end-users.

    • Events: Located in io.github.jwdeveloper.tiktok.data.events.
    • Models: Data used within events is under io.github.jwdeveloper.tiktok.data.models.
    • ProtocolBuffer Messages: Generated classes are in the io.github.jwdeveloper.tiktok.messages namespace (found in API/target/classes/io/github/jwdeveloper/tiktok/messages).

    Client Module

    Contains the core implementation logic.

    • TikTokLiveClient: Manages connection and disconnection.
    • TikTokLiveClientBuilder: Used to configure and create a TikTokLiveClient.
    • TikTokMessageHandler: The core component that finds mappers for incoming data and triggers event mapping.
    • TikTokMessageHandlerRegistration: Defines the mappings between ProtocolBuffer classes and Events.
    • TikTokEventObserver: Handles event registration and triggering.

    Tools & Examples

    • Examples: Playground for testing new features.
    • Tools: Contains GenerateGiftsEnum (generates Gift enum from TikTok JSON) and other utilities.
    • Tools-EventsCollector: Stores ProtocolBuffer and Event data in SQLite or JSON for debugging.
    • Tools-EventsWebViewer: A web-based tool to display raw TikTok data.
  2. Understand the TikTokLiveJava architecture

    master

    The library operates in four main stages:

    1. Metadata Retrieval: Performs three HTTPS requests to obtain the Room_ID, specific live metadata (title, host name, etc.), and an access token from the Sign API.
    2. WebSocket Connection: Connects to the TikTok pushServer to receive ProtocolBuffer messages in binary format.
    3. Data Mapping: Maps incoming ProtocolBuffer classes (which are subject to change by TikTok) to stable library-specific Event classes to maintain consistent code structure.
    4. Event Triggering: Publishes the mapped event objects via the TikTokEventObserver.
  3. Use Custom Listeners for complex event logic

    master

    If your event handling logic is complex, use the addListener method instead of inline lambda handlers. To create a custom listener, implement the TikTokEventListener interface.

    Requirements for event methods in a TikTokEventListener:

    1. Must be annotated with @TikTokEventObserver.
    2. Must have exactly 2 parameters.
    3. The first parameter must be LiveClient.
    4. The second parameter must be a class that extends TikTokEvent.
    public static class CustomListener implements TikTokEventListener {
    
        @TikTokEventObserver
        public void onLike(LiveClient liveClient, TikTokLikeEvent event) {
            System.out.println(event.toString());
        }
    
        @TikTokEventObserver
        public void onComment(LiveClient liveClient, TikTokCommentEvent event) {
            var userName = event.getUser().getName();
            var text = event.getText();
            liveClient.getLogger().info(userName + ": " + text);
        }
    }
    
    // Usage
    TikTokLive.newClient("host-name")
        .addListener(new CustomListener())
        .buildAndConnect();
  4. Create a basic TikTok Live connection

    master

    Use TikTokLive.newClient(uniqueId) to initialize a connection to a specific TikTok streamer using their username. You can chain event listeners like onGift, onRoomInfo, onJoin, and onConnected before calling buildAndConnect() to start the stream processing.

    TikTokLive.newClient("bangbetmenygy")
            .onGift((liveClient, event) ->
            {
                String message = switch (event.getGift()) {
                    case ROSE -> "ROSE!";
                    case GG -> "GOOD GAME";
                    case TIKTOK -> "Ye";
                    case CORGI -> "Nice gift";
                    default -> "Thank you for " + event.getGift().getName();
                };
                System.out.println(event.getUser().getProfileName() + " sends " + message);
            })
            .onGiftCombo((liveClient, event) ->
            {
                System.out.println(event.getComboState()+ " " + event.getCombo() + " " + event.getGift().getName());
            })
            .onRoomInfo((liveClient, event) ->
            {
                var roomInfo = event.getRoomInfo();
                System.out.println("Room Id: "+roomInfo.getRoomId());
                System.out.println("Likes: "+roomInfo.getLikesCount());
                System.out.println("Viewers: "+roomInfo.getViewersCount());
            })
            .onJoin((liveClient, event) ->
            {
                System.out.println(event.getUser().getProfileName() + "Hello on my stream! ");
            })
            .onConnected((liveClient, event) ->
            {
                System.out.println("Connected to live ");
            })
            .onError((liveClient, event) ->
            {
                System.out.println("Error! " + event.getException().getMessage());
            })
            .buildAndConnect();
  5. Install extension-collector via Maven

    master

    To use the extension-collector for collecting live data into a MongoDB database, add the JitPack repository and the following dependencies to your pom.xml file.

       <repositories>
            <repository>
                <id>jitpack.io</id>
                <url>https://jitpack.io</url>
            </repository>
        </repositories>
        <dependencies>
            <dependency>
                <groupId>com.github.jwdeveloper.TikTok-Live-Java</groupId>
                <artifactId>Client</artifactId>
                <version>1.1.0-Release</version>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>com.github.jwdeveloper.TikTok-Live-Java</groupId>
                <artifactId>extension-collector</artifactId>
                <version>1.1.0-Release</version>
            </dependency>
        </dependencies>
  6. Create a basic TikTok LIVE chat connection

    master

    Use TikTokLive.newClient(uniqueId) to start a connection to a specific TikTok user's live stream. You can chain event listeners (like .onGift, .onJoin, .onConnected) and finally call .buildAndConnect() to establish the connection. No credentials are required; you only need the user's uniqueId.

    TikTokLive.newClient("bangbetmenygy")
            .onGift((liveClient, event) ->
            {
                String message = switch (event.getGift()) {
                    case ROSE -> "ROSE!";
                    case GG -> "GOOD GAME";
                    case TIKTOK -> "Ye";
                    case CORGI -> "Nice gift";
                    default -> "Thank you for " + event.getGift().getName();
                };
                System.out.println(event.getUser().getProfileName() + " sends " + message);
            })
            .onGiftCombo((liveClient, event) ->
            {
                System.out.println(event.getComboState()+ " " + event.getCombo() + " " + event.getGift().getName());
            })
            .onRoomInfo((liveClient, event) ->
            {
                var roomInfo = event.getRoomInfo();
                System.out.println("Room Id: "+roomInfo.getRoomId());
                System.out.println("Likes: "+roomInfo.getLikesCount());
                System.out.println("Viewers: "+roomInfo.getViewersCount());
            })
            .onJoin((liveClient, event) ->
            {
                System.out.println(event.getUser().getProfileName() + "Hello on my stream! ");
            })
            .onConnected((liveClient, event) ->
            {
                System.out.println("Connected to live ");
            })
            .onError((liveClient, event) ->
            {
                System.out.println("Error! " + event.getException().getMessage());
            })
            .buildAndConnect();
  7. Install TikTok LIVE API for Java

    master

    You can install the library using Maven or Gradle via JitPack.

    Maven

    Add the JitPack repository and the Client dependency to your pom.xml:

    Gradle

    Add the JitPack repository to your dependencyResolutionManagement and the Client dependency to your dependencies block.

    ### Maven
    <repositories>
        <repository>
            <id>jitpack.io</id>
            <url>https://jitpack.io</url>
        </repository>
    </repositories>
    
    <dependencies>
        <dependency>
            <groupId>com.github.jwdeveloper.TikTok-Live-Java</groupId>
            <artifactId>Client</artifactId>
            <version>1.11.0-Release</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    
    ### Gradle
    dependencyResolutionManagement {
        repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
        repositories {
            mavenCentral()
            maven { url 'https://jitpack.io' }
        }
    }
    
    dependencies {
        implementation 'com.github.jwdeveloper.TikTok-Live-Java:Client:1.10.0-Release'
    }
  8. Set up the TikTokLiveJava development environment

    master

    To develop with or contribute to the library, clone the repository and use Maven to generate necessary classes. If you encounter missing class errors after cloning, run the Maven compile command on the root project to generate the ProtocolBuffer classes from the .proto files.

    mvn compile
  9. How to add a new custom Event

    master

    To implement a new event, follow these three steps:

    1. Create the Event Class

    Define a class in the io.github.jwdeveloper.tiktok.data.events package. It is recommended to extend TikTokHeaderEvent and use Lombok's @Data annotation.

    package io.github.jwdeveloper.tiktok.data.events;
    
    import io.github.jwdeveloper.tiktok.annotations.EventMeta;
    import io.github.jwdeveloper.tiktok.annotations.EventType;
    import io.github.jwdeveloper.tiktok.data.events.common.TikTokHeaderEvent;
    import io.github.jwdeveloper.tiktok.messages.data.User;
    import lombok.Data;
    
    @Data
    @EventMeta(eventType = EventType.Message)
    public class CustomEvent extends TikTokHeaderEvent
    {
        private final User user;
        private final String title;
    
        public CustomEvent(User user, String title)
        {
             this.user = user;
             this.title = title;
        }
    }

    2. Register the Mapping

    In io.github.jwdeveloper.tiktok.handlers.TikTokMessageHandlerRegistration, use registerMapping to link a ProtocolBuffer class (e.g., WebcastGiftMessage) to your new event. You must manually parse the bytes and map the internal ProtocolBuffer models to the library's stable models.

    public void init() {
        registerMapping(WebcastGiftMessage.class, bytes ->
        {
            try {
                WebcastGiftMessage tiktokData = WebcastGiftMessage.parseFrom(bytes);
                io.github.jwdeveloper.tiktok.messages.data.User tiktokProtocolBufferUser = tiktokData.getUser();
                io.github.jwdeveloper.tiktok.data.models.users.User tiktokLiveJavaUser = User.map(tiktokProtocolBufferUser);
    
                return new CustomEvent(tiktokLiveJavaUser, "hello word");
            } catch (Exception e) {
                throw new TikTokLiveException("Unable to parse our custom event", e);
            }
        });
    }

    3. Expose the Event in the Builder

    Add a handler method to TikTokLiveClientBuilder and update the EventsBuilder interface to make the event accessible via the fluent API.

    In TikTokLiveClientBuilder:

    public LiveClientBuilder onCustomEvent(EventConsumer<CustomEvent> event) {
        tikTokEventHandler.subscribe(CustomEvent.class, event);
        return this;
    }

    In EventsBuilder interface:

    T onCustomEvent(EventConsumer<CustomEvent> event);
  10. Install extension-recorder via Maven

    master

    To use the extension-recorder functionality, you must add the JitPack repository and the following dependencies to your pom.xml. Note that you need both the core Client and the extension-recorder artifact.

    Ensure you use the correct groupId (com.github.jwdeveloper.TikTok-Live-Java) and the appropriate version (e.g., 1.1.0-Release).

    <repositories>
        <repository>
            <id>jitpack.io</id>
            <url>https://jitpack.io</url>
        </repository>
    </repositories>
    
    <dependencies>
        <dependency>
            <groupId>com.github.jwdeveloper.TikTok-Live-Java</groupId>
            <artifactId>Client</artifactId>
            <version>1.1.0-Release</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.github.jwdeveloper.TikTok-Live-Java</groupId>
            <artifactId>extension-recorder</artifactId>
            <version>1.1.0-Release</version>
        </dependency>
    </dependencies>