### Install pytchat Source: https://github.com/taizan-hokuto/pytchat/blob/master/README.md Install the library using pip. ```bash pip install pytchat ``` -------------------------------- ### Complete example of multiple processor usage Source: https://github.com/taizan-hokuto/pytchat/wiki/Multiple-chat-processors A full implementation demonstrating initialization, data retrieval, and iteration over chat items with speed calculation. ```python from pytchat import LiveChat, DefaultProcessor, SpeedCalculator def multiple_processor(): chat = LiveChat("video_id", processor = ( DefaultProcessor(), SpeedCalculator() )) while chat.is_alive(): data, speed = chat.get() for c in data.items: print(f"{c.elapsedTime.rjust(8)} <{c.datetime}> [{c.author.name}]-{c.message}") data.tick() print(f"[speed:{speed} it/m]") if __name__ =='__main__': multiple_processor() ``` -------------------------------- ### JSON Lines Data Format Example Source: https://github.com/taizan-hokuto/pytchat/wiki/JsonfileArchiver Example of the output format produced by the archiver. Each line is a separate JSON object. ```json {"addChatItemAction": {"item": {"liveChatTextMessageRenderer": {"message": {"runs": [{"text": ...} {"addChatItemAction": {"item": {"liveChatPaidMessageRenderer": {"id": "xxx", "timestampUsec": ...} {"addChatItemAction": {"item": {"liveChatTextMessageRenderer": {"message": {"runs": [{"text": ...} ``` -------------------------------- ### Retrieve data from multiple processors Source: https://github.com/taizan-hokuto/pytchat/wiki/Multiple-chat-processors The get() method returns a tuple corresponding to the order of processors defined during initialization. ```python data, speed = chat.get() ``` -------------------------------- ### Constructor: LiveChat Source: https://github.com/taizan-hokuto/pytchat/wiki/LiveChat Initializes the LiveChat object to start fetching chat data from a specified YouTube video. ```APIDOC ## Constructor: LiveChat ### Description Initializes the LiveChat instance to begin fetching chat data from a YouTube video or URL. ### Parameters #### Request Body - **video_id** (str) - Required - ID of YouTube video, or YouTube URL that includes ID. - **processor** (ChatProcessor) - Optional - Default: DefaultProcessor - **buffer** (Buffer) - Optional - Buffer of chat data fetched in background. Default: Buffer(maxsize=20) - **interruptable** (bool) - Optional - Allows keyboard interrupts. Default: True - **callback** (func) - Optional - Function called periodically. - **done_callback** (func) - Optional - Function called when listener ends. - **direct_mode** (bool) - Optional - If True, invoke specified callback function without using buffer. Default: False - **force_replay** (bool) - Optional - Force to fetch archived chat data, even if specified video is live. Default: False - **topchat_only** (bool) - Optional - If True, get only top chat. Default: False - **logger** (logging.Logger) - Optional - Any Logger object. - **replay_continuation** (str) - Optional - Continuation parameter for archived chat data. ``` -------------------------------- ### ReplayChat Methods Source: https://github.com/taizan-hokuto/pytchat/wiki/ReplayChat Documentation for the core methods of the ReplayChat class: get(), pause(), resume(), is_alive(), and terminate(). ```APIDOC ## ReplayChat Methods ### Description Provides methods to interact with the ReplayChat object after initialization, including retrieving data, controlling the fetching process, and checking its status. ### Methods #### get() ##### Description Get processed chat data from the buffer. ##### Return Value Processed chat data. #### pause() ##### Description Pause chat fetching to the buffer. ##### Return Value None #### resume() ##### Description Resume chat fetching to the buffer. ##### Return Value None #### is_alive() ##### Description Check if the chat stream is alive. ##### Return Value bool #### terminate() ##### Description Terminate fetching chat. ##### Return Value None ``` -------------------------------- ### get() Source: https://github.com/taizan-hokuto/pytchat/wiki/LiveChat Retrieves processed chat data from the internal buffer. ```APIDOC ## get() ### Description Fetches processed chat data from the buffer. Note: This function is not available if a callback parameter is set in the constructor. ### Response - **data** (object) - Processed chat data. ``` -------------------------------- ### JSON Output Source: https://github.com/taizan-hokuto/pytchat/wiki/DefaultProcessor Details on how to get chat data in JSON format. ```APIDOC ## JSON Output This section describes how to obtain chat data in JSON format. ### `json()` - **Description**: Returns chat data in JSON format. #### Request Example (for entire chat data) ```python import time chat = pytchat.create(video_id="xxxxxxxx") while chat.is_alive(): print(chat.get().json()) time.sleep(5) ``` #### Request Example (for individual chat items) ```python # Each chat item can also be output in JSON format. for c in chat.get().sync_items(): print(c.json()) ``` ``` -------------------------------- ### Fetch and Display Live YouTube Chat Messages Source: https://github.com/taizan-hokuto/pytchat/wiki/CompatibleProcessor Use this snippet to retrieve live chat messages from a YouTube stream and print them to the console. Ensure you have the pytchat library installed. The processor is compatible with YT API structures. ```python from pytchat import LiveChat, CompatibleProcessor import time chat = LiveChat("uIx8l2xlYVY", processor = CompatibleProcessor() ) while chat.is_alive(): try: data = chat.get() polling = data['pollingIntervalMillis']/1000 for c in data['items']: if c.get('snippet'): print(f"[{c['authorDetails']['displayName']}]") f"-{c['snippet']['displayMessage']}") time.sleep(polling/len(data['items'])) except KeyboardInterrupt: chat.terminate() ``` -------------------------------- ### Calculate and Display Superchat Totals Source: https://github.com/taizan-hokuto/pytchat/wiki/SuperchatCalculator This snippet aggregates Superchat amounts by currency for a given YouTube video. It displays the total amount at regular intervals. The video ID can be for a live or archived stream. Ensure pytchat is installed and the asyncio event loop is properly managed. ```python '''Display the total result up to that point at regular intervals. video_id can be both live and archived.''' import asyncio from concurrent.futures import CancelledError from pytchat import ( LiveChatAsync, DefaultProcessor, SuperchatCalculator) video_id = "_i_AxXSfceM" async def main(): chat = LiveChatAsync(video_id, callback = display, processor = DefaultProcessor(), SuperchatCalculator() ) while chat.is_alive(): await asyncio.sleep(3) async def display(data, amount): print(data.items[-1].elapsedTime, amount) if __name__ =='__main__': loop = asyncio.get_event_loop() try: loop.run_until_complete(main()) except asyncio.CancelledError: pass ``` -------------------------------- ### Initialize and use ReplayChat Source: https://github.com/taizan-hokuto/pytchat/wiki/ReplayChat Demonstrates initializing a ReplayChat instance with a video ID and callback, then monitoring the stream status. ```python from pytchat import ReplayChat import time chat = ReplayChat("gb01h_eT0pw", seektime = 1000, callback = disp) while chat.is_alive(): time.sleep(3) def disp(data): for c in data.items: print(f"{c.datetime} [{c.author.name}]-{c.message} {c.amountString}") time.sleep(3) ``` -------------------------------- ### Initialize ReplayChatAsync Source: https://github.com/taizan-hokuto/pytchat/wiki/ReplayChatAsync Instantiate the ReplayChatAsync class with a video ID and optional seek time. ```python from pytchat import ReplayChatAsync chat = ReplayChatAsync("gb01h_eT0pw", seektime = 1000) ``` -------------------------------- ### Initialize Chat with DefaultProcessor Source: https://github.com/taizan-hokuto/pytchat/wiki/DefaultProcessor Create a chat instance using the DefaultProcessor to retrieve and print chat items synchronously. ```python import pytchat # `DefaultProcessor` parameter is optional. chat = pytchat.create(video_id="uIx8l2xlYVY", processor=DefaultProcessor()) while chat.is_alive(): for c in chat.get().sync_items(): print(f"{c.datetime} [{c.author.name}]- {c.message}") ``` -------------------------------- ### Initialize and Use LiveChatAsync Source: https://github.com/taizan-hokuto/pytchat/wiki/LiveChatAsync Demonstrates how to initialize the LiveChatAsync object, define a callback function for processing chat data, and handle termination. ```python from pytchat import LiveChatAsync import asyncio async def main(): livechat = LiveChatAsync("uIx8l2xlYVY", callback = func) while livechat.is_alive(): await asyncio.sleep(3) #other background operation. # If you want to check the reason for the termination, # you can use `raise_for_status()` function. try: livechat.raise_for_status() except pytchat.ChatDataFinished: print("Chat data finished.") except Exception as e: print(type(e), str(e)) #callback function is automatically called periodically. async def func(chatdata): for c in chatdata.items: print(f"{c.datetime} [{c.author.name}]-{c.message} {c.amountString}") await chatdata.tick_async() if __name__=='__main__': try: loop = asyncio.get_event_loop() loop.run_until_complete(main()) except asyncio.exceptions.CancelledError: pass ``` -------------------------------- ### pytchat.create Source: https://github.com/taizan-hokuto/pytchat/blob/master/README.md Initializes a chat instance for a specific YouTube video to begin fetching live chat data. ```APIDOC ## pytchat.create ### Description Creates a new chat instance to fetch live chat data from a YouTube video using its video ID. ### Parameters #### Request Body - **video_id** (str) - Required - The unique identifier of the YouTube video. ### Request Example ```python import pytchat chat = pytchat.create(video_id="uIx8l2xlYVY") ``` ### Response #### Success Response (200) - **chat** (object) - A chat instance object that provides methods like `is_alive()` and `get()` to interact with the chat stream. ``` -------------------------------- ### Initialize and fetch live chat data Source: https://github.com/taizan-hokuto/pytchat/wiki/LiveChat Basic implementation for connecting to a YouTube video and printing chat messages in a loop. ```python from pytchat import LiveChat import time chat = LiveChat(video_id = "uIx8l2xlYVY") while chat.is_alive(): try: data = chat.get() items = data.items for c in items: print(f"{c.datetime} [{c.author.name}]- {c.message}") time.sleep(3) except KeyboardInterrupt: chat.terminate() break ``` -------------------------------- ### HTMLArchiver Initialization Source: https://github.com/taizan-hokuto/pytchat/wiki/HTMLArchiver This endpoint/component documentation covers the initialization and usage of the HTMLArchiver to save live chat data. ```APIDOC ## HTMLArchiver ### Description Archives live chat data as an HTML file, with embedded custom emojis. ### Parameters #### Initialization Parameters - **save_path** (str) - Required - The file system path where the HTML file will be saved. ### Request Example ```python import asyncio from pytchat import HTMLArchiver, LiveChatAsync video_id = "**********" async def main(): livechat = LiveChatAsync(video_id, processor=HTMLArchiver("v:/test.html")) while livechat.is_alive(): await livechat.get() await asyncio.sleep(1) asyncio.run(main()) ``` ``` -------------------------------- ### Fetch Chat with pytchat.create() Source: https://context7.com/taizan-hokuto/pytchat/llms.txt Initializes a simple non-buffered chat stream. Suitable for basic synchronous fetching of live or archived chat. ```python import pytchat import time # Create chat stream using video ID or full URL chat = pytchat.create(video_id="uIx8l2xlYVY") # Fetch chat messages in a loop while chat.is_alive(): # Get chat data and iterate with synchronized timing for c in chat.get().sync_items(): print(f"{c.datetime} [{c.author.name}] {c.message}") # Access additional chat properties if c.type == "superChat": print(f" SuperChat: {c.amountString} ({c.currency})") # Author details available print(f" Channel: {c.author.channelId}") print(f" Is Moderator: {c.author.isChatModerator}") # Check termination reason try: chat.raise_for_status() except pytchat.ChatDataFinished: print("Chat stream ended normally") except pytchat.InvalidVideoIdException: print("Invalid video ID provided") ``` -------------------------------- ### ReplayChat Initialization and Usage Source: https://github.com/taizan-hokuto/pytchat/wiki/ReplayChat This snippet demonstrates how to initialize the ReplayChat object with a video ID, seek time, and a callback function, and then how to listen for chat data. ```APIDOC ## ReplayChat Initialization and Usage ### Description Initializes the ReplayChat object to fetch past chat data from an archived YouTube video and processes it using a callback function. ### Method `ReplayChat(video_id: str, seektime: int = 0, callback: Optional[Callable] = None, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Parameters - **video_id** (str) - Required - ID of the YouTube video. - **seektime** (int) - Optional - Seek time of the chat in seconds. Defaults to 0 (start of chat data). - **callback** (func) - Optional - Function called periodically with processed chat data. - **processor** (ChatProcessor) - Optional - Processor for chat data. Defaults to `DefaultProcessor`. - **buffer** (Buffer) - Optional - Buffer for chat data fetched in the background. Defaults to `Buffer(maxsize=20)`. - **interruptable** (bool) - Optional - Whether the process is interruptable. Defaults to `True`. - **done_callback** (func) - Optional - Function called when the listener ends. - **direct_mode** (bool) - Optional - If True, invoke the callback function directly without using a buffer. Defaults to `False`. ### Request Example ```python from pytchat import ReplayChat import time def disp(data): for c in data.items: print(f"{c.datetime} [{c.author.name}]-{c.message} {c.amountString}") time.sleep(3) chat = ReplayChat("gb01h_eT0pw", seektime = 1000, callback = disp) while chat.is_alive(): time.sleep(3) ``` ### Response #### Success Response (200) None (This is a class initialization and listening process) #### Response Example None ``` -------------------------------- ### DefaultProcessor Usage Source: https://github.com/taizan-hokuto/pytchat/wiki/DefaultProcessor Demonstrates how to initialize pytchat with the DefaultProcessor to process chat messages. ```APIDOC ## DefaultProcessor Usage This section shows how to use the `DefaultProcessor` with pytchat to fetch and display chat messages from a YouTube video. ### Usage Example ```python import pytchat from pytchat.processors import DefaultProcessor # Initialize pytchat with DefaultProcessor (optional) chat = pytchat.create(video_id="uIx8l2xlYVY", processor=DefaultProcessor()) # Continuously fetch and print chat messages while chat.is_alive(): for c in chat.get().sync_items(): print(f"{c.datetime} [{c.author.name}]- {c.message}") ``` ``` -------------------------------- ### Initialize JsonfileArchiver with LiveChatAsync Source: https://github.com/taizan-hokuto/pytchat/wiki/JsonfileArchiver Configures the processor within a LiveChatAsync instance. Requires an existing video ID and a callback function. ```python import asyncio from pytchat import LiveChatAsync video_id = "8PIe_F9MI80" async def main(): chat = LiveChatAsync(  video_id, callback = func, processor = JsonfileArchiver("c:/temp/test.data") ) while chat.is_alive(): await asyncio.sleep(5) async def func(param): pass loop = asyncio.get_event_loop() try: loop.run_until_complete(async_def_callback()) except asyncio.CancelledError: print('Cancelled') ``` -------------------------------- ### Initialize LiveChat with multiple processors Source: https://github.com/taizan-hokuto/pytchat/wiki/Multiple-chat-processors Pass a tuple of processor instances to the processor argument to enable concurrent processing. ```python chat = LiveChat("video_id", processor = (DefaultProcessor(), SpeedCalculator()) ) ``` -------------------------------- ### Retrieve chat data using continuation Source: https://github.com/taizan-hokuto/pytchat/wiki/PytchatCore Demonstrates how to terminate a stream, capture the continuation parameter, and resume fetching chat data from that point. ```python import pytchat import time stream = pytchat.create(video_id = "uIx8l2xlYVY") i = 0 while stream.is_alive(): data = stream.get() items = data.items for c in items: print(f"{c.datetime} [{c.author.name}]- {c.message}") time.sleep(3) i += 1 if i == 3: # get the continuation parameter continuation = stream.continuation stream.terminate() break # retrieve chatdata from the continuation. stream = pytchat.create(video_id = "uIx8l2xlYVY", replay_continuation=continuation) data = stream.get() items = data.items for c in items: print(f"{c.datetime} [{c.author.name}]- {c.message}") stream.terminate() ``` -------------------------------- ### LiveChatAsync Initialization and Usage Source: https://github.com/taizan-hokuto/pytchat/wiki/LiveChatAsync This snippet demonstrates how to initialize and use the LiveChatAsync object to fetch live chat data, process it with a callback function, and handle potential exceptions. ```APIDOC ## LiveChatAsync Initialization and Usage ### Description Initializes the LiveChatAsync object to fetch chat data from a YouTube video and process it using a callback function. It runs in an asyncio event loop and allows for background operations and error handling. ### Method `LiveChatAsync(video_id, callback=None, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Parameters | Name | Type | Required | Remarks | Default Value | |------------------|-----------|----------|--------------------------------------------------------------------------------------------------------|---------------| | video_id | str | * | ID of youtube video, or youtube URL that includes ID. | - | | processor | ChatPrcessor | | | DefaultProcessor | | buffer | Buffer | | buffer of chat data fetched background. | Buffer(maxsize=20) | | interruptable | bool | | Allows keyboard interrupts. Set this parameter to False if your own threading program causes the problem. | True | | callback | func | | function called from _listen() periodically. | None | | done_callback | func | | function called when listener ends. | None | | exception_handler| func | | function called when exceptions occur. | None | | direct_mode | bool | | If True, invoke specified callback function without using buffer. | False | | seektime | int | | ~~start position of fetching chat (seconds). This option is valid for archived chat only. If negative value, fetches chatdata which is posted before start broadcasting.~~ **This parameter is not working well. We'll deal with it as soon as possible.** | 0 | | force_replay | bool | | force to fetch archived chat data, even if specified video is live. | False | | topchat_only | bool | | If True, get only top chat. | False | | replay_continuation | str | | continuation parameter(archived chat only) | None | ### Request Example ```python from pytchat import LiveChatAsync import asyncio async def main(): livechat = LiveChatAsync("uIx8l2xlYVY", callback = func) while livechat.is_alive(): await asyncio.sleep(3) #other background operation. try: livechat.raise_for_status() except pytchat.ChatDataFinished: print("Chat data finished.") except Exception as e: print(type(e), str(e)) async def func(chatdata): for c in chatdata.items: print(f"{c.datetime} [{c.author.name}]-{c.message} {c.amountString}") await chatdata.tick_async() if __name__== '__main__': try: loop = asyncio.get_event_loop() loop.run_until_complete(main()) except asyncio.exceptions.CancelledError: pass ``` ### Response None (processed by callback function) ### Error Handling Exceptions can be caught using `livechat.raise_for_status()` after `is_alive()` returns `False`. ``` -------------------------------- ### Fetch chat data with pytchat Source: https://github.com/taizan-hokuto/pytchat/blob/master/README.md Initialize a chat object with a video ID and iterate through live chat items synchronously. ```python import pytchat chat = pytchat.create(video_id="uIx8l2xlYVY") while chat.is_alive(): for c in chat.get().sync_items(): print(f"{c.datetime} [{c.author.name}]- {c.message}") ``` -------------------------------- ### ReplayChatAsync Constructor and Usage Source: https://github.com/taizan-hokuto/pytchat/wiki/ReplayChatAsync This snippet shows how to initialize and use the ReplayChatAsync class to fetch past chat data from YouTube videos. Note that ReplayChatAsync is deprecated and its functionality is integrated into LiveChatAsync. ```APIDOC ## ReplayChatAsync Constructor ### Description Initializes the ReplayChatAsync object to fetch past chat data of archived videos and stores them in a buffer. It can respond to user inquiries of get() and invoke a callback function with processed chat data. It can also retrieve chat data that was disabled by editing the video. **Warning**: `ReplayChatAsync` is deprecated and will be removed. This feature is already integrated into `LiveChatAsync`. ### Usage ```python from pytchat import ReplayChatAsync chat = ReplayChatAsync("gb01h_eT0pw", seektime = 1000) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Parameters - **video_id** (str) - Required - ID of youtube video. - **processor** (ChatProcessor) - Optional - Processor for chat data. - **buffer** (Buffer) - Optional - Buffer for chat data fetched in the background. Defaults to `Buffer(maxsize=20)`. - **interruptable** (bool) - Optional - Controls if the process is interruptable. Defaults to `True`. - **callback** (func) - Optional - Function called from `_listen()` periodically. - **done_callback** (func) - Optional - Function called when the listener ends. - **direct_mode** (bool) - Optional - If True, invoke the specified callback function without using a buffer. Defaults to `False`. - **seektime** (int) - Optional - Seek time of chat in seconds. Defaults to `0` (start of chat). ``` -------------------------------- ### ReplayChatAsync Methods Source: https://github.com/taizan-hokuto/pytchat/wiki/ReplayChatAsync This snippet details the available methods for interacting with the ReplayChatAsync object after initialization. ```APIDOC ## ReplayChatAsync Methods ### get() #### Description Get processed chat data from the buffer. #### Return Value processed chat data ### pause() #### Description Pause chat fetching to the buffer. #### Return Value - ### resume() #### Description Resume chat fetching to the buffer. #### Return Value - ### is_alive() #### Description Check if the chat stream is alive. #### Return Value bool ### terminate() #### Description Terminate fetching chat. #### Return Value - ``` -------------------------------- ### Retrieve chat data using continuation parameter Source: https://github.com/taizan-hokuto/pytchat/wiki/LiveChat Demonstrates how to capture a continuation token to resume or fetch specific segments of archived chat data. ```python from pytchat import LiveChat import time stream = LiveChat(video_id = "uIx8l2xlYVY") i = 0 while stream.is_alive(): data = stream.get() items = data.items for c in items: print(f"{c.datetime} [{c.author.name}]- {c.message}") time.sleep(3) i += 1 if i == 3: # get the continuation parameter continuation = stream.continuation stream.terminate() break # retrieve chatdata from the continuation. stream = LiveChat(video_id = "uIx8l2xlYVY", replay_continuation=continuation) data = stream.get() items = data.items for c in items: print(f"{c.datetime} [{c.author.name}]- {c.message}") stream.terminate() ``` -------------------------------- ### Enable logging with pytchat Source: https://github.com/taizan-hokuto/pytchat/wiki/Logging-pytchat Configures a logger instance during LiveChat initialization to capture debug information. ```python from pytchat import LiveChat, config, logging chat = LiveChat(video_id = "Zvp1pJpie4I", logger = config.logger(__name__, logging.DEBUG)) while chat.is_alive(): try: data = chat.get() items = data.items for c in items: print(f"{c.datetime} [{c.author.name}]- {c.message}") data.tick() except KeyboardInterrupt: chat.terminate() break ``` -------------------------------- ### JsonfileArchiver Class Source: https://github.com/taizan-hokuto/pytchat/wiki/JsonfileArchiver Details on initializing the JsonfileArchiver and its return structure. ```APIDOC ## JsonfileArchiver ### Description Saves chat data as text of JSON lines. If a file with the same name exists, it is automatically saved under a different name with a numeric suffix. ### Parameters - **save_path** (str) - Required - The file path where the chat data will be saved. ### Return - **save_path** (str) - The actual save path of the file. - **total_lines** (int) - The count of total lines written to the file. ### Data Format The output file consists of text formatted as JSON lines. Each line is a valid JSON object. The file cannot be imported as a single JSON object; it must be parsed line by line. ``` -------------------------------- ### Combine Multiple Processors in LiveChat Source: https://context7.com/taizan-hokuto/pytchat/llms.txt Pass multiple processors as a tuple to LiveChat to execute them simultaneously. Returns from chat.get() match the order of the processors provided. ```python from pytchat import LiveChat, DefaultProcessor, SpeedCalculator, SuperchatCalculator # Combine three processors chat = LiveChat( video_id="uIx8l2xlYVY", processor=( DefaultProcessor(), SpeedCalculator(), SuperchatCalculator() ) ) while chat.is_alive(): # Returns match processor order chatdata, speed, superchat_totals = chat.get() print(f"\n=== Speed: {speed} msg/min ===") print(f"=== SuperChat Totals: {superchat_totals} ===\n") for c in chatdata.items: print(f"{c.elapsedTime.rjust(8)} [{c.author.name}] {c.message}") chatdata.tick() # With callback mode def process_all(chatdata, speed, totals): print(f"Speed: {speed}, Totals: {totals}") for c in chatdata.items: print(c.message) chat = LiveChat( video_id="uIx8l2xlYVY", processor=(DefaultProcessor(), SpeedCalculator(), SuperchatCalculator()), callback=process_all ) ``` -------------------------------- ### Fetch live chat data with Pytchat Source: https://github.com/taizan-hokuto/pytchat/wiki/PytchatCore Basic implementation for retrieving and printing live chat data using a loop, including error handling with raise_for_status. ```python import pytchat import time chat = pytchat.create(video_id="uIx8l2xlYVY") while chat.is_alive(): chatdata = chat.get() print(chatdata.json()) time.sleep(5) try: chat.raise_for_status() except pytchat.ChatdataFinished: print("chat data finished") except Exception as e: print(type(e), str(e)) ``` -------------------------------- ### Continuation Parameter Source: https://github.com/taizan-hokuto/pytchat/wiki/LiveChatAsync Explanation of the `replay_continuation` parameter for fetching archived chat data. ```APIDOC ## Continuation Parameter ### `replay_continuation` #### Description The continuation parameter for recent chat data. This parameter can be used for retrieving chat data of any timing by specifying it in the constructor as `replay_continuation`. This parameter is valid only for archived chat data. #### Usage Pass the continuation string to the `replay_continuation` argument when initializing `LiveChatAsync`. ```python # Example usage (assuming you have a continuation string) # livechat = LiveChatAsync(video_id="VIDEO_ID", replay_continuation="CONTINUATION_STRING") ``` ``` -------------------------------- ### Resume Chat Fetching with Continuation Parameter Source: https://context7.com/taizan-hokuto/pytchat/llms.txt Uses the continuation token to resume fetching from a specific point in the chat history. ```python import pytchat # First session - save continuation stream = pytchat.create(video_id="uIx8l2xlYVY") saved_continuation = None for i in range(5): if not stream.is_alive(): break data = stream.get() for c in data.items: print(f"{c.datetime} {c.message}") # Save continuation before terminating saved_continuation = stream.continuation stream.terminate() print(f"Saved continuation: {saved_continuation[:50]}...") ``` -------------------------------- ### Process Chat with CompatibleProcessor Source: https://context7.com/taizan-hokuto/pytchat/llms.txt Outputs chat data in a format compatible with the official YouTube Data API response structure. ```python import pytchat from pytchat import CompatibleProcessor import json chat = pytchat.create( video_id="uIx8l2xlYVY", processor=CompatibleProcessor() ) while chat.is_alive(): response = chat.get() # Response structure matches YouTube API print(f"Kind: {response['kind']}") # youtube#liveChatMessageListResponse print(f"Polling Interval: {response['pollingIntervalMillis']}ms") print(f"Total Results: {response['pageInfo']['totalResults']}") for item in response['items']: print(f"ID: {item['id']}") print(f"Kind: {item['kind']}") # youtube#liveChatMessage snippet = item['snippet'] print(f"Type: {snippet['type']}") print(f"Message: {snippet.get('displayMessage', '')}") print(f"Published: {snippet['publishedAt']}") # SuperChat details in snippet if 'superChatDetails' in snippet: sc = snippet['superChatDetails'] print(f"Amount: {sc['amountDisplayString']}") print(f"Currency: {sc['currency']}") author = item['authorDetails'] print(f"Author: {author['displayName']}") print(f"Channel: {author['channelId']}") print(f"Is Verified: {author['isVerified']}") # Serialize to JSON for API compatibility print(json.dumps(response, ensure_ascii=False, indent=2)) ``` -------------------------------- ### Direct Mode Live Chat with Immediate Callback Source: https://context7.com/taizan-hokuto/pytchat/llms.txt Utilizes pytchat's direct mode for minimal latency by bypassing the buffer and invoking a callback immediately upon receiving chat data. This is suitable for real-time applications. ```python from pytchat import LiveChat, DefaultProcessor def immediate_handler(chatdata): """Called immediately when chat data is received""" for c in chatdata.items: print(f"[LIVE] {c.author.name}: {c.message}") # Direct mode requires callback chat = LiveChat( video_id="uIx8l2xlYVY", callback=immediate_handler, direct_mode=True, # Skip buffer, call immediately processor=DefaultProcessor() ) while chat.is_alive(): pass # Callback handles everything # Note: get() cannot be used with direct_mode # chat.get() # Raises IllegalFunctionCall ``` -------------------------------- ### Chat Instance Methods Source: https://github.com/taizan-hokuto/pytchat/wiki/PytchatCore Methods available on the chat object to manage the stream and retrieve data. ```APIDOC ## get() ### Description Retrieves the processed chat data. ### Returns - **data** (object) - Processed chat data. ## is_alive() ### Description Checks if the live chat stream is currently active. ### Returns - **status** (bool) - True if alive, False otherwise. ## is_replay() ### Description Checks if the instance is replaying archived chat. ### Returns - **status** (bool) - True if replaying, False otherwise. ## terminate() ### Description Terminates the fetching of chat data. ## raise_for_status() ### Description Raises an internal exception if one occurred during fetching. Only valid when hold_exception is True. ``` -------------------------------- ### LiveChatAsync Methods Source: https://github.com/taizan-hokuto/pytchat/wiki/LiveChatAsync Details on the available methods for interacting with the LiveChatAsync object, including fetching data, checking status, and managing the chat stream. ```APIDOC ## LiveChatAsync Methods ### `await get()` #### Description Retrieves processed chat data from the internal buffer. #### Return Value - `processed chat data`: The chat data fetched and processed by the object. ### `is_alive()` #### Description Checks if the live chat stream is currently active and fetching data. #### Return Value - `bool`: `True` if the stream is alive, `False` otherwise. ### `pause()` #### Description Pauses the fetching of chat messages. This method is applicable only in callback mode. ### `resume()` #### Description Resumes the fetching of chat messages after it has been paused. This method is applicable only in callback mode. ### `terminate()` #### Description Stops the process of fetching chat messages and terminates the live chat stream. ### `raise_for_status()` #### Description Raises an internal exception if the live chat stream has terminated unexpectedly. This should be called after `is_alive()` returns `False` to diagnose the reason for termination. #### Exceptions - `pytchat.ChatDataFinished`: If the chat data stream has naturally concluded. - Other `Exception` types: For various other errors that may occur during data fetching or processing. ``` -------------------------------- ### terminate() Source: https://github.com/taizan-hokuto/pytchat/wiki/LiveChat Stops the live chat fetching process. ```APIDOC ## terminate() ### Description Terminates the background thread fetching live chat data. ``` -------------------------------- ### Fetch Chat with LiveChatAsync Source: https://context7.com/taizan-hokuto/pytchat/llms.txt Provides asynchronous support for integration with asyncio-based applications. Includes both callback-driven and manual awaitable fetching patterns. ```python from pytchat import LiveChatAsync import asyncio async def main(): livechat = LiveChatAsync( video_id="uIx8l2xlYVY", callback=display_chat ) while livechat.is_alive(): await asyncio.sleep(3) # Perform other async operations here try: livechat.raise_for_status() except Exception as e: print(f"Chat ended: {type(e).__name__}") async def display_chat(chatdata): async for c in chatdata.async_items(): print(f"{c.datetime} [{c.author.name}] {c.message}") if c.amountString: print(f" Donation: {c.amountString}") if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) # Alternative: Manual get() with async async def manual_fetch(): livechat = LiveChatAsync(video_id="uIx8l2xlYVY") while livechat.is_alive(): chatdata = await livechat.get() for c in chatdata.items: print(f"{c.message}") await asyncio.sleep(2) livechat.terminate() ``` -------------------------------- ### Archive live chat data using HTMLArchiver Source: https://github.com/taizan-hokuto/pytchat/wiki/HTMLArchiver Uses the HTMLArchiver processor with LiveChatAsync to save chat data to a specified file path. Requires an active video ID and an asynchronous loop to process incoming chat messages. ```python import asyncio from pytchat import HTMLArchiver, LiveChatAsync video_id = "**********" async def main(): livechat = LiveChatAsync(video_id, processor=HTMLArchiver("v:/test.html")) while livechat.is_alive(): await livechat.get() await asyncio.sleep(1) asyncio.run(main()) ``` -------------------------------- ### Calculate chat speed using on-demand style Source: https://github.com/taizan-hokuto/pytchat/wiki/SpeedCalculator Polls the chat processor for speed data within a loop. Requires the time module for sleep intervals. ```python from pytchat import LiveChat, SpeedCalculator chat = LiveChat(video_id = "xxxxxxxxxxx", processor = SpeedCalculator(capacity = 20)) while chat.is_alive(): speed = chat.get() print(speed) time.sleep(3) ``` -------------------------------- ### is_alive() Source: https://github.com/taizan-hokuto/pytchat/wiki/LiveChat Checks the status of the live chat stream. ```APIDOC ## is_alive() ### Description Checks if the live chat stream is currently active. ### Response - **status** (bool) - True if the stream is alive, False otherwise. ``` -------------------------------- ### Output chat data as JSON Source: https://github.com/taizan-hokuto/pytchat/blob/master/README.md Retrieve chat data and output it as a JSON string using the DefaultProcessor. ```python import pytchat import time chat = pytchat.create(video_id="uIx8l2xlYVY") while chat.is_alive(): print(chat.get().json()) time.sleep(5) ''' # Each chat item can also be output in JSON format. for c in chat.get().items: print(c.json()) ''' ``` -------------------------------- ### Deprecated Methods Source: https://github.com/taizan-hokuto/pytchat/wiki/DefaultProcessor Information about deprecated methods for waiting for the next chat. ```APIDOC ## Deprecated Methods The following methods are deprecated and should not be used in new code. ### `tick()` [DEPRECATED] - **Description**: Waits for the next chat message. - **Return Value**: - ### `tick_async()` [DEPRECATED] - **Description**: Waits for the next chat message in an asyncio context. - **Return Value**: - ``` -------------------------------- ### Error Handling for YouTube Live Chat Source: https://context7.com/taizan-hokuto/pytchat/llms.txt Demonstrates robust error handling for YouTube live chat streams using pytchat. It catches various exceptions like invalid video IDs, network errors, and stream termination. ```python import pytchat from pytchat import ( ChatDataFinished, InvalidVideoIdException, RetryExceedMaxCount, NoContents, NoContinuation ) chat = pytchat.create( video_id="uIx8l2xlYVY", hold_exception=True # Hold exceptions for later inspection ) while chat.is_alive(): try: data = chat.get() for c in data.items: print(c.message) except KeyboardInterrupt: print("User interrupted") chat.terminate() break # Check termination reason try: chat.raise_for_status() except ChatDataFinished: print("Chat stream ended (video ended or chat disabled)") except InvalidVideoIdException as e: print(f"Invalid video ID: {e.doc}") except RetryExceedMaxCount: print("Network error - max retries exceeded") except NoContents: print("Chat data unavailable") except NoContinuation: print("No more chat data available") except Exception as e: print(f"Unexpected error: {type(e).__name__}: {e}") ``` ```python from pytchat import LiveChat def done_callback(future): try: future.result() except Exception as e: print(f"Stream ended with error: {e}") chat = LiveChat( video_id="uIx8l2xlYVY", done_callback=done_callback ) ``` -------------------------------- ### Calculate chat speed using callback style Source: https://github.com/taizan-hokuto/pytchat/wiki/SpeedCalculator Processes speed data asynchronously via a callback function. The callback must be defined to handle the speed output. ```python from pytchat import LiveChat, SpeedCalculator chat = LiveChat("xxxxxxxxxxx", processor = SpeedCalculator(), callback = disp_speed) while chat.is_alive(): time.sleep(3) def disp_speed(speed): print(speed) ``` -------------------------------- ### Fetch Chat with LiveChat Threading Source: https://context7.com/taizan-hokuto/pytchat/llms.txt Uses a background thread with a buffer for non-blocking chat retrieval. Supports both manual polling and automatic callback processing. ```python from pytchat import LiveChat import time # Basic usage with manual get() chat = LiveChat(video_id="uIx8l2xlYVY") while chat.is_alive(): try: data = chat.get() for c in data.items: print(f"{c.datetime} [{c.author.name}] {c.message}") time.sleep(3) except KeyboardInterrupt: chat.terminate() break # Callback mode - process chat automatically def process_chat(chatdata): for c in chatdata.items: print(f"{c.datetime} [{c.author.name}] {c.message}") chatdata.tick() # Synchronized display timing chat_with_callback = LiveChat( video_id="uIx8l2xlYVY", callback=process_chat, topchat_only=True, # Only get top chat messages force_replay=False # Auto-detect live vs archived ) while chat_with_callback.is_alive(): time.sleep(1) chat_with_callback.raise_for_status() ``` -------------------------------- ### Track Superchat Donations with SuperchatCalculator Source: https://context7.com/taizan-hokuto/pytchat/llms.txt Aggregates SuperChat and SuperSticker donations by currency. Can be used alone or combined with other processors like DefaultProcessor. ```python from pytchat import LiveChat, SuperchatCalculator chat = LiveChat( video_id="uIx8l2xlYVY", processor=SuperchatCalculator() ) while chat.is_alive(): totals = chat.get() # Dict: {currency_symbol: total_amount} for currency, amount in totals.items(): print(f"{currency}: {amount:.2f}") # Example output: # $: 1250.00 # ¥: 45000 # €: 320.50 # Combined with chat display from pytchat import DefaultProcessor chat = LiveChat( video_id="uIx8l2xlYVY", processor=(DefaultProcessor(), SuperchatCalculator()) ) while chat.is_alive(): data, totals = chat.get() for c in data.items: if c.type == "superChat": print(f"SUPERCHAT: {c.author.name} sent {c.amountString}") print(f"Running totals: {totals}") ``` -------------------------------- ### Process Chat with DefaultProcessor Source: https://context7.com/taizan-hokuto/pytchat/llms.txt Transforms raw chat data into structured Python objects containing message content, author details, and superchat information. ```python import pytchat from pytchat import DefaultProcessor chat = pytchat.create(video_id="uIx8l2xlYVY", processor=DefaultProcessor()) while chat.is_alive(): chatdata = chat.get() # Output all chat as JSON print(chatdata.json()) # Access individual items for c in chatdata.items: # Message types: textMessage, superChat, superSticker, newSponsor print(f"Type: {c.type}") print(f"Message: {c.message}") print(f"Timestamp: {c.timestamp}") # Unix milliseconds print(f"DateTime: {c.datetime}") # Formatted string # Extended message with emoji data for item in c.messageEx: if isinstance(item, dict): # Emoji: {'id': 'emoji_id', 'txt': ':emoji:', 'url': 'https://...'} print(f"Emoji: {item['txt']}") else: print(f"Text: {item}") # SuperChat details (if applicable) if c.type == "superChat": print(f"Amount: {c.amountValue}") # Float: 1234.0 print(f"Display: {c.amountString}") # String: "$ 1,234" print(f"Currency: {c.currency}") # ISO 4217: "USD" print(f"Background: {c.bgColor}") # RGB int # Author information print(f"Author: {c.author.name}") print(f"Channel ID: {c.author.channelId}") print(f"Channel URL: {c.author.channelUrl}") print(f"Image: {c.author.imageUrl}") print(f"Badge: {c.author.badgeUrl}") print(f"Verified: {c.author.isVerified}") print(f"Owner: {c.author.isChatOwner}") print(f"Member: {c.author.isChatSponsor}") print(f"Moderator: {c.author.isChatModerator}") # Individual item JSON print(c.json()) ``` -------------------------------- ### Archive Chat as HTML with HTMLArchiver Source: https://context7.com/taizan-hokuto/pytchat/llms.txt Saves chat data to an HTML file. Requires calling terminate() to ensure the file is finalized. ```python from pytchat import LiveChat, HTMLArchiver # Basic HTML archiving archiver = HTMLArchiver("chat_archive.html") chat = LiveChat( video_id="uIx8l2xlYVY", processor=archiver ) while chat.is_alive(): save_path, line_count = chat.get() print(f"Saved {line_count} messages to {save_path}") # Important: finalize() writes the complete HTML file chat.terminate() # This calls archiver.finalize() internally # With progress callback def on_progress(_, count): print(f"Processed message #{count}") archiver = HTMLArchiver("chat_archive.html", callback=on_progress) chat = LiveChat(video_id="uIx8l2xlYVY", processor=archiver) while chat.is_alive(): chat.get() ``` -------------------------------- ### Calculate Chat Speed Metrics Source: https://context7.com/taizan-hokuto/pytchat/llms.txt Calculates message rates per minute to monitor activity, optionally combined with other processors. ```python from pytchat import LiveChat, SpeedCalculator chat = LiveChat( video_id="uIx8l2xlYVY", processor=SpeedCalculator(capacity=10) # Calculate over 10 intervals ) while chat.is_alive(): speed = chat.get() # Returns messages per minute print(f"Chat Speed: {speed} messages/min") # Detect activity spikes if speed > 100: print("High chat activity detected!") # Combined with DefaultProcessor for full data from pytchat import DefaultProcessor chat_multi = LiveChat( video_id="uIx8l2xlYVY", processor=(DefaultProcessor(), SpeedCalculator()) ) while chat_multi.is_alive(): data, speed = chat_multi.get() # Tuple of results for c in data.items: print(f"[{speed} msg/min] {c.author.name}: {c.message}") data.tick() ``` -------------------------------- ### Display chats at intervals Source: https://github.com/taizan-hokuto/pytchat/wiki/PytchatCore Iterate through chat items synchronously and print formatted messages at defined intervals. ```python import pytchat chat = pytchat.create(video_id="uIx8l2xlYVY") while chat.is_alive(): for c in chat.get().sync_items(): print(f"{c.datetime} {c.author.name} {c.message}") ``` -------------------------------- ### Archive Live Chat Data as TSV Source: https://github.com/taizan-hokuto/pytchat/wiki/TSVArchiver Use TSVArchiver to save live chat data to a specified file path. Ensure the video ID is valid and the script is run in an environment that supports asyncio. ```python import time from pytchat import TSVArchiver, LiveChat video_id = "**********" async def main(): livechat = LiveChat(video_id, processor=TSVArchiver("v:/test.txt")) while livechat.is_alive(): livechat.get() time.sleep(1) main() ``` -------------------------------- ### Output Chat Data in JSON Format Source: https://github.com/taizan-hokuto/pytchat/wiki/DefaultProcessor Retrieve chat data as JSON objects, including individual chat items. ```python chat = pytchat.create(video_id="xxxxxxxx") while chat.is_alive(): print(chat.get().json()) time.sleep(5) ''' # Each chat item can also be output in JSON format. for c in chat.get().sync_items(): print(c.json()) ''' ```