Giter Club home page Giter Club logo

tiktoklive's Introduction

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.

Enterprise Access

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 - Current viewer count information
  • 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.repeat_count}x \"{event.gift.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.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.repeat_count}x \"{event.gift.name}\"")

    # Non-streakable gift
    elif not event.gift.streakable:
        print(f"{event.user.unique_id} sent \"{event.gift.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(...).

Checking If A User Is Live

It is considered inefficient to use the connect method to check if a user is live. It is better to use the dedicated await client.is_live() method.

There is a complete example of how to do this in the examples folder.

Contributors

  • Isaac Kogan - Creator, Primary Maintainer, and Reverse-Engineering - isaackogan
  • Zerody - Initial Reverse-Engineering Protobuf & Support - Zerody
  • Davincible - Reverse-Engineering Stream Downloads - davincible

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.

tiktoklive's People

Contributors

bryangoble avatar isaackogan avatar linkly-ai avatar setiaone-tech avatar tmokmss avatar wingceltis-c avatar xtwist avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tiktoklive's Issues

Some sort of error popping up all the time

Hello I am getting this type of error sometimes.

`Error while fetching room data
ERROR:root:Traceback (most recent call last):
File "C:\Users\Gatis_2\AppData\Local\Programs\Python\Python310\lib\site-packages\TikTokLive\client\base.py", line 152, in __fetch_room_polling
await self.__fetch_room_data()
File "C:\Users\Gatis_2\AppData\Local\Programs\Python\Python310\lib\site-packages\TikTokLive\client\base.py", line 174, in __fetch_room_data
await self._handle_webcast_messages(webcast_response)
File "C:\Users\Gatis_2\AppData\Local\Programs\Python\Python310\lib\site-packages\TikTokLive\client\client.py", line 67, in _handle_webcast_messages
response: Optional[AbstractEvent] = self.__parse_message(webcast_message=message)
File "C:\Users\Gatis_2\AppData\Local\Programs\Python\Python310\lib\site-packages\TikTokLive\client\client.py", line 117, in _parse_message
webcast_message["gift"] = json.loads(gift)
File "C:\Users\Gatis_2\AppData\Local\Programs\Python\Python310\lib\json_init
.py", line 339, in loads
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not NoneType

Error while fetching room data`

I am also getting this at start
PS C:\Users\Gatis_2\Desktop\Tiktoklive> & C:/Users/Gatis_2/AppData/Local/Programs/Python/Python310/python.exe c:/Users/Gatis_2/Desktop/Tiktoklive/AccTiktok.py c:\Users\Gatis_2\Desktop\Tiktoklive\AccTiktok.py:36: RuntimeWarning: coroutine 'BaseClient.retrieve_available_gifts' was never awaited client.retrieve_available_gifts() RuntimeWarning: Enable tracemalloc to get the object allocation traceback

I am using Stable version of python Python 3.10.4

I think sometimes it makes some gifts skip.

webcast_message.get("giftJson") sends beck None

Live downloads

Is there a way to download the live itself or to access/download live replays?

To Do: v0.8.2

  • Hide that ClientSession warning about not being closed when error/program exits (honestly, I'm probably misusing the ClientSession- let's look into that)
  • Add a separate table for TikTokLive Printing. Should range from $30 base to $60 max & include a ton of customization options.
  • Implement new Gift proto structure
  • Add aliases to maintain backwards compatibility with old Gift structure
  • Release a PyPi package fork of python-escpos under "python-escpos-win" with modified Windows support
  • Fix Invalid JSON for Gifts

Cancelled "Transpose method from GoTikTokLive for fetching current prices of coins" because I can't find out how to get a valid response after checking out https://github.com/Davincible/gotiktoklive/blob/master/tiktok.go. Assistance appreciated for the next version! Don't have time to do more debugging, need this new version out with the breaking gift change.

Also couldn't find the whole discovering new streams thing. @Davincible any help appreciated!

{
	"data": [],
	"extra": {
		"apple_pay_hint_url": "",
		"badge_icon": "",
		"channel": "",
		"channel_id": 0,
		"currency_list": [],
		"customized_ids": [],
		"default_currency": "",
		"default_packet_id": 0,
		"deprecated1": "",
		"deprecated2": [],
		"deprecated3": false,
		"extra_diamond_list": [],
		"first_charge_packet_id": 0,
		"is_default": false,
		"is_recommend": false,
		"large_pay_url": "",
		"max_customized_diamond_cnt": 2500000,
		"merchant_id": "",
		"min_customized_diamond_cnt": 30,
		"need_auth": 0,
		"now": 1649801498036,
		"ploy_trace_id": 0,
		"recently_purchased_packet_id": 0,
		"recommended_packet_id": 0,
		"should_display_customized_web_recharge": false,
		"show_hint": 0,
		"sign_infos": [],
		"total_signed": 0
	},
	"status_code": 0
}

Version 4.2.5

Changelog

  • Move AsyncIOEventEmitter inheritence from TikTokLiveClient to BaseClient
  • Add the ability to connect to livestreams via websocket
  • Use Websockets by default
  • Only allow long polling if a sessionid is provided
  • Refactor project (e.g. _client_params moved to _http)
  • Change polling_interval_ms to ping_interval_ms
  • Remove ProxyContainer in favour of regular proxying
  • Add websocket_enabled BaseClient parameter
  • Remove fetch_room_info_on_connect BaseClient parameter
  • Removed ProxyContainer related methods
  • Added set_proxies and get_proxies methods
  • Add missing documentation
  • Add deserialize_websocket_message to allow users to deserialize messages from Websocket polling
  • Update documentation
  • Refactor BaseClient for readability purposes

If you were using the ProxyContainer API, you must switch to the new proxy handling system. There are no other breaking changes.

FailedConnection: Failed to fetch room id from WebCast

Traceback (most recent call last):
File "/home/tailer12/.local/lib/python3.9/site-packages/aiohttp/connector.py", line 986, in _wrap_create_connection
return await self._loop.create_connection(*args, **kwargs) # type: ignore[return-value] # noqa
File "/usr/local/lib/python3.9/asyncio/base_events.py", line 1056, in create_connection
raise exceptions[0]
File "/usr/local/lib/python3.9/asyncio/base_events.py", line 1041, in create_connection
sock = await self._connect_sock(
File "/usr/local/lib/python3.9/asyncio/base_events.py", line 955, in _connect_sock
await self.sock_connect(sock, address)
File "/usr/local/lib/python3.9/asyncio/selector_events.py", line 502, in sock_connect
return await fut
File "/usr/local/lib/python3.9/asyncio/selector_events.py", line 537, in _sock_connect_cb
raise OSError(err, f'Connect call failed {address}')
ConnectionRefusedError: [Errno 111] Connect call failed ('23.199.71.187', 443)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/tailer12/.local/lib/python3.9/site-packages/TikTokLive/client/base.py", line 110, in __fetch_room_id
html: str = await self._http.get_livestream_page_html(self.__unique_id)
File "/home/tailer12/.local/lib/python3.9/site-packages/TikTokLive/client/http.py", line 115, in get_livestream_page_html
response: bytes = await self.__aiohttp_get_bytes(f"{TikTokHTTPClient.TIKTOK_URL_WEB}@{unique_id}/live")
File "/home/tailer12/.local/lib/python3.9/site-packages/TikTokLive/client/http.py", line 67, in __aiohttp_get_bytes
async with session.get(request_url, headers=self.headers, timeout=self.timeout, proxy=self.proxy_container.get()) as request:
File "/home/tailer12/.local/lib/python3.9/site-packages/aiohttp/client.py", line 1138, in aenter
self._resp = await self._coro
File "/home/tailer12/.local/lib/python3.9/site-packages/aiohttp/client.py", line 535, in _request
conn = await self._connector.connect(
File "/home/tailer12/.local/lib/python3.9/site-packages/aiohttp/connector.py", line 542, in connect
proto = await self._create_connection(req, traces, timeout)
File "/home/tailer12/.local/lib/python3.9/site-packages/aiohttp/connector.py", line 907, in _create_connection
_, proto = await self._create_direct_connection(req, traces, timeout)
File "/home/tailer12/.local/lib/python3.9/site-packages/aiohttp/connector.py", line 1206, in _create_direct_connection
raise last_exc
File "/home/tailer12/.local/lib/python3.9/site-packages/aiohttp/connector.py", line 1175, in _create_direct_connection
transp, proto = await self._wrap_create_connection(
File "/home/tailer12/.local/lib/python3.9/site-packages/aiohttp/connector.py", line 992, in _wrap_create_connection
raise client_error(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host www.tiktok.com:443 ssl:default [Connect call failed ('23.199.71.187', 443)]

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/tailer12/.local/lib/python3.9/site-packages/TikTokLive/client/base.py", line 221, in _connect
await self.__fetch_room_id()
File "/home/tailer12/.local/lib/python3.9/site-packages/TikTokLive/client/base.py", line 115, in __fetch_room_id
await self._on_error(ex, FailedFetchRoomInfo("Failed to fetch room id from WebCast, see stacktrace for more info."))
File "/home/tailer12/.local/lib/python3.9/site-packages/TikTokLive/client/client.py", line 55, in _on_error
raise _exc
File "/home/tailer12/.local/lib/python3.9/site-packages/TikTokLive/client/client.py", line 49, in _on_error
raise append from original
TikTokLive.types.errors.FailedFetchRoomInfo: Failed to fetch room id from WebCast, see stacktrace for more info.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/tailer12/my/basic.py", line 52, in
client.run()
File "/home/tailer12/.local/lib/python3.9/site-packages/TikTokLive/client/base.py", line 305, in run
self.loop.run_until_complete(self._connect())
File "/usr/local/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
return future.result()
File "/home/tailer12/.local/lib/python3.9/site-packages/TikTokLive/client/client.py", line 87, in _connect
result: str = await super(TikTokLiveClient, self)._connect()
File "/home/tailer12/.local/lib/python3.9/site-packages/TikTokLive/client/base.py", line 257, in _connect
await self._on_error(ex, FailedConnection(message))
File "/home/tailer12/.local/lib/python3.9/site-packages/TikTokLive/client/client.py", line 55, in _on_error
raise _exc
File "/home/tailer12/.local/lib/python3.9/site-packages/TikTokLive/client/client.py", line 49, in _on_error
raise append from original
TikTokLive.types.errors.FailedConnection: Failed to fetch room id from WebCast, see stacktrace for more info.

Current Plans v0.7.0

  • Debug option "on_debug"
  • Add is_friend and is_following attributes on User object
  • Add is_moderator attribute on User object
  • Add extended gift info
  • Look into missing gift info
  • Fix chat repitition

Not able to connect

TikTokLive.types.errors.InitialCursorMissing: Missing cursor in initial fetch response.
Can't connect to the Tik-Tok

Version 4.3.0

There are no breaking changes at this time.

Upgrade with pip install TikTokLive --upgrade

Version 4.2.0

  • Implement subscriber badges (image badges) ⭐
  • Implement subscriber emotes ⭐
  • Implement envelope event (sending treasure boxes)
  • Repair is_moderator "User" attribute with new proto
  • Add is_new_gifter "User" attribute
  • Add is_subscriber "User" attribute
  • Add "through_share" attribute to JoinEvent
  • Add MoreShareEvent when a user shares to more than 5, 10 TikTok users
  • Update HTTP Parameters
  • Add "subscribe" event ⭐
  • Add weekly rankings events
  • Add support for TikTok Battles
  • Add the ability to download streams including the "download" and "stop_download" methods on the BaseClient class ⭐
  • Add the stream download example
  • Updated documentation & README.md

There are no breaking changes at this time.
⭐'s represent important/large changes

Downloading Streams

Using ffmpeg, you can now download streams with audio, video, etc.

You can download streams FOREVER in the background, or, for X seconds in the background and automatically stop. See the docs.

New Issue

File "C:\Users\NOEL GARCIA\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokLive\client\client.py", line 48, in _on_error raise append from original TikTokLive.types.errors.FailedConnection: Invalid type for url. Expected str or httpx.URL, got <class 'NoneType'>: None

Generate MSToken and Signature

Hi, Could you share me How to generate MSToken and signature ? At the moment, I saw that call to your api to get it. But we met the case cursor missing. So I want to test change some info for msToken to get it. Hope receive your response. Thank you

To Do: v0.8.0

  • Fix live count not working
  • Proper library documentation
  • Fix headers not being included in requests
  • Remove double-quoted headers
  • Enable trust-env, add proper proxy support
  • Remove sessions or implement cookie saving
  • Rebuild docs with updated pricelist

Version 4.2.6

  • Make failed html parsing error more user-friendly to read (8dfbad2)
  • Add serialize_message proto method to allow reserialization of decoded data
  • Add send_ack message on WebcastWebsocket object to send acknowledgements and fix an issue where lack of acknowledgements caused TikTok to close the websocket connection after ~3 minutes
  • Update Documentation

There are no breaking changes at this time.

Upgrade with pip install TikTokLive --upgrade

Websocket Disconnecting on windows with ver 4.2.6

data transfer failed
Traceback (most recent call last):
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\site-packages\websockets\legacy\protocol.py", line 945, in transfer_data
message = await self.read_message()
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\site-packages\websockets\legacy\protocol.py", line 1015, in read_message
frame = await self.read_data_frame(max_size=self.max_size)
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\site-packages\websockets\legacy\protocol.py", line 1090, in read_data_frame
frame = await self.read_frame(max_size)
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\site-packages\websockets\legacy\protocol.py", line 1145, in read_frame
frame = await Frame.read(
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\site-packages\websockets\legacy\framing.py", line 100, in read
data = await reader(length)
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\asyncio\streams.py", line 716, in readexactly
self._maybe_resume_transport()
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\asyncio\streams.py", line 446, in _maybe_resume_transport
self._transport.resume_reading()
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\asyncio\sslproto.py", line 343, in resume_reading
self._ssl_protocol._transport.resume_reading()
AttributeError: 'NoneType' object has no attribute 'resume_reading'
Task exception was never retrieved
future: <Task finished name='Task-9' coro=<WebcastWebsocket.connection_loop() done, defined at C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\site-packages\TikTokLive\client\websocket.py:88> exception=ConnectionClosedError(None, Close(code=1011, reason=''), None)>
Traceback (most recent call last):
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\site-packages\websockets\legacy\protocol.py", line 945, in transfer_data
message = await self.read_message()
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\site-packages\websockets\legacy\protocol.py", line 1015, in read_message
frame = await self.read_data_frame(max_size=self.max_size)
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\site-packages\websockets\legacy\protocol.py", line 1090, in read_data_frame
frame = await self.read_frame(max_size)
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\site-packages\websockets\legacy\protocol.py", line 1145, in read_frame
frame = await Frame.read(
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\site-packages\websockets\legacy\framing.py", line 100, in read
data = await reader(length)
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\asyncio\streams.py", line 716, in readexactly
self._maybe_resume_transport()
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\asyncio\streams.py", line 446, in _maybe_resume_transport
self._transport.resume_reading()
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\asyncio\sslproto.py", line 343, in resume_reading
self._ssl_protocol._transport.resume_reading()
AttributeError: 'NoneType' object has no attribute 'resume_reading'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\site-packages\TikTokLive\client\websocket.py", line 114, in connection_loop
self.__client.emit("error", ex)
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\site-packages\pyee\base.py", line 179, in emit
self._emit_handle_potential_error(event, args[0] if args else None)
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\site-packages\pyee\base.py", line 139, in _emit_handle_potential_error
raise error
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\site-packages\TikTokLive\client\websocket.py", line 104, in connection_loop
await self.send_ack(decoded["id"])
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\site-packages\TikTokLive\client\websocket.py", line 130, in send_ack
await self._connection.send(message)
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\site-packages\websockets\legacy\protocol.py", line 620, in send
await self.ensure_open()
File "C:\Users\GeneralKnow\AppData\Local\Programs\Python\Python310\lib\site-packages\websockets\legacy\protocol.py", line 930, in ensure_open
raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedError: sent 1011 (unexpected error); no close frame received

Desktop (please complete the following information):

  • OS: win10
  • Browser: windows powershell
  • Version 4.2.6

Version 0.8.9

  • Advanced error handling via the "error" event. If a custom handler is not added, runtime errors will be automatically logged in the console. If a handler is added, handling (and logging) is fully up to the user. If client.connected is False, handlers will NOT be used.
  • Update documentation

Trying to get Like Count....

I have found a variable called likeCount inside the like event... but it seems to not make sense the # it returns....

Is Like Count possible?

Thanks!

TikTokLive.types.errors.FailedConnection

Dear developer!

Code of programme:

from TikTokLive import TikTokLiveClient
from TikTokLive.types.events import ConnectEvent, CommentEvent

sessionid = "bf08457a76b7837a00eec1addc0d62fa"
sid_guard = "bf08457a76b7837a00eec1addc0d62fa%7C1658488742%7C5184000%7CTue%2C+20-Sep-2022+11%3A19%3A02+GMT"

client = TikTokLiveClient("@alon_2021", **{
    "headers": {
        "Cookie": f"sessionid={sessionid}; sid_guard={sid_guard};"
    }
})

@client.on("connect")
async def on_connect(_: ConnectEvent):
    print("Connected to Room ID:", client.room_id)


@client.on("comment")
async def on_comment(event: CommentEvent):
    print(f"{event.user.nickname} -> {event.comment}")


if __name__ == '__main__':
    client.run()

ERROR:

Traceback (most recent call last):
  File "C:\Users\danyl\OneDrive\Рабочий стол\tiktok.py", line 19, in <module>
    client.run()
  File "C:\Users\danyl\AppData\Local\Programs\Python\Python310\lib\site-packages\TikTokLive\client\base.py", line 314, in run
    self.loop.run_until_complete(self._connect())
  File "C:\Users\danyl\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 641, in run_until_complete
    return future.result()
  File "C:\Users\danyl\AppData\Local\Programs\Python\Python310\lib\site-packages\TikTokLive\client\client.py", line 88, in _connect
    result: str = await super(TikTokLiveClient, self)._connect()
  File "C:\Users\danyl\AppData\Local\Programs\Python\Python310\lib\site-packages\TikTokLive\client\base.py", line 266, in _connect
    await self._on_error(ex, FailedConnection(message))
  File "C:\Users\danyl\AppData\Local\Programs\Python\Python310\lib\site-packages\TikTokLive\client\client.py", line 56, in _on_error
    raise _exc
  File "C:\Users\danyl\AppData\Local\Programs\Python\Python310\lib\site-packages\TikTokLive\client\client.py", line 50, in _on_error
    raise append from original
TikTokLive.types.errors.FailedConnection

i have logged into account, and all cookies are valid. it is 100% info
Screenshot_1

the gift urls are not shown or are None

Hi Isaac,

i tried to display the gift image urls but it is showing None
then i tried to add a print in your base.py then it showed me them

`async def __fetch_available_gifts(self) -> Optional[Dict[int, ExtendedGift]]:
"""
Fetch available gifts from Webcast API
:return: Gift info dict

    """

    try:
        response = await self._http.get_json_object_from_webcast_api("gift/list/", self._client_params)
        # print(f"GIFT RESPONSE: {response}"  )
        print("##########################################################################################")
        if response and 'gifts' in response and response['gifts'] and len(response['gifts']) > 0: 
            for gift in response['gifts']:
                print(f"NAME: {gift['describe']} | DIAMONDS: {gift['diamond_count']} | URL LIST: {gift['image']['url_list']}")
                # print(f"NAME: {gift}")
        else:
            print("gift error")
        gifts: Optional[List] = response.get("gifts")

        if isinstance(gifts, list):
            for gift in gifts:
                try:
                    _gift: ExtendedGift = from_dict(ExtendedGift, gift)
                    self.__available_gifts[_gift.id] = _gift
                except:
                    logging.error(traceback.format_exc() + "\nFailed to parse gift's extra info")

        return self.__available_gifts
    except Exception as err:
        logging.error(traceback.format_exc() + "\nFailed to retrieve gifts from webcast api")
        print(f"ERROR: {err}")
        return None`

maybe you could fix it in the next ersion or i could also fix it if you want

i will attach a file with the output i wanted and got after i set my own prints

gift_urls

InitialCursorMissing occurs In Version 4.3.3

In v4.3.3, running basic.py in exsample or simple code such as the following now causes an error.

from TikTokLive import TikTokLiveClient
from TikTokLive.types.events import CommentEvent, ConnectEvent

# Cookies > sessionid
sessionid = ""

# Cookies > sid_guard
sid_guard = ""

client = TikTokLiveClient("@tv_asahi_news", **{
    "headers": {
        "Cookie": f"sessionid={sessionid}; sid_guard={sid_guard};"
    }
})

# Notice no decorator?
async def on_comment(event: CommentEvent):
    print(f"{event.user.nickname} -> {event.comment}")


if __name__ == '__main__':
    # Run the client and block the main thread
    # await client.start() to run non-blocking
    client.run(session_id=sessionid)
Traceback (most recent call last):
  File "C:\Users\you-r\scoop\apps\python\current\lib\site-packages\TikTokLive\client\base.py", line 380, in _connect
    await self.__fetch_room_data(True)
  File "C:\Users\you-r\scoop\apps\python\current\lib\site-packages\TikTokLive\client\base.py", line 221, in __fetch_room_data
    raise InitialCursorMissing("Missing cursor in initial fetch response.")
TikTokLive.types.errors.InitialCursorMissing: Missing cursor in initial fetch response.

When I bring it down to v4.2.0, the error no longer occurs but it is not responsive.
Two weeks ago it was working fine.
Is there something I am missing?

Issue with retrieving room_id

Describe the bug
When i launch the script it raise an raise Exception("User might be offline" if valid_response else "Your IP or country might be blocked by TikTok.") Exception: Your IP or country might be blocked by TikTok.
This error happens in this line of code self.__room_id = get_room_id_from_main_page_html(html) that can be found in TikTokLive/utils.py.
I'm in italy and tiktok is not blocked i can watch live streams with no problem from smartphone or laptop.

Additional context
Is raised because inside the html variable (html: str = await self._http.get_livestream_page_html(self.__unique_id)) there isn't a room_id and that happens cause when get_livestream_page_html(unique_id) is called tiktok redirect to a login page to be authenticated.
It's not a real bug instead a lack of control, i guess. Last thing if i hardcode the room_id then the script work flawless.

Desktop (please complete the following information):

  • OS: Windows 10

Traceback:

ERROR:root:Traceback (most recent call last):
  File "C:\Users\mari\Desktop\ycharmProjects\tiktok\tiktok\lib\site-packages\TikTokLive\client\base.py", line 91, in __fetch_room_id
    self.__room_id = get_room_id_from_main_page_html(html)
  File "C:\Users\mari\Desktop\ycharmProjects\tiktok\tiktok\lib\site-packages\TikTokLive\utils.py", line 20, in get_room_id_from_main_page_html
    raise Exception("User might be offline" if valid_response else "Your IP or country might be blocked by TikTok.")
Exception: Your IP or country might be blocked by TikTok.

Failed to retrieve room id from page source
Traceback (most recent call last):
  File "C:\Users\mari\Desktop\ycharmProjects\tiktok\tiktok\lib\site-packages\TikTokLive\client\base.py", line 210, in _connect
    raise LiveNotFound()
TikTokLive.types.errors.LiveNotFound

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\mari\Desktop\ycharmProjects\tiktok\live.py", line 23, in <module>
    client.run()
  File "C:\Users\mari\Desktop\ycharmProjects\tiktok\tiktok\lib\site-packages\TikTokLive\client\base.py", line 285, in run
    self.loop.run_until_complete(self._connect())
  File "C:\Users\mari\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "C:\Users\mari\Desktop\ycharmProjects\tiktok\tiktok\lib\site-packages\TikTokLive\client\client.py", line 39, in _connect
    result: str = await super(TikTokLiveClient, self)._connect()
  File "C:\Users\mari\Desktop\ycharmProjects\tiktok\tiktok\lib\site-packages\TikTokLive\client\base.py", line 239, in _connect
    raise FailedConnection(message)
TikTokLive.types.errors.FailedConnection```

Follow, unfollow, follow

Hello,
I have a problem, when someone follows, unfollows and then follows again they are treated like a new follower. Is there any way to prevent this?
Thank you.

error when running on a new thread

Hi I'm a newbie who just started exploring TikTok world and thank you for developing this great toolkit!
I found a weird behavior as below. Could you confirm it as expected or not? Thanks!

Describe the bug
When I execute TikTokLiveClient.run on a newly created thread, it crashes.

To Reproduce
Run the code below:

import threading
import time
import asyncio
from TikTokLive import TikTokLiveClient

def start_tiktok():
    # loop = asyncio.new_event_loop()
    # asyncio.set_event_loop(loop)
    client = TikTokLiveClient(unique_id='@isaackogz')
    client.run()

thread = threading.Thread(target=start_tiktok)
thread.daemon = True
thread.start()

time.sleep(10)

and we get this error:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/home/ec2-user/.local/lib/python3.7/site-packages/TikTokLive/client/base.py", line 73, in __init__
    self.loop: AbstractEventLoop = asyncio.get_event_loop()
  File "/usr/lib64/python3.7/asyncio/events.py", line 644, in get_event_loop
    % threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Thread-1'.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib64/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/usr/lib64/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "repro.py", line 9, in start_tiktok
    subscription = TikTokLiveClient(unique_id='@tv_asahi_news')
  File "/home/ec2-user/.local/lib/python3.7/site-packages/TikTokLive/client/client.py", line 31, in __init__
    BaseClient.__init__(self, unique_id, **options)
  File "/home/ec2-user/.local/lib/python3.7/site-packages/TikTokLive/client/base.py", line 75, in __init__
    self.loop: AbstractEventLoop = asyncio.get_running_loop()
RuntimeError: no running event loop

If I uncomment the two lines, it works without problem.

     loop = asyncio.new_event_loop()
     asyncio.set_event_loop(loop)

Shouldn't this be handled inside the library? I saw the following description in README.md

Optionally supply your own asyncio event loop for usage by the client. When set to None, the client pulls the current active loop or creates a new one. This option is mostly useful for people trying to nest asyncio.

Expected behavior
Code runs without problem.

Additional context
Add any other context about the problem here.

Error with the GiftEvent

Hi, the GiftEvent doesn't seem to work properly. Usually it works, but sometimes when they send gifts the same error always pops up, see the image:
https://prnt.sc/9EwlAhlqgLaY
How can this be fixed? Is this happening to other people?
I hope you can help me, thanks for your attention.

start and stop method not work

Please help

This is my code:

import tkinter as tk
from tkinter import *
from TikTokLive import TikTokLiveClient
from TikTokLive.types.events import *

class MainApp:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title('Tiktok')
        self.root.geometry("850x450")
        self.startBtn = Button(self.root, text="start", command=self.start)
        self.startBtn.grid(row=0, column=0)
        self.stopBtn = Button(self.root, text="stop", command=self.stop)
        self.stopBtn.grid(row=0, column=1)

        self.client: TikTokLiveClient = TikTokLiveClient(
            unique_id=f"@tannguyenchungkhoan", debug=True, **(
                {
                    "process_initial_data": True,
                    "fetch_room_info_on_connect": True,
                    "enable_extended_gift_info": True,
                    "polling_interval_ms": 1000,
                    "client_params": {},
                    "headers": {},
                    # "timeout_ms": 1000,
                    "loop": None
                }
            )
        )

        self.client.retrieve_available_gifts()

        @self.client.on("connect")
        async def on_connect(_: ConnectEvent):
            print('connect')

        @self.client.on("comment")
        async def on_comment(event: CommentEvent):
            print(f"{event.user.nickname} -> {event.comment}")

        @self.client.on("disconnect")
        async def on_disconnect(event: DisconnectEvent):
            print('Disconnected')

        self.root.mainloop()

    async def start(self):
        await self.client.start()

    def stop(self):
        self.client.stop()


if __name__ == "__main__":
    app = MainApp()

TikTokLive package ceased working on new connections 30 minutes ago

Dear team,

The exact same code as previously worked, failed to initiate a connection.

I upgraded TikTokLive to the latest version, and it still no longer connects.

Here is the log.

Any help or update will be useful.
Thanks.
S

ERROR:root:Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\TikTokLive\client\base.py", line 114, in __fetch_room_info
response = await self._http.get_json_object_from_webcast_api("room/info/", self._client_params)
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\TikTokLive\client\http.py", line 144, in get_json_object_from_webcast_api
response: dict = await self.__aiohttp_get_json(self.TIKTOK_URL_WEBCAST + path, params)
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\TikTokLive\client\http.py", line 102, in __aiohttp_get_json
async with session.get(request_url, headers=self.headers, timeout=self.timeout, proxy=self.proxy_container.get()) as request:
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\aiohttp\client.py", line 1138, in aenter
self._resp = await self._coro
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\aiohttp\client.py", line 559, in _request
await resp.start(conn)
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\aiohttp\client_reqrep.py", line 898, in start
message, payload = await protocol.read() # type: ignore[union-attr]
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\aiohttp\streams.py", line 616, in read
await self._waiter
aiohttp.client_exceptions.ServerDisconnectedError: Server disconnected

Failed to retrieve room info from webcast api
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\TikTokLive\client\base.py", line 215, in _connect
if self.__room_info.get("status", 4) == 4:
AttributeError: 'NoneType' object has no attribute 'get'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\User\Desktop\t.py", line 25, in
client.run()
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\TikTokLive\client\base.py", line 293, in run
self.loop.run_until_complete(self._connect())
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 646, in run_until_complete
return future.result()
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\TikTokLive\client\client.py", line 38, in _connect
result: str = await super(TikTokLiveClient, self)._connect()
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\TikTokLive\client\base.py", line 244, in _connect
raise FailedConnection(message)
TikTokLive.types.errors.FailedConnection: 'NoneType' object has no attribute 'get'

Version 0.8.5

  • Implement to_user_id Gift attribute
  • Implement chat sending functionality
  • Language Change Option

Version 4.3.2 / 4.3.3

Version 4.3.2

  • Add error message if websocket connection lost.
  • Add websocket_timeout_ms and set default to 15,000
  • Remove 0.5s delay between websocket queries in the websocket connection loop, apparently tornado is supposed to handle this
  • client.stop is no-longer an asynchronous method

Hotfix 4.3.3

  • Remove websocket_timeout_ms
  • Add ping loop

client.stop() is no longer asynchronous. Remove await when using. There are no other breaking changes at this time.

Upgrade with pip install TikTokLive --upgrade

Not getting events anymore.

Describe the bug
A clear and concise description of what the bug is.
I am just not getting comments or other events coming through. I can connect and I get a room id but thats it.
To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.
comments and likes to be printed out.
Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

No bug display. No error output. Just randomly misses a few gifts and comments. Sometimes nothing displays at all.

Describe the bug
It doesn't get all comments and gifts.

To Reproduce
Steps to reproduce the behavior:

  1. Compile python code
  2. Run exe on CMD, "TikTokMonitor.exe (username)" without the parenthesis

Expected behavior
To catch all gifts and comments

Code
`from TikTokLive import TikTokLiveClient
from TikTokLive.types.events import GiftEvent, ShareEvent, LikeEvent, FollowEvent, ConnectEvent, CommentEvent

client = TikTokLiveClient(sys.argv[1])

@client.on("gift")
async def on_gift(event: GiftEvent):
if event.gift.gift_type == 1 and event.gift.repeat_end == 1:
output = (f"Gift,{event.user.profilePicture.avatar_url},{event.user.uniqueId},{event.gift.repeat_count},{event.gift.extended_gift.name},{event.gift.giftDetails.giftImage.giftPictureUrl},{event.gift.giftDetails.diamondCount}")
print(output.encode("utf-8"),flush=True)

elif event.gift.gift_type != 1:
    output = (f"Gift,{event.user.profilePicture.avatar_url},{event.user.uniqueId},1,{event.gift.extended_gift.name},{event.gift.giftDetails.giftImage.giftPictureUrl},{event.gift.giftDetails.diamondCount}")
    print(output.encode("utf-8"),flush=True)

@client.on("like")
async def on_like(event: LikeEvent):
if event.likeCount > 10:
output = (f"Like,{event.user.profilePicture.avatar_url},{event.user.uniqueId},{event.likeCount}")
print(output.encode("utf-8"),flush=True)

@client.on("share")
async def on_share(event: ShareEvent):
output = (f"Share,{event.user.profilePicture.avatar_url},{event.user.uniqueId}")
print(output.encode("utf-8"),flush=True)

@client.on("follow")
async def on_follow(event: FollowEvent):
output = (f"Follow,{event.user.profilePicture.avatar_url},{event.user.uniqueId}")
print(output.encode("utf-8"),flush=True)

@client.on("comment")
async def on_follow(event: CommentEvent):
output = (f"Comment,{event.user.profilePicture.avatar_url},{event.user.uniqueId},{event.comment}")
print(output.encode("utf-8"),flush=True)

client.run()`

Desktop (please complete the following information):

  • OS: Windows 10

Additional context
I also noticed that some gifts and comments misses out on browser (chrome)

Issue with client run

File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/ssl.py", line 974, in do_handshake
self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)

Getting this bug when running the following code:

`from TikTokLive import TikTokLiveClient
from TikTokLive.types.events import CommentEvent, GiftEvent, ConnectEvent

client: TikTokLiveClient = TikTokLiveClient(
unique_id="sasarban", **(
{
"enable_extended_gift_info": True
}
)
)

@client.on("connect")
async def on_connect(_: ConnectEvent):
print(client.room_id)

@client.on("comment")
async def on_connect(event: CommentEvent):
print(f"{event.user.uniqueId} -> {event.comment}")

if name == "main":
client.run()`

It occurs when I execute this part of the code:
if name == "main":
client.run()

I have installed pip install TikTokLive as well as working on python 3.7

Version 0.8.6

  • Address issue with TikTokLive package failure to retrieve Room ID: #23

Hotfix release. No new additional features will be included. No breaking changes.

TimeoutError

TimeoutError currently is an annoying error that sometimes happens after either TikTok or the client drop HTTP connections. There should be a parameter that allows this error to be ignored rather than displayed.

Simply check is_instance(error, TimeoutError) and use the user's config via kwargs to determine whether or not it should be displayed.

add request_polling_interval_ms to the client constructor

Hi,

if i add the additional options to the client constructor i get following error:

client: TikTokLiveClient = TikTokLiveClient(
unique_id="@oldskoldj", **(
{
"process_initial_data": True,
"fetch_room_info_on_connect": True,
"enable_extended_gift_info": False,
"request_polling_interval_ms": 1000,
"client_params": {},
"request_headers": {}
}
)
)

ERROR:

aseClient.init() got an unexpected keyword argument 'request_polling_interval_ms'

Disconnect after 30 secs

If there is no activity in the live for 30 secs it disconnects.

I added the TikTokLiveClient("timeout_ms: None") but that didn't work.

I may be missing something or just need a brain boost in the right direction to get this to stay connected.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.