Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Request failed with status code 401 #44

Open
EticalPy opened this issue Jul 4, 2023 · 6 comments
Open

Request failed with status code 401 #44

EticalPy opened this issue Jul 4, 2023 · 6 comments

Comments

@EticalPy
Copy link

EticalPy commented Jul 4, 2023

Captura desde 2023-07-04 12-41-05

@fdciabdul
Copy link
Member

You need to set openAI api key

@EticalPy
Copy link
Author

EticalPy commented Jul 4, 2023

no era del api key sino de los caracteres especiales. Pero ya solucionado. Una maravilla tu bot.

@fdciabdul
Copy link
Member

no era del api key sino de los caracteres especiales. Pero ya solucionado. Una maravilla tu bot.

Qué carácter está jodiendo el funcionamiento del programa?

@EticalPy
Copy link
Author

EticalPy commented Jul 5, 2023

ăâîșț

Esta solucionado ahora. Me gustaria hablar contigo en privado. Te mando un email para ver como lo podemos hacer eso si, claro, si no te molesta. Gracias por todo. ([email protected])

@EticalPy
Copy link
Author

EticalPy commented Jul 6, 2023

Hise unas pequeñas modificaciones en multi.js si quieres los puedes añadir a tu repositorio. Se trata de getInfo pues en multi.js aiCommented no tenia informacion del video que comentaba. Te dejo mas abajo el codigo

const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth')();
const {
    executablePath
} = require('puppeteer');
const cliSpinners = require('cli-spinners');
const Spinners = require('spinnies');
const fs = require('fs');
const selector = require("./modules/constant/selector");
const {
    Config
} = require("./modules/constant/BrowserConfig")
const {
    randomUserAgent,
    subsribe,
    copycommnet,
    manualComment,
    autoscroll,
    likeVideos,
    Logger,
    getInfo,
    aiCommented,
    Banner
} = require('./modules');
const config = require('./config.multi');
const spinners = new Spinners(cliSpinners.star.frames, {
    text: 'Loading',
    stream: process.stdout,
    onTick(frame, index) {
        process.stdout.write(frame);
    },
});
puppeteer.use(StealthPlugin);
const paths = `${process.cwd()}/ublock`;
let delay = (Math.floor(Math.random() * 60) + 60) * 1000;
StealthPlugin.enabledEvasions.delete('iframe.contentWindow');
['chrome.runtime', 'navigator.languages'].forEach((a) => StealthPlugin.enabledEvasions.delete(a));
console.log(Banner.show);
async function startApp(config, browserconfig) {
    const keyword = config.keywords;
    const browser = await puppeteer.launch(browserconfig);
    const page = await browser.newPage();
    await page.setViewport({
        width: 1366,
        height: 768
    });
    await page.evaluateOnNewDocument(() => {
        delete navigator.__proto__.webdriver;
    });
    await page.setUserAgent(randomUserAgent.UA());
    await page.goto('https://accounts.google.com/signin/v2/identifier?service=youtube', {
        waituntil: "domcontentloaded"
    });
    spinners.add('user', {
        text: 'Login..',
        color: 'green'
    });
    try {
        const checklogin = await page.$(selector.checkLogin);
        await page.evaluate((el) => el.textContent, checklogin);
        spinners.succeed('user', {
            text: 'You already logged in..',
            color: 'yellow',
        });
    } catch {
        await page.waitForSelector(selector.username);
        await page.type(selector.username, config.usernamegoogle, {
            delay: 200
        });
        await page.keyboard.press('Enter');
        await page.waitForNavigation({
            waituntil: "domcontentloaded"
        });
        await page.waitForSelector(selector.showpass);
        // await page.click(selector.showpass , {delay :1000});

        await page.type(selector.password, config.passwordgoogle, {
            delay: 400
        });
        await page.keyboard.press('Enter');
        await page.waitForNavigation({
            waituntil: "domcontentloaded"
        });
    }
    console.log('=========== Start Commenting ==============');
    try {
        await subsribe.subscribeChannel(page);
    } catch (error) {
        spinners.add('sub', {
            text: 'Thank you <3',
            color: 'green',
        });
    }
    spinners.add('first-spinner', {
        text: 'Searching for videos..',
        color: 'yellow',
    });
    for (let i = 0; i < keyword.length; i++) {
        if (config.trending == true) {
            await page.goto('https://www.youtube.com/feed/trending');
            await autoscroll._autoScroll(page);
        } else {
            if (config.newVideos == true) {
                await page.goto(`https://www.youtube.com/results?search_query=${keyword[i]}&sp=CAI%253D`, );
            } else {
                await page.goto(`https://www.youtube.com/results?search_query=${keyword[i]}`, );
            }
            const element = await page.$(selector.shortvideos, );
            if (element) {
                await page.evaluate(() => {
                    document.querySelector("ytd-section-list-renderer > #contents > .style-scope:nth-child(1)").remove();
                });
            }
            await autoscroll._autoScroll(page);
        }
        await page.waitForTimeout(3000);
        spinners.succeed('first-spinner', {
            text: 'done..',
            color: 'yellow'
        });
        await page.waitForTimeout(7000);
        spinners.add('hasil', {
            text: 'Collecting videos..',
            color: 'yellow'
        });
        //collecting links
        let linked = await Promise.all((await page.$$(selector.videoTitleinSearch)).map(async a => {
            return {
                url: await (await a.getProperty('href')).jsonValue(),
                title: await (await a.getProperty('title')).jsonValue()
            };
        }));
        let hrefs = await Promise.all((await page.$$(selector.shortsTitleinSearch)).map(async a => {
            return await (await a.getProperty('href')).jsonValue();
        }));
        if (hrefs.length === 0) {
            linked.push(hrefs);
        }
        const linkz = linked.filter((el) => el.url != null);
        spinners.succeed('hasil', {
            text: `FOUND ${linkz.length}LINKS`,
            color: 'yellow',
        });
        // randomize links
        const link = linkz.sort(() => Math.random() - Math.random()).slice(0, linkz.length);
        for (let j = 0; j < link.length; j++) {
            if (readLog().includes(link[j])) {
                spinners.add('already', {
                    text: 'The video has been commented..',
                    color: 'blue',
                });
                continue;
            }
            spinners.add('comment', {
                text: 'Now commenting in the video..',
                color: 'yellow',
            });
            const tweet = link[j].url;
            const title = link[j].title;
            const pages = await browser.newPage();
            await pages.setViewport({
                width: 1366,
                height: 768
            });
            await pages.setUserAgent(randomUserAgent.UA());
            try {
                if (tweet.includes("shorts")) {
                    await pages.goto(tweet.replace(/shorts/, "watch"));
                } else {
                    // console.log(tweet);
                    await pages.goto(tweet);
                }
                try {
                    await likeVideos.likeVideos(pages);
                } catch (error) {
                    console.log(error);
                }
                await pages.bringToFront();
                await pages.waitForTimeout(4000);
                await pages.evaluate(() => {
                    window.scrollBy(0, 550);
                });
                try {
                    await pages.waitForSelector(selector.catchErrorInComment, {
                        timeout: 4000
                    });
                    console.log("Can't Comment");
                    await pages.close();
                } catch {
                    await pages.waitForSelector(selector.inputComment, {
                        timeout: 4000,
                    });
                    await pages.evaluate(() => {
                        document.querySelector('div#placeholder-area').click();
                    });
                    spinners.update('comment', {
                        text: 'So.. we need collecting those comment , so we can copy that ',
                        color: 'yellow',
                    });
                    if (config.copycomment && config.ai == false) {
                        await copycommnet.copyComment(pages, spinners, config);
                    } else if (config.ai) {
                     const info = await getInfo.extractChannelInfo(pages);
                  //   console.log(info);
                        await aiCommented.createComments(pages, spinners, info, config)
                    } else if (!config.copycomment && !config.ai) {
                        await manualComment.manualComment(pages, spinners, config);
                    } else {
                        console.log(" Check Your Configuration")
                    }
                    spinners.add('delay', {
                        text: `We will wait for ${delay} seconds`,
                        color: 'yellow',
                    });
            
                        spinners.add('act', {
                            text: `While delaying .. we actin like human to scroll comment`,
                            color: 'yellow',
                        });
                        await autoscroll._autoScroll(pages);
                 
                    await page.waitForTimeout(delay);
                    await pages.close();
                    spinners.succeed('comment', {
                        text: 'Success commenting',
                        color: 'yellow',
                    });
                    Logger.log('./logs/succesCommenting.log', config.usernamegoogle, tweet, 'success')
                }
            } catch (e) {
                console.log(e);
                //   await pages.close();
                Logger.log('./logs/errorCommenting.log', config.usernamegoogle, tweet, 'failed', e)
            }
        }
    }
    spinners.add('done', {
        text: `WE ARE DONE , THANKS FOR USING THIS APP <3`,
        color: 'green',
    });
    await browser.close();
}

async function startMulti() {
  const promiseChain = config.accounts.reduce(async (promiseChain, account) => {
    await promiseChain;
    return new Promise((resolve) => {
      setTimeout(() => {
        startApp(account, Config(paths, account, executablePath("chrome"), account.userdatadir))
          .then(resolve);
      }, 2000);
    });
  }, Promise.resolve());

  await promiseChain;
}



startMulti();
function readLog() {
    const data = fs.readFileSync('./logs/succesCommenting.log', 'utf8');
    return data;

ademas en ai.Commented.js he añadido varios promts para que la AI lo use alternativamente:

"use strict";

const { Configuration, OpenAIApi } = require("openai");

/**
 * Create comments on social video platforms through AI simulation
 * @module createComments
 * @param {any} pages
 * @param {any} spinners
 * @param {object} info - Info about the video
 * @param {object} config - Object containing apiKey parameter
 * @returns {any}
 */
const createComments = async (pages, spinners, info, config) => {
  try {
    const configuration = new Configuration({
      apiKey: config.apiKey,
    });

    const openai = new OpenAIApi(configuration);

    const prompts = [
     `simulate reply to this youtube video from channel ${info.channelName} with title "{info.title}" with natural emotion , 
     not like a bot , 
     dont act like you are suprised , 
     dont use wow ,
     Compose the entire comment as a single comprehensive paragraph without any breaks ,
     always write in Romanian  ,
     please remind that he was have subscriber {info.subscriberCount}  ,
     Also, suggest that it would be beneficial for the channel ${info.channelName} to use subtitles to increase its audience, 
     as videos like {info.title} deserve to be seen by the international public.
     If necessary, encourage him to contact you for help  ,
     \n: `,
     
     `Imagine you are a regular viewer of the channel ${info.channelName} Comment on the video titled "${info.title}" in a calm and composed manner, 
     without expressing surprise or using words like "wow". 
     Write a single, comprehensive paragraph, and do not forget to mention the subscriber count of ${info.subscriberCount}. 
     Suggest subtly that adding subtitles could help the video reach a larger, international audience, as it deserves more views. 
     Offer help, if necessary. \n: `,
     
     `Pareces ser un espectador frecuente del canal ${info.channelName}. Comenta sobre el video titulado "${info.title}" de una manera relajada y natural, 
     evitando mostrar sorpresa o usar palabras como "wow". 
     Escribe un solo párrafo coherente y no olvides mencionar la cantidad de suscriptores que tiene: ${info.subscriberCount}. 
     La respuesta debe ser en español. 
     Sugiere, de forma sutil, que agregar subtítulos podría ayudar a que el video llegue a un público más grande a nivel internacional, ya que se merece más visualizaciones. 
     Ofrece tu ayuda, si es necesario. \n: `,
  
     `Presupune că ești un vizualizator obișnuit al canalului ${info.channelName}. 
     Comentează la videoclipul cu titlul "${info.title}" într-un mod calm și natural, evitând să arăți surpriză sau folosind cuvinte ca "wow". 
     Scrie un singur paragraf comprehensiv și nu uita să menționezi numărul de abonați, care este de ${info.subscriberCount}. 
     Sugerează, subtil, că adăugarea de subtitrări ar putea ajuta videoclipul să ajungă la un public mai mare la nivel internațional, deoarece merită mai multe vizualizări. 
     Oferă ajutorul tău, dacă este necesar. \n: `
      ];

    const promptIndex = Math.floor(Math.random() * prompts.length);
    const prompt = prompts[promptIndex];

    const response = await openai.createChatCompletion({
      model: "gpt-4",
      messages: [{ role: "user", content: prompt }],
    });

    const comment = response.data.choices[0].message.content;
    await pages.keyboard.type(comment, { delay: 10 });
    await pages.waitForTimeout(100);
    await pages.keyboard.press("Enter");
    await pages.evaluate(() =>
      document.querySelector("#submit-button").click()
    );
    spinners.update("comment", { text: `Success ${comment}`, color: "blue" });
    await pages.waitForTimeout(5000);
  } catch (error) {
    console.error(`Cannot create comment!\n${error}`);
  }
};

module.exports = { createComments };

Otra modificacion que hise y creo que esta si es util es la de modificar el comportamento del delay del fichero main.js. respectivamente multi.js
Tu lo tienes en el principio lo que hace que se calcula un delay una sola vez (random, es verdad pero una sola vez). Yo lo puse abajo y recomiendo esa opcion para que el delay sea random antes de cada video

delay = (Math.floor(Math.random() * 240) + 60) * 1000;
                    spinners.add('delay', {
                        text: `We will wait for ${delay / 1000}  seconds`,
                        color: 'yellow',
                    });
            
                        spinners.add('act', {
                            text: `While delaying .. we actin like human to scroll comment`,
                            color: 'yellow',

No se si sirven mis modificaciones pero por si alquien estaria interesado
De cualquier manera, grand trabajo

@yashu1wwww
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants