NopeCHALLC / nopecha-python

Automated CAPTCHA solver for Python.
MIT License
976 stars 9 forks source link

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

Closed cheryiit closed 4 months ago

cheryiit commented 4 months ago

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()
j-w-yun commented 4 months ago

It looks like you are submitting a token job but never retrieving the token solution. Our inference engine is asynchronous, and you must poll for the solution until it is ready. Read more here: https://developers.nopecha.com/token/hcaptcha/

cheryiit commented 4 months ago

Also the site has cloudflare it should be for this i think

j-w-yun commented 4 months ago

If the issue persists, you should open a ticket on Discord.

Navigate to the channel #create-ticket and choose the following options:

image

Please provide your IP address or API key in the ticket so we can try to identify the cause of your issue.