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

编辑推荐精选

博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

AI办公办公工具AI工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

iTerms

iTerms

企业专属的AI法律顾问

iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。

SimilarWeb流量提升

SimilarWeb流量提升

稳定高效的流量提升解决方案,助力品牌曝光

稳定高效的流量提升解决方案,助力品牌曝光

Sora2视频免费生成

Sora2视频免费生成

最新版Sora2模型免费使用,一键生成无水印视频

最新版Sora2模型免费使用,一键生成无水印视频

Transly

Transly

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

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

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
TRAE编程

TRAE编程

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

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

AI工具TraeAI IDE协作生产力转型热门
商汤小浣熊

商汤小浣熊

最强AI数据分析助手

小浣熊家族Raccoon,您的AI智能助手,致力于通过先进的人工智能技术,为用户提供高效、便捷的智能服务。无论是日常咨询还是专业问题解答,小浣熊都能以快速、准确的响应满足您的需求,让您的生活更加智能便捷。

imini AI

imini AI

像人一样思考的AI智能体

imini 是一款超级AI智能体,能根据人类指令,自主思考、自主完成、并且交付结果的AI智能体。

下拉加载更多