исправь ошибки полный код: import asyncio
from telethon import TelegramClient, functions, types, errors
from urllib.parse import unquote
import aiohttp
import random
import os
import config as cfg

# Initialize your API credentials
api_id = cfg.API_ID
api_hash = cfg.API_HASH
report_bug_text = "If you have done all the steps correctly and you think this is a bug, report it to github.com/aDarkDev with response. response: {}"
authenticate_error = "Please follow the steps correctly. Not authenticated."

class Colors:
    # ANSI color codes
    BLACK = "\033[0;30m"
    RED = "\033[0;31m"
    GREEN = "\033[0;32m"
    BROWN = "\033[0;33m"
    BLUE = "\033[0;34m"
    PURPLE = "\033[0;35m"
    CYAN = "\033[0;36m"
    LIGHT_GRAY = "\033[0;37m"
    DARK_GRAY = "\033[1;30m"
    LIGHT_RED = "\033[1;31m"
    LIGHT_GREEN = "\033[1;32m"
    YELLOW = "\033[1;33m"
    LIGHT_BLUE = "\033[1;34m"
    LIGHT_PURPLE = "\033[1;35m"
    LIGHT_CYAN = "\033[1;36m"
    LIGHT_WHITE = "\033[1;37m"
    BOLD = "\033[1m"
    FAINT = "\033[2m"
    ITALIC = "\033[3m"
    UNDERLINE = "\033[4m"
    BLINK = "\033[5m"
    NEGATIVE = "\033[7m"
    CROSSED = "\033[9m"
    END = "\033[0m"
    # Cancel SGR codes if not writing to a terminal
    if not __import__("sys").stdout.isatty():
        for _ in dir():
            if isinstance(_, str) and _[0] != "_":
                locals()[_] = ""
    else:
        # Set Windows console in VT mode
        if __import__("platform").system() == "Windows":
            import ctypes
            kernel32 = ctypes.windll.kernel32
            kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
            del kernel32

class NotPx:
    def __init__(self, client: TelegramClient):
        self.client = client
        self.session = None  # Will initialize aiohttp session in async context

    async def __aenter__(self):
        self.session = aiohttp.ClientSession(headers={
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'en-US,en;q=0.9',
            'Priority': 'u=1, i',
            'Referer': 'https://notpx.app/',
            'Sec-Ch-Ua': 'Chromium;v=119, Not?A_Brand;v=24',
            'Sec-Ch-Ua-Mobile': '?0',
            'Sec-Ch-Ua-Platform': 'Linux',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-origin',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.105 Safari/537.36',
        })
        await self.__update_headers_async()
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.session.close()

    async def __update_headers_async(self):
        webapp_data = await GetWebAppData(self.client)
        if webapp_data:
            self.session.headers['Authorization'] = f'initData {webapp_data}'
            print(f"[+] {Colors.GREEN}Authorization header updated!{Colors.END}")
        else:
            print(f"[!] {Colors.RED}Failed to update headers.{Colors.END}")

    async def request(self, method, end_point, key_check, data=None):
        url = f"https://notpx.app/api/v1{end_point}"
        for attempt in range(5):  # Retry up to 5 times
            try:
                if method.lower() == "get":
                    async with self.session.get(url, timeout=5) as response:
                        text = await response.text()
                        status = response.status
                else:
                    async with self.session.post(url, json=data, timeout=5) as response:
                        text = await response.text()
                        status = response.status

                # Handle NotPixel heavy load error
                if "failed to parse" in text:
                    print(f"[x] {Colors.RED}NotPixel internal error. Waiting for 5 minutes...{Colors.END}")
                    await asyncio.sleep(5 * 60)
                    return None  # Return None on failure

                if status == 200:
                    if key_check in text:
                        return await response.json()  # Return the JSON response
                    else:
                        raise Exception(report_bug_text.format(text))
                elif status >= 500:
                    print(f"[!] {Colors.RED}Server error (status: {status}). Retrying...{Colors.END}")
                    await asyncio.sleep(5)
                    continue  # Retry on server error
                else:
                    await self.__update_headers_async()
                    print(f"[+] {Colors.GREEN}Authentication renewed!{Colors.END}")
                    return None  # Return None if authentication is needed

            except aiohttp.ClientConnectionError:
                print(f"[!] {Colors.RED}ConnectionError{Colors.END} {end_point}. Sleeping for 5s...")
                await asyncio.sleep(5)
            except aiohttp.ClientError as e:
                print(f"[!] {Colors.RED}ClientError{Colors.END} {end_point}. Error: {e}. Sleeping for 5s...")
                await asyncio.sleep(5)
            except asyncio.TimeoutError:
                print(f"[!] {Colors.RED}Timeout Error{Colors.END} {end_point}. Sleeping for 5s...")
                await asyncio.sleep(5)
        print(f"[!] {Colors.RED}Max retries reached for {end_point}.{Colors.END}")
        return None  # Return None after max retries

    async def claim_mining(self):
        response = await self.request("get", "/mining/claim", "claimed")
        return response['claimed'] if response else None

    async def accountStatus(self):
        response = await self.request("get", "/mining/status", "speedPerSecond")
        return response if response else None

    async def autoPaintPixel(self):
        # Making pixel randomly
        colors = ["#FFFFFF", "#000000", "#00CC78", "#BE0039"]
        random_pixel = (random.randint(100, 990) * 1000) + random.randint(100, 990)
        data = {"pixelId": random_pixel, "newColor": random.choice(colors)}

        response = await self.request("post", "/repaint/start", "balance", data)
        return response['balance'] if response else None

    async def paintPixel(self, x, y, hex_color):
        pixelformated = (y * 1000) + x + 1
        data = {"pixelId": pixelformated, "newColor": hex_color}

        response = await self.request("post", "/repaint/start", "balance", data)
        return response['balance'] if response else None

async def GetWebAppData(client: TelegramClient):
    try:
        notcoin = await client.get_entity("notpixel")
        # Corrected function name and parameters
        msg = await client(functions.messages.RequestWebView(
            peer=notcoin,
            url="https://notpx.app/",  # The URL for the web app
            platform="android",
            theme=types.WebViewThemeDark()  # Choose the appropriate theme
        ))
        url = msg.url
        print(f"Received URL: {url}")  # Debug statement
        separator = '#tgWebAppData='
        if separator not in url:
            print(f"[!] {Colors.RED}Unexpected URL format: {url}{Colors.END}")
            return None
        webappdata_global = url.split(separator)[1].split('&tgWebAppVersion=')[0]
        webappdata_global = unquote(webappdata_global)
        return webappdata_global
    except Exception as e:
        print(f"[!] {Colors.RED}Failed to get web app data: {e}{Colors.END}")
        return None

print(r"""{}
 _   _       _  ______       ______       _   
| \ | |     | | | ___ \      | ___ \     | |  
|  \| | ___ | |_| |_/ /_  __ | |_/ / ___ | |_ 
| . ` |/ _ \| __|  __/\ \/ / | ___ \/ _ \| __|
| |\  | (_) | |_| |    >  <  | |_/ / (_) | |_ 
\_| \_/\___/ \__\_|   /_/\_\ \____/ \___/ \__|
                                            
        NotPx Auto Paint & Claim by aDarkDev - v1.5 {}""".format(Colors.BLUE, Colors.END))

async def painter(NotPxClient: NotPx, session_name: str):
    print(f"[+] {Colors.CYAN}Auto painting started{Colors.END}.")
    while True:
        try:
            charges_data = await NotPxClient.accountStatus()
            if not charges_data:
                await asyncio.sleep(5)
                continue
            charges = charges_data.get('charges', 0)

            if charges > 0:
                for _ in range(charges):
                    balance = await NotPxClient.autoPaintPixel()
                    if balance is not None:
                        print(f"[+] {Colors.CYAN}{session_name}{Colors.END}: 1 {Colors.GREEN}Pixel painted{Colors.END} successfully. User new balance: {Colors.GREEN}{balance}{Colors.END}")
                    t = random.randint(1, 6)
                    print(f"[!] {Colors.CYAN}{session_name} anti-detect{Colors.END}: Sleeping for {t}s...")
                    await asyncio.sleep(t)
            else:
                print(f"[!] {Colors.CYAN}{session_name}{Colors.END}: {Colors.YELLOW}No charge available{Colors.END}. Sleeping for 10 minutes...")
                await asyncio.sleep(600)
        except Exception as e:
            print(f"[!] {Colors.CYAN}{session_name}{Colors.END}: {Colors.RED}Error:{Colors.END} {e}. Sleeping for 5s...")
            await asyncio.sleep(5)

async def mine_claimer(NotPxClient: NotPx, session_name: str):
    await asyncio.sleep(5)  # Start with delay...

    print(f"[+] {Colors.CYAN}Auto claiming started{Colors.END}.")
    while True:
        try:
            acc_data = await NotPxClient.accountStatus()

            # Check if acc_data is None
            if acc_data is None:
                print(f"[!] {Colors.CYAN}{session_name}{Colors.END}: {Colors.RED}Failed to retrieve account status. Retrying...{Colors.END}")
                await asyncio.sleep(5)  # Wait before retrying
                continue

            # Check if the necessary keys exist in acc_data
            if 'fromStart' in acc_data and 'speedPerSecond' in acc_data:
                fromStart = acc_data['fromStart']
                speedPerSecond = acc_data['speedPerSecond']
                if fromStart * speedPerSecond > 0.3:
                    claimed_count = await NotPxClient.claim_mining()
                    if claimed_count is not None:
                        print(f"[+] {Colors.CYAN}{session_name}{Colors.END}: {claimed_count} NotPx Token {Colors.GREEN}claimed{Colors.END}.")
            else:
                print(f"[!] {Colors.CYAN}{session_name}{Colors.END}: {Colors.RED}Unexpected account data format. Retrying...{Colors.END}")

            print(f"[!] {Colors.CYAN}{session_name}{Colors.END}: Sleeping for 1 hour...")
            await asyncio.sleep(3600)
        except Exception as e:
            print(f"[!] {Colors.CYAN}{session_name}{Colors.END}: {Colors.RED}Error:{Colors.END} {e}. Sleeping for 5s...")
            await asyncio.sleep(5)

async def multithread_starter():
    dirs = os.listdir("sessions/")
    sessions = [x.split(".session")[0] for x in dirs if x.endswith(".session")]
    tasks = []
    for session_name in sessions:
        try:
            client = TelegramClient("sessions/" + session_name, api_id, api_hash)
            await client.start()
            notpx_client = NotPx(client)
            # Use context manager to ensure session is properly managed
            async with notpx_client:
                task_painter = asyncio.create_task(painter(notpx_client, session_name))
                task_claimer = asyncio.create_task(mine_claimer(notpx_client, session_name))
                tasks.extend([task_painter, task_claimer])
        except errors.RPCError as e:
            print(f"[!] {Colors.RED}Error loading session{Colors.END} \"{session_name}\", error: {e}")
        except Exception as e:
            print(f"[!] {Colors.RED}Unexpected error on session{Colors.END} \"{session_name}\", error: {e}")
    if tasks:
        await asyncio.gather(*tasks)

# Start script
async def main():
    if not os.path.exists("sessions"):
        os.mkdir("sessions")

    while True:
        option = input(f"{Colors.BLUE}\nПиши 1{Colors.END} чтобы добавить аккаунт{Colors.BLUE}\nПиши 2{Colors.END} чтобы начать майнинг\n: ")
        if option == "1":
            name = input("\nНапиши название для аккаунта: ")
            if not any(name == x.split(".session")[0] for x in os.listdir("sessions/") if x.endswith(".session")):
                client = TelegramClient(f"sessions/{name}", api_id, api_hash)
                try:
                    await client.start()
                    await client.disconnect()
                    print(f"[+] Успешно {name} {Colors.GREEN}сохранено{Colors.END}.")
                except Exception as e:
                    print(f"[x] Ошибка {name} {Colors.RED}что-то не так{Colors.END}. Error: {e}")
            else:
                print(f"[x] Ошибка {name} {Colors.RED}аккаунт уже существует{Colors.END}.")
        elif option == "2":
            await multithread_starter()
            break
        else:
            print(f"[!] {Colors.RED}Неверный ввод. Пожалуйста, попробуйте снова.{Colors.END}")

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except