Ver Fonte

refactor: replace print statements with logging for improved traceability and error handling in cursor_pro_keep_alive.py

chengchongzhen há 1 ano atrás
pai
commit
a953db3bb8
1 ficheiros alterados com 58 adições e 34 exclusões
  1. 58 34
      cursor_pro_keep_alive.py

+ 58 - 34
cursor_pro_keep_alive.py

@@ -18,7 +18,7 @@ from config import Config
 
 
 
 
 def handle_turnstile(tab):
 def handle_turnstile(tab):
-    print("开始突破难关")
+    logging.info("正在检测 Turnstile 验证...")
     try:
     try:
         while True:
         while True:
             try:
             try:
@@ -31,29 +31,28 @@ def handle_turnstile(tab):
                 )
                 )
 
 
                 if challengeCheck:
                 if challengeCheck:
-                    print("开始突破")
+                    logging.info("检测到 Turnstile 验证,正在处理...")
                     time.sleep(random.uniform(1, 3))
                     time.sleep(random.uniform(1, 3))
                     challengeCheck.click()
                     challengeCheck.click()
                     time.sleep(2)
                     time.sleep(2)
-                    print("突破成功")
+                    logging.info("Turnstile 验证通过")
                     return True
                     return True
             except:
             except:
                 pass
                 pass
 
 
             if tab.ele("@name=password"):
             if tab.ele("@name=password"):
-                print("突破成功")
+                logging.info("验证成功 - 已到达密码输入页面")
                 break
                 break
             if tab.ele("@data-index=0"):
             if tab.ele("@data-index=0"):
-                print("突破成功")
+                logging.info("验证成功 - 已到达验证码输入页面")
                 break
                 break
             if tab.ele("Account Settings"):
             if tab.ele("Account Settings"):
-                print("突破成功")
+                logging.info("验证成功 - 已到达账户设置页面")
                 break
                 break
 
 
             time.sleep(random.uniform(1, 2))
             time.sleep(random.uniform(1, 2))
     except Exception as e:
     except Exception as e:
-        print(e)
-        print("突破失败")
+        logging.error(f"Turnstile 验证失败: {str(e)}")
         return False
         return False
 
 
 
 
@@ -65,7 +64,7 @@ def get_cursor_session_token(tab, max_attempts=3, retry_interval=2):
     :param retry_interval: 重试间隔(秒)
     :param retry_interval: 重试间隔(秒)
     :return: session token 或 None
     :return: session token 或 None
     """
     """
-    print("开始获取cookie")
+    logging.info("开始获取cookie")
     attempts = 0
     attempts = 0
 
 
     while attempts < max_attempts:
     while attempts < max_attempts:
@@ -77,18 +76,20 @@ def get_cursor_session_token(tab, max_attempts=3, retry_interval=2):
 
 
             attempts += 1
             attempts += 1
             if attempts < max_attempts:
             if attempts < max_attempts:
-                print(
+                logging.warning(
                     f"第 {attempts} 次尝试未获取到CursorSessionToken,{retry_interval}秒后重试..."
                     f"第 {attempts} 次尝试未获取到CursorSessionToken,{retry_interval}秒后重试..."
                 )
                 )
                 time.sleep(retry_interval)
                 time.sleep(retry_interval)
             else:
             else:
-                print(f"已达到最大尝试次数({max_attempts}),获取CursorSessionToken失败")
+                logging.error(
+                    f"已达到最大尝试次数({max_attempts}),获取CursorSessionToken失败"
+                )
 
 
         except Exception as e:
         except Exception as e:
-            print(f"获取cookie失败: {str(e)}")
+            logging.error(f"获取cookie失败: {str(e)}")
             attempts += 1
             attempts += 1
             if attempts < max_attempts:
             if attempts < max_attempts:
-                print(f"将在 {retry_interval} 秒后重试...")
+                logging.info(f"将在 {retry_interval} 秒后重试...")
                 time.sleep(retry_interval)
                 time.sleep(retry_interval)
 
 
     return None
     return None
@@ -103,43 +104,51 @@ def update_cursor_auth(email=None, access_token=None, refresh_token=None):
 
 
 
 
 def sign_up_account(browser, tab):
 def sign_up_account(browser, tab):
-    print("开始执行...")
+    logging.info("=== 开始注册账号流程 ===")
+    logging.info(f"正在访问注册页面: {sign_up_url}")
     tab.get(sign_up_url)
     tab.get(sign_up_url)
 
 
     try:
     try:
         if tab.ele("@name=first_name"):
         if tab.ele("@name=first_name"):
+            logging.info("正在填写个人信息...")
             tab.actions.click("@name=first_name").input(first_name)
             tab.actions.click("@name=first_name").input(first_name)
+            logging.info(f"已输入名字: {first_name}")
             time.sleep(random.uniform(1, 3))
             time.sleep(random.uniform(1, 3))
 
 
             tab.actions.click("@name=last_name").input(last_name)
             tab.actions.click("@name=last_name").input(last_name)
+            logging.info(f"已输入姓氏: {last_name}")
             time.sleep(random.uniform(1, 3))
             time.sleep(random.uniform(1, 3))
 
 
             tab.actions.click("@name=email").input(account)
             tab.actions.click("@name=email").input(account)
+            logging.info(f"已输入邮箱: {account}")
             time.sleep(random.uniform(1, 3))
             time.sleep(random.uniform(1, 3))
 
 
+            logging.info("提交个人信息...")
             tab.actions.click("@type=submit")
             tab.actions.click("@type=submit")
 
 
     except Exception as e:
     except Exception as e:
-        print("打开注册页面失败")
+        logging.error(f"注册页面访问失败: {str(e)}")
         return False
         return False
 
 
     handle_turnstile(tab)
     handle_turnstile(tab)
 
 
     try:
     try:
         if tab.ele("@name=password"):
         if tab.ele("@name=password"):
+            logging.info("正在设置密码...")
             tab.ele("@name=password").input(password)
             tab.ele("@name=password").input(password)
             time.sleep(random.uniform(1, 3))
             time.sleep(random.uniform(1, 3))
 
 
+            logging.info("提交密码...")
             tab.ele("@type=submit").click()
             tab.ele("@type=submit").click()
-            print("请稍等...")
+            logging.info("密码设置完成,等待系统响应...")
 
 
     except Exception as e:
     except Exception as e:
-        print("执行失败")
+        logging.error(f"密码设置失败: {str(e)}")
         return False
         return False
 
 
     time.sleep(random.uniform(1, 3))
     time.sleep(random.uniform(1, 3))
     if tab.ele("This email is not available."):
     if tab.ele("This email is not available."):
-        print("执行失败")
+        logging.error("注册失败:邮箱已被使用")
         return False
         return False
 
 
     handle_turnstile(tab)
     handle_turnstile(tab)
@@ -147,26 +156,34 @@ def sign_up_account(browser, tab):
     while True:
     while True:
         try:
         try:
             if tab.ele("Account Settings"):
             if tab.ele("Account Settings"):
+                logging.info("注册成功 - 已进入账户设置页面")
                 break
                 break
             if tab.ele("@data-index=0"):
             if tab.ele("@data-index=0"):
+                logging.info("正在获取邮箱验证码...")
                 code = email_handler.get_verification_code()
                 code = email_handler.get_verification_code()
                 if not code:
                 if not code:
+                    logging.error("获取验证码失败")
                     return False
                     return False
 
 
+                logging.info(f"成功获取验证码: {code}")
+                logging.info("正在输入验证码...")
                 i = 0
                 i = 0
                 for digit in code:
                 for digit in code:
                     tab.ele(f"@data-index={i}").input(digit)
                     tab.ele(f"@data-index={i}").input(digit)
                     time.sleep(random.uniform(0.1, 0.3))
                     time.sleep(random.uniform(0.1, 0.3))
                     i += 1
                     i += 1
+                logging.info("验证码输入完成")
                 break
                 break
         except Exception as e:
         except Exception as e:
-            print(e)
+            logging.error(f"验证码处理过程出错: {str(e)}")
 
 
     handle_turnstile(tab)
     handle_turnstile(tab)
     wait_time = random.randint(3, 6)
     wait_time = random.randint(3, 6)
     for i in range(wait_time):
     for i in range(wait_time):
-        print(f"等待中... {wait_time-i}秒")
+        logging.info(f"等待系统处理中... 剩余 {wait_time-i} 秒")
         time.sleep(1)
         time.sleep(1)
+
+    logging.info("正在获取账户信息...")
     tab.get(settings_url)
     tab.get(settings_url)
     try:
     try:
         usage_selector = (
         usage_selector = (
@@ -178,11 +195,12 @@ def sign_up_account(browser, tab):
         if usage_ele:
         if usage_ele:
             usage_info = usage_ele.text
             usage_info = usage_ele.text
             total_usage = usage_info.split("/")[-1].strip()
             total_usage = usage_info.split("/")[-1].strip()
-            print("可用上限: " + total_usage)
+            logging.info(f"账户可用额度上限: {total_usage}")
     except Exception as e:
     except Exception as e:
-        print("获取可用上限失败")
-    print("注册完成")
-    account_info = f"\nCursor 账号: {account}  密码: {password}"
+        logging.error(f"获取账户额度信息失败: {str(e)}")
+
+    logging.info("\n=== 注册完成 ===")
+    account_info = f"Cursor 账号信息:\n邮箱: {account}\n密码: {password}"
     logging.info(account_info)
     logging.info(account_info)
     time.sleep(5)
     time.sleep(5)
     return True
     return True
@@ -225,53 +243,59 @@ if __name__ == "__main__":
     print_logo()
     print_logo()
     browser_manager = None
     browser_manager = None
     try:
     try:
-        ExitCursor()
-        # 初始化浏览器
+        logging.info("\n=== 初始化程序 ===")
+        # ExitCursor()
+        logging.info("正在初始化浏览器...")
         browser_manager = BrowserManager()
         browser_manager = BrowserManager()
         browser = browser_manager.init_browser()
         browser = browser_manager.init_browser()
 
 
-        # 初始化邮箱验证处理器
+        logging.info("正在初始化邮箱验证模块...")
         email_handler = EmailVerificationHandler(browser)
         email_handler = EmailVerificationHandler(browser)
 
 
-        # 固定的 URL 配置
+        logging.info("\n=== 配置信息 ===")
         login_url = "https://authenticator.cursor.sh"
         login_url = "https://authenticator.cursor.sh"
         sign_up_url = "https://authenticator.cursor.sh/sign-up"
         sign_up_url = "https://authenticator.cursor.sh/sign-up"
         settings_url = "https://www.cursor.com/settings"
         settings_url = "https://www.cursor.com/settings"
         mail_url = "https://tempmail.plus"
         mail_url = "https://tempmail.plus"
 
 
-        # 生成随机邮箱
+        logging.info("正在生成随机账号信息...")
         email_generator = EmailGenerator()
         email_generator = EmailGenerator()
         account = email_generator.generate_email()
         account = email_generator.generate_email()
         password = email_generator.default_password
         password = email_generator.default_password
         first_name = email_generator.default_first_name
         first_name = email_generator.default_first_name
         last_name = email_generator.default_last_name
         last_name = email_generator.default_last_name
 
 
+        logging.info(f"生成的邮箱账号: {account}")
         auto_update_cursor_auth = True
         auto_update_cursor_auth = True
 
 
         tab = browser.latest_tab
         tab = browser.latest_tab
         tab.run_js("try { turnstile.reset() } catch(e) { }")
         tab.run_js("try { turnstile.reset() } catch(e) { }")
 
 
+        logging.info("\n=== 开始注册流程 ===")
+        logging.info(f"正在访问登录页面: {login_url}")
         tab.get(login_url)
         tab.get(login_url)
 
 
         if sign_up_account(browser, tab):
         if sign_up_account(browser, tab):
+            logging.info("正在获取会话令牌...")
             token = get_cursor_session_token(tab)
             token = get_cursor_session_token(tab)
             if token:
             if token:
+                logging.info("更新认证信息...")
                 update_cursor_auth(
                 update_cursor_auth(
                     email=account, access_token=token, refresh_token=token
                     email=account, access_token=token, refresh_token=token
                 )
                 )
 
 
+                logging.info("重置机器码...")
                 MachineIDResetter().reset_machine_ids()
                 MachineIDResetter().reset_machine_ids()
+                logging.info("所有操作已完成")
             else:
             else:
-                print("账户注册失败")
-
-        print("执行完毕")
+                logging.error("获取会话令牌失败,注册流程未完成")
 
 
     except Exception as e:
     except Exception as e:
-        logging.error(f"程序执行出错: {str(e)}")
+        logging.error(f"程序执行出: {str(e)}")
         import traceback
         import traceback
 
 
         logging.error(traceback.format_exc())
         logging.error(traceback.format_exc())
     finally:
     finally:
         if browser_manager:
         if browser_manager:
             browser_manager.quit()
             browser_manager.quit()
-        input("\n按回车键退出...")
+        input("\n程序执行完毕,按回车键退出...")