Before connecting to a livestream, you may want to check if a user is currently live. TikTokLive provides an efficient method for this.
Using is_live() Method
Using is_live() is more efficient than attempting to connect, as it doesn’t establish a WebSocket connection.
The is_live() method is an asynchronous function that returns a boolean indicating whether the user is currently streaming.
Basic Usage
import asyncio
from TikTokLive import TikTokLiveClient
client: TikTokLiveClient = TikTokLiveClient(
unique_id="@username"
)
async def main():
is_live = await client.is_live()
if is_live:
print("User is live!")
else:
print("User is not live.")
if __name__ == "__main__":
asyncio.run(main())
Polling for Live Status
You can create a monitoring loop that checks if a user goes live:
Import required modules
import asyncio
from TikTokLive import TikTokLiveClient
from TikTokLive.client.logger import LogLevel
Create the client
client: TikTokLiveClient = TikTokLiveClient(
unique_id="@tv_asahi_news"
)
Implement polling loop
async def main():
# Run forever
while True:
is_live = await client.is_live()
if not is_live:
client.logger.info(
"Client is currently not live. "
"Checking again in 60 seconds."
)
await asyncio.sleep(60)
continue
# User is live
client.logger.info("Requested client is LIVE!")
# Connect to the livestream
await client.connect()
# Once the stream ends, loop back and keep polling
client.logger.info("Stream ended. Checking again in 60 seconds.")
await asyncio.sleep(60)
Complete Example
import asyncio
from TikTokLive import TikTokLiveClient
from TikTokLive.client.logger import LogLevel
# Replace with any username you want to monitor
client: TikTokLiveClient = TikTokLiveClient(
unique_id="@tv_asahi_news"
)
async def main():
# Run forever
while True:
is_live = await client.is_live()
if not is_live:
client.logger.info(
"Client is currently not live. "
"Checking again in 60 seconds."
)
await asyncio.sleep(60)
continue
# User is live – fetch avatar URL via profile HTML
avatar_url = await client.get_avatar_url()
client.logger.info("Requested client is LIVE!")
client.logger.info(f"Avatar URL: {avatar_url!r}")
# Optionally connect to the livestream
await client.connect()
# Once the stream ends, loop back and keep polling
client.logger.info("Stream ended. Checking again in 60 seconds.")
await asyncio.sleep(60)
if __name__ == "__main__":
client.logger.setLevel(LogLevel.INFO.value)
asyncio.run(main())
Best Practices
Set an appropriate polling interval (e.g., 60 seconds) to avoid making excessive requests to TikTok’s servers.
Don’t use connect() to check if a user is live. Always use is_live() instead for efficiency.
Additional Features
When a user is live, you can also fetch their avatar URL:
if await client.is_live():
avatar_url = await client.get_avatar_url()
print(f"Avatar URL: {avatar_url}")