npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

yt-livechat

v2.1.1

Published

Interact with any YouTube liveChat.

Downloads

10

Readme

YT-Livechat Build StatusGreenkeeper badge

NPM

Create easily chat bots for any YouTube stream's LiveChat.

Install

Install via NPM, PNPM or Yarn from repo

$ npm i yt-livechat --save
$ pnpm i yt-livechat
$ yarn add yt-livechat

Simple example

// Import the lib
const { LiveChat } = require("yt-livechat");
// Or with TypeScript:
// import LiveChat from "yt-livechat"

// Let's do some config
const config = {
    liveChatID: process.env.LIVE_CHAT_ID || "", // ID of the LiveChat
    oauth: { // OAuth2 keys from Google Developers Console
        client_id: process.env.CLIENT_ID || "",
        client_secret: process.env.CLIENT_SECRET || "",
        refresh_token: process.env.REFRESH_TOKEN || "",
    },
};

const chat = new LiveChat(config); // Init chat object

// Register some events
chat.on("connected", () => console.log("Connected to the YouTube API."));
chat.on("error", (error) => console.log(error));

chat.on("chat", (message) => {
    console.log(`New message from ${message.authorDetails.displayName}.`);
    if (message.snippet.displayMessage === "/hello") {
        chat.say("Hello world !");
	}
});

// Start polling messages
chat.connect();

Summary

Constructor

Usage
const { LiveChat } = require("yt-livechat");
const config = { ... };
const chat = new LiveChat(config);
Config structure
{
    oauth: { // See this: https://developers.google.com/identity/protocols/OAuth2
    	client_id?: string;
    	client_secret?: string;
    	refresh_token?: string;
        access_token?: string;
   		token_type?: "Bearer" | string;
    	expiry_date?: number;
    };
    liveChatID: string; // ID of the LiveChat
    interval?: number; // Force time interval in ms between each poll.
}

You might be able to find ID of the Live Chat with this API endpoint.

Properties

auth: OAuth2Client

OAuth2 client from the google-auth-library lib. You can use it to make custom authenticated requests for example.

connected: boolean

Equals true if the lib polls messages. Else equals false.

Methods

connect(): Promise<this>

Start polling messages from the chat.

Usage
chat.connect()

disconnect(): Promise<this>

Stop polling messages from the chat.

Usage
chat.disconnect()

reconnect(): Promise<this>

Re-create OAuth client and just execute disconnect()and connect().

Usage
chat.reconnect()

say(message: string): Promise<LiveChatMessage>

Send a message.

Usage
chat.say("Hello !")

delete(messageId: string): Promise<this>

Delete a message based on his ID.

Usage
chat.delete("MESSAGE ID")

Events

connected -> ()

Emitted when the lib start polling messages from YouTube. Usually after the execution of the connect()method

Usage
chat.on('connected', () => ... )

disconnected -> ()

Emitted when the lib stop polling messages from YouTube. Usually after the execution of the disconnect()method

Usage
chat.on('disconnected', () => ... )

reconnected -> ()

Emitted when the lib reconnects to YouTube. Usually after the execution of the reconnect() methods.

Usage
chat.on('reconnected', () => ... )

polling -> ()

Emitted when the lib poll messages from YouTube. /!\ This event is usually issued a lot of times in less than a second: if you perform too many operations, you risk running out of resources!

Usage
chat.on('polling', () => ...)

tokens -> (tokens: Tokens)

Emitted when the access token is refreshed.

Usage
chat.on('tokens', (tokens) => ...)
Data structure
{
    access_token?: string;
    token_type?: "Bearer" | string;
    expiry_date?: number;
}

error -> (error: Error)

Emitted when an error occured.

Usage
chat.on('error', (error) => ...)
How to handle errors

The error object is very VERY VERY big because it contains all the request and response ! But just a small part can be enough :happy:

chat.on('error', (error) => {
    console.log(error.errors); // In this example, I faked the live chat ID to produce an error.
})

Let's take a look at the result:

[
    {
        domain: 'youtube.liveChat',
        reason: 'liveChatNotFound',
        message: 'The live chat that you are trying to retrieve cannot be found. Check the value of the requests <code>liveChatId</code> parameter to ensure that it is correct.'
    }
]

With this link to help you, I think it's enough to understand how to handle errors :smiley:

chat -> (message: LiveChatMessage)

Emitted when an user sent a message. (Pretty obvious...)

Usage
chat.on('chat', (message) => ...)
Data structure

Take a look here : https://developers.google.com/youtube/v3/live/docs/liveChatMessages#resource

Todo List

A checked item is considered as a work in progress.

  • [x] Write unit tests
  • [x] Methods should return promises (but still support events)
  • [ ] Add methods to get a Live Chat ID

Feel free to suggest features !

Feature Requests

Contributions

You're free to contribute by publishing pull requests, issues, ideas, ...

You can also buy me a drink :heart: