-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
169 lines (135 loc) · 4.57 KB
/
main.js
File metadata and controls
169 lines (135 loc) · 4.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
const puppeteer = require("puppeteer");
const { speak } = require("./tts");
const https = require("https");
const videoUrl = "https://www.youtube.com/watch?v=CODE";
let continuation = null;
let clientVersion = null;
const seenMessageIds = new Set();
const messageQueue = [];
let isSpeaking = false;
async function processQueue() {
if (isSpeaking) return;
if (!messageQueue.length) return;
isSpeaking = true;
const message = messageQueue.shift();
await new Promise((resolve) => {
speak(message, { voice: "Microsoft Zira Desktop", speed: 1.0 });
const duration = Math.max(message.length * 150, 3000);
setTimeout(resolve, duration);
});
isSpeaking = false;
if (messageQueue.length) processQueue();
}
async function initContinuation() {
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
await page.goto(videoUrl, { waitUntil: "networkidle2" });
const html = await page.content();
await browser.close();
const contMatch = html.match(/"continuation":"(.*?)"/);
const versionMatch = html.match(/"clientVersion":"(.*?)"/);
if (!contMatch || !versionMatch) {
console.error("Failed to get continuation or clientVersion");
process.exit(1);
}
continuation = contMatch[1];
clientVersion = versionMatch[1];
console.log("Initialization complete");
}
function postJSON(url, data) {
return new Promise((resolve, reject) => {
const parsedUrl = new URL(url);
const options = {
hostname: parsedUrl.hostname,
path: parsedUrl.pathname + parsedUrl.search,
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(JSON.stringify(data)),
"User-Agent": "Mozilla/5.0",
},
};
const req = https.request(options, (res) => {
let body = "";
res.on("data", (chunk) => (body += chunk));
res.on("end", () => resolve(JSON.parse(body)));
});
req.on("error", (err) => reject(err));
req.write(JSON.stringify(data));
req.end();
});
}
async function skipOldMessages() {
const url =
"https://www.youtube.com/youtubei/v1/live_chat/get_live_chat?prettyPrint=false";
try {
const payload = {
context: { client: { clientName: "WEB", clientVersion } },
continuation,
};
const data = await postJSON(url, payload);
const actions =
data.continuationContents.liveChatContinuation.actions || [];
for (const action of actions) {
try {
const msgData =
action.addChatItemAction.item.liveChatTextMessageRenderer;
const messageId = msgData.id;
seenMessageIds.add(messageId);
} catch {}
}
const continuations =
data.continuationContents.liveChatContinuation.continuations[0];
continuation =
continuations.invalidationContinuationData?.continuation ||
continuations.timedContinuationData?.continuation;
console.log(
`Skipped ${seenMessageIds.size} old messages, now listening for new messages...`
);
} catch (err) {
console.error("Error skipping old messages:", err);
}
}
async function pollChat() {
const url =
"https://www.youtube.com/youtubei/v1/live_chat/get_live_chat?prettyPrint=false";
while (true) {
try {
const payload = {
context: { client: { clientName: "WEB", clientVersion } },
continuation,
};
const data = await postJSON(url, payload);
const continuations =
data.continuationContents.liveChatContinuation.continuations[0];
continuation =
continuations.invalidationContinuationData?.continuation ||
continuations.timedContinuationData?.continuation;
const actions =
data.continuationContents.liveChatContinuation.actions || [];
for (const action of actions) {
try {
const msgData =
action.addChatItemAction.item.liveChatTextMessageRenderer;
const messageId = msgData.id;
if (seenMessageIds.has(messageId)) continue;
seenMessageIds.add(messageId);
const author = msgData.authorName.simpleText;
const message = msgData.message.runs[0].text;
console.log(`${author} says: ${message}`);
messageQueue.push(`${author} says: ${message}`);
processQueue();
} catch {}
}
await new Promise((resolve) => setTimeout(resolve, 1500));
} catch (err) {
console.error("Error fetching chat:", err);
await new Promise((resolve) => setTimeout(resolve, 5000));
}
}
}
(async () => {
await initContinuation();
await skipOldMessages();
pollChat();
})();