youtube-chat

repository·develop·Indexed 42 days ago

https://github.com/linatsukusu/youtube-chat

A library for fetching YouTube live chat data without requiring the official YouTube API. Version 2.2.0 provides the LiveChat class to stream incoming messages using a channelId, liveId, or handle, and emits events such as 'chat', 'start', 'end', and 'error'. It processes chat data into structured ChatItem objects containing author details, message content, and superchat information.

Tokens
2.8K
Snippets
13
Records
13
Agent score
52%

What's inside youtube-chat

  1. Quickstart: Fetch YouTube live chat

    develop

    To use youtube-chat, import the LiveChat class, instantiate it with either a channelId or a liveId, set up event listeners for chat messages and lifecycle events, and then call .start().

    Note: If you provide a channelId, the library will automatically attempt to acquire the current liveId for that channel.

    const { LiveChat } = require("youtube-chat");
    
    // Recommended: use channelId to automatically find the current liveId
    const liveChat = new LiveChat({ channelId: "CHANNEL_ID_HERE" });
    
    // Listen for chat messages
    liveChat.on("chat", (chatItem) => {
      console.log(chatItem.author.name, chatItem.message);
    });
    
    // Start the fetch loop
    const ok = await liveChat.start();
    if (!ok) {
      console.log("Failed to start, check emitted error");
    }
    
    // To stop the loop later:
    // liveChat.stop();
  2. Use LiveChat events

    develop

    The LiveChat instance emits several events that you can subscribe to using .on(eventName, callback).

    • start: Emitted when the chat observation begins. Returns the liveId (string).
    • end: Emitted when the observation ends. Returns an optional reason (string).
    • chat: Emitted when a new chat item is received. Returns a ChatItem object.
    • error: Emitted when an error occurs. Returns an Error or other error object.
    // Emit at start of observation chat.
    // liveId: string
    liveChat.on("start", (liveId) => {
      /* Your code here! */
    })
    
    // Emit at end of observation chat.
    // reason: string?
    liveChat.on("end", (reason) => {
      /* Your code here! */
    })
    
    // Emit at receive chat.
    // chat: ChatItem
    liveChat.on("chat", (chatItem) => {
      /* Your code here! */
    })
    
    // Emit when an error occurs
    // err: Error or any
    liveChat.on("error", (err) => {
      /* Your code here! */
    })
  3. Reference the ChatItem data structure

    develop

    The chat event returns a ChatItem object containing information about the author, the message content, and metadata about the user's status (membership, verification, etc.).

    ChatItem Structure:

    • author: Object containing name, channelId, and optional thumbnail (ImageItem) or badge ({ thumbnail: ImageItem, label: string }).
    • message: An array of MessageItem (either text or emojis).
    • superchat: Optional object containing amount, color, and optional sticker (ImageItem).
    • isMembership: boolean
    • isVerified: boolean
    • isOwner: boolean
    • isModerator: boolean
    • timestamp: Date
    interface ChatItem {
       author: {
          name: string
          thumbnail?: ImageItem
          channelId: string
          badge?: {
             thumbnail: ImageItem
             label: string
          }
       }
       message: MessageItem[]
       superchat?: {
          amount: string
          color: string
          sticker?: ImageItem
       }
       isMembership: boolean
       isVerified: boolean
       isOwner: boolean
       isModerator: boolean
       timestamp: Date
    }
    
    type MessageItem = { text: string } | EmojiItem
    
    interface ImageItem {
      url: string
      alt: string
    }
    
    interface EmojiItem extends ImageItem {
      emojiText: string
      isCustomEmoji: boolean
    }
  4. Use the LiveChat class to listen to YouTube live chat events

    develop

    The LiveChat class is an EventEmitter used to connect to a YouTube live chat and stream incoming messages. You initialize it with a YoutubeId (which can contain a channelId, liveId, or handle) and an optional polling interval.

    To begin receiving chat items, call .start(). You can listen for the following events:

    • start: Emitted when the connection is successfully established. Carries the liveId.
    • chat: Emitted whenever a new ChatItem is fetched. Carries the chatItem object.
    • end: Emitted when the chat session is stopped. Carries an optional reason string.
    • error: Emitted when an error occurs during fetching or initialization. Carries an Error object.
    import { LiveChat } from './src/live-chat';
    
    // Initialize with a liveId, channelId, or handle
    const liveChat = new LiveChat({ liveId: 'YOUR_LIVE_VIDEO_ID' }, 2000);
    
    liveChat.on('start', (liveId) => {
      console.log(`Started listening to live chat for: ${liveId}`);
    });
    
    liveChat.on('chat', (chatItem) => {
      console.log('New message:', chatItem);
    });
    
    liveChat.on('error', (err) => {
      console.error('Chat error:', err);
    });
    
    liveChat.on('end', (reason) => {
      console.log('Chat ended:', reason);
    });
    
    await liveChat.start();
    
    // Later, to stop polling:
    // liveChat.stop('Manual stop');
  5. Control the LiveChat lifecycle with start() and stop()

    develop

    Use start() to begin the polling process and stop() to terminate it.

    • start(): An asynchronous method that attempts to fetch the live page options. If successful, it sets up a periodic interval to fetch chat items and emits the start event. Returns true if started, false if already running or if an error occurred.
    • stop(reason?: string): Clears the internal polling interval and emits the end event with the provided reason.
    const liveChat = new LiveChat({ liveId: '...' });
    
    // Start polling
    const success = await liveChat.start();
    
    if (success) {
      // ... listen to events ...
    }
    
    // Stop polling
    liveChat.stop('Closing application');
  6. Use the LiveChat class

    develop

    The LiveChat class is the primary entry point for interacting with YouTube live chat. You can import it from the youtube-chat package to manage live chat sessions.

    import { LiveChat } from "youtube-chat";
    
    // Usage depends on the implementation details of LiveChat
    // typically involving providing a video ID or chat ID.
  7. Initialize LiveChat with YoutubeId

    develop

    The LiveChat constructor requires a YoutubeId object. The object must contain at least one of the following keys:

    • liveId: The specific ID of the live broadcast.
    • channelId: The ID of the YouTube channel.
    • handle: The YouTube handle of the creator.

    If none of these are provided, the constructor throws a TypeError.

    // Example valid YoutubeId shapes:
    new LiveChat({ liveId: 'abc123xyz' });
    new LiveChat({ channelId: 'UC...' });
    new LiveChat({ handle: '@username' });
  8. Use the ChatItem interface for processed chat data

    develop

    The ChatItem interface represents the structured format of a single chat entry after processing. It contains information about the author, the message content (which can be text or emojis), superchat details, and user status flags (membership, verification, ownership, and moderation).

    export interface ChatItem {
      id: string
      author: {
        name: string
        thumbnail?: ImageItem
        channelId: string
        badge?: {
          thumbnail: ImageItem
          label: string
        }
      }
      message: MessageItem[]
      superchat?: {
        amount: string
        color: string
        sticker?: ImageItem
      }
      isMembership: boolean
      isVerified: boolean
      isOwner: boolean
      isModerator: boolean
      timestamp: Date
    }
  9. Identify YouTube targets with YoutubeId

    develop

    The YoutubeId type is a union used to specify which YouTube entity to target for chat retrieval. It can be identified by a channelId, a liveId (for a specific live stream), or a handle.

    export type YoutubeId = { channelId: string } | { liveId: string } | { handle: string }
  10. Use EmojiItem for custom emoji data

    develop

    The EmojiItem interface extends ImageItem and is used when a chat message contains a custom emoji. It includes the emojiText and a flag isCustomEmoji to distinguish it from standard images.

    export interface EmojiItem extends ImageItem {
      emojiText: string
      isCustomEmoji: boolean
    }