### Build and Run Masterchat Examples (Bash) Source: https://github.com/sigvt/masterchat/blob/master/examples/README.md Provides the necessary bash commands to install dependencies, build the main project, navigate to the examples directory, install example dependencies, and execute the example scripts using node and ts-node. ```bash # build masterchat yarn install yarn build # move to examples folder cd ./examples yarn install # run example scripts node ./iter.mjs yarn ts-node ./iter.ts # ... ``` -------------------------------- ### Start Masterchat Development Server - Bash Source: https://github.com/sigvt/masterchat/blob/master/CONTRIBUTING.md Starts the development server for the masterchat project using yarn. ```bash yarn dev ``` -------------------------------- ### Build Masterchat Project - Bash Source: https://github.com/sigvt/masterchat/blob/master/CONTRIBUTING.md Clones the masterchat repository, switches to the development branch, installs dependencies, and builds the project. ```bash git clone https://github.com/holodata/masterchat cd masterchat git switch dev yarn install yarn build ``` -------------------------------- ### Release Masterchat Project - Bash Source: https://github.com/sigvt/masterchat/blob/master/CONTRIBUTING.md Initiates the release process for the masterchat project using the 'np' tool (Maintainers only). ```bash np ``` -------------------------------- ### Install Masterchat Library (npm) Source: https://github.com/sigvt/masterchat/blob/master/README.md This command installs the core Masterchat library as a project dependency using npm. ```bash npm install masterchat ``` -------------------------------- ### Install Masterchat CLI (npm) Source: https://github.com/sigvt/masterchat/blob/master/README.md This command installs the Masterchat command-line interface globally using npm, allowing it to be run from any terminal. ```bash npm i -g masterchat-cli ``` -------------------------------- ### Running the Electron App - Shell Source: https://github.com/sigvt/masterchat/blob/master/extra/credential-fetcher/README.md This command launches the Electron application from the current directory. It is the standard way to start an Electron app during development or testing. ```Shell electron . ``` -------------------------------- ### Getting video transcript (JavaScript) Source: https://github.com/sigvt/masterchat/blob/master/MANUAL.md Shows how to fetch the video transcript using `new Masterchat()` and the `mc.getTranscript()` method. It demonstrates iterating through the transcript items and printing their start time in milliseconds and the text snippet. ```javascript import { Masterchat, stringify } from "masterchat"; const mc = new Masterchat("", ""); const transcript = await mc.getTranscript(); for (const item of transcript) { console.log(item.startMs, stringify(item.snippet)); } ``` -------------------------------- ### Link Masterchat and Masterchat-CLI for Development - Bash Source: https://github.com/sigvt/masterchat/blob/master/CONTRIBUTING.md Builds and links the masterchat project locally, then clones, builds, and links the masterchat-cli project, finally linking masterchat-cli to the local masterchat build for testing. ```bash yarn build yarn link cd .. git clone https://github.com/holodata/masterchat-cli cd masterchat-cli yarn install yarn build yarn link yarn link masterchat DEBUG=masterchat mc live DEBUG=masterchat mc events ``` -------------------------------- ### Initializing Masterchat and getting metadata (JavaScript) Source: https://github.com/sigvt/masterchat/blob/master/MANUAL.md Demonstrates how to initialize the Masterchat library using `Masterchat.init()` with a video ID to fetch basic video metadata such as the title, channel ID, and channel name. ```javascript import { Masterchat, stringify } from "masterchat"; const { title, channelId, channelName } = await Masterchat.init(""); console.log(`info: ${title} @ ${channelName} (${channelId})`); ``` -------------------------------- ### Run Jest Tests with Recorded Fixtures - Bash Source: https://github.com/sigvt/masterchat/blob/master/CONTRIBUTING.md Executes Jest tests using previously recorded network response fixtures. ```bash jest ``` -------------------------------- ### Watch Live Chats using Masterchat CLI (bash) Source: https://github.com/sigvt/masterchat/blob/master/README.md This command uses the installed Masterchat CLI to watch live chats, demonstrating how to filter or specify parameters, such as watching chats for a specific organization like Hololive. ```bash mc watch --org Hololive ``` -------------------------------- ### Record Test Fixtures with Jest - Bash Source: https://github.com/sigvt/masterchat/blob/master/CONTRIBUTING.md Runs Jest tests in record mode to capture network responses and save them as fixtures for future test runs. ```bash NOCK_BACK_MODE=record jest ``` -------------------------------- ### Disable Test Fixtures with Jest - Bash Source: https://github.com/sigvt/masterchat/blob/master/CONTRIBUTING.md Runs Jest tests without using recorded fixtures, allowing tests to make live network requests. ```bash NOCK_BACK_MODE=wild jest ``` -------------------------------- ### Getting video comments (JavaScript) Source: https://github.com/sigvt/masterchat/blob/master/MANUAL.md Explains how to fetch video comments (distinct from live chats) using `new Masterchat()` and the `mc.getComments()` method. It shows how to iterate through paginated comment results and how to retrieve a specific comment by its ID using `mc.getComment()`. Requires a video ID and an empty string for channel ID when instantiating. ```javascript import { Masterchat } from "masterchat"; const mc = new Masterchat("", ""); // Iterate over all comments let res = await mc.getComments({ top: true }); while (true) { console.log(res.comments); if (!res.next) break; res = await res.next(); } // Get comment by id const comment = await mc.getComment(""); console.log(comment); ``` -------------------------------- ### Iterating live chats using Event Emitter API (JavaScript) Source: https://github.com/sigvt/masterchat/blob/master/MANUAL.md Shows how to use the event emitter pattern to listen for various live chat events, including new chat messages, all actions, errors, and the end of the stream. It lists common error codes and requires calling `mc.listen()` to start polling. ```javascript import { Masterchat, stringify } from "masterchat"; const mc = await Masterchat.init(""); // Listen for live chat mc.on("chat", (chat) => { console.log(chat.authorName, stringify(chat.message)); }); // Listen for any events // See below for a list of available action types mc.on("actions", (actions) => { const chats = actions.filter( (action) => action.type === "addChatItemAction" ); const superChats = actions.filter( (action) => action.type === "addSuperChatItemAction" ); const superStickers = actions.filter( (action) => action.type === "addSuperStickerItemAction" ); // ... }); // Handle errors mc.on("error", (err) => { console.log(err.code); // "disabled" => Live chat is disabled // "membersOnly" => No permission (members-only) // "private" => No permission (private video) // "unavailable" => Deleted OR wrong video id // "unarchived" => Live stream recording is not available // "denied" => Access denied (429) // "invalid" => Invalid request }); // Handle end event mc.on("end", () => { console.log("Live stream has ended"); }); // Start polling live chat API mc.listen(); ``` -------------------------------- ### Listening for Masterchat Events (After v0.12.0) - JavaScript Source: https://github.com/sigvt/masterchat/blob/master/CHANGELOG.md This snippet illustrates the updated event-driven approach for handling Masterchat actions introduced in version 0.12.0. It attaches listeners for "chats" and "error" events using the `.on()` method and starts processing by calling `.listen()`. The `mc.stop()` method is used to halt processing. ```JavaScript const mc = new Masterchat(videoId, ...) .on("chats", chats => { ... if (youWant) mc.stop(); }) .on("error", err => { ... }) mc.listen() ``` -------------------------------- ### Faster Masterchat instantiation and metadata population (JavaScript) Source: https://github.com/sigvt/masterchat/blob/master/MANUAL.md Describes an alternative, faster way to instantiate `Masterchat` by providing the video ID and channel ID directly (`new Masterchat(videoId, channelId, { mode })`), which skips the initial metadata fetching done by `Masterchat.init()`. It then shows how to explicitly fetch the metadata later if needed using `await live.populateMetadata()`. ```javascript const live = new Masterchat(videoId, channelId, { mode: "live" }); // To get metadata later: await live.populateMetadata(); // will scrape metadata from watch page console.log(live.title); console.log(live.channelName); ``` -------------------------------- ### Initialize Masterchat with Credentials (JavaScript) Source: https://github.com/sigvt/masterchat/blob/master/MANUAL.md Demonstrates how to initialize the Masterchat client using a previously obtained credential token string. The token is passed as part of the options object during initialization. ```javascript const credentials = "eyJTSUQiOiJL[omit]iJBSEwx"; const client = await Masterchat.init(id, { credentials }); ``` -------------------------------- ### Fetch Masterchat Credentials (Bash) Source: https://github.com/sigvt/masterchat/blob/master/MANUAL.md Instructions to run the credential-fetcher tool located in the extra directory. This script uses Electron to log in and output a credential token required for Masterchat initialization. ```bash cd extra/credentials-fetcher npm i npm start ``` -------------------------------- ### Initialize Masterchat and Process Live Chats (JavaScript) Source: https://github.com/sigvt/masterchat/blob/master/README.md This JavaScript snippet demonstrates how to initialize Masterchat for a specific video ID, iterate through incoming live chat actions, filter for chat messages, and print the author's name and the message content. ```js import { Masterchat, stringify } from "masterchat"; const mc = await Masterchat.init("oyxvhJW1Cf8"); const chats = mc.iter().filter((action) => action.type === "addChatItemAction"); for await (const chat of chats) { console.log(`${chat.authorName}: ${stringify(chat.message)}`); } ``` -------------------------------- ### Initialize Masterchat with Custom Axios Client (JavaScript) Source: https://github.com/sigvt/masterchat/blob/master/MANUAL.md Shows how to configure the Masterchat client to use a custom Axios instance. This allows for advanced configuration of HTTP requests, such as setting timeouts or managing HTTPS agents. ```javascript import axios from "axios"; import https from "https"; import { Masterchat } from "masterchat"; const axiosInstance = axios.create({ timeout: 4000, httpsAgent: new https.Agent({ keepAlive: true }), }); const mc = await Masterchat.init("", { axiosInstance }); ``` -------------------------------- ### Iterating live chats using Async Iterator API (JavaScript) Source: https://github.com/sigvt/masterchat/blob/master/MANUAL.md Illustrates how to fetch live chat actions using the async iterator pattern (`for await...of`) provided by `mc.iter()`. It shows filtering for chat messages and includes error handling using `try...catch` and checking for `MasterchatError` instances. ```javascript import { Masterchat, MasterchatError, stringify } from "masterchat"; try { const mc = await Masterchat.init(""); const chats = mc .iter() .filter((action) => action.type === "addChatItemAction"); for await (const chat of chats) { console.log(`${chat.authorName}: ${stringify(chat.message)}`); } } catch (err) { // Handle errors if (err instanceof MasterchatError) { console.log(err.code); // "disabled" => Live chat is disabled // "membersOnly" => No permission (members-only) // "private" => No permission (private video) // "unavailable" => Deleted OR wrong video id // "unarchived" => Live stream recording is not available // "denied" => Access denied (429) // "invalid" => Invalid request return; } throw err; } console.log("Live stream has ended"); ``` -------------------------------- ### Saving replay chats to JSONL file (JavaScript) Source: https://github.com/sigvt/masterchat/blob/master/MANUAL.md Shows how to fetch replay chat actions using the async iterator, filter for chat messages, convert each chat object to a JSON string followed by a newline (JSONL format), and append it to a local file using Node.js file system promises. ```javascript import { Masterchat } from "masterchat"; import { appendFile, writeFile, readFile } from "node:fs/promises"; const mc = await Masterchat.init(""); await mc .iter() .filter((action) => action.type === "addChatItemAction") // only chat events .map((chat) => JSON.stringify(chat) + "\n") // convert to JSONL .forEach((jsonl) => appendFile("./chats.jsonl", jsonl)) // append to the file ``` -------------------------------- ### Implementing a chat moderation bot (JavaScript) Source: https://github.com/sigvt/masterchat/blob/master/MANUAL.md Demonstrates creating a basic moderation bot that connects to live chat using provided YouTube session credentials. It iterates through chat messages, checks for spam using an external library (`spamreaper`) or specific keywords, and removes flagged messages using the `mc.remove()` method. ```javascript import { Masterchat, stringify } from "masterchat"; import { isSpam } from "spamreaper"; // \`credentials\` is an object containing YouTube session cookie or a base64-encoded JSON string of them const credentials = { SAPISID: "", APISID: "", HSID: "", SID: "", SSID: "" }; const mc = await Masterchat.init("", { credentials }); const iter = mc.iter().filter((action) => action.type === "addChatItemAction"); for await (const chat of iter) { const message = stringify(chat.message, { // omit emojis emojiHandler: (emoji) => "" }); if (isSpam(message) || /UGLY/.test(message)) { // delete chat // if flagged as spam by Spamreaper // or contains "UGLY" await mc.remove(action.id); } } ``` -------------------------------- ### Iterating Masterchat Actions (Before v0.12.0) - JavaScript Source: https://github.com/sigvt/masterchat/blob/master/CHANGELOG.md This snippet shows the previous method for processing chat actions in Masterchat before version 0.12.0. It uses the `iterate()` method with a `for await...of` loop to asynchronously fetch and process actions, filtering for chat messages. It includes basic error handling. ```JavaScript const mc = new Masterchat(videoId, ...) try { for await (const { actions } of mc.iterate()) { const chats = actions.filter(action => action.type === "addChatItemAction") ... if (youWant) break; } } catch(err) { ... } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.