TikTokLive

TikTokLive

Python库实现TikTok直播实时连接和事件监听

TikTokLive是一个连接TikTok直播的Python库,通过WebSocket接收实时评论、礼物和点赞等事件。只需用户名即可连接,无需额外凭据。该库提供简洁API,支持自定义事件监听和处理多种直播事件。TikTokLive还具备检查用户在线状态的功能,并支持HTTP请求和WebSocket连接的代理设置。适用于开发者构建TikTok直播相关应用和分析工具。

TikTokLivePython库直播连接实时事件WebSocketGithub开源项目

TikTokLive

The definitive Python library to connect to TikTok LIVE.

Connections Downloads Stars Forks Issues

<!-- [![HitCount](https://hits.dwyl.com/isaackogan/TikTokLive.svg?style=flat)](http://hits.dwyl.com/isaackogan/TikTokLive) -->

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

<div align="left"> <a href="https://eulerstream.com" target="_blank"> <div> <b>Eulerstream</b> offers paid plans for enterprises for increased TikTokLive access & TikTok API tokens for data collection </div> <br/> <img src="https://github.com/isaackogan/TikTokLive/assets/65869106/b56cef89-5d87-4f2f-ac3e-0685af21b28d)" width="100" alt="Eulerstream"> </a> </div>

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 NameRequiredDefaultDescription
unique_idYesN/AThe 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_proxyNoNoneTikTokLive 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_proxyNoNoneTikTokLive supports proxying the websocket connection. This parameter accepts an httpx.Proxy. Using this proxy will never be subject to reduced connection limits.
web_kwargsNo{}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_kwargsNo{}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 NameNotesDescription
runN/AConnect to the livestream and block the main thread. This is best for small scripts.
add_listenerN/AAdds 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
connectasyncConnects to the tiktok live chat while blocking the current future. When the connection ends (e.g. livestream is over), the future is released.
startasyncConnects to the live chat without blocking the main thread. This returns an asyncio.Task object with the client loop.
disconnectasyncDisconnects the client from the websocket gracefully, processing remaining events before ending the client loop.

Properties

A TikTokLiveClient object contains the following important properties:

Attribute NameDescription
room_idThe Room ID of the livestream room the client is currently connected to.
webThe TikTok HTTP client. This client has a lot of useful routes you should explore!
connectedWhether you are currently connected to the livestream.
loggerThe internal logger used by TikTokLive. You can use client.logger.setLevel(...) method to enable client debug.
room_infoRoom 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_infoExtra 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.

ParameterTypeDescription
tiktok_app_urlstrThe TikTok app URL (https://www.tiktok.com) used to scrape the room.
tiktok_sign_urlstrThe signature server used to generate tokens to connect to TikTokLive.
tiktok_webcast_urlstrThe TikTok livestream URL (https://webcast.tiktok.com) where livestreams can be accessed from.
client_paramsdictThe URL parameters added on to TikTok requests from the HTTP client.
client_headersdictThe headers added on to TikTok requests from the HTTP client.
tiktok_sign_api_keystrA 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

编辑推荐精选

即梦AI

即梦AI

一站式AI创作平台

提供 AI 驱动的图片、视频生成及数字人等功能,助力创意创作

扣子-AI办公

扣子-AI办公

AI办公助手,复杂任务高效处理

AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!

Keevx

Keevx

AI数字人视频创作平台

Keevx 一款开箱即用的AI数字人视频创作平台,广泛适用于电商广告、企业培训与社媒宣传,让全球企业与个人创作者无需拍摄剪辑,就能快速生成多语言、高质量的专业视频。

TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI辅助写作AI工具蛙蛙写作AI写作工具学术助手办公助手营销助手AI助手
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

下拉加载更多