### Java Usage Example for TikTok Live Recorder
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/extension-recorder/README.md
This example demonstrates how to configure and start recording a TikTok live stream to an FLV file. Ensure ffmpeg is correctly placed and paths are set.
```java
public static void main(String[] args) {
TikTokLive.newClient("bangbetmenygy")
.configure(liveClientSettings ->
{
liveClientSettings.setPrintToConsole(true);
})
.onError((liveClient, event) ->
{
event.getException().printStackTrace();
})
.addListener(TikTokLiveRecorder.use(recorderSettings ->
{
recorderSettings.setFfmpegPath("C:\\Users\\ja\\IdeaProjects\\TikTokLiveJava\\extension-recorder\\libs\\ffmpeg.exe");
recorderSettings.setOutputPath("C:\\Users\\ja\\IdeaProjects\\TikTokLiveJava\\extension-recorder\\out");
recorderSettings.setOutputFileName("test.flv");
}))
.onEvent(TikTokLiveRecorderStartedEvent.class, (liveClient, event) ->
{
System.out.println(event.getDownloadData().getFullUrl());
})
.buildAndConnect();
}
```
--------------------------------
### Maven Installation for TikTok Live Java Client
Source: https://context7.com/jwdeveloper/tiktoklivejava/llms.txt
Add the JitPack repository and the Client artifact to your pom.xml to install the library using Maven.
```xml
jitpack.io
https://jitpack.io
com.github.jwdeveloper.TikTok-Live-Java
Client
1.11.0-Release
compile
```
--------------------------------
### Gradle Installation for TikTok Live Java Client
Source: https://context7.com/jwdeveloper/tiktoklivejava/llms.txt
Configure your Gradle build to use the JitPack repository and include the Client artifact for TikTok Live Java.
```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'
}
```
--------------------------------
### Connect to a TikTok Live Stream
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/tools-readme/src/main/resources/template.md
This is a basic example of how to connect to a TikTok live stream using the library. Replace 'uniqueId' with the target user's unique ID. This setup allows you to start receiving events.
```java
TikTokLive.connect("uniqueId", new TikTokLiveConfig() {
@Override
public void onConnected(String uniqueId) {
System.out.println("Connected to " + uniqueId + "'s stream!");
}
@Override
public void onDisconnected(String uniqueId) {
System.out.println("Disconnected from " + uniqueId + "'s stream.");
}
});
```
--------------------------------
### Create a Basic TikTok Live Chat Connection
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/tools-readme/src/main/resources/output.md
Initiate a connection to a TikTok live stream and set up handlers for various events like gifts, room information, and user joins. This is the fundamental way to start interacting with a live stream.
```java
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();
```
--------------------------------
### Mapping Messages to Custom Events
Source: https://github.com/jwdeveloper/tiktoklivejava/wiki/Creating-custom-Events-and-message-mapping
This example demonstrates how to map a specific incoming message (`WebcastChatMessage`) to a custom event (`CustomChatEvent`). It uses the `onMapping` method and `mapper.webcastObjectToEvent()` to convert the raw message bytes into a structured event object. This is the standard way to integrate custom event handling for known message types.
```java
TikTokLive.newClient("test")
.onMapping(mapper ->
{
mapper.forMessage(WebcastChatMessage.class)
.onMapping((inputBytes, messageName, mapperHelper) ->
{
System.out.println("onMapping mapping: " + messageName);
var message = mapperHelper.bytesToWebcastObject(inputBytes, WebcastChatMessage.class);
var language = chatMessage.getContentLanguage();
var userName = chatMessage.getUser().getNickname();
var content= chatMessage.getContent();
var event = new CustomChatEvent(language, userName, content);
return MappingResult.of(message, event);
})
}).buildAndConnect();
```
--------------------------------
### Implement Custom TikTok Event Listener
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/tools-readme/src/main/resources/output.md
This example demonstrates how to create a custom listener class that implements TikTokEventListener. Methods annotated with @TikTokEventObserver will be invoked for specific events. Ensure methods have two parameters: LiveClient and the specific TikTokEvent subclass.
```java
/**
*
* Listeners are an alternative way of handling events.
* I would to suggest to use then when logic of handing event
* is more complex
*
*/
public static void main(String[] args) throws IOException {
showLogo();
CustomListener customListener = new CustomListener();
TikTokLive.newClient(SimpleExample.TIKTOK_HOSTNAME)
.addListener(customListener)
.buildAndConnect();
System.in.read();
}
/**
*
* Method in TikTokEventListener should meet 4 requirements to be detected
* - must have @TikTokEventObserver annotation
* - must have 2 parameters
* - first parameter must be LiveClient
* - second must be class that extending TikTokEvent
*/
public static class CustomListener implements TikTokEventListener {
@TikTokEventObserver
public void onLike(LiveClient liveClient, TikTokLikeEvent event) {
System.out.println(event.toString());
}
@TikTokEventObserver
public void onError(LiveClient liveClient, TikTokErrorEvent event) {
// event.getException().printStackTrace();
}
@TikTokEventObserver
public void onComment(LiveClient liveClient, TikTokCommentEvent event) {
var userName = event.getUser().getName();
var text = event.getText();
liveClient.getLogger().info(userName + ": " + text);
}
@TikTokEventObserver
public void onGift(LiveClient liveClient, TikTokGiftEvent event) {
var message = switch (event.getGift()) {
case ROSE -> "Thanks :)";
case APPETIZERS -> ":OO";
case APRIL -> ":D";
case TIKTOK -> ":P";
case CAP -> ":F";
default -> ":I";
};
liveClient.getLogger().info(message);
}
@TikTokEventObserver
public void onAnyEvent(LiveClient liveClient, TikTokEvent event) {
liveClient.getLogger().info(event.getClass().getSimpleName());
}
}
//
```
--------------------------------
### Register Message Mapping Handlers
Source: https://github.com/jwdeveloper/tiktoklivejava/wiki/Event-lifetime
Initializes the mapping of incoming Webcast message classes to their corresponding handler methods or event classes. This setup is crucial for processing various TikTok Live events.
```java
public void init() {
//ConnectionEvents events
registerMapping(WebcastControlMessage.class, this::handleWebcastControlMessage);
//Room status events
registerMapping(WebcastLiveIntroMessage.class, roomInfoHandler::handleIntro);
registerMapping(WebcastRoomUserSeqMessage.class, roomInfoHandler::handleUserRanking);
registerMapping(WebcastCaptionMessage.class, TikTokCaptionEvent.class);
//User Interactions events
registerMapping(WebcastChatMessage.class, TikTokCommentEvent.class);
registerMappings(WebcastLikeMessage.class, this::handleLike);
registerMappings(WebcastGiftMessage.class, giftHandler::handleGift);
registerMapping(WebcastSocialMessage.class, socialHandler::handle);
registerMappings(WebcastMemberMessage.class, this::handleMemberMessage);
}
```
--------------------------------
### Register and Map Custom Events
Source: https://github.com/jwdeveloper/tiktoklivejava/wiki/Creating-custom-Events-and-message-mapping
Register a custom event handler using .onEvent and define message mapping logic using .onMapping. This example maps 'WebcastMemberMessage' to CustomChatEvent.
```java
public static void main(String[] args) {
TikTokLive.newClient("test")
.onEvent(CustomChatEvent.class, (liveClient, event) ->
{
System.out.println("hello world!");
})
.onMapping(mapper ->
{
mapper.forMessage("WebcastMemberMessage")
.onMapping((inputBytes, messageName, mapperHelper) ->
{
System.out.println("onMapping mapping: " + messageName);
var message = mapperHelper.bytesToWebcastObject(inputBytes, WebcastChatMessage.class);
var language = message.getContentLanguage();
var userName = message.getUser().getNickname();
var content = message.getContent();
var event = new CustomChatEvent(language, userName, content);
return MappingResult.of(message, event);
})
}).buildAndConnect();
}
```
--------------------------------
### Handle Gift Combos with onGiftCombo
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/tools-readme/src/main/resources/output.md
Detects every instance a gift is sent, including the start, active, and finished states of a combo. Note that a finished combo also triggers the onGift event.
```java
TikTokLive.newClient("host-name")
.onGiftCombo((liveClient, event) ->
{
})
.buildAndConnect();
```
--------------------------------
### Building and Connecting a Live Client
Source: https://context7.com/jwdeveloper/tiktoklivejava/llms.txt
Demonstrates how to create a new client instance for a specific streamer, register various event handlers (connected, disconnected, comment, join, like, follow, share, subscribe, live ended, error), and then build and connect to the live stream. Supports both blocking and non-blocking connection modes.
```APIDOC
## TikTokLive.newClient
### Description
Creates a new `LiveClientBuilder` for a given streamer's username, allowing for fluent configuration of event handlers and connection options before building and connecting to the live stream.
### Method Signature
`TikTokLive.newClient(String hostName)`
### Usage
```java
import io.github.jwdeveloper.tiktok.TikTokLive;
TikTokLive.newClient("streamer_username")
.onConnected((liveClient, event) ->
System.out.println("Connected to live stream!"))
.onDisconnected((liveClient, event) ->
System.out.println("Disconnected: " + event.getReason()))
.onComment((liveClient, event) ->
System.out.println(event.getUser().getName() + ": " + event.getText()))
.onJoin((liveClient, event) ->
System.out.println(event.getUser().getName() + " joined!"))
.onLike((liveClient, event) ->
System.out.println(event.getUser().getName() + " sent " + event.getLikes() + " likes"))
.onFollow((liveClient, event) ->
System.out.println(event.getUser().getName() + " followed!"))
.onShare((liveClient, event) ->
System.out.println(event.getUser().getName() + " shared the stream"))
.onSubscribe((liveClient, event) ->
System.out.println(event.getUser().getName() + " subscribed!"))
.onLiveEnded((liveClient, event) ->
System.out.println("Live ended."))
.onError((liveClient, event) ->
event.getException().printStackTrace())
.buildAndConnect(); // blocking; use buildAndConnectAsync() for non-blocking
```
### Event Handlers
- `onConnected`: Called when the client successfully connects to the live stream.
- `onDisconnected`: Called when the client disconnects from the live stream, providing a reason.
- `onComment`: Called when a new comment is received.
- `onJoin`: Called when a user joins the live stream.
- `onLike`: Called when likes are sent to the stream.
- `onFollow`: Called when a user follows the streamer.
- `onShare`: Called when the stream is shared.
- `onSubscribe`: Called when a user subscribes.
- `onLiveEnded`: Called when the live stream ends.
- `onError`: Called when an error occurs during connection or streaming.
```
--------------------------------
### Define a Custom Chat Event
Source: https://github.com/jwdeveloper/tiktoklivejava/wiki/Creating-custom-Events-and-message-mapping
Create a custom event by extending the TikTokEvent class. This example defines a CustomChatEvent with language, username, and message properties.
```java
@Data
public class CustomChatEvent extends TikTokEvent {
private final String langauge;
private final String userName;
private final String message;
public CustomChatEvent(String language, String userName, String message) {
this.langauge = language;
this.userName = userName;
this.message = message;
}
}
```
--------------------------------
### Build and Connect TikTok Live Client
Source: https://github.com/jwdeveloper/tiktoklivejava/wiki/Event-lifetime
Initializes a TikTok Live client with a given ID and sets up a gift event listener. This is the entry point for connecting to TikTok Live streams.
```java
TikTokLive.newClient("test")
.onGift((liveClient, event) ->
{
System.out.println("hello world");
}).buildAndConnect();
```
--------------------------------
### Building and Connecting to a TikTok Live Stream
Source: https://context7.com/jwdeveloper/tiktoklivejava/llms.txt
Use TikTokLive.newClient to create a client instance and register event handlers for various live stream events. Connect synchronously with buildAndConnect() or asynchronously with buildAndConnectAsync().
```java
import io.github.jwdeveloper.tiktok.TikTokLive;
TikTokLive.newClient("streamer_username")
.onConnected((liveClient, event) ->
System.out.println("Connected to live stream!"))
.onDisconnected((liveClient, event) ->
System.out.println("Disconnected: " + event.getReason()))
.onComment((liveClient, event) ->
System.out.println(event.getUser().getName() + ": " + event.getText()))
.onJoin((liveClient, event) ->
System.out.println(event.getUser().getName() + " joined!"))
.onLike((liveClient, event) ->
System.out.println(event.getUser().getName() + " sent " + event.getLikes() + " likes"))
.onFollow((liveClient, event) ->
System.out.println(event.getUser().getName() + " followed!"))
.onShare((liveClient, event) ->
System.out.println(event.getUser().getName() + " shared the stream"))
.onSubscribe((liveClient, event) ->
System.out.println(event.getUser().getName() + " subscribed!"))
.onLiveEnded((liveClient, event) ->
System.out.println("Live ended."))
.onError((liveClient, event) ->
event.getException().printStackTrace())
.buildAndConnect(); // blocking; use buildAndConnectAsync() for non-blocking
```
--------------------------------
### configure
Source: https://context7.com/jwdeveloper/tiktoklivejava/llms.txt
The `configure` method allows for detailed customization of the TikTok Live client's connection behavior, authentication, logging, and retry mechanisms before the client is built.
```APIDOC
## configure — Client Settings
The `configure` builder method accepts a `Consumer` allowing full customisation of connection behaviour, authentication, logging, and retry logic before the client is built.
```java
import java.time.Duration;
import java.util.logging.Level;
TikTokLive.newClient("streamer_username")
.configure(settings -> {
settings.setClientLanguage("en"); // ISO language code sent to TikTok
settings.setTimeout(Duration.ofSeconds(5)); // HTTP connection timeout
settings.setLogLevel(Level.ALL); // java.util.logging level
settings.setPrintToConsole(true); // echo all log messages to stdout
settings.setRetryOnConnectionFailure(true); // auto-reconnect if host goes offline
settings.setRetryConnectionTimeout(Duration.ofSeconds(3)); // delay between retries
settings.setFetchGifts(true); // pre-fetch gift catalogue at connect
settings.setPingInterval(5000); // WebSocket heartbeat ms (min 250)
// Provide a TikTok session cookie to receive all chat messages
settings.setSessionId("86c3c8bf4b17ebb2d74bb7fa66fd0000");
settings.setTtTargetIdc("useast5"); // paired with sessionId
// Override room ID if username lookup fails
settings.setRoomId("7388123456789012345");
// Eulerstream alternative WebSocket (requires API key)
settings.setUseEulerstreamWebsocket(false);
})
.onConnected((liveClient, event) ->
System.out.println("Connected: " + liveClient.getRoomInfo().getHostName()))
.onError((liveClient, event) ->
event.getException().printStackTrace())
.buildAndConnect();
```
```
--------------------------------
### Handle Connection with onConnected
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/tools-readme/src/main/resources/output.md
Set up a listener that triggers when the connection to the TikTok live stream is successfully established.
```java
TikTokLive.newClient("host-name")
.onConnected((liveClient, event) ->
{
})
.buildAndConnect();
```
--------------------------------
### Add extension-recorder to pom.xml
Source: https://context7.com/jwdeveloper/tiktoklivejava/llms.txt
Add the extension-recorder module to your project's pom.xml to enable FFmpeg integration for saving live video streams to a local file.
```xml
com.github.jwdeveloper.TikTok-Live-Java
extension-recorder
1.11.0-Release
```
--------------------------------
### Configure TikTok Live Java Client Settings
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/README.md
Customizes the client's behavior, including hostname, language, timeouts, log level, retry mechanisms, and optional session ID or room ID overrides. Use this to fine-tune connection and logging.
```java
TikTokLive.newClient("bangbetmenygy")
.configure((settings) ->
{
settings.setHostName("bangbetmenygy"); // This method is useful in case you want change hostname later
settings.setClientLanguage("en"); // Language
settings.setTimeout(Duration.ofSeconds(2)); // Connection timeout
settings.setLogLevel(Level.ALL); // Log level
settings.setPrintToConsole(true); // Printing all logs to console even if log level is Level.OFF
settings.setRetryOnConnectionFailure(true); // Reconnecting if TikTok user is offline
settings.setRetryConnectionTimeout(Duration.ofSeconds(1)); // Timeout before next reconnection
//Optional: Sometimes not every message from chat are send to TikTokLiveJava to fix this issue you can set sessionId
// documentation how to obtain sessionId https://github.com/isaackogan/TikTok-Live-Connector#send-chat-messages
settings.setSessionId("86c3c8bf4b17ebb2d74bb7fa66fd0000");
//Optional:
//RoomId can be used as an override if you're having issues with HostId.
//You can find it in the HTML for the livestream-page
settings.setRoomId("XXXXXXXXXXXXXXXXX");
})
.buildAndConnect();
```
--------------------------------
### Handle Follows with onFollow
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/tools-readme/src/main/resources/output.md
Listen for new followers. This event is categorized under social interactions.
```java
TikTokLive.newClient("host-name")
.onFollow((liveClient, event) ->
{
})
.buildAndConnect();
```
--------------------------------
### Record Live Streams with extension-recorder
Source: https://context7.com/jwdeveloper/tiktoklivejava/llms.txt
Integrates FFmpeg to save the live video stream to a local file. Add it as a listener via TikTokLiveRecorder.use(...).
```java
import io.github.jwdeveloper.tiktok.extension.recorder.TikTokLiveRecorder;
import io.github.jwdeveloper.tiktok.extension.recorder.impl.event.TikTokLiveRecorderStartedEvent;
import java.io.File;
TikTokLive.newClient("streamer_username")
.configure(s -> s.setPrintToConsole(true))
.addListener(TikTokLiveRecorder.use((recorderSettings, liveClient) -> {
recorderSettings.setFfmpegPath("/usr/bin/ffmpeg"); // path to FFmpeg binary
recorderSettings.setOutputFile(new File("/tmp", "live.flv")); // output file
}))
.onEvent(TikTokLiveRecorderStartedEvent.class, (liveClient, event) ->
System.out.println("Recording URL: " + event.getDownloadData().getFullUrl()))
.onError((liveClient, event) -> event.getException().printStackTrace())
.buildAndConnect();
```
--------------------------------
### Configure HTTP Proxy Support
Source: https://context7.com/jwdeveloper/tiktoklivejava/llms.txt
Route HTTP requests through a SOCKS or HTTP proxy list. A callback is fired when the active proxy changes. Requires `java.net.Proxy` import.
```java
import java.net.Proxy;
TikTokLive.newClient("streamer_username")
.configure(settings -> {
settings.setPrintToConsole(true);
settings.getHttpSettings().configureProxy(proxy -> {
proxy.setType(Proxy.Type.SOCKS); // or Proxy.Type.HTTP
proxy.addProxy("proxy1.example.com", 1080);
proxy.addProxy("proxy2.example.com", 1080);
proxy.setOnProxyUpdated(proxyData ->
System.out.println("Active proxy: " + proxyData));
});
})
.onConnected((liveClient, event) ->
liveClient.getLogger().info("Connected via proxy"))
.onComment((liveClient, event) ->
liveClient.getLogger().info(event.getUser().getName() + ": " + event.getText()))
.onError((liveClient, event) -> event.getException().printStackTrace())
.buildAndConnect();
```
--------------------------------
### Configure TikTok Live Client Settings
Source: https://context7.com/jwdeveloper/tiktoklivejava/llms.txt
Customize connection behavior, authentication, logging, and retry logic before building the client. Provide a session cookie for all chat messages and optionally override the room ID.
```java
import java.time.Duration;
import java.util.logging.Level;
TikTokLive.newClient("streamer_username")
.configure(settings -> {
settings.setClientLanguage("en"); // ISO language code sent to TikTok
settings.setTimeout(Duration.ofSeconds(5)); // HTTP connection timeout
settings.setLogLevel(Level.ALL); // java.util.logging level
settings.setPrintToConsole(true); // echo all log messages to stdout
settings.setRetryOnConnectionFailure(true); // auto-reconnect if host goes offline
settings.setRetryConnectionTimeout(Duration.ofSeconds(3)); // delay between retries
settings.setFetchGifts(true); // pre-fetch gift catalogue at connect
settings.setPingInterval(5000); // WebSocket heartbeat ms (min 250)
// Provide a TikTok session cookie to receive all chat messages
settings.setSessionId("86c3c8bf4b17ebb2d74bb7fa66fd0000");
settings.setTtTargetIdc("useast5"); // paired with sessionId
// Override room ID if username lookup fails
settings.setRoomId("7388123456789012345");
// Eulerstream alternative WebSocket (requires API key)
settings.setUseEulerstreamWebsocket(false);
})
.onConnected((liveClient, event) ->
System.out.println("Connected: " + liveClient.getRoomInfo().getHostName()))
.onError((liveClient, event) ->
event.getException().printStackTrace())
.buildAndConnect();
```
--------------------------------
### Handle Viewer Questions with onQuestion
Source: https://context7.com/jwdeveloper/tiktoklivejava/llms.txt
Use the `onQuestion` event to capture and process questions submitted by viewers through the Q&A feature. This handler is triggered for each new question posted during the live stream.
```java
TikTokLive.newClient("streamer_username")
.onQuestion((liveClient, event) -> {
String asker = event.getUser().getName();
String question = event.getText();
System.out.println("Question from " + asker + ": " + question);
// Expected output:
// Question from viewer123: What is your setup?
})
.onError((liveClient, event) -> event.getException().printStackTrace())
.buildAndConnect();
```
--------------------------------
### Add extension-collector to pom.xml
Source: https://context7.com/jwdeveloper/tiktoklivejava/llms.txt
Add the extension-collector module to your project's pom.xml to record live-stream events to a file or database.
```xml
com.github.jwdeveloper.TikTok-Live-Java
extension-collector
1.11.0-Release
```
--------------------------------
### Handling Messages Without Proto Classes
Source: https://github.com/jwdeveloper/tiktoklivejava/wiki/Creating-custom-Events-and-message-mapping
This snippet shows how to handle incoming messages for which a corresponding proto class might not be available. It uses `mapper.forMessage()` with the message name string and `onBeforeMapping` to inspect the message. If a proto class exists, it's converted to an object; otherwise, the raw bytes are converted into a proto buffer structure for inspection. This is useful for analyzing unknown or newly introduced message types.
```java
mapper.forMessage("WebcastMemberMessage")
.onBeforeMapping((inputBytes, messageName, mapperHelper) ->
{
if (mapperHelper.isMessageHasProtoClass(messageName)) {
var messageObject = mapperHelper.bytesToWebcastObject(inputBytes, messageName);
// System.out.println(mapperHelper.toJson(messageObject));
} else {
var structure = mapperHelper.bytesToProtoBufferStructure(inputBytes);
// System.out.println(structure.toJson());
}
return inputBytes;
});
```
--------------------------------
### Handle Subscriptions with onSubscribe
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/tools-readme/src/main/resources/output.md
Triggered when a user initiates a subscription. This event is part of social interactions.
```java
TikTokLive.newClient("host-name")
.onSubscribe((liveClient, event) ->
{
})
.buildAndConnect();
```
--------------------------------
### Handle Room Info Updates with onRoomInfo
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/tools-readme/src/main/resources/output.md
Receive updates on live room information, such as viewer counts and likes. Useful for displaying stream statistics.
```java
TikTokLive.newClient("host-name")
.onRoomInfo((liveClient, event) ->
{
})
.buildAndConnect();
```
--------------------------------
### Maven Dependencies for TikTok Live Java
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/extension-recorder/README.md
Add these dependencies to your pom.xml to include the TikTok Live Java client and the extension recorder.
```xml
jitpack.io
https://jitpack.io
com.github.jwdeveloper.TikTok-Live-Java
Client
1.1.0-Release
compile
com.github.jwdeveloper.TikTok-Live-Java
extension-recorder
1.1.0-Release
```
--------------------------------
### extension-recorder
Source: https://context7.com/jwdeveloper/tiktoklivejava/llms.txt
The optional extension-recorder module integrates FFmpeg to save the live video stream to a local file. Add it as a listener via TikTokLiveRecorder.use(...).
```APIDOC
## extension-recorder — Record Live Streams to File
The optional `extension-recorder` module integrates FFmpeg to save the live video stream to a local file. Add it as a listener via `TikTokLiveRecorder.use(...)`.
```xml
com.github.jwdeveloper.TikTok-Live-Java
extension-recorder
1.11.0-Release
```
```java
import io.github.jwdeveloper.tiktok.extension.recorder.TikTokLiveRecorder;
import io.github.jwdeveloper.tiktok.extension.recorder.impl.event.TikTokLiveRecorderStartedEvent;
import java.io.File;
TikTokLive.newClient("streamer_username")
.configure(s -> s.setPrintToConsole(true))
.addListener(TikTokLiveRecorder.use((recorderSettings, liveClient) -> {
recorderSettings.setFfmpegPath("/usr/bin/ffmpeg"); // path to FFmpeg binary
recorderSettings.setOutputFile(new File("/tmp", "live.flv")); // output file
}))
.onEvent(TikTokLiveRecorderStartedEvent.class, (liveClient, event) ->
System.out.println("Recording URL: " + event.getDownloadData().getFullUrl()))
.onError((liveClient, event) -> event.getException().printStackTrace())
.buildAndConnect();
```
```
--------------------------------
### Initialize and Use TikTokLiveCollector
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/extension-collector/README.md
This Java code demonstrates how to initialize the TikTokLiveCollector with MongoDB connection settings, connect to the database, and set up listeners for multiple TikTok users. It filters out 'message' data types before processing.
```java
public static void main(String[] args) throws IOException {
var collector = TikTokLiveCollector.use(settings ->
{
settings.setConnectionUrl("mongodb+srv://" + mongoUser + ":" + mongoPassword + "@" + mongoDatabase + "/?retryWrites=true&w=majority");
settings.setDatabaseName("tiktok");
});
collector.connectDatabase();
var users = List.of("tehila_723", "dino123597", "domaxyzx", "dash4214", "obserwacje_live");
var sessionTag = "Tag1";
for (var user : users) {
TikTokLive.newClient(user)
.configure(liveClientSettings ->
{
liveClientSettings.setPrintToConsole(true);
})
.onError((liveClient, event) ->
{
event.getException().printStackTrace();
})
.addListener(collector.newListener(Map.of("sessionTag", sessionTag), document ->
{
if (document.get("dataType") == "message") {
return false;
}
return true;
}))
.buildAndConnectAsync();
}
System.in.read();
collector.disconnectDatabase();
}
```
--------------------------------
### Configure TikTok Live Client Settings
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/tools-readme/src/main/resources/output.md
Customize the behavior of the TikTok live client by setting various configuration options. This includes network settings, logging levels, and retry mechanisms for connection failures.
```java
TikTokLive.newClient("bangbetmenygy")
.configure((settings) ->
{
settings.setHostName("bangbetmenygy"); // This method is useful in case you want change hostname later
settings.setClientLanguage("en"); // Language
settings.setLogLevel(Level.ALL); // Log level
settings.setPrintToConsole(true); // Printing all logs to console even if log level is Level.OFF
settings.setRetryOnConnectionFailure(true); // Reconnecting if TikTok user is offline
settings.setRetryConnectionTimeout(Duration.ofSeconds(1)); // Timeout before next reconnection
//Optional: Sometimes not every message from chat are send to TikTokLiveJava to fix this issue you can set sessionId
// documentation how to obtain sessionId https://github.com/isaackogan/TikTok-Live-Connector#send-chat-messages
settings.setSessionId("86c3c8bf4b17ebb2d74bb7fa66fd0000");
//Optional:
//RoomId can be used as an override if you're having issues with HostId.
//You can find it in the HTML for the livestream-page
settings.setRoomId("XXXXXXXXXXXXXXXXX");
})
.buildAndConnect();
```
--------------------------------
### Add Dependencies to Maven Project
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/extension-collector/README.md
Include these repositories and dependencies in your Maven project's pom.xml to use the TikTok Live Java client and extension collector.
```xml
jitpack.io
https://jitpack.io
com.github.jwdeveloper.TikTok-Live-Java
Client
1.1.0-Release
compile
com.github.jwdeveloper.TikTok-Live-Java
extension-collector
1.1.0-Release
```
--------------------------------
### Protoc Jar Maven Plugin Configuration
Source: https://github.com/jwdeveloper/tiktoklivejava/wiki/About-protocol-buffer,-and-updating-its-structure
Configures the protoc-jar-maven-plugin in the API module's pom.xml to generate Java classes from .proto files. Ensure the 'generate-sources' phase is used.
```xml
com.github.os72
protoc-jar-maven-plugin
3.11.4
generate-sources
run
direct
src/main/proto
```
--------------------------------
### onJoin
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/tools-readme/src/main/resources/output.md
Triggered when a user joins the stream.
```APIDOC
## onJoin [TikTokJoinEvent]
### Description
Triggered when a user joins the stream.
### Code Example
```java
TikTokLive.newClient("host-name")
.onJoin((liveClient, event) ->
{
})
.buildAndConnect();
```
```
--------------------------------
### Handle TikTok Live Gift and Gift Combo Events
Source: https://context7.com/jwdeveloper/tiktoklivejava/llms.txt
Listen for `onGift` for non-combo gifts or finished combos, and `onGiftCombo` for individual combo ticks. `onGiftCombo` exposes the current combo state (Begin, Active, or Finished).
```java
import io.github.jwdeveloper.tiktok.data.models.gifts.GiftComboStateType;
TikTokLive.newClient("streamer_username")
.onGift((liveClient, event) -> {
// Fires for non-combo gifts, or when a combo has finished
String sender = event.getUser().getProfileName();
String name = event.getGift().getName();
int diamonds = event.getGift().getDiamondCost();
int quantity = event.getCombo();
String reaction = switch (event.getGift().getName()) {
case "ROSE" -> "Thank you for the rose!";
case "GG" -> "GOOD GAME!";
case "TIKTOK" -> "Thanks for the TikTok!";
default -> "Thanks for " + name + " x" + quantity + " (" + diamonds + " diamonds)";
};
System.out.println(sender + " → " + reaction);
})
.onGiftCombo((liveClient, event) -> {
// Fires on EVERY combo tick (Begin, Active, Finished)
GiftComboStateType state = event.getComboState();
int combo = event.getCombo();
String gift = event.getGift().getName();
if (state == GiftComboStateType.Begin) System.out.println("Combo started: " + gift);
if (state == GiftComboStateType.Active) System.out.println("Combo x" + combo + ": " + gift);
if (state == GiftComboStateType.Finished) System.out.println("Combo finished x" + combo + ": " + gift);
// Expected output progression:
// Combo started: Rose
// Combo x4: Rose
// Combo x8: Rose
// Combo finished x12: Rose
})
.onError((liveClient, event) -> event.getException().printStackTrace())
.buildAndConnect();
```
--------------------------------
### Connect with Custom Listeners for Event Handling
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/README.md
Demonstrates how to use custom listeners to handle TikTok events. Listeners are suitable for more complex event logic and require specific annotations and method signatures.
```java
/**
*
* Listeners are an alternative way of handling events.
* I would to suggest to use then when logic of handing event
* is more complex
*
*/
public static void main(String[] args) throws IOException {
showLogo();
CustomListener customListener = new CustomListener();
TikTokLive.newClient(SimpleExample.TIKTOK_HOSTNAME)
.addListener(customListener)
.buildAndConnect();
System.in.read();
}
/**
*
* Method in TikTokEventListener should meet 4 requirements to be detected
* - must have @TikTokEventHandler annotation
* - must have 2 parameters
* - first parameter must be LiveClient
* - second must be class that extending TikTokEvent
*/
public static class CustomListener {
@TikTokEventObserver
public void onLike(LiveClient liveClient, TikTokLikeEvent event) {
System.out.println(event.toString());
}
@TikTokEventObserver
public void onError(LiveClient liveClient, TikTokErrorEvent event) {
// event.getException().printStackTrace();
}
@TikTokEventObserver
public void onComment(LiveClient liveClient, TikTokCommentEvent event) {
var userName = event.getUser().getName();
var text = event.getText();
liveClient.getLogger().info(userName + ": " + text);
}
@TikTokEventObserver
public void onGift(LiveClient liveClient, TikTokGiftEvent event) {
var message = switch (event.getGift()) {
case ROSE -> "Thanks :)";
case APPETIZERS -> ":OO";
case APRIL -> ":D";
case TIKTOK -> ":P";
case CAP -> ":F";
default -> ":I";
};
liveClient.getLogger().info(message);
}
@TikTokEventHandler
public void onAnyEvent(LiveClient liveClient, TikTokEvent event) {
liveClient.getLogger().info(event.getClass().getSimpleName());
}
}
```
--------------------------------
### onQuestion
Source: https://context7.com/jwdeveloper/tiktoklivejava/llms.txt
Handles questions submitted by viewers through the Q&A feature during a live stream.
```APIDOC
## onQuestion — Q&A Feature
Triggered when a viewer submits a question through TikTok's built-in Q&A feature during a live stream.
```java
TikTokLive.newClient("streamer_username")
.onQuestion((liveClient, event) -> {
String asker = event.getUser().getName();
String question = event.getText();
System.out.println("Question from " + asker + ": " + question);
// Expected output:
// Question from viewer123: What is your setup?
})
.onError((liveClient, event) -> event.getException().printStackTrace())
.buildAndConnect();
```
```
--------------------------------
### Add TikTok Live Java Dependency via Maven
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/tools-readme/src/main/resources/output.md
Include these configurations in your pom.xml to add the TikTok Live Java client library as a dependency.
```xml
jitpack.io
https://jitpack.io
com.github.jwdeveloper.TikTok-Live-Java
Client
NOT_FOUND
compile
```
--------------------------------
### onRoomInfo
Source: https://context7.com/jwdeveloper/tiktoklivejava/llms.txt
Triggered when TikTok pushes updated live-room metadata including viewer count, like count, and host information.
```APIDOC
## onRoomInfo — Room Statistics
Triggered when TikTok pushes updated live-room metadata including viewer count, like count, and host information.
```java
TikTokLive.newClient("streamer_username")
.onRoomInfo((liveClient, event) -> {
var info = event.getRoomInfo();
System.out.println("Room ID: " + info.getRoomId());
System.out.println("Host: " + info.getHostName());
System.out.println("Title: " + info.getTitle());
System.out.println("Viewers: " + info.getViewersCount());
System.out.println("Total viewers: " + info.getTotalViewersCount());
System.out.println("Likes: " + info.getLikesCount());
System.out.println("Age restricted: " + info.isAgeRestricted());
// Expected output:
// Room ID: 7388123456789012345
// Host: streamer_username
// Viewers: 4210
// Likes: 81500
})
.buildAndConnect();
```
```
--------------------------------
### onGift / onGiftCombo
Source: https://context7.com/jwdeveloper/tiktoklivejava/llms.txt
`onGift` fires when a non-combo gift is sent or a gift combo finishes. `onGiftCombo` fires on every individual combo tick and exposes the current combo state (`Begin`, `Active`, or `Finished`).
```APIDOC
## onGift / onGiftCombo — Gift Events
`onGift` fires when a non-combo gift is sent or a gift combo finishes. `onGiftCombo` fires on every individual combo tick and exposes the current combo state (`Begin`, `Active`, or `Finished`).
```java
import io.github.jwdeveloper.tiktok.data.models.gifts.GiftComboStateType;
TikTokLive.newClient("streamer_username")
.onGift((liveClient, event) -> {
// Fires for non-combo gifts, or when a combo has finished
String sender = event.getUser().getProfileName();
String name = event.getGift().getName();
int diamonds = event.getGift().getDiamondCost();
int quantity = event.getCombo();
String reaction = switch (event.getGift().getName()) {
case "ROSE" -> "Thank you for the rose!";
case "GG" -> "GOOD GAME!";
case "TIKTOK" -> "Thanks for the TikTok!";
default -> "Thanks for " + name + " x" + quantity + " (" + diamonds + " diamonds)";
};
System.out.println(sender + " → " + reaction);
})
.onGiftCombo((liveClient, event) -> {
// Fires on EVERY combo tick (Begin, Active, Finished)
GiftComboStateType state = event.getComboState();
int combo = event.getCombo();
String gift = event.getGift().getName();
if (state == GiftComboStateType.Begin) System.out.println("Combo started: " + gift);
if (state == GiftComboStateType.Active) System.out.println("Combo x" + combo + ": " + gift);
if (state == GiftComboStateType.Finished) System.out.println("Combo finished x" + combo + ": " + gift);
// Expected output progression:
// Combo started: Rose
// Combo x4: Rose
// Combo x8: Rose
// Combo finished x12: Rose
})
.onError((liveClient, event) -> event.getException().printStackTrace())
.buildAndConnect();
```
```
--------------------------------
### onSubscribe
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/tools-readme/src/main/resources/output.md
Triggers when a user creates a subscription to the live stream.
```APIDOC
## onSubscribe
### Description
Triggers when a user creates a subscription.
### Method
`onSubscribe`
### Parameters
- `liveClient`: The TikTokLive client instance.
- `event`: A `TikTokSubscribeEvent` object related to the subscription.
```
--------------------------------
### Collect Live Data with extension-collector
Source: https://context7.com/jwdeveloper/tiktoklivejava/llms.txt
Records all live-stream events from one or many concurrent streams to a file or database, with optional custom metadata tags per session.
```java
import io.github.jwdeveloper.tiktok.extension.collector.TikTokLiveCollector;
import java.io.File;
import java.util.List;
import java.util.Map;
// Create and start a shared collector backed by a local file
var collector = TikTokLiveCollector.useFile(settings ->
settings.setParentFile(new File("/tmp/tiktok-data")));
collector.connect();
// Monitor several streamers simultaneously
var streamers = List.of("streamer1", "streamer2", "streamer3");
Map sessionMeta = Map.of("sessionTag", "batch-2024");
for (var user : streamers) {
TikTokLive.newClient(user)
.configure(s -> s.setPrintToConsole(false))
.addListener(collector.newListener(sessionMeta)) // attach shared collector
.onError((liveClient, event) -> event.getException().printStackTrace())
.buildAndConnectAsync();
}
// Keep alive until terminated
System.in.read();
collector.disconnect();
```
--------------------------------
### onHttpResponse
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/tools-readme/src/main/resources/output.md
Handles HTTP responses.
```APIDOC
## onHttpResponse [TikTokHttpResponseEvent]
### Description
Handles HTTP responses.
### Code Example
```java
TikTokLive.newClient("host-name")
.onHttpResponse((liveClient, event) ->
{
})
.buildAndConnect();
```
```
--------------------------------
### Handle Chat Comments with onComment
Source: https://github.com/jwdeveloper/tiktoklivejava/blob/master/tools-readme/src/main/resources/output.md
Listen for incoming chat messages in real-time. This is fundamental for interactive live stream applications.
```java
TikTokLive.newClient("host-name")
.onComment((liveClient, event) ->
{
})
.buildAndConnect();
```
--------------------------------
### onPreConnection
Source: https://context7.com/jwdeveloper/tiktoklivejava/llms.txt
A hook that fires after room metadata is fetched but before the WebSocket connection is opened. Allows for conditional cancellation of the connection.
```APIDOC
## onPreConnection — Pre-Connection Hook and Cancellation
`onPreConnection` fires after room metadata is fetched but before the WebSocket is opened. The event can be cancelled to abort the connection without throwing an exception.
```java
TikTokLive.newClient("streamer_username")
.onPreConnection((liveClient, event) -> {
var userData = event.getUserData();
var liveData = event.getLiveData();
System.out.println("About to connect, room: " + liveData.getTitle());
// Conditionally abort connection
if (liveData.isAgeRestricted()) {
event.setCancelConnection(true);
System.out.println("Cancelled: age-restricted stream.");
}
})
.onConnected((liveClient, event) -> System.out.println("Connected!"))
.onError((liveClient, event) -> event.getException().printStackTrace())
.buildAndConnect();
```
```