GithubHelp home page GithubHelp logo

nopechallc / nopecha-python Goto Github PK

View Code? Open in Web Editor NEW
968.0 2.0 6.0 44 KB

Automated CAPTCHA solver for Python.

License: MIT License

Python 100.00%
aws-waf-captcha captcha funcaptcha funcaptcha-bypass funcaptcha-solver hcaptcha hcaptcha-bypass hcaptcha-solver recaptcha recaptcha-bypass

nopecha-python's Introduction

NopeCHA

PyPI - Version NPM Version GitHub Release Chrome Web Store Version Mozilla Add-on Version

API bindings for the NopeCHA CAPTCHA service.

Installation

To install from PyPI, run python3 -m pip install nopecha.

API Usage

This package provides API wrappers for the following http packages:

Note: You will need to install the http package you want to use separately (except for urllib, as it's built-in but not recommended).

Requests example

from nopecha.api.requests import RequestsAPIClient

api = RequestsAPIClient("YOUR_API_KEY")
solution = api.solve_hcaptcha("b4c45857-0e23-48e6-9017-e28fff99ffb2", "https://nopecha.com/demo/hcaptcha#easy")

print("token is", solution["data"])

Async HTTPX example

from nopecha.api.httpx import AsyncHTTPXAPIClient

async def main():
    api = AsyncHTTPXAPIClient("YOUR_API_KEY")
    solution = await api.solve_hcaptcha("b4c45857-0e23-48e6-9017-e28fff99ffb2", "https://nopecha.com/demo/hcaptcha#easy")
    print("token is", solution["data"])

asyncio.run(main())

Extension builder

This package also provides a extension builder for Automation builds which includes:

  1. downloading the extension
  2. updating the extension
  3. updating the extension's manifest to include your settings

Example

from nopecha.extension import build_chromium

# will download the extension to the current working directory
output = build_chromium({
    "key": "YOUR_API_KEY",
})

# custom output directory
from pathlib import Path
output = build_chromium({
    "key": "YOUR_API_KEY",
}, Path("extension"))

You can plug the output path directly into your browser's extension manager to load the extension:

import undetected_chromedriver as uc
from nopecha.extension import build_chromium

output = build_chromium({
    "key": "YOUR_API_KEY",
})

options = uc.ChromeOptions()
options.add_argument(f"load-extension={output}")

Building

To build from source, you will need to install build (python3 -m pip install --upgrade build ).

Then simply run python3 -m build to build the package.

Uploading to PyPI

To upload to PyPI, you will need to install twine (python3 -m pip install --upgrade twine).

Then simply run python3 -m twine upload dist/* to upload the package.

Migrate from v1

If you are migrating from v1, you will need to update your code to use the new client classes.

V1 was synchronous only, using the requests HTTP library. V2 supports both synchronous and asynchronous code, and multiple HTTP libraries.

To migrate, you will need to:

  1. Install the http library you want to use (requests, aiohttp, httpx) or use the built-in urllib.
  2. Replace nopecha.api_key with creating a client instance.
# Before
import nopecha

nopecha.api_key = "YOUR_API_KEY"

# Now
from nopecha.api.requests import RequestsAPIClient

client = RequestsAPIClient("YOUR_API_KEY")
  1. Replace nopecha.Token.solve()/nopecha.Recognition.solve()/nopecha.Balance.get() with the appropriate method on the client instance.
# Before
import nopecha
nopecha.api_key = "..."

clicks = nopecha.Recognition.solve(
    type='hcaptcha',
    task='Please click each image containing a cat-shaped cookie.',
    image_urls=[f"https://nopecha.com/image/demo/hcaptcha/{i}.png" for i in range(9)],
)
print(clicks)

token = nopecha.Token.solve(
    type='hcaptcha',
    sitekey='ab803303-ac41-41aa-9be1-7b4e01b91e2c',
    url='https://nopecha.com/demo/hcaptcha',
)
print(token)

balance = nopecha.Balance.get()
print(balance)

# Now
from nopecha.api.requests import RequestsAPIClient

client = RequestsAPIClient("YOUR_API_KEY")

clicks = client.recognize_hcaptcha(
    'Please click each image containing a cat-shaped cookie.',
    [f"https://nopecha.com/image/demo/hcaptcha/{i}.png" for i in range(9)],
)
print(clicks)

token = client.solve_hcaptcha(
    'ab803303-ac41-41aa-9be1-7b4e01b91e2c',
    'https://nopecha.com/demo/hcaptcha',
)
print(token)

balance = client.status()
print(balance)

nopecha-python's People

Contributors

j-w-yun avatar le0developer avatar nopechallc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

nopecha-python's Issues

HTTP 409 (Conflict) hcaptcha error.

private async void nopecatpchatken_Click(object sender, EventArgs e)
{
string apiKey = "I'm Api Key"; // API anahtarınızı buraya ekleyin
string siteKey = "ab803303-ac41-41aa-9be1-7b4e01b91e2c";
string apiUrl = "https://api.nopecha.com/token";

    // hCaptcha request
    using (HttpClient client = new HttpClient())
    {
        var requestContent = new
        {
            type = "hcaptcha",
            sitekey = siteKey,
            url = "https://nopecha.com/demo/hcaptcha#hard",
            key = apiKey
        };

        var response = await client.PostAsJsonAsync(apiUrl, requestContent);

        if (response.IsSuccessStatusCode)
        {
            var responseData = await response.Content.ReadAsAsync<dynamic>();
            string job_id = responseData.data;

            // hCaptcha HTTP 409 ERROR
            var tokenResponse = await client.GetStringAsync($"{apiUrl}?key={apiKey}&id={job_id}");
            var hCaptchaToken = tokenResponse.Trim();

           nopecaptchatext.Text = $"hCaptcha Token: {hCaptchaToken}";
        }
        else
        {
            nopecaptchatext.Text =  $"Error: {response.StatusCode} - {response.ReasonPhrase}";
        }
    }
}

Times out after 10 retries

After using the token solve api via this extension it returns a timed out after 10 retries. It shows up in the activity monitor but doesn't get past the POST, it returns the data of the POST and gets stuck at the GET nor does it show the GET in the activity monitor leaving me to believe it's an API issue and not an extension. I have no idea where else to report this issue however.

why am i getting 502 response can anyone help me pls?

I'm trying something for hobby purposes but I'm getting an error.

vote system for https://minecraftbestservers.com/server-complex-gaming.77/vote

I am getting token but when i try the api always happen the 502 response, main request method is send_vote method.

import random
import time
import cloudscraper
from itertools import cycle
from random_user_agent.user_agent import UserAgent
from random_user_agent.params import SoftwareName, OperatingSystem
import urllib.parse


# Load proxies from a file
def load_proxies(filepath):
    with open(filepath, 'r') as file:
        return [line.strip() for line in file.readlines()]


# Constants
PROXY_FILE = 'proxies.txt'  # Adjust this to your proxy file's path
proxies = load_proxies(PROXY_FILE)
proxy_pool = cycle(proxies)


def case_variations(text):
    if not text:
        yield ""
    else:
        first, rest = text[0], text[1:]
        for variant in case_variations(rest):
            yield first.lower() + variant
            yield first.upper() + variant


class SessionManager:
    def __init__(self):
        # Initialize cloudscraper to handle Cloudflare's challenges
        self.scraper = cloudscraper.create_scraper()
        # Initialize user agent rotator specifically for Windows Chrome browsers
        self.user_agent_rotator = UserAgent(software_names=[SoftwareName.CHROME.value],
                                            operating_systems=[OperatingSystem.WINDOWS.value])
        self.update_session()  # Initialize session with first proxy and user agent

    def get_next_proxy(self):
        # Cycle through the proxy pool and return the next available proxy
        return next(proxy_pool)

    def parse_proxy(self, proxy):
        # Parse the proxy string to extract HTTP proxy settings only
        ip_port, username, password = proxy.rsplit(':', 2)
        ip, port = ip_port.rsplit(':', 1)
        return {
            'http': f'http://{username}:{password}@{ip}:{port}',
            # Comment out the HTTPS part if proxy only supports HTTP
            # 'https': f'https://{username}:{password}@{ip}:{port}'
        }

    def renew_session(self):
        # Reset the existing session and update it with new settings
        self.scraper = cloudscraper.create_scraper()
        self.update_session()

    def update_session(self):
        # Update session with a new proxy and user agent
        proxy_settings = self.parse_proxy(self.get_next_proxy())
        self.scraper.proxies.update(proxy_settings)
        new_user_agent = self.user_agent_rotator.get_random_user_agent()
        self.scraper.headers.update({'User-Agent': new_user_agent})
        print(f"Using proxy: {proxy_settings} and User-Agent: {new_user_agent}")

    def fetch_captcha_token(self, err_count=0):
        if err_count >= 10:
            return "Max retries reached."

        try:
            # Get the current proxy details from the session
            current_proxy = self.scraper.proxies.get('http')  # Adjusted to use 'http'
            parsed_proxy = urllib.parse.urlparse(current_proxy)
            proxy_auth, proxy_host = parsed_proxy.netloc.split('@')
            username, password = proxy_auth.split(':')
            host, port = proxy_host.split(':')

            # Prepare the payload with proxy details
            payload = {
                'key': 'MY_KEY',
                'type': 'hcaptcha',
                'sitekey': 'f7581d18-8739-40a0-90ff-2983225aa9a0',
                'url': 'https://minecraftbestservers.com/server-complex-gaming.77/vote',
                'proxy': {
                    'scheme': parsed_proxy.scheme,
                    'host': host,
                    'port': port,
                    'username': username,
                    'password': password
                }
            }

            # Use cloudscraper to send the request to the CAPTCHA solving service
            response = self.scraper.post('https://api.nopecha.com/token/', json=payload)
            response.raise_for_status()  # Raise an exception for HTTP errors

            return response.json().get('data')

        except Exception as e:
            print(f"Error fetching CAPTCHA token: {e}")
            time.sleep(random.uniform(0, 1))
            return self.fetch_captcha_token(err_count + 1)

    def send_vote(self, username):
        # Renew session for each vote to use a new proxy and user agent
        self.renew_session()
        vote_url = "https://minecraftbestservers.com/server-complex-gaming.77/vote"
        self.scraper.get(vote_url)
        captcha_token = self.fetch_captcha_token()

        headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'Accept-Encoding': 'gzip, deflate, br, zstd',
            'Accept-Language': 'tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7,la;q=0.6',
            'Cache-Control': 'max-age=0',
            'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryNGYzOdh0nG6SAUGF',
            'Origin': 'https://minecraftbestservers.com',
            'Priority': 'u=0, i',
            'Referer': vote_url,
            'Sec-Ch-Ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
            'Sec-Ch-Ua-Mobile': '?0',
            'Sec-Ch-Ua-Platform': '"Windows"',
            'Sec-Fetch-Dest': 'document',
            'Sec-Fetch-Mode': 'navigate',
            'Sec-Fetch-Site': 'same-origin',
            'Sec-Fetch-User': '?1',
            'Sec-Gpc': '1',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': self.scraper.headers['User-Agent']
        }
        data = {
            'username': username,
            'g-recaptcha-response': captcha_token,
            'h-captcha-response': captcha_token
        }

        response = self.scraper.post(vote_url, headers=headers, data=data)
        return response.status_code

    def send_votes(self, base_username):
        results = []
        # Generate case variations of the username
        for username in case_variations(base_username):
            result = self.send_vote(username)
            results.append((username, result))
            print(f"Vote sent for {username}: {result}")
        return results


def main():
    manager = SessionManager()
    results = manager.send_votes("myusername")
    for username, status in results:
        print(f"Username: {username}, Status Code: {status}")


if __name__ == '__main__':
    main()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.