сделай чтобы в случае если временно пропал интернет результат вернулся после его появления и сделай код профессиональнее:class Megafon:
    BASE_URL = "https://lk.megafon.ru"
    HEADERS_TEMPLATE = {
            "Connection": "keep-alive",

            "Pragma": "no-cache",
            "Cache-Control": "no-cache",
            "X-Cabinet-Capabilities": "web-2020",
            "User-Agent": "Mozilla/5.0 (Linux; Android 9; Nexus 5 Build/PQ3A.190801.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/81.0.4044.117 Mobile Safari/537.36",
            "Content-Type": "application/json",
            "Accept": "application/json, text/plain, */*",
            "X-App-Type": "webView",
            "Origin": "https://lk.megafon.ru",
            "X-Requested-With": "ru.megafon.mlk",
            "Sec-Fetch-Site": "same-origin",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Dest": "empty",
            "Referer": "https://lk.megafon.ru/login",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "ru,en-US;q=0.9,en;q=0.8",
    }

    def __init__(self, phone_number, pin):

        self.phone_number = phone_number
        self.pin = pin
        self.session = requests.Session()
        self.jwt_token = None
        self.cookies_file = f"{self.phone_number}.cookies"
        self._setup_session()

    def _setup_session(self):

        if self._load_cookies():
            logger.info("Куки успешно загружены.")

            self.refresh_session()

        else:
            logger.info("Куки не найдены. Начинаем новую сессию.")
            self.authenticate()
            

    def _load_cookies(self):

        if os.path.exists(self.cookies_file):
            with open(self.cookies_file, 'rb') as f:
                cookies = pickle.load(f)
                self.session.cookies.update(cookies)
            return True
        return False

    def _save_cookies(self):
        # Перед сохранением добавляем 'X-App-Type': 'react_lk' в куки
        self.session.cookies.set('X-App-Type', 'webView')
        with open(self.cookies_file, 'wb') as f:
            pickle.dump(self.session.cookies, f)
        logger.info("Куки успешно сохранены.")

    @staticmethod
    def generate_traceparent():

        version = "00"
        trace_id = os.urandom(16).hex()
        while trace_id == "0" * 32:
            trace_id = os.urandom(16).hex()
        parent_id = os.urandom(8).hex()
        while parent_id == "0" * 16:
            parent_id = os.urandom(8).hex()
        trace_flags = "01"
        traceparent = f"{version}-{trace_id}-{parent_id}-{trace_flags}"
        pattern = re.compile(r"^[\da-f]{2}-[\da-f]{32}-[\da-f]{16}-[\da-f]{2}$")
        if not pattern.match(traceparent):
            raise ValueError("Сгенерированное значение `traceparent` не соответствует требуемому формату.")
        return traceparent

    def get_headers(self):

        headers = self.HEADERS_TEMPLATE.copy()
        headers['traceparent'] = self.generate_traceparent()
        return headers

    def send_code(self):
        url = f"{self.BASE_URL}/api/auth/otp/request"
        data = f"login=7{self.phone_number}&captchaReady=true"
        headers = self.get_headers()
        headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8"
        response = self.session.post(url, data=data, headers=headers)
        if response.status_code == 200 and response.json().get("ok") == True:
            logger.info("Сообщение с кодом успешно отправлено.")
        else:
            logger.error("Не удалось отправить сообщение с кодом.")

    def submit_code(self, code):
        url = f"{self.BASE_URL}/api/auth/otp/submit"
        data = f"login=7{self.phone_number}&otp={code}"
        headers = self.get_headers()
        headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8"
        response = self.session.post(url, data=data, headers=headers)

        if response.status_code == 200 and response.json().get("authenticated") == True:
            json_res = response.json()
            self.jwt_token = json_res.get("jwtToken")
            logger.info(f"Код подтвержден. ФИО: {json_res.get('name')}")
            self._save_cookies()
        else:
            logger.error("Ошибка при подтверждении кода.")
    def auth_pin(self):
        url = "https://lk.megafon.ru/api/auth/pin"
        data = {"pin":self.pin,"msisdn":self.phone_number}
        headers = self.get_headers()
        response = self.session.post(url, json=data, headers=headers)
        if response.status_code == 200 and response.json().get("authenticated") == True:
            json_res = response.json()
            if self.jwt_token is None:
                logger.info(f"ФИО: {json_res.get('name')}")
            self.jwt_token = json_res.get("jwtToken")
            self._save_cookies()
            logger.info("Токен успешно обновлен с помощью пина.")
        else:
            logger.info("Не удалось авторизоваться с помощью пин-кода")
            self.authenticate()
    def set_pin(self,pin):
        url = f"{self.BASE_URL}/api/profile/pin"
        data = {"pin":self.pin}
        headers = self.get_headers()
        headers['X-Cabinet-Authorization'] = f"Bearer {self.jwt_token}"

        headers['X-CSRF-TOKEN'] = self.session.cookies.get("CSRF-TOKEN")
        response = self.session.post(url, json=data, headers=headers)
        if response.status_code == 200:
            logger.info("Пин-код успешно установлен")
        else:
            logger.error("При установке пин-кода что-то пошло не так")
    def authenticate(self):
        self.send_code()
        code = input("Введите полученный код: ")
        self.submit_code(code)
        self.set_pin()
    def refresh_session(self):
        logger.info("Обновление токена сессии...")
        url = f"{self.BASE_URL}/api/auth/sessionCheck"
        headers = self.get_headers()
        headers.pop('Content-Type', None)
        response = self.session.get(url, headers=headers)
        if response.status_code == 200 and response.json().get("authenticated") == True:
            json_res = response.json()
            if self.jwt_token is None:
                logger.info(f"ФИО: {json_res.get('name')}")
            self.jwt_token = json_res.get("jwtToken")
            self._save_cookies()
            logger.info("Токен успешно обновлен.")
        else:
            self.auth_pin()

    def get_balance(self):
        url = f"{self.BASE_URL}/api/main/balance"
        headers = self.get_headers()
        headers['X-Cabinet-Authorization'] = f"Bearer {self.jwt_token}"
        headers.pop('Content-Type', None)
        response = self.session.get(url, headers=headers)

        if response.status_code == 200:
            balance_info = response.json()
            return balance_info.get("balanceWithLimit")
        elif response.status_code == 401:
            logger.warning("Неавторизован. Обновление сессии.")
            self.refresh_session()
            return self.get_balance()
        else:
            logger.error("Ошибка при получении баланса.")
            return None
    def search_dop(self,favorite_number=""):
        url = f"https://lk.megafon.ru/api/additionalNumbers/availableForAdd?types=FEDERAL&filter={favorite_number}"
        headers = self.get_headers()
        headers['X-Cabinet-Authorization'] = f"Bearer {self.jwt_token}"
        headers.pop('Content-Type', None)
        response = self.session.get(url, headers=headers)

        if response.status_code == 200:
            dop_info = response.json()
            if "conflicts" in dop_info:
                return None
            else:
                return dop_info.get("availableForAdd")[0].get("numbersInfo")
        elif response.status_code == 401:
            logger.warning("Неавторизован. Обновление сессии.")
            self.refresh_session()
            return self.get_dop()
        else:
            logger.error("Ошибка при получении списка доп номеров.")
            return None
    def addnum(self,id_num, phone):
        print(id_num + " " + phone)
        global s
        url = "https://lk.megafon.ru/api/additionalNumbers/" + id_num
        headers = self.get_headers()
        headers['X-Cabinet-Authorization'] = f"Bearer {self.jwt_token}"
        try:
            response = session.post(url, headers=headers)
            if response.status_code == 200:
                print("подключен")
                return "подключен"
            else:
                response_json = response.json()
                if response_json["code"] == "adn.3":
                    print("limit")
                    return "limit"
                else:
                    print("занят")
                    return "занят"
        except:
            time.sleep(3)
            self.addnum(id_num, phone)
    def del_all_dop(self):
        url = "https://lk.megafon.ru/api/additionalNumbers/list"
        headers = self.get_headers()
        headers['X-Cabinet-Authorization'] = f"Bearer {self.jwt_token}"
        headers.pop('Content-Type', None)
        response = self.session.get(url, headers=headers)
        if response.status_code == 401:
            logger.warning("Неавторизован. Обновление сессии.")
            self.refresh_session()
            return self.del_all_dop()
        if "additionalNumbersList" in response:
            list_number=response["additionalNumbersList"]
            if len(list_number) != 0:
                for number in list_number:
                    headers['traceparent'] = self.generate_traceparent()
                    resp_delete = s.delete('https://lk.megafon.ru/api/additionalNumbers/'+str(number["id"]),headers=headers)
                    if resp_delete.status_code == 401:
                        logger.warning("Неавторизован. Обновление сессии.")
                        self.refresh_session()
                        return self.del_all_dop()
                    else:
                        logger.info(f"{number['number']} успешно отключен")
            else:
                logger.info(f"Похоже доп. номеров нет")
        else:
            logger.info(f"Похоже доп. номеров нет")