使用Nodejs实时取消聊天

时间:2019-04-01 18:17:49

标签: node.js firebase puppeteer

我想做的是在 NodeJs 上构建 scrap应用,通过它可以实时监控聊天并存储某些消息在任何数据库中?

我想要做的是以下操作,我想从聊天平台流中捕获数据,从而捕获一些有用的信息,以帮助那些正在进行流服务的人;

但是我不知道如何开始使用NodeJs

到目前为止,我已经能够捕获消息的数据,但是我无法实时监控新消息, 在这方面有帮助吗?

我到目前为止所做的:

server.js

var express     = require('express');
var fs          = require('fs');
var request     = require('request');
var puppeteer = require('puppeteer');
var app         = express();

app.get('/', function(req, res){

    url = 'https://www.nimo.tv/live/6035521326';

    (async() => {

        const browser = await puppeteer.launch();

        const page = await browser.newPage();
        await page.goto(url);
        await page.waitForSelector('.msg-nickname');

        const messages = await page.evaluate(() => {
            return Array.from(document.querySelectorAll('.msg-nickname'))
                    .map(item => item.innerText);
        });

        console.log(messages);
    })();
    res.send('Check your console!')

});

app.listen('8081') 
console.log('Magic happens on port 8081'); 
exports = module.exports = app;

通过此操作,我获得了“用户昵称”消息并将其放入一个数组中,我想让我的应用程序运行并在聊天中完成输入后自动接收新的昵称, 对这个挑战有帮助吗?

也许我将需要使用WebSocket

1 个答案:

答案 0 :(得分:4)

如果可能的话,您应该使用API​​,即正在使用聊天。尝试在Chrome开发者工具中打开“网络”标签,然后尝试找出正在发生的网络请求。


如果这不可能,则可以使用MutationObserver来监视DOM更改。通过page.exposeFunction公开功能,然后聆听相关更改。然后,您可以将获取的数据插入数据库中。

以下是一些示例代码,可以帮助您入门:

const puppeteer = require('puppeteer');
const { Client } = require('pg');

(async () => {
    const client = new Client(/* ... */);
    await client.connect(); // connect to database

    const browser = await puppeteer.launch({ headless: false });
    const [page] = await browser.pages();

    // call a handler when a mutation happens
    async function mutationListener(addedText) {
        console.log(`Added text: ${addedText}`);

        // insert data into database
        await client.query('INSERT INTO users(text) VALUES($1)', [addedText]);
    }
    page.exposeFunction('mutationListener', mutationListener);

    await page.goto('http://...');
    await page.waitForSelector('.msg-nickname');

    await page.evaluate(() => {
        // wait for any mutations inside a specific element (e.g. the chatbox)
        const observerTarget = document.querySelector('ELEMENT-TO-MONITOR');
        const mutationObserver = new MutationObserver((mutationsList) => {
            // handle change by checking which elements were added and which were deleted
            for (const mutation of mutationsList) {
                const { removedNodes, addedNodes } = mutation;
                // example: pass innerText of first added element to our mutationListener
                mutationListener(addedNodes[0].innerText);
            }
        });
        mutationObserver.observe( // start observer
            observerTarget,
            { childList: true }, // wait for new child nodes to be added/removed
        );
    });
})();