Project Icon

TikTokLive

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

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

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

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

项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

白日梦AI

白日梦AI提供专注于AI视频生成的多样化功能,包括文生视频、动态画面和形象生成等,帮助用户快速上手,创造专业级内容。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

讯飞绘镜

讯飞绘镜是一个支持从创意到完整视频创作的智能平台,用户可以快速生成视频素材并创作独特的音乐视频和故事。平台提供多样化的主题和精选作品,帮助用户探索创意灵感。

Project Cover

讯飞文书

讯飞文书依托讯飞星火大模型,为文书写作者提供从素材筹备到稿件撰写及审稿的全程支持。通过录音智记和以稿写稿等功能,满足事务性工作的高频需求,帮助撰稿人节省精力,提高效率,优化工作与生活。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号