summaryrefslogtreecommitdiff
path: root/index.js
blob: 88930aab2c27b83e0775183228c737da844c5ce7 (plain)
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
const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth')
puppeteer.use(StealthPlugin())
 
async function goThere(channel) {
  const browser = await puppeteer.launch({
    headless: 'new',
    // need real Chrome to stream video
    executablePath: '/usr/bin/google-chrome-stable',
  });
  const page = await browser.newPage();
  await page.goto(
    `https://www.twitch.tv/${channel}`,
    { waitUntil: 'domcontentloaded', timeout: 60000 },
  );
 
  // set some bits to cheat Twitch a bit more
  await page.evaluate(() => {
    localStorage.setItem(
      'content-classification-labels-acknowledged',
      `{"loggedIn":{},"loggedOut":{"MatureGame":${Date.now() + 86400000}}}`,
    );
    localStorage.setItem('video-muted', '{"default":false}');
    localStorage.setItem('volume', '0.5');
    localStorage.setItem('video-quality', '{"default":"160p30"}');
  });
 
  await page.setViewport({ width: 1280, height: 720 });
  await page.reload({
    waitUntil: ['domcontentloaded']
  });
 
  return {browser,page};
}
 
// scrape comments, just to pretend we're doing something useful
async function seeComments(page) {
  /* wait for chat to be visible */
  await page.waitForSelector(
    'div.chat-shell',
    { timeout: 60000 },
  );
 
  try {
    let chatText = await page.evaluate(() => {
      let scrapeComments = [];
      const comments = document.querySelectorAll('div.chat-line__message');
 
      comments.forEach(comment => {
        const commentAuthor = comment.querySelector('span.chat-line__username span.chat-author__display-name').innerText;
        const commentContent = comment.querySelector('span.text-fragment')?.innerText;
 
        scrapeComments.push({ commentAuthor, commentContent });
      });
 
      return { 'userComments': scrapeComments };
    });
 
    console.log(await chatText);
  } catch (err) {
    console.log(err.message);
  }
}
 
// there must be some more built-in way to do this...
function delayP(delay) {
  return new Promise((resolve, reject) => {
    setTimeout(
      () => { resolve(1) },
      delay,
    );
  });
}
 
(async () => {
  const channel = 'yogscast'; // a random channel
  const runForMs = 3600 * 1000; // 1 hour
 
  const x = await goThere(channel);
 
  const started = Date.now();
 
  while ((Date.now() - started) < runForMs ) {
    await seeComments(x.page);
    await delayP(5000);
  }
 
  await x.browser.close();
})();