isaackogan / tiktoklive Goto Github PK
View Code? Open in Web Editor NEWPython library to receive live stream events (comments, gifts, etc.) in realtime from TikTok LIVE.
Home Page: https://isaackogan.github.io/TikTokLive/
License: MIT License
Python library to receive live stream events (comments, gifts, etc.) in realtime from TikTok LIVE.
Home Page: https://isaackogan.github.io/TikTokLive/
License: MIT License
Login Credentials for TikTok live is stored in the Cookies.
I have tested this and it did work so we might have a valid approach!
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
Version 4.3.2
websocket_timeout_ms
and set default to 15,000client.stop
is no-longer an asynchronous methodHotfix 4.3.3
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
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.
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?
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):
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```
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):
Describe the bug
Running the examples/gifts.py can't get the live broadcast information,
Not sure if it has something to do with my network。
Has tiktok modified the protocol?
like how to for example make a screenhot when someone send a rose, or play a sound only on gg gift?
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.
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'
Hotfix release. No new additional features will be included. No breaking changes.
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:
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):
Smartphone (please complete the following information):
Additional context
Add any other context about the problem here.
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.
ERROR:root:Traceback (most recent call last):
File "F:\Programs\Python\Python310\lib\site-packages\TikTokLive\client\base.py", line 253, in __try_websocket_upgrade
connection: WebSocketClientConnection = await websocket_connect(
tornado.websocket.WebSocketError: Non-websocket response
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.
TikTokLive.types.errors.InitialCursorMissing: Missing cursor in initial fetch response.
Can't connect to the Tik-Tok
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
The code can connect to Room ID but doesn't get client information, i hope you fix the code. Big Thanks.
Implement missing features
Unclosed client session
client_session: <aiohttp.client.ClientSession
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
"viewer_count" is always None
serialize_message
proto method to allow reserialization of decoded datasend_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 minutesThere are no breaking changes at this time.
Upgrade with pip install TikTokLive --upgrade
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
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'
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!
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
}
Add handling for rate limits (custom error)
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.
Is there a way to download the live itself or to access/download live replays?
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.
AsyncIOEventEmitter
inheritence from TikTokLiveClient
to BaseClient
polling_interval_ms
to ping_interval_ms
websocket_enabled
BaseClient parameterfetch_room_info_on_connect
BaseClient parameterset_proxies
and get_proxies
methodsIf you were using the ProxyContainer API, you must switch to the new proxy handling system. There are no other breaking changes.
Not receiving live messages
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
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
Like title says, did I miss anything? Do I need to purchase the printer in order to learn how to do this?
Describe the bug
It doesn't get all comments and gifts.
To Reproduce
Steps to reproduce the behavior:
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):
Additional context
I also noticed that some gifts and comments misses out on browser (chrome)
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.
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()
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.