напиши ошибки отдельно , не выписывай весь код 
import sys
import asyncio
import logging
import aiofile
from asyncio import Lock
import random
from datetime import timedelta
from telethon import TelegramClient, events, types
import requests
from telethon.tl.types import InputGeoPoint
from telethon.tl.functions.channels import GetFullChannelRequest
from telethon.tl import functions
import socks
import subprocess
import os
from telethon.tl.types import InputPeerUser, InputPeerChat, InputPeerChannel
import aiofile
import managemessage
import command
import proxymanagment
import cache
import pickle
from telethon.tl.functions.account import SetPrivacyRequest
from telethon.tl.types import InputPrivacyKeyPhoneCall, InputPrivacyValueDisallowAll
from telethon.tl.functions.channels import LeaveChannelRequest
from telethon.tl.functions.messages import DeleteChatUserRequest
from functools import partial
from telethon import errors
import python_socks
import argparse
from logger_config import setup_logger

parser = argparse.ArgumentParser(description='Telethon client script.')
parser.add_argument('--api_id', required=True, help='API ID for Telegram')
parser.add_argument('--api_hash', required=True, help='API Hash for Telegram')
parser.add_argument('--device_model', required=True, help='Device model')
parser.add_argument('--system_version', required=True, help='System version')
parser.add_argument('--app_version', required=True, help='App version')
parser.add_argument('--session_file', required=True,
                    help='Path to the session file')
parser.add_argument('--status_file', required=True,
                    help='Path to the status file')
parser.add_argument('--log_file', required=True, help='Path to the log file')
parser.add_argument('--command_file', required=True,
                    help='Path to the command file')
parser.add_argument('--proxy_addr', required=True, help='Proxy address')
parser.add_argument('--proxy_port', type=int, required=True, help='Proxy port')
parser.add_argument('--proxy_username', required=True, help='Proxy username')
parser.add_argument('--proxy_password', required=True, help='Proxy password')
parser.add_argument('--message_file', required=True, help='Path to the message file')
parser.add_argument('--system_lang_code', required=True, help='System language code')
parser.add_argument('--app_lang_code', required=True, help='App language code')
parser.add_argument('--country_proxy', required=True, help='Work country')
parser.add_argument("--cache_dir", help="Path to the cache directory", default="cache")
parser.add_argument('--zenproxy_type', required=True, help='proxy type', default="HTTP")


error_info = None

args = parser.parse_args()
tasks = []
setup_logger(args)
print(sys.argv)
logger = logging.getLogger(__name__)
proxy_type_str = args.zenproxy_type

proxy_types = {
    "HTTP": python_socks.ProxyType.HTTP,
    "SOCKS4": python_socks.ProxyType.SOCKS4,
    "SOCKS5": python_socks.ProxyType.SOCKS5
}

if proxy_type_str not in proxy_types:
    raise ValueError(f"Invalid proxy type: {proxy_type_str}")

proxy_credentials = {
    'proxy_type': proxy_types[proxy_type_str],
    'addr': args.proxy_addr,
    'port': args.proxy_port,
    'username': args.proxy_username,
    'password': args.proxy_password,
    'rdns': True
}



exception_occurred = False 

async def main():
    global tasks
    proxy_change_count = 0
    exit_flag = asyncio.Event()
    print(exit_flag.is_set())
    delays = [5, 10, 30, 60, 600, 1800]  # Задержки прокси

    while True:
        connected = False
        print(f"Подключились к телеграмм с сессией: {args.session_file}")
        logger.info("Main начал цикл с нуля , беру прокси")
        proxy_type_str = args.zenproxy_type

        proxy_types = {
            "HTTP": python_socks.ProxyType.HTTP,
            "SOCKS4": python_socks.ProxyType.SOCKS4,
            "SOCKS5": python_socks.ProxyType.SOCKS5
        }

        if proxy_type_str not in proxy_types:
            raise ValueError(f"Invalid proxy type: {proxy_type_str}")
        proxy = proxy_credentials



        if not proxy:
            logger.info("Иду получать новый прокси")
            return
        logger.info(f"взял проки и подключаюсь {proxy}")
        try:
            connected = await proxymanagment.wait_proxy(proxy)
        except Exception as e:
            proxy = await proxymanagment.check_proxy(proxy, args.country_proxy)
            logger.info("Вернулся в майн")
        connection_attempts = 0
        try:
            logger.info(f"цикл вайл connected -  {connected}, proxy - {proxy} ")
        except Exception as e:
            logger.info(f"хуй в логе {e}")
        while not connected and connection_attempts < 5:
            logger.info("запрос прокси в вайле")
            connection_attempts += 1
            connected = await proxymanagment.check_proxy(proxy, args.country_proxy)
        logger.info("Возле if connect false")
        if connected == False:
            logger.info("Иду получать новый прокси")
            if proxy_change_count < len(delays):
                proxy = proxymanagment.get_new_proxy(args.country_proxy)
                await asyncio.sleep(delays[proxy_change_count])
                proxy_change_count += 1
            else:
                await asyncio.sleep(random.randint(1000, 2000))
            continue
        try:
            logger.info("Создаю клиент с  пркоси")
            client = TelegramClient(
                args.session_file,
                args.api_id,
                args.api_hash,
                device_model=args.device_model,
                system_version=args.system_version,
                app_version=args.app_version,
                system_lang_code=args.system_lang_code,
                lang_code=args.app_lang_code,
                proxy=(proxy_types[proxy_type_str], proxy['addr'], proxy['port'], True, proxy['username'], proxy['password']),
                retry_delay=30,
                auto_reconnect=False,
                sequential_updates=True
            )
        except Exception as e:
            logger.info(f"Ошибка в клиенте {e}")
            await asyncio.sleep(100000)

        logger.info(f"Подключились к телеграмм с сессией: {args.session_file} , работаем с клиентом {client}")
        await asyncio.sleep(1)
        logger.info(f"делаю sign in")
        error_message = "You must provide a phone and a code the first time, and a password only if an RPCError was raised before"
        try:
            await client.connect()
            await client.sign_in()                       
        except Exception as e:
            await asyncio.sleep(5)
            if await client.is_user_authorized():
                logger.info("авторизован")
            else:
                logger.info("Не авторизован")
                await ban_accaunt(e)
        
            await asyncio.sleep(1)
        logger.info(f"Сделал sign in")
        await asyncio.sleep(1)
        if await client.is_user_authorized():
            logger.info("авторизован")
        else:
            logger.info("Не авторизован")
        entity_cache = {}
        async with client:
                logger.info(f"Запускаю Эвент хендлер")
                client.add_event_handler(partial(message_handler, entity_cache=entity_cache), events.NewMessage(incoming=True))

                logger.info(f"Запускаю второй эвент хендлер")
                client.add_event_handler(on_user_update, events.UserUpdate)

                logger.info(f"Запускаю Командную функцию")
                process_commands_task = client.loop.create_task(command.process_commands(client, args.command_file, args.message_file, args.cache_dir, exit_flag))
                tasks.append(process_commands_task)
                logger.info(f"Запускаю запись статуса")
                write_status_task = client.loop.create_task(managemessage.write_status(args.status_file))
                try:
                    await client.run_until_disconnected()  # Диссконнект
                except Exception as e:
                    logger.error(f"Произошел дисконнект: {e}")
                    
        while True:
                logger.info(f"Цикл Вайл запущен")
                try:
                    await client.run_until_disconnected()
                except errors.AuthKeyDuplicatedError as e:
                    client.disconnect()
                    logger.error(f"ошибка аутентификации : {e}")
                except errors.RPCError as e:
                    if "You must provide a phone and a code the first time, and a password only if an RPCError was raised before" in e:
                        while True:    
                            try:
                                async with aiofile.async_open(args.message_file, "a", encoding="utf-8") as message_file:
                                    logger.info(f"прошел запись в файл")
                                    await message_file.write(f"{error_message}\n")
                                    await asyncio.sleep(100000)
                                    exit_flag.set()
                                    sys.exit()
                            except Exception as e:
                                logger.info(f"не могу записать в файл жду 2 секунды и пробую снова {e}")
                                client.disconnect()
                                continue                        
                    logger.error(f"RPCEErr : {e}")
                except errors.FloodWaitError as e:
                    client.disconnect()
                    logger.error(f"Поймал флуд {e}")

                except Exception as e:
                    client.disconnect()
                    logger.error(f" не известная ошибка {e}")
                    await asyncio.sleep(3)
                    if exit_flag.is_set():
                        logger.error(f"Пытаюсь закрыть инстанс получил эксит флаг")
                        sys.exit()
                    logger.info(f"блок проверки процесс комманд")
                    if process_commands_task.done():
                        logger.info(f"Блок Проверки результата процесс комманд")   
                        try:
                            result = process_commands_task.result()
                            if result:
                                logger.error(f"Хрень в процесс комманд: {result}")

                                
                        except Exception as e:      
                            logger.error(f"Возможно ошибка в процесс комманд: {e}")
                            continue
                    if not exit_flag.is_set():
                        logger.info(f"Блок if not exit flag")
                        await reconnect(client)
                        await asyncio.sleep(10)
                        logger.info(f"if not exit_flag.is_set(): проблема тут ")
                        continue                           

                    else:
                        logger.error(f"Сделал функцию рекоонект  в самом низу вайла")
                        try:
                            await reconnect(client)
                            try:
                                await client.run_until_disconnected()
                            except Exception as e:
                                logger.error(f"Получил ошибку : {e}")
                                continue          # Оберните вызов функции в блок try-except
                        except Exception as e:
                            logger.error(f"Ошибка в функции reconnect: {e}")
                            continue                   
async def no_auth():
    logger.info(f"Не известная ошибка авторизации")
    e = "Please enter your phone (or bot token)"
    ban_accaunt(e)

async def ban_accaunt(e):
    logger.info(f" мы в функции бан аккаунт. Не известная ошибка авторизации {e}")
    
    if "You must provide a phone and a code the first time, and a password only if an RPCError was raised before" in str(e):
        while True:    
            try:
                error_message = "You must provide a phone and a code the first time, and a password only if an RPCError was raised before"
                async with aiofile.async_open(args.message_file, "a", encoding="utf-8") as message_file:
                    await message_file.write(f"{error_message}\n")
                    logger.info(f"прошел запись в файл")
                logger.error(f"RPCEErr : {e}")
                await asyncio.sleep(30)
                sys.exit()  # Раскомментируйте, если нужно завершить выполнение программы
            except Exception as e:
                logger.info(f"не могу записать в файл жду 2 секунды и пробую снова {e}")
                continue
    elif "different IP addresses simultaneously," in str(e):
        while True:    
            try:
                error_message = "You must provide a phone and a code the first time, and a password only if an RPCError was raised before"
                async with aiofile.async_open(args.message_file, "a", encoding="utf-8") as message_file:
                    await message_file.write(f"{error_message}\n")
                    logger.info(f"прошел запись в файл")
                logger.error(f"RPCEErr : {e}")
                await asyncio.sleep(20)
                sys.exit()  # Раскомментируйте, если нужно завершить выполнение программы
            except Exception as e:
                logger.info(f"не могу записать в файл жду 2 секунды и пробую снова {e}")
                continue               
    else:
        logger.info(f"Не известная ошибка авторизации {e}")
        await asyncio.sleep(200000)



                
                



async def message_handler(event, entity_cache):
    logger.info("Start Message Handler")
    try:
        sender = entity_cache.get(event.sender_id)
        if sender is None:
            sender = cache.load_cache(args.cache_dir, f"sender_{event.sender_id}")
            logger.info("Loading data from cache") 
            if sender is None:
                sender = await event.get_sender()
                logger.info("GET SENDER ID")
                cache.save_cache(sender, cache.get_cache_file_path(args.cache_dir, f"sender_{event.sender_id}"))
            else:
                logger.info("Read in cache Sender ID")
            entity_cache[event.sender_id] = sender


        chat = entity_cache.get(event.chat_id)
        if chat is None:
            chat = cache.load_cache(args.cache_dir, f"chat_{event.chat_id}")
            logger.info("Loading data from cache") 
            if chat is None:
                chat = await event.get_chat()
                logger.info("GET CHAT ID")
                cache.save_cache(chat, cache.get_cache_file_path(args.cache_dir, f"chat_{event.chat_id}"))
            else:
                logger.info("Chat id in memory")
            entity_cache[event.chat_id] = chat


            sender_type = "unknown"
        if isinstance(sender, types.User):
            if sender.bot:
                sender_type = "bot"
            else:
                sender_type = "user"
        elif isinstance(sender, types.Chat):
            sender_type = "group"
        elif isinstance(sender, types.Channel):
            if sender.megagroup:
                sender_type = "megagroup"
            else:
                sender_type = "channel"

        chat_type = "unknown"
        if event.is_private:
            chat_type = "private"
        elif event.is_group:
            chat_type = "group"
        elif event.is_channel:
            chat_type = "channel"

        event_type = "unknown"
        media_type = None

        if isinstance(event.original_update, types.MessageActionPhoneCall):
            event_type = "call"
        elif event.message:
            event_type = "message"
            if event.message.media:
                if isinstance(event.message.media, types.MessageMediaPhoto):
                    media_type = "photo"
                elif isinstance(event.message.media, types.MessageMediaDocument):
                    if event.message.media.document.mime_type.startswith("video"):
                        media_type = "video"
                    elif event.message.media.document.mime_type.startswith("audio"):
                        media_type = "audio"
                        
        sender_username = sender.username if hasattr(sender, 'username') else None
        sender_first_name = sender.first_name if hasattr(sender, 'first_name') else None
        sender_last_name = sender.last_name if hasattr(sender, 'last_name') else None

        while True:
            try:
                async with aiofile.async_open(args.message_file, 'a', encoding='utf-8') as file:
                    await file.write(f"Event received: event_type={event_type}, chat_type={chat_type}, chat_id={event.chat_id}, sender_id={event.message.sender_id}, sender_username={sender_username}, sender_first_name={sender_first_name}, sender_last_name={sender_last_name}, sender_type={sender_type}, message_id={event.id}, message_date={event.date}, text={event.text}, media_type={media_type}, media={event.media}, reply_to_msg_id={event.reply_to_msg_id}, fwd_from={event.fwd_from}, message={event.message}, peer_id={event.message.peer_id}, access_hashchat={sender.access_hash},\n")
                break
            except Exception as e:
                logger.info(f"Баг в Мессендж хендлере {e}")
                await asyncio.sleep(1)
                continue

    except Exception as e:
        logger.info(f"Error in message_handler: {e}")

import time



async def on_user_update(event):
    if not event.client.is_connected():
        print("Disconnected, trying to reconnect...")
        await reconnect(event.client, args)


changeproxytime = ()
last_reconnect_time = time.time()
changeproxytime = 0

async def reconnect(client, reconnect_attempts=4, proxy_change_count=0):
    global tasks
    global last_reconnect_time
    global changeproxytime

    if client.is_connected():
        logger.info("Клиент уже подключен. Завершаем функцию reconnect.")
        return True
    logger.info(f"сейчас чейндж прокси {changeproxytime}:")
    if changeproxytime == 3:
        logger.info("Перезагружаем скрипт после 50 попыток реконнекта")

        # Отмените все зап
        # ущенные асинхронные задачи перед перезапуском скрипта
        for task in tasks:
            task.cancel()
            logger.info("Отмена всех открытых тасков")
            changeproxytime = 0
        logger.info("Перезагружаю скрипт")
        restart_script()

    else:
        logger.info(f"увеличил изменение прокси:{changeproxytime}")
        changeproxytime += 1

    logger.info("Ошибка соединения:")
    success = False
    attempt = 0

    while not success and attempt < reconnect_attempts:
        time_since_last_reconnect = time.time() - last_reconnect_time

        if time_since_last_reconnect > 600:
            attempt = 0

        if attempt < 3:
            delay = 10
        elif attempt == 3:
            delay = 30
        elif attempt == 4:
            delay = 60
        elif attempt == 5:
            delay = 75
        else:
            delay = 180

        logger.info(f"Попытка реконнекта #{attempt}. Ждем {delay} секунд.")
        await asyncio.sleep(delay)
        try:
            await client.connect()
        except Exception as e:
            (f"возможна ошибка {e}:")
        try:
            await client.sign_in()
        except errors.AuthKeyDuplicatedError as e:
            logger.info(f"возможна ошибка {e}:")
        last_reconnect_time = time.time()
        attempt += 1

        if client.is_connected():
            logger.info("Успешное подключение.")
            success = True

    if not success:
        if proxy_change_count < 2:
            logger.info("Смена прокси и попытка реконнекта...")
            new_proxy = proxymanagment.get_new_proxy(args.country_proxy)
            if new_proxy:
                client.session.set_proxy(
                    socks.SOCKS5,
                    new_proxy['addr'],
                    new_proxy['port'],
                    True,
                    new_proxy['username'],
                    new_proxy['password'],
                )
                return await reconnect(client, reconnect_attempts, proxy_change_count + 1)
            else:
                logger.info("Не удалось получить новый прокси.")
                return False
        else:
            logger.info("Превышено количество попыток смены прокси. Закрываем соединение.")
            await client.disconnect()
            return False

    return success
def restart_script():
    logger.info("Вошел в перезагрузку скрипты.")
    python_executable = sys.executable
    script_file = sys.argv[0]
    subprocess.Popen([python_executable, script_file] + sys.argv[1:])
    sys.exit()



if __name__ == '__main__':
    import asyncio
    asyncio.run(main())