NopeCHALLC / nopecha-extension

Automated CAPTCHA solver for your browser. Works with Selenium, Puppeteer, Playwright, and more.
MIT License
6.92k stars 99 forks source link

How can i programmatically enter api key for browser extension? #56

Closed magaldima closed 4 months ago

magaldima commented 4 months ago

Hi, I want to programmatically enter my subscription API Key to use as part of a browser extension programmatically. How can I do this?

Le0Developer commented 4 months ago

https://developers.nopecha.com/guides/extension_advanced/

j-w-yun commented 4 months ago

You have a couple ways:

  1. Pre-configure your extension using the automation version. More details here.
  2. Use a URL to set the extension settings. Export your extension settings in URL format using the extension and when you open the link while the extension is installed, your settings will be imported automatically. More details here This method does not work for the automation version.

Below code snippets are examples for method (1).

Python example:

import json, os, requests, tempfile, zipfile
from playwright.sync_api import sync_playwright  # pip install pytest-playwright && python -m playwright install

def download_file(url, local_filename):
    with requests.get(url, stream=True) as r:
        r.raise_for_status()
        with open(local_filename, 'wb') as f:
            for chunk in r.iter_content(chunk_size=8192):
                f.write(chunk)
    return local_filename

def unzip_file(zip_path, extract_to):
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        zip_ref.extractall(extract_to)

def edit_manifest(extension, key):
    manifest_path = os.path.join(extension, 'manifest.json')
    with open(manifest_path, 'r') as f:
        manifest = json.load(f)
    manifest['nopecha']['key'] = key
    with open(manifest_path, 'w') as f:
        json.dump(manifest, f, indent=4)

def download_extension(key, extension):
    url = 'https://github.com/NopeCHALLC/nopecha-extension/releases/latest/download/chromium_automation.zip'
    # Download and extract
    zip_path = 'chromium.zip'
    download_file(url, zip_path)
    unzip_file(zip_path, extension)
    # Edit manifest.json
    edit_manifest(extension, key)

if __name__ == '__main__':
    key = '<YOUR_NOPECHA_KEY>'  # Replace with your NopeCHA API key
    extension = 'nopecha_extension'  # Extension directory
    download_extension(key, extension)

    with sync_playwright() as playwright:
        tmp_dir = tempfile.TemporaryDirectory()
        context = playwright.chromium.launch_persistent_context(
            user_data_dir=tmp_dir.name,
            headless=False,
            no_viewport=True,
            args=[f'--disable-extensions-except={extension}', f'--load-extension={extension}'],
            ignore_default_args=['--enable-automation'],
        )
        page = context.pages[0]
        page.goto('https://nopecha.com/captcha/recaptcha')
        input('Press any key to exit...')
        context.close()

Node.js example:

const puppeteer = require('puppeteer')  // npm install puppeteer
const fs = require('fs')
const https = require('https')
const unzipper = require('unzipper')  // npm install unzipper

async function resolveUrl(url) {
    return new Promise((resolve, reject) => {
        https.get(url, r => {
            const status = r.statusCode ?? 0
            if (status >= 300 && status < 400 && r.headers.location) resolve(resolveUrl(r.headers.location))
            else if (status === 200) resolve(url)
            else reject(new Error(`Failed to resolve URL: ${url} (status code: ${status})`))
        }).on('error', err => reject(err))
    })
}

async function downloadFile(url, dest) {
    url = await resolveUrl(url)
    return new Promise((resolve, reject) => {
        const file = fs.createWriteStream(dest)
        https.get(url, r => {
            if (r.statusCode !== 200) return reject(new Error(`failed to download '${url}' (${r.statusCode})`))
            r.pipe(file)
        })
        file.on('finish', () => file.close(resolve))
        file.on('error', err => fs.unlink(dest, () => reject(err)))
    })
}

async function unzipFile(zipPath, dest) {
    return fs.createReadStream(zipPath).pipe(unzipper.Extract({ path: dest })).promise()
}

async function download_extension(key, extension) {
    const url = 'https://github.com/NopeCHALLC/nopecha-extension/releases/latest/download/chromium_automation.zip'
    const zipPath = 'chromium.zip'
    // Download and extract
    await downloadFile(url, zipPath)
    await unzipFile(zipPath, extension)
    // Edit manifest.json
    const fp = `${extension}/manifest.json`
    const data = fs.readFileSync(fp)
    const manifest = JSON.parse(data.toString())
    manifest.nopecha.key = key
    fs.writeFileSync(fp, JSON.stringify(manifest, null, 4))
}

async function main() {
    const key = '<YOUR_NOPECHA_KEY>'  // Replace with your NopeCHA API key
    const extension = 'nopecha_extension'  // Extension directory
    await download_extension(key, extension)

    const browser = await puppeteer.launch({
        headless: false,
        defaultViewport: null,
        args: [`--disable-extensions-except=${extension}`, `--load-extension=${extension}`],
    })
    const [page] = await browser.pages()
    await page.goto('https://nopecha.com/captcha')
    // await browser.close()
}

if (require.main === module) main()