Spaces:
Paused
Paused
refactor: 全局 print 替换为 logging + rich 美化输出
Browse files- 所有模块 print() 替换为 logging.info/warning/error
- 引入 rich 依赖,日志使用 RichHandler 带颜色和时间戳
- 状态表格使用 rich.Table 渲染,带边框、颜色、状态图标
- 百分比按阈值着色(>30% 绿、>0% 黄、0% 红)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Files changed (10)
5 unmodified lines678910115 unmodified linesdependencies = ["playwright>=1.40.0","requests>=2.28.0","xvfbwrapper>=0.2.9",]5 unmodified lines67891011125 unmodified linesdependencies = ["playwright>=1.40.0","requests>=2.28.0","rich>=14.3.4","xvfbwrapper>=0.2.9",]
123"""AutoTeam - ChatGPT Team 账号自动轮转管理工具"""__version__ = "0.1.0"12345678910111213"""AutoTeam - ChatGPT Team 账号自动轮转管理工具"""__version__ = "0.1.0"import loggingfrom rich.logging import RichHandlerlogging.basicConfig(level=logging.INFO,format="%(message)s",datefmt="[%H:%M:%S]",handlers=[RichHandler(rich_tracebacks=True, show_path=False, markup=True)],)
1 unmodified line2345671 unmodified line9101112131433 unmodified lines484950515253541 unmodified line5657585960616251 unmodified lines1141151161171181191209 unmodified lines13013113213313413513610 unmodified lines14714814915015115215318 unmodified lines17217317417517617717817918018118218310 unmodified lines19419519619719819920015 unmodified lines21621721821922022122222322422522623 unmodified lines25025125225325425525625725834 unmodified lines29329429529629729829930030130230330430530630730830931031131210 unmodified lines3233243253263273283293303313323333343351 unmodified lineimport autoteam.display # noqa: F401import jsonimport timeimport uuidfrom pathlib import Path1 unmodified linefrom autoteam.config import CHATGPT_ACCOUNT_IDPROJECT_ROOT = Path(__file__).parent.parent.parentBASE_DIR = PROJECT_ROOTSCREENSHOT_DIR = PROJECT_ROOT / "screenshots"33 unmodified linesself.page = self.context.new_page()# 先访问 chatgpt.com 过 Cloudflareprint("[ChatGPT] 访问 chatgpt.com 过 Cloudflare...")self.page.goto("https://chatgpt.com/", wait_until="domcontentloaded", timeout=60000)time.sleep(5)1 unmodified linehtml = self.page.content()[:1000].lower()if "verify you are human" not in html and "challenge" not in self.page.url:breakprint(f" 等待 Cloudflare... ({i*5}s)")time.sleep(5)# 注入 session cookie(分片格式)51 unmodified lines})self.context.add_cookies(cookies)print("[ChatGPT] 已注入 session cookies")# 获取 access tokenself._fetch_access_token()9 unmodified linesreturn # 已配置if not config.CHATGPT_ACCOUNT_ID:print("[ChatGPT] ⚠️ 请在 .env 中配置 CHATGPT_ACCOUNT_ID")return# 用 account_id 调 API 获取 workspace 信息10 unmodified linesif result and result.get("workspace_name"):config.CHATGPT_WORKSPACE_NAME = result["workspace_name"]print(f"[ChatGPT] 自动检测到 workspace 名称: {result['workspace_name']}")return# fallback: 从 admin 页面提取 workspace 名称18 unmodified lines}''')if name:config.CHATGPT_WORKSPACE_NAME = nameprint(f"[ChatGPT] 自动检测到 workspace 名称: {name}")returnexcept Exception:passprint("[ChatGPT] ⚠️ 未能自动获取 workspace 名称,请在 .env 中配置 CHATGPT_WORKSPACE_NAME")def _fetch_access_token(self):"""通过浏览器 fetch 获取 access token"""10 unmodified linesif result.get("ok") and "accessToken" in result.get("data", {}):self.access_token = result["data"]["accessToken"]print("[ChatGPT] 已获取 access token")return# 尝试通过 sentinel chat requirements 获取 token15 unmodified linesbearer_file = BASE_DIR / "bearer_token"if bearer_file.exists():self.access_token = bearer_file.read_text().strip()print("[ChatGPT] 从 bearer_token 文件加载 access token")return# 最后手段:导航到 chatgpt.com 让前端 JS 获取 token,然后从 localStorage 读取print("[ChatGPT] 尝试通过页面获取 access token...")self.page.goto("https://chatgpt.com/", wait_until="networkidle", timeout=60000)time.sleep(10)23 unmodified linesif token:self.access_token = tokenprint("[ChatGPT] 从页面获取到 access token")else:print("[ChatGPT] 警告: 未能获取 access token,将尝试无 token 调用")def _api_fetch(self, method, path, body=None):"""在浏览器内用 fetch 调用 ChatGPT API"""34 unmodified lines"resend_emails": True,}print(f"[ChatGPT] 发送邀请到 {email} (seat_type={seat_type})...")result = self._api_fetch("POST", path, body)status = result["status"]resp_body = result["body"]print(f"[ChatGPT] 响应状��: {status}")try:data = json.loads(resp_body)print(f"[ChatGPT] 响应内容: {json.dumps(data, indent=2)[:500]}")except Exception:data = resp_bodyprint(f"[ChatGPT] 响应内容: {resp_body[:500]}")# 新账号用 usage_based 绕过后,需要改回 defaultif status == 200 and seat_type == "usage_based" and isinstance(data, dict):10 unmodified linespath = f"/backend-api/accounts/{self.account_id}/invites/{invite_id}"body = {"seat_type": seat_type}print(f"[ChatGPT] 修改邀请 seat_type -> {seat_type}...")result = self._api_fetch("PATCH", path, body)if result["status"] == 200:print(f"[ChatGPT] ✅ seat_type 已改为 {seat_type}")else:print(f"[ChatGPT] ❌ 修改 seat_type 失败: {result['status']} {result['body'][:200]}")def list_invites(self):"""获取当前邀请列表"""1 unmodified line23456781 unmodified line101112131415161733 unmodified lines515253545556571 unmodified line5960616263646551 unmodified lines1171181191201211221239 unmodified lines13313413513613713813910 unmodified lines15015115215315415515618 unmodified lines17517617717817918018118218318418518610 unmodified lines19719819920020120220315 unmodified lines21922022122222322422522622722822923 unmodified lines25325425525625725825926026134 unmodified lines29629729829930030130230330430530630730830931031131231331431510 unmodified lines3263273283293303313323333343353363373381 unmodified lineimport autoteam.display # noqa: F401import jsonimport loggingimport timeimport uuidfrom pathlib import Path1 unmodified linefrom autoteam.config import CHATGPT_ACCOUNT_IDlogger = logging.getLogger(__name__)PROJECT_ROOT = Path(__file__).parent.parent.parentBASE_DIR = PROJECT_ROOTSCREENSHOT_DIR = PROJECT_ROOT / "screenshots"33 unmodified linesself.page = self.context.new_page()# 先访问 chatgpt.com 过 Cloudflarelogger.info("[ChatGPT] 访问 chatgpt.com 过 Cloudflare...")self.page.goto("https://chatgpt.com/", wait_until="domcontentloaded", timeout=60000)time.sleep(5)1 unmodified linehtml = self.page.content()[:1000].lower()if "verify you are human" not in html and "challenge" not in self.page.url:breaklogger.info("[ChatGPT] 等待 Cloudflare... (%ds)", i * 5)time.sleep(5)# 注入 session cookie(分片格式)51 unmodified lines})self.context.add_cookies(cookies)logger.info("[ChatGPT] 已注入 session cookies")# 获取 access tokenself._fetch_access_token()9 unmodified linesreturn # 已配置if not config.CHATGPT_ACCOUNT_ID:logger.warning("[ChatGPT] 请在 .env 中配置 CHATGPT_ACCOUNT_ID")return# 用 account_id 调 API 获取 workspace 信息10 unmodified linesif result and result.get("workspace_name"):config.CHATGPT_WORKSPACE_NAME = result["workspace_name"]logger.info("[ChatGPT] 自动检测到 workspace 名称: %s", result['workspace_name'])return# fallback: 从 admin 页面提取 workspace 名称18 unmodified lines}''')if name:config.CHATGPT_WORKSPACE_NAME = namelogger.info("[ChatGPT] 自动检测到 workspace 名称: %s", name)returnexcept Exception:passlogger.warning("[ChatGPT] 未能自动获取 workspace 名称,请在 .env 中配置 CHATGPT_WORKSPACE_NAME")def _fetch_access_token(self):"""通过浏览器 fetch 获取 access token"""10 unmodified linesif result.get("ok") and "accessToken" in result.get("data", {}):self.access_token = result["data"]["accessToken"]logger.info("[ChatGPT] 已获取 access token")return# 尝试通过 sentinel chat requirements 获取 token15 unmodified linesbearer_file = BASE_DIR / "bearer_token"if bearer_file.exists():self.access_token = bearer_file.read_text().strip()logger.info("[ChatGPT] 从 bearer_token 文件加载 access token")return# 最后手段:导航到 chatgpt.com 让前端 JS 获取 token,然后从 localStorage 读取logger.info("[ChatGPT] 尝试通过页面获取 access token...")self.page.goto("https://chatgpt.com/", wait_until="networkidle", timeout=60000)time.sleep(10)23 unmodified linesif token:self.access_token = tokenlogger.info("[ChatGPT] 从页面获取到 access token")else:logger.warning("[ChatGPT] 未能获取 access token,将尝试无 token 调用")def _api_fetch(self, method, path, body=None):"""在浏览器内用 fetch 调用 ChatGPT API"""34 unmodified lines"resend_emails": True,}logger.info("[ChatGPT] 发送邀请到 %s (seat_type=%s)...", email, seat_type)result = self._api_fetch("POST", path, body)status = result["status"]resp_body = result["body"]logger.info("[ChatGPT] 响应状态: %d", status)try:data = json.loads(resp_body)logger.debug("[ChatGPT] 响应内容: %s", json.dumps(data, indent=2)[:500])except Exception:data = resp_bodylogger.debug("[ChatGPT] 响应内容: %s", resp_body[:500])# 新账号用 usage_based 绕过后,需要改回 defaultif status == 200 and seat_type == "usage_based" and isinstance(data, dict):10 unmodified linespath = f"/backend-api/accounts/{self.account_id}/invites/{invite_id}"body = {"seat_type": seat_type}logger.info("[ChatGPT] 修改邀请 seat_type -> %s...", seat_type)result = self._api_fetch("PATCH", path, body)if result["status"] == 200:logger.info("[ChatGPT] seat_type 已改为 %s", seat_type)else:logger.error("[ChatGPT] 修改 seat_type 失败: %d %s", result['status'], result['body'][:200])def list_invites(self):"""获取当前邀请列表"""
123453 unmodified lines9101112131428 unmodified lines434445464748497 unmodified lines5758596061626324 unmodified lines888990919293944 unmodified lines9910010110210310410512 unmodified lines1181191201211221231241251261271281291301311 unmodified line1331341351361371381392 unmodified lines142143144145146"""CloudMail API 客户端 - 管理临时邮箱和读取邮件"""import reimport timeimport uuid3 unmodified linesCLOUDMAIL_DOMAIN, EMAIL_POLL_INTERVAL, EMAIL_POLL_TIMEOUT,)class CloudMailClient:def __init__(self):28 unmodified linesif resp["code"] != 200:raise Exception(f"CloudMail 登录失败: {resp.get('message')}")self.token = resp["data"]["token"]print(f"[CloudMail] 登录成功")return self.tokendef create_temp_email(self, prefix=None):7 unmodified linesraise Exception(f"创建邮箱失败: {resp.get('message')}")account_id = resp["data"]["accountId"]print(f"[CloudMail] 临时邮箱已创建: {email} (accountId={account_id})")return account_id, emaildef search_emails_by_recipient(self, to_email, size=10):24 unmodified linesdef wait_for_email(self, to_email, timeout=None, sender_keyword=None):"""轮询等待邮件到达(用 admin API 按收件人搜索)"""timeout = timeout or EMAIL_POLL_TIMEOUTprint(f"[CloudMail] 等待邮件到达 {to_email}... (超时 {timeout}s)")start = time.time()while time.time() - start < timeout:4 unmodified linesif sender_keyword and sender_keyword.lower() not in sender.lower():continuesubject = email.get("subject", "")print(f"\n[CloudMail] 收到邮件: {subject} (from: {sender})")return emailelapsed = int(time.time() - start)12 unmodified lineslinks = re.findall(r'href="(https://chatgpt\.com/auth/login\?[^"]*)"', html)if links:link = links[0]print(f"[CloudMail] 提取到邀请链接: {link[:80]}...")return link# 从纯文本中提取links = re.findall(r'(https://chatgpt\.com/auth/login\?[^\s<>"\']+)', text)if links:link = links[0]print(f"[CloudMail] 提取到邀请链接: {link[:80]}...")return link# 通用链接提取1 unmodified linematch = re.search(link_pattern, html or text, re.IGNORECASE)if match:link = match.group(0)print(f"[CloudMail] 提取到链接: {link[:80]}...")return linkreturn None2 unmodified lines"""删除临时邮箱账户"""resp = self._delete("/account/delete", {"accountId": account_id})if resp["code"] == 200:print(f"[CloudMail] 临时邮箱已删除 (accountId={account_id})")return resp1234563 unmodified lines101112131415161728 unmodified lines464748495051527 unmodified lines6061626364656624 unmodified lines919293949596974 unmodified lines10210310410510610710812 unmodified lines1211221231241251261271281291301311321331341 unmodified line1361371381391401411422 unmodified lines145146147148149"""CloudMail API 客户端 - 管理临时邮箱和读取邮件"""import loggingimport reimport timeimport uuid3 unmodified linesCLOUDMAIL_DOMAIN, EMAIL_POLL_INTERVAL, EMAIL_POLL_TIMEOUT,)logger = logging.getLogger(__name__)class CloudMailClient:def __init__(self):28 unmodified linesif resp["code"] != 200:raise Exception(f"CloudMail 登录失败: {resp.get('message')}")self.token = resp["data"]["token"]logger.info("[CloudMail] 登录成功")return self.tokendef create_temp_email(self, prefix=None):7 unmodified linesraise Exception(f"创建邮箱失败: {resp.get('message')}")account_id = resp["data"]["accountId"]logger.info("[CloudMail] 临时邮箱已创建: %s (accountId=%s)", email, account_id)return account_id, emaildef search_emails_by_recipient(self, to_email, size=10):24 unmodified linesdef wait_for_email(self, to_email, timeout=None, sender_keyword=None):"""轮询等待邮件到达(用 admin API 按收件人搜索)"""timeout = timeout or EMAIL_POLL_TIMEOUTlogger.info("[CloudMail] 等待邮件到达 %s... (超时 %ds)", to_email, timeout)start = time.time()while time.time() - start < timeout:4 unmodified linesif sender_keyword and sender_keyword.lower() not in sender.lower():continuesubject = email.get("subject", "")logger.info("[CloudMail] 收到邮件: %s (from: %s)", subject, sender)return emailelapsed = int(time.time() - start)12 unmodified lineslinks = re.findall(r'href="(https://chatgpt\.com/auth/login\?[^"]*)"', html)if links:link = links[0]logger.info("[CloudMail] 提取到邀请链接: %s...", link[:80])return link# 从纯文本中提取links = re.findall(r'(https://chatgpt\.com/auth/login\?[^\s<>"\']+)', text)if links:link = links[0]logger.info("[CloudMail] 提取到邀请链接: %s...", link[:80])return link# 通用链接提取1 unmodified linematch = re.search(link_pattern, html or text, re.IGNORECASE)if match:link = match.group(0)logger.info("[CloudMail] 提取到链接: %s...", link[:80])return linkreturn None2 unmodified lines"""删除临时邮箱账户"""resp = self._delete("/account/delete", {"accountId": account_id})if resp["code"] == 200:logger.info("[CloudMail] 临时邮箱已删除 (accountId=%s)", account_id)return resp
2 unmodified lines3456782 unmodified lines11121314151658 unmodified lines757677787980818 unmodified lines9091929394959638 unmodified lines13513613713813914014115 unmodified lines1571581591601611621631641651661671681691701713 unmodified lines1751761771781791801812 unmodified lines18418518618718818919012 unmodified lines2032042052062072082097 unmodified lines2172182192202212222234 unmodified lines22822923023123223323438 unmodified lines27327427527627727827913 unmodified lines29329429529629729829930030130230330430530630730830931031131213 unmodified lines32632732832933033133233333433533633733833934034134234334434534634734834914 unmodified lines3643653663673683693708 unmodified lines3793803813823833843857 unmodified lines39339439539639739839911 unmodified lines4114124134144154164171 unmodified line41942042142242342442514 unmodified lines4404414424434444454461 unmodified line4484494504514524534544554564574584594604614626 unmodified lines46947047147247347447511 unmodified lines4874884894904914924939 unmodified lines50350450550650750850912 unmodified lines52252352452552652752823 unmodified lines55255355455555655755855956056156256356456531 unmodified lines5975985996006016026032 unmodified linesimport jsonimport hashlibimport timeimport base64import os2 unmodified linesfrom pathlib import Pathfrom playwright.sync_api import sync_playwrightPROJECT_ROOT = Path(__file__).parent.parent.parentAUTH_DIR = PROJECT_ROOT / "auths"SCREENSHOT_DIR = PROJECT_ROOT / "screenshots"58 unmodified lines}auth_url = f"{CODEX_AUTH_URL}?{urllib.parse.urlencode(params)}"print(f"[Codex] 开始 OAuth 登录: {email}")auth_code = None8 unmodified lines)# === Step 0: 先登录 ChatGPT 并切换到 Team workspace ===print("[Codex] 先登录 ChatGPT 选择 Team workspace...")_page = context.new_page()_page.goto("https://chatgpt.com/auth/login", wait_until="domcontentloaded", timeout=60000)time.sleep(5)38 unmodified linesci = _page.locator('input[name="code"]').firstif ci.is_visible(timeout=5000) and mail_client:import re as _re2print("[Codex] ChatGPT 登录需要验证码...")otp = Nonet0 = time.time()while time.time() - t0 < 120:15 unmodified linespass_screenshot(_page, "codex_00_chatgpt_login.png")print(f"[Codex] ChatGPT 登录后 URL: {_page.url}")# 如果是 workspace 选择页面,选择 Teamif "workspace" in _page.url:print("[Codex] 检测到 workspace 选择页面...")try:ws_btn = _page.locator(f'text="{CHATGPT_WORKSPACE_NAME}"').firstif CHATGPT_WORKSPACE_NAME and ws_btn.is_visible(timeout=3000):print(f"[Codex] 选择 workspace: {CHATGPT_WORKSPACE_NAME}")ws_btn.click()time.sleep(5)else:3 unmodified linestry:text = opt.inner_text(timeout=1000).strip()if text and "个人" not in text and "Personal" not in text and text not in ("ChatGPT", ""):print(f"[Codex] 选择 workspace: {text}")opt.click()time.sleep(5)break2 unmodified linesexcept Exception:pass_screenshot(_page, "codex_00_after_workspace.png")print(f"[Codex] 选择 workspace 后 URL: {_page.url}")# 确保 _account cookie 设置为 Team account IDif CHATGPT_ACCOUNT_ID:12 unmodified lines"secure": True,"sameSite": "Lax",}])print(f"[Codex] 已设置 _account cookie = {CHATGPT_ACCOUNT_ID}")# 关闭 ChatGPT 页面但保留 context_page.close()7 unmodified linesqs = urllib.parse.parse_qs(parsed.query)auth_code = qs.get("code", [None])[0]if auth_code:print(f"[Codex] 捕获到 auth code!")# 也监听 response/framenavigated 来捕获 redirect URLdef on_response(response):4 unmodified linesqs = urllib.parse.parse_qs(parsed.query)auth_code = qs.get("code", [None])[0]if auth_code:print(f"[Codex] 从 response 捕获到 auth code!")page = context.new_page()page.on("request", on_request)38 unmodified linescode_input = Noneif code_input and mail_client:print("[Codex] 需要登录验证码,从 CloudMail 获取...")import re as _restart_t = time.time()otp_code = None13 unmodified linestime.sleep(3)if otp_code:print(f"[Codex] 获取到验证码: {otp_code}")code_input.fill(otp_code)time.sleep(0.5)page.locator('button:has-text("Continue"), button:has-text("继续"), button[type="submit"]').first.click()time.sleep(5)_screenshot(page, "codex_03c_after_otp.png")else:print("[Codex] 未获取到验证码")elif code_input:print("[Codex] 需要验证码但无 mail_client,无法自动获取")# 处理 about-you 页面(可能出现在 OAuth 流程中)if "about-you" in page.url:print("[Codex] 检测到 about-you 页面,填写个人信息...")try:name_input = page.locator('input[name="name"]').firstif name_input.is_visible(timeout=3000):13 unmodified linestime.sleep(0.2)page.keyboard.type(val, delay=80)time.sleep(0.3)print(" 填入生日: 1995/06/15 (spinbutton)")else:# 类型 B:普通年龄数字输入框age_input = page.locator('input[name="age"], input[placeholder*="年龄"]').firsttry:if age_input.is_visible(timeout=3000):age_input.fill("25")print(" 填入年龄: 25")except Exception:print(" 未找到年龄/生日输入框")time.sleep(0.5)page.locator('button:has-text("继续"), button:has-text("Continue"), button:has-text("完成帐户创建"), button[type="submit"]').first.click()time.sleep(5)_screenshot(page, "codex_03d_after_aboutyou.png")print(f"[Codex] about-you 完成,当前 URL: {page.url}")except Exception as e:print(f"[Codex] about-you 处理失败: {e}")# 处理多个授权/同意页面(可能有多步)for step in range(10):14 unmodified linesif ws_btn.is_visible(timeout=2000):ws_btn.click()time.sleep(1)print(f"[Codex] 已选择 workspace: {CHATGPT_WORKSPACE_NAME} (step {step+1})")except Exception:pass8 unmodified linestext = opt.inner_text(timeout=1000).strip()if text and "新组织" not in text and "New" not in text:opt.click()print(f"[Codex] 选择已有组织: {text}")breakelse:if options:7 unmodified linesotp_input = page.locator('input[name="code"], input[inputmode="numeric"]').firstif otp_input.is_visible(timeout=2000) and mail_client:import re as _re3print(f"[Codex] 需要邮箱验证码 (step {step+1})...")otp = Nonet0 = time.time()while time.time() - t0 < 120:11 unmodified linestime.sleep(0.5)page.locator('button[type="submit"], button:has-text("Continue"), button:has-text("继续")').first.click()time.sleep(5)print(f"[Codex] 已输入验证码: {otp}")continue # 重新循环检查下一个页面except Exception:pass1 unmodified linetry:consent_btn = page.locator('button:has-text("继续"), button:has-text("Continue"), button:has-text("Allow")').firstif consent_btn.is_visible(timeout=5000):print(f"[Codex] 点击同意/继续按钮 (step {step+1})...")consent_btn.click()time.sleep(5)_screenshot(page, f"codex_04_consent_{step+1}.png")14 unmodified linesqs = urllib.parse.parse_qs(parsed.query)auth_code = qs.get("code", [None])[0]if auth_code:print(f"[Codex] 从 URL 捕获到 auth code!")breakexcept Exception:pass1 unmodified lineif not auth_code:_screenshot(page, "codex_05_no_callback.png")print(f"[Codex] 未获取到 auth code,当前 URL: {page.url}")browser.close()if not auth_code:print("[Codex] OAuth 登录失败:未获取到 authorization code")return Noneprint(f"[Codex] 获取到 auth code,交换 token...")# 用 auth code 换 tokenimport requests6 unmodified lines}, headers={"Content-Type": "application/x-www-form-urlencoded"})if resp.status_code != 200:print(f"[Codex] Token 交换失败: {resp.status_code} {resp.text[:200]}")return Nonetoken_data = resp.json()11 unmodified lines"expired": time.time() + token_data.get("expires_in", 3600),}print(f"[Codex] 登录成功: {bundle['email']} (plan: {bundle['plan_type']})")return bundle9 unmodified lines# 清理同一邮箱的旧文件(避免 free/team 并存)for old in AUTH_DIR.glob(f"codex-{email}-*.json"):old.unlink()print(f"[Codex] 清理旧文件: {old.name}")filename = f"codex-{email}-{plan_type}-{hash_id}.json"filepath = AUTH_DIR / filename12 unmodified linesfilepath.write_text(json.dumps(auth_data, indent=2))os.chmod(filepath, 0o600)print(f"[Codex] 认证文件已保存: {filepath}")return str(filepath)23 unmodified linestimeout=30,)except Exception as e:print(f"[Codex] 请求异常: {e}")return "auth_error", Noneif resp.status_code in (401, 403):return "auth_error", Noneif resp.status_code != 200:print(f"[Codex] wham/usage 异常: {resp.status_code} {resp.text[:200]}")return "auth_error", Nonetry:31 unmodified lines}, headers={"Content-Type": "application/x-www-form-urlencoded"})if resp.status_code != 200:print(f"[Codex] Token 刷新失败: {resp.status_code}")return Nonedata = resp.json()2 unmodified lines34567892 unmodified lines121314151617181958 unmodified lines787980818283848 unmodified lines9394959697989938 unmodified lines13813914014114214314415 unmodified lines1601611621631641651661671681691701711721731743 unmodified lines1781791801811821831842 unmodified lines18718818919019119219312 unmodified lines2062072082092102112127 unmodified lines2202212222232242252264 unmodified lines23123223323423523623738 unmodified lines27627727827928028128213 unmodified lines29629729829930030130230330430530630730830931031131231331431513 unmodified lines32933033133233333433533633733833934034134234334434534634734834935035135214 unmodified lines3673683693703713723738 unmodified lines3823833843853863873887 unmodified lines39639739839940040140211 unmodified lines4144154164174184194201 unmodified line42242342442542642742814 unmodified lines4434444454464474484491 unmodified line4514524534544554564574584594604614624634644656 unmodified lines47247347447547647747811 unmodified lines4904914924934944954969 unmodified lines50650750850951051151212 unmodified lines52552652752852953053123 unmodified lines55555655755855956056156256356456556656756831 unmodified lines6006016026036046056062 unmodified linesimport jsonimport hashlibimport loggingimport timeimport base64import os2 unmodified linesfrom pathlib import Pathfrom playwright.sync_api import sync_playwrightlogger = logging.getLogger(__name__)PROJECT_ROOT = Path(__file__).parent.parent.parentAUTH_DIR = PROJECT_ROOT / "auths"SCREENSHOT_DIR = PROJECT_ROOT / "screenshots"58 unmodified lines}auth_url = f"{CODEX_AUTH_URL}?{urllib.parse.urlencode(params)}"logger.info("[Codex] 开始 OAuth 登录: %s", email)auth_code = None8 unmodified lines)# === Step 0: 先登录 ChatGPT 并切换到 Team workspace ===logger.info("[Codex] 先登录 ChatGPT 选择 Team workspace...")_page = context.new_page()_page.goto("https://chatgpt.com/auth/login", wait_until="domcontentloaded", timeout=60000)time.sleep(5)38 unmodified linesci = _page.locator('input[name="code"]').firstif ci.is_visible(timeout=5000) and mail_client:import re as _re2logger.info("[Codex] ChatGPT 登录需要验证码...")otp = Nonet0 = time.time()while time.time() - t0 < 120:15 unmodified linespass_screenshot(_page, "codex_00_chatgpt_login.png")logger.info("[Codex] ChatGPT 登录后 URL: %s", _page.url)# 如果是 workspace 选择页面,选择 Teamif "workspace" in _page.url:logger.info("[Codex] 检测到 workspace 选择页面...")try:ws_btn = _page.locator(f'text="{CHATGPT_WORKSPACE_NAME}"').firstif CHATGPT_WORKSPACE_NAME and ws_btn.is_visible(timeout=3000):logger.info("[Codex] 选择 workspace: %s", CHATGPT_WORKSPACE_NAME)ws_btn.click()time.sleep(5)else:3 unmodified linestry:text = opt.inner_text(timeout=1000).strip()if text and "个人" not in text and "Personal" not in text and text not in ("ChatGPT", ""):logger.info("[Codex] 选择 workspace: %s", text)opt.click()time.sleep(5)break2 unmodified linesexcept Exception:pass_screenshot(_page, "codex_00_after_workspace.png")logger.info("[Codex] 选择 workspace 后 URL: %s", _page.url)# 确保 _account cookie 设置为 Team account IDif CHATGPT_ACCOUNT_ID:12 unmodified lines"secure": True,"sameSite": "Lax",}])logger.debug("[Codex] 已设置 _account cookie = %s", CHATGPT_ACCOUNT_ID)# 关闭 ChatGPT 页面但保留 context_page.close()7 unmodified linesqs = urllib.parse.parse_qs(parsed.query)auth_code = qs.get("code", [None])[0]if auth_code:logger.info("[Codex] 捕获到 auth code!")# 也监听 response/framenavigated 来捕获 redirect URLdef on_response(response):4 unmodified linesqs = urllib.parse.parse_qs(parsed.query)auth_code = qs.get("code", [None])[0]if auth_code:logger.info("[Codex] 从 response 捕获到 auth code!")page = context.new_page()page.on("request", on_request)38 unmodified linescode_input = Noneif code_input and mail_client:logger.info("[Codex] 需要登录验证码,从 CloudMail 获取...")import re as _restart_t = time.time()otp_code = None13 unmodified linestime.sleep(3)if otp_code:logger.info("[Codex] 获取到验证码: %s", otp_code)code_input.fill(otp_code)time.sleep(0.5)page.locator('button:has-text("Continue"), button:has-text("继续"), button[type="submit"]').first.click()time.sleep(5)_screenshot(page, "codex_03c_after_otp.png")else:logger.warning("[Codex] 未获取到验证码")elif code_input:logger.warning("[Codex] 需要验证码但无 mail_client,无法自动获取")# 处理 about-you 页面(可能出现在 OAuth 流程中)if "about-you" in page.url:logger.info("[Codex] 检测到 about-you 页面,填写个人信息...")try:name_input = page.locator('input[name="name"]').firstif name_input.is_visible(timeout=3000):13 unmodified linestime.sleep(0.2)page.keyboard.type(val, delay=80)time.sleep(0.3)logger.info("[Codex] 填入生日: 1995/06/15 (spinbutton)")else:# 类型 B:普通年龄数字输入框age_input = page.locator('input[name="age"], input[placeholder*="年龄"]').firsttry:if age_input.is_visible(timeout=3000):age_input.fill("25")logger.info("[Codex] 填入年龄: 25")except Exception:logger.warning("[Codex] 未找到年龄/生日输入框")time.sleep(0.5)page.locator('button:has-text("继续"), button:has-text("Continue"), button:has-text("完成帐户创建"), button[type="submit"]').first.click()time.sleep(5)_screenshot(page, "codex_03d_after_aboutyou.png")logger.info("[Codex] about-you 完成,当前 URL: %s", page.url)except Exception as e:logger.error("[Codex] about-you 处理失败: %s", e)# 处理多个授权/同意页面(可能有多步)for step in range(10):14 unmodified linesif ws_btn.is_visible(timeout=2000):ws_btn.click()time.sleep(1)logger.info("[Codex] 已选择 workspace: %s (step %d)", CHATGPT_WORKSPACE_NAME, step + 1)except Exception:pass8 unmodified linestext = opt.inner_text(timeout=1000).strip()if text and "新组织" not in text and "New" not in text:opt.click()logger.info("[Codex] 选择已有组织: %s", text)breakelse:if options:7 unmodified linesotp_input = page.locator('input[name="code"], input[inputmode="numeric"]').firstif otp_input.is_visible(timeout=2000) and mail_client:import re as _re3logger.info("[Codex] 需要邮箱验证码 (step %d)...", step + 1)otp = Nonet0 = time.time()while time.time() - t0 < 120:11 unmodified linestime.sleep(0.5)page.locator('button[type="submit"], button:has-text("Continue"), button:has-text("继续")').first.click()time.sleep(5)logger.info("[Codex] 已输入验证码: %s", otp)continue # 重新循环检查下一个页面except Exception:pass1 unmodified linetry:consent_btn = page.locator('button:has-text("继续"), button:has-text("Continue"), button:has-text("Allow")').firstif consent_btn.is_visible(timeout=5000):logger.info("[Codex] 点击同意/继续按钮 (step %d)...", step + 1)consent_btn.click()time.sleep(5)_screenshot(page, f"codex_04_consent_{step+1}.png")14 unmodified linesqs = urllib.parse.parse_qs(parsed.query)auth_code = qs.get("code", [None])[0]if auth_code:logger.info("[Codex] 从 URL 捕获到 auth code!")breakexcept Exception:pass1 unmodified lineif not auth_code:_screenshot(page, "codex_05_no_callback.png")logger.warning("[Codex] 未获取到 auth code,当前 URL: %s", page.url)browser.close()if not auth_code:logger.error("[Codex] OAuth 登录失败: 未获取到 authorization code")return Nonelogger.info("[Codex] 获取到 auth code,交换 token...")# 用 auth code 换 tokenimport requests6 unmodified lines}, headers={"Content-Type": "application/x-www-form-urlencoded"})if resp.status_code != 200:logger.error("[Codex] Token 交换失败: %d %s", resp.status_code, resp.text[:200])return Nonetoken_data = resp.json()11 unmodified lines"expired": time.time() + token_data.get("expires_in", 3600),}logger.info("[Codex] 登录成功: %s (plan: %s)", bundle['email'], bundle['plan_type'])return bundle9 unmodified lines# 清理同一邮箱的旧文件(避免 free/team 并存)for old in AUTH_DIR.glob(f"codex-{email}-*.json"):old.unlink()logger.info("[Codex] 清理旧文件: %s", old.name)filename = f"codex-{email}-{plan_type}-{hash_id}.json"filepath = AUTH_DIR / filename12 unmodified linesfilepath.write_text(json.dumps(auth_data, indent=2))os.chmod(filepath, 0o600)logger.info("[Codex] 认证文件已保存: %s", filepath)return str(filepath)23 unmodified linestimeout=30,)except Exception as e:logger.error("[Codex] 请求异常: %s", e)return "auth_error", Noneif resp.status_code in (401, 403):return "auth_error", Noneif resp.status_code != 200:logger.error("[Codex] wham/usage 异常: %d %s", resp.status_code, resp.text[:200])return "auth_error", Nonetry:31 unmodified lines}, headers={"Content-Type": "application/x-www-form-urlencoded"})if resp.status_code != 200:logger.error("[Codex] Token 刷新失败: %d", resp.status_code)return Nonedata = resp.json()
123456789106 unmodified lines171819202122233 unmodified lines272829303132335 unmodified lines394041424344454647486 unmodified lines5556575859606162636432 unmodified lines9798991001011021031041051061071081091102 unmodified lines113114115116117118119120121122123124125126"""CPA (CLIProxyAPI) 认证文件同步 - 保持本地 codex 认证文件与 CPA 一致"""import jsonimport requestsfrom pathlib import Pathfrom autoteam.config import CPA_URL, CPA_KEYPROJECT_ROOT = Path(__file__).parent.parent.parentAUTH_DIR = PROJECT_ROOT / "auths"6 unmodified lines"""获取 CPA 中所有认证文件"""resp = requests.get(f"{CPA_URL}/v0/management/auth-files", headers=_headers(), timeout=10)if resp.status_code != 200:print(f"[CPA] 获取文件列表失败: {resp.status_code}")return []data = resp.json()return data.get("files", [])3 unmodified lines"""上传认证文件到 CPA"""filepath = Path(filepath)if not filepath.exists():print(f"[CPA] 文件不存在: {filepath}")return Falsewith open(filepath, "rb") as f:5 unmodified lines)if resp.status_code == 200:print(f"[CPA] ✅ 已上传: {filepath.name}")return Trueelse:print(f"[CPA] ❌ 上传失败: {resp.status_code} {resp.text[:200]}")return False6 unmodified linestimeout=10,)if resp.status_code == 200:print(f"[CPA] ✅ 已删除: {name}")return Trueelse:print(f"[CPA] ❌ 删除失败: {resp.status_code} {resp.text[:200]}")return False32 unmodified linescpa_files = list_cpa_files()cpa_names = {f["name"]: f for f in cpa_files}print(f"\nactive 认证文件: {len(active_files)}")print(f"CPA 认证文件: {len(cpa_files)}")# 上传:active 有但 CPA 没有uploaded = 0for name, path in active_files.items():if name not in cpa_names:print(f"\n上传: {name}")if upload_to_cpa(path):uploaded += 12 unmodified linesfor name, cpa_file in cpa_names.items():email = cpa_file.get("email", "").lower()if email in local_emails and name not in active_files:print(f"\n删除非 active 文件: {name} ({email})")if delete_from_cpa(name):deleted += 1print(f"\n同步完成: 上传 {uploaded}, 删除 {deleted}")# 最终状态final_cpa = list_cpa_files()final_local_managed = [f for f in final_cpa if f.get("email", "").lower() in local_emails]print(f"CPA 中本地管理的认证文件: {len(final_local_managed)}")print(f"本地 active 认证文件: {len(active_files)}")123456789101112136 unmodified lines202122232425263 unmodified lines303132333435365 unmodified lines424344454647484950516 unmodified lines5859606162636465666732 unmodified lines1001011021031041051061071081091101111122 unmodified lines115116117118119120121122123124125126127"""CPA (CLIProxyAPI) 认证文件同步 - 保持本地 codex 认证文件与 CPA 一致"""import jsonimport loggingimport requestsfrom pathlib import Pathfrom autoteam.config import CPA_URL, CPA_KEYlogger = logging.getLogger(__name__)PROJECT_ROOT = Path(__file__).parent.parent.parentAUTH_DIR = PROJECT_ROOT / "auths"6 unmodified lines"""获取 CPA 中所有认证文件"""resp = requests.get(f"{CPA_URL}/v0/management/auth-files", headers=_headers(), timeout=10)if resp.status_code != 200:logger.error("[CPA] 获取文件列表失败: %d", resp.status_code)return []data = resp.json()return data.get("files", [])3 unmodified lines"""上传认证文件到 CPA"""filepath = Path(filepath)if not filepath.exists():logger.warning("[CPA] 文件不存在: %s", filepath)return Falsewith open(filepath, "rb") as f:5 unmodified lines)if resp.status_code == 200:logger.info("[CPA] 已上传: %s", filepath.name)return Trueelse:logger.error("[CPA] 上传失败: %d %s", resp.status_code, resp.text[:200])return False6 unmodified linestimeout=10,)if resp.status_code == 200:logger.info("[CPA] 已删除: %s", name)return Trueelse:logger.error("[CPA] 删除失败: %d %s", resp.status_code, resp.text[:200])return False32 unmodified linescpa_files = list_cpa_files()cpa_names = {f["name"]: f for f in cpa_files}logger.info("[CPA] active 认证文件: %d, CPA 认证文件: %d", len(active_files), len(cpa_files))# 上传:active 有但 CPA 没有uploaded = 0for name, path in active_files.items():if name not in cpa_names:logger.info("[CPA] 上传: %s", name)if upload_to_cpa(path):uploaded += 12 unmodified linesfor name, cpa_file in cpa_names.items():email = cpa_file.get("email", "").lower()if email in local_emails and name not in active_files:logger.info("[CPA] 删除非 active 文件: %s (%s)", name, email)if delete_from_cpa(name):deleted += 1logger.info("[CPA] 同步完成: 上传 %d, 删除 %d", uploaded, deleted)# 最终状态final_cpa = list_cpa_files()final_local_managed = [f for f in final_cpa if f.get("email", "").lower() in local_emails]logger.info("[CPA] CPA 中本地管理: %d, 本地 active: %d", len(final_local_managed), len(active_files))
1234567"""自动设置虚拟显示器(无头服务器)— 在 import 时执行"""import osif not os.environ.get("DISPLAY"):try:from xvfbwrapper import Xvfb12345678910"""自动设置虚拟显示器(无头服务器)— 在 import 时执行"""import loggingimport oslogger = logging.getLogger(__name__)if not os.environ.get("DISPLAY"):try:from xvfbwrapper import Xvfb
17 unmodified lines1819202122232425262728292 unmodified lines323334353637381 unmodified line404142434445466 unmodified lines535455565758595 unmodified lines656667686970711 unmodified line7374757677787980818283847 unmodified lines9293949596979816 unmodified lines1151161171181191201217 unmodified lines1291301311321331341356 unmodified lines14214314414514614714812 unmodified lines1611621631641651661671 unmodified line1691701711721731741751761771781791801811821831841851861871881899 unmodified lines1992002012022032042059 unmodified lines21521621721821922022122 unmodified lines2442452462472482492506 unmodified lines25725825926026126226324 unmodified lines2882892902912922932942952962972982993007 unmodified lines3083093103113123133141 unmodified line3163173183193203213223233243253263273 unmodified lines33133233333433533633733833934034134234334434534634734834935035135235312 unmodified lines3663673683693703713723733743753763773782 unmodified lines38138238338438538638738838939039139239339417 unmodified linesimport sysimport osimport timeimport refrom autoteam.cloudmail import CloudMailClientfrom autoteam.chatgpt_api import ChatGPTTeamAPIfrom playwright.sync_api import sync_playwrightMAIL_TIMEOUT = int(os.environ.get("MAIL_TIMEOUT", "180"))SCREENSHOT_DIR = "screenshots"2 unmodified linesos.makedirs(SCREENSHOT_DIR, exist_ok=True)path = f"{SCREENSHOT_DIR}/{name}"page.screenshot(path=path, full_page=True)print(f" [截图] {path}")def find_and_click(page, selectors, label="元素", timeout=3000):1 unmodified linetry:loc = page.locator(sel).firstif loc.is_visible(timeout=timeout):print(f" 找到{label}: {sel}")loc.click()return Trueexcept Exception:6 unmodified linestry:loc = page.locator(sel).firstif loc.is_visible(timeout=timeout):print(f" 找到{label}: {sel}")return locexcept Exception:continue5 unmodified lineshtml = page.content()[:2000].lower()if "verify you are human" not in html and "challenge" not in page.url:return Trueprint(f" 等待 Cloudflare... ({i*5}s)")time.sleep(5)return False1 unmodified linedef register_with_invite(page, invite_link, email, mail_client, password=None):"""用邀请链接注册 ChatGPT 账号并加入 workspace,返回 (success, password)"""print(f"\n[注册] 打开邀请链接...")page.goto(invite_link, wait_until="domcontentloaded", timeout=60000)time.sleep(5)wait_for_cloudflare(page)screenshot(page, "reg_01_invite_page.png")print(f" 当前 URL: {page.url}")# 可能需要点击 Sign upfind_and_click(page, [7 unmodified linesscreenshot(page, "reg_02_signup.png")# 输入邮箱print(f"[注册] 输入邮箱: {email}")email_input = find_visible(page, ['input[name="email"]','input[type="email"]',16 unmodified linestime.sleep(5)screenshot(page, "reg_03_after_email.png")else:print(" 未找到邮箱输入框,可能页面已自动填入")screenshot(page, "reg_03_no_email_input.png")# 可能需要输入密码(注册流程)7 unmodified linesif not password:import uuidpassword = f"Tmp_{uuid.uuid4().hex[:12]}!"print(f"[注册] 设置密码: {password}")pwd_input.fill(password)time.sleep(1)6 unmodified linesscreenshot(page, "reg_04_after_password.png")# 等待验证码邮件print(f"\n[注册] 等待 ChatGPT 发送验证码到 {email}...")verification_code = Nonetry:# 搜索来自 OpenAI 的验证码邮件(不是邀请邮件)12 unmodified linescode_match = re.search(r'\b(\d{6})\b', text)if code_match:verification_code = code_match.group(1)print(f"\n[CloudMail] 收到验证码: {verification_code}")breakif verification_code:break1 unmodified lineprint(f"\r[CloudMail] 等待验证码... ({elapsed}s)", end="", flush=True)time.sleep(3)except Exception as e:print(f"\n等待验证码异常: {e}")if not verification_code:print(f"\n未自动获取到验证码")screenshot(page, "reg_05_no_code.png")return False, password# 输入验证码print(f"[注册] 输入验证码: {verification_code}")screenshot(page, "reg_05_before_code.png")# 检查是否是多个单字符输入框single_inputs = page.locator('input[maxlength="1"]').all()if len(single_inputs) >= 4:print(f" 检测到 {len(single_inputs)} 个单字符输入框")for i, char in enumerate(verification_code):if i < len(single_inputs):single_inputs[i].fill(char)9 unmodified linesif code_input:code_input.fill(verification_code)else:print(" 未找到验证码输入框")screenshot(page, "reg_05_no_code_input.png")return False, password9 unmodified linestime.sleep(8)screenshot(page, "reg_06_after_code.png")print(f" 当前 URL: {page.url}")# 填写个人信息(全名 + 生日/年龄)name_input = find_visible(page, [22 unmodified linestime.sleep(0.2)page.keyboard.type(val, delay=80)time.sleep(0.3)print(" 填入生日: 1995/06/15 (spinbutton)")filled_age = Trueelse:# 类型 B:普通年龄数字输入框6 unmodified lines], "年龄输入框", timeout=3000)if age_input:age_input.fill("25")print(" 填入年龄: 25")filled_age = Trueif name_input or filled_age:24 unmodified linespage_text = page.inner_text("body")[:500].lower()if "chatgpt.com" in current_url and "auth" not in current_url:print(f"\n✅ 注册成功并已加入 workspace!")return True, passwordelif "workspace" in page_text or "welcome" in page_text:print(f"\n✅ 已加入 workspace!")return True, passwordelse:print(f"\n⚠️ 注册流程可能未完成,请查看截图")return False, password7 unmodified linesmail_client = CloudMailClient()mail_client.login()account_id, email = mail_client.create_temp_email()print(f"\n临时邮箱: {email}")# Step 2: 发送 Team 邀请chatgpt = ChatGPTTeamAPI()1 unmodified linestatus, data = chatgpt.invite_member(email)if status != 200:print(f"\n❌ 邀请失败 (HTTP {status})")return Falseprint(f"\n✅ 邀请已发送")# Step 3: 等待邀请邮件print(f"\n等待邀请邮件...")invite_link = Nonetry:email_data = mail_client.wait_for_email(3 unmodified lines)invite_link = mail_client.extract_invite_link(email_data)except TimeoutError:print(f"\n⏰ 等待邀请邮件超时")except Exception as e:print(f"\n❌ 获取邀请邮件失败: {e}")if not invite_link:print("❌ 未获取到邀请链接")return Falseprint(f"\n邀请链接: {invite_link}")# Step 4: 关闭 ChatGPT API 浏览器,开新浏览器做注册chatgpt.stop()chatgpt = Noneprint(f"\n{'='*50}")print(f" 开始注册 ChatGPT 账号")print(f"{'='*50}")with sync_playwright() as p:browser = p.chromium.launch(12 unmodified linesbrowser.close()if result:print(f"\n{'='*50}")print(f" ✅ 成功!{email} 已注册并加入 ChatGPT Team")print(f"{'='*50}")else:print(f"\n{'='*50}")print(f" ❌ 流程未完成,请查看 screenshots/ 目录")print(f"{'='*50}")return result2 unmodified lineschatgpt.stop()# 不删除临时邮箱,保留账号if mail_client and account_id:print(f"\n临时邮箱保留: {email} (accountId={account_id})")def main():print("=" * 50)print(" ChatGPT Team 自动邀请 + 注册工具")print("=" * 50)result = run()sys.exit(0 if result else 1)17 unmodified lines1819202122232425262728293031322 unmodified lines353637383940411 unmodified line434445464748496 unmodified lines565758596061625 unmodified lines686970717273741 unmodified line7677787980818283848586877 unmodified lines959697989910010116 unmodified lines1181191201211221231247 unmodified lines1321331341351361371386 unmodified lines14514614714814915015112 unmodified lines1641651661671681691701 unmodified line1721731741751761771781791801811821831841851861871881891901911929 unmodified lines2022032042052062072089 unmodified lines21821922022122222322422 unmodified lines2472482492502512522536 unmodified lines26026126226326426526624 unmodified lines2912922932942952962972982993003013023037 unmodified lines3113123133143153163171 unmodified line3193203213223233243253263273283293303 unmodified lines33433533633733833934034134234334434534634734834935035135235335412 unmodified lines3673683693703713723733743752 unmodified lines37837938038138238338438538638738817 unmodified linesimport sysimport osimport loggingimport timeimport refrom autoteam.cloudmail import CloudMailClientfrom autoteam.chatgpt_api import ChatGPTTeamAPIfrom playwright.sync_api import sync_playwrightlogger = logging.getLogger(__name__)MAIL_TIMEOUT = int(os.environ.get("MAIL_TIMEOUT", "180"))SCREENSHOT_DIR = "screenshots"2 unmodified linesos.makedirs(SCREENSHOT_DIR, exist_ok=True)path = f"{SCREENSHOT_DIR}/{name}"page.screenshot(path=path, full_page=True)logger.debug("[截图] %s", path)def find_and_click(page, selectors, label="元素", timeout=3000):1 unmodified linetry:loc = page.locator(sel).firstif loc.is_visible(timeout=timeout):logger.debug("[注册] 找到%s: %s", label, sel)loc.click()return Trueexcept Exception:6 unmodified linestry:loc = page.locator(sel).firstif loc.is_visible(timeout=timeout):logger.debug("[注册] 找到%s: %s", label, sel)return locexcept Exception:continue5 unmodified lineshtml = page.content()[:2000].lower()if "verify you are human" not in html and "challenge" not in page.url:return Truelogger.info("[注册] 等待 Cloudflare... (%ds)", i * 5)time.sleep(5)return False1 unmodified linedef register_with_invite(page, invite_link, email, mail_client, password=None):"""用邀请链接注册 ChatGPT 账号并加入 workspace,返回 (success, password)"""logger.info("[注册] 打开邀请链接...")page.goto(invite_link, wait_until="domcontentloaded", timeout=60000)time.sleep(5)wait_for_cloudflare(page)screenshot(page, "reg_01_invite_page.png")logger.info("[注册] 当前 URL: %s", page.url)# 可能需要点击 Sign upfind_and_click(page, [7 unmodified linesscreenshot(page, "reg_02_signup.png")# 输入邮箱logger.info("[注册] 输入邮箱: %s", email)email_input = find_visible(page, ['input[name="email"]','input[type="email"]',16 unmodified linestime.sleep(5)screenshot(page, "reg_03_after_email.png")else:logger.info("[注册] 未找到邮箱输入框,可能页面已自动填入")screenshot(page, "reg_03_no_email_input.png")# 可能需要输入密码(注册流程)7 unmodified linesif not password:import uuidpassword = f"Tmp_{uuid.uuid4().hex[:12]}!"logger.info("[注册] 设置密码: %s", password)pwd_input.fill(password)time.sleep(1)6 unmodified linesscreenshot(page, "reg_04_after_password.png")# 等待验证码邮件logger.info("[注册] 等待 ChatGPT 发送验证码到 %s...", email)verification_code = Nonetry:# 搜索来自 OpenAI 的验证码邮件(不是邀请邮件)12 unmodified linescode_match = re.search(r'\b(\d{6})\b', text)if code_match:verification_code = code_match.group(1)logger.info("[CloudMail] 收到验证码: %s", verification_code)breakif verification_code:break1 unmodified lineprint(f"\r[CloudMail] 等待验证码... ({elapsed}s)", end="", flush=True)time.sleep(3)except Exception as e:logger.error("[注册] 等待验证码异常: %s", e)if not verification_code:logger.warning("[注册] 未自动获取到验证码")screenshot(page, "reg_05_no_code.png")return False, password# 输入验证码logger.info("[注册] 输入验证码: %s", verification_code)screenshot(page, "reg_05_before_code.png")# 检查是否是多个单字符输入框single_inputs = page.locator('input[maxlength="1"]').all()if len(single_inputs) >= 4:logger.debug("[注册] 检测到 %d 个单字符输入框", len(single_inputs))for i, char in enumerate(verification_code):if i < len(single_inputs):single_inputs[i].fill(char)9 unmodified linesif code_input:code_input.fill(verification_code)else:logger.warning("[注册] 未找到验证码输入框")screenshot(page, "reg_05_no_code_input.png")return False, password9 unmodified linestime.sleep(8)screenshot(page, "reg_06_after_code.png")logger.info("[注册] 当前 URL: %s", page.url)# 填写个人信息(全名 + 生日/年龄)name_input = find_visible(page, [22 unmodified linestime.sleep(0.2)page.keyboard.type(val, delay=80)time.sleep(0.3)logger.info("[注册] 填入生日: 1995/06/15 (spinbutton)")filled_age = Trueelse:# 类型 B:普通年龄数字输入框6 unmodified lines], "年龄输入框", timeout=3000)if age_input:age_input.fill("25")logger.info("[注册] 填入年龄: 25")filled_age = Trueif name_input or filled_age:24 unmodified linespage_text = page.inner_text("body")[:500].lower()if "chatgpt.com" in current_url and "auth" not in current_url:logger.info("[注册] 注册成功并已加入 workspace!")return True, passwordelif "workspace" in page_text or "welcome" in page_text:logger.info("[注册] 已加入 workspace!")return True, passwordelse:logger.warning("[注册] 注册流程可能未完成,请查看截图")return False, password7 unmodified linesmail_client = CloudMailClient()mail_client.login()account_id, email = mail_client.create_temp_email()logger.info("[邀请] 临时邮箱: %s", email)# Step 2: 发送 Team 邀请chatgpt = ChatGPTTeamAPI()1 unmodified linestatus, data = chatgpt.invite_member(email)if status != 200:logger.error("[邀请] 邀请失败 (HTTP %d)", status)return Falselogger.info("[邀请] 邀请已发送")# Step 3: 等待邀请邮件logger.info("[邀请] 等待邀请邮件...")invite_link = Nonetry:email_data = mail_client.wait_for_email(3 unmodified lines)invite_link = mail_client.extract_invite_link(email_data)except TimeoutError:logger.error("[邀请] 等待邀请邮件超时")except Exception as e:logger.error("[邀请] 获取邀请邮件失败: %s", e)if not invite_link:logger.error("[邀请] 未获取到邀请链接")return Falselogger.info("[邀请] 邀请链接: %s", invite_link)# Step 4: 关闭 ChatGPT API 浏览器,开新浏览器做注册chatgpt.stop()chatgpt = Nonelogger.info("[邀请] 开始注册 ChatGPT 账号")with sync_playwright() as p:browser = p.chromium.launch(12 unmodified linesbrowser.close()if result:logger.info("[邀请] %s 已注册并加入 ChatGPT Team", email)else:logger.error("[邀请] 流程未完成,请查看 screenshots/ 目录")return result2 unmodified lineschatgpt.stop()# 不删除临时邮箱,保留账号if mail_client and account_id:logger.info("[邀请] 临时邮箱保留: %s (accountId=%s)", email, account_id)def main():logger.info("ChatGPT Team 自动邀请 + 注册工具")result = run()sys.exit(0 if result else 1)
20 unmodified lines21222324252611 unmodified lines38394041424361 unmodified lines10510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715827 unmodified lines18618718818919019119219319419519619719819920020120217 unmodified lines2202212222232242252261 unmodified line2282292302312322332346 unmodified lines2412422432442452462472482492502512522532541 unmodified line2562572582592602612622632642652662672682692702712722732742752762772782792802812822832842854 unmodified lines2902912922932942952962972982993006 unmodified lines3073083093103113123133143153163173183193205 unmodified lines3263273283293303313322 unmodified lines3353363373383393403413423433444 unmodified lines3493503513523533543553563573584 unmodified lines3633643653663673683698 unmodified lines3783793803813823833841 unmodified line38638738838939039139239339439539614 unmodified lines4114124134144154164174184194204214226 unmodified lines42943043143243343443543643743830 unmodified lines46947047147247347447515 unmodified lines49149249349449549649710 unmodified lines50850951051151251351410 unmodified lines52552652752852953053114 unmodified lines54654754854955055155211 unmodified lines56456556656756856957057157257357457557657757857958058115 unmodified lines5975985996006016026036046056066076086093 unmodified lines61361461561661761861910 unmodified lines6306316326336346356366376385 unmodified lines6446456466476486496506516526536544 unmodified lines65966066166266366466566666766866967067167210 unmodified lines68368468568668768868963 unmodified lines75375475575675775875911 unmodified lines7717727737747757767777787797807817827837844 unmodified lines7897907917927937947957 unmodified lines80380480580680780880981081128 unmodified lines8408418428438448458468478488492 unmodified lines8528538548558568578581 unmodified line8608618628638648658668678682 unmodified lines8718728738748758768778788798808818821 unmodified line8848858868878888898908918928938948958961 unmodified line8988999009019029039045 unmodified lines9109119129139149159169179189199209219229239249259269279289292 unmodified lines9329339349359369379388 unmodified lines94794894995095195295395495595620 unmodified lines9779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010113 unmodified lines101510161017101810191020102110221023102410258 unmodified lines10341035103610371038103910405 unmodified lines104610471048104910501051105210531054105510561057105810595 unmodified lines10651066106710681069107010711072107310741075107610771078107910801081108210837 unmodified lines1091109210931094109510961097109810994 unmodified lines11041105110611071108110911101111111211137 unmodified lines11211122112311241125112611271128112920 unmodified linesimport sysimport osimport jsonimport timefrom pathlib import Path11 unmodified linesfrom autoteam.config import CHATGPT_ACCOUNT_IDfrom autoteam.cpa_sync import sync_to_cpaMAIL_TIMEOUT = int(os.environ.get("MAIL_TIMEOUT", "180"))61 unmodified lines"last_active_at": None,})changed = Trueprint(f"[同步] 发现 Team 中新成员: {email}(已添加到本地)")if changed:save_accounts(accounts)def _format_quota_row(email, status, qi):"""格式化单行账号额度信息"""if qi:p_pct = f"{100 - qi.get('primary_pct', 0)}%"w_pct = f"{100 - qi.get('weekly_pct', 0)}%"p_reset = time.strftime("%m-%d %H:%M", time.localtime(qi["primary_resets_at"])) if qi.get("primary_resets_at") else "-"w_reset = time.strftime("%m-%d %H:%M", time.localtime(qi["weekly_resets_at"])) if qi.get("weekly_resets_at") else "-"else:p_pct = w_pct = p_reset = w_reset = "-"return f" {email:<38} {status:<10} {p_pct:<8} {w_pct:<8} {p_reset:<14} {w_reset:<14}"def _print_status_table(accounts, quota_cache=None):"""打印账号状态表格"""if quota_cache is None:quota_cache = {}print(f"\n {'邮箱':<38} {'状态':<10} {'5h':<8} {'周':<8} {'5h重置':<14} {'周重置':<14}")print(f" {'─' * 96}")for acc in accounts:email = acc["email"]qi = quota_cache.get(email) or acc.get("last_quota")print(_format_quota_row(email, acc["status"], qi))active = [a for a in accounts if a["status"] == STATUS_ACTIVE]standby = [a for a in accounts if a["status"] == STATUS_STANDBY]exhausted = [a for a in accounts if a["status"] == STATUS_EXHAUSTED]print(f"\n 活跃: {len(active)} 待命: {len(standby)} 额度用完: {len(exhausted)} 总计: {len(accounts)}")def cmd_status():"""显示所有账号状态(先同步 Team 实际状态,active 账号实时��询额度)"""sync_account_states()accounts = load_accounts()if not accounts:print("暂无账号")return# active 账号实时查询额度quota_cache = {}for acc in accounts:if acc["status"] == STATUS_ACTIVE and acc.get("auth_file") and Path(acc["auth_file"]).exists():auth_data = json.loads(Path(acc["auth_file"]).read_text())27 unmodified lines# token 过期,尝试刷新if status == "auth_error" and rt:print(f"[{email}] token 过期,尝试刷新...")new_tokens = refresh_access_token(rt)if new_tokens:auth_data["access_token"] = new_tokens["access_token"]auth_data["refresh_token"] = new_tokens.get("refresh_token", rt)auth_data["last_refresh"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())Path(auth_file).write_text(json.dumps(auth_data, indent=2))print(f"[{email}] token 已刷新,重新检查额度...")status, info = check_codex_quota(new_tokens["access_token"])else:print(f"[{email}] token 刷新失败")return status, info17 unmodified linesno_auth_list.append(a)if not active_with_auth and not no_auth_list:print("没有可检查的 active 账号")return []# 检查有认证文件的账号额度1 unmodified lineauth_error_list = []if active_with_auth:print(f"\n检查 {len(active_with_auth)} 个 active 账号的额度...\n")for acc in active_with_auth:email = acc["email"]status_str, info = _check_and_refresh(acc)6 unmodified linesw_reset = info.get("weekly_resets_at", 0)p_time = time.strftime("%m-%d %H:%M", time.localtime(p_reset)) if p_reset else "?"w_time = time.strftime("%m-%d %H:%M", time.localtime(w_reset)) if w_reset else "?"print(f"[{email}] ✅ 5h: {p_remain}% (重置 {p_time}) | 周: {w_remain}% (重置 {w_time})")# 保存最新额度快照,供 status 离线展示update_account(email, last_quota=info)else:print(f"[{email}] ✅ 额度可用")elif status_str == "exhausted":resets_at = infoprint(f"[{email}] ❌ 额度已用完")update_account(email,status=STATUS_EXHAUSTED,quota_exhausted_at=time.time(),1 unmodified line)exhausted_list.append(acc)elif status_str == "auth_error":print(f"[{email}] ⚠️ 认证失败,需要重新登录 Codex")auth_error_list.append(acc)# 无认证文件的 active 账号也需要重新登录if no_auth_list:print(f"\n发现 {len(no_auth_list)} 个 active 账号无认证文件,需要登录 Codex:")for a in no_auth_list:print(f" {a['email']}")auth_error_list.extend(no_auth_list)# auth_error + 无认证文件的统一重新登录 Codexif auth_error_list:print(f"\n=== 重新登录 {len(auth_error_list)} 个 token 失效的账号 ===")mail_client = CloudMailClient()mail_client.login()for acc in auth_error_list:email = acc["email"]password = acc.get("password", "")print(f"\n[{email}] 重新 Codex 登录...")bundle = login_codex_via_browser(email, password, mail_client=mail_client)if bundle:auth_file = save_auth_file(bundle)update_account(email, auth_file=auth_file)print(f"[{email}] ✅ token 已更新")# 重新检查额度status_str, info = _check_and_refresh(find_account(load_accounts(), email))4 unmodified linesquota_resets_at=info,)exhausted_list.append(acc)print(f"[{email}] ❌ 额度已用完")elif status_str == "ok":print(f"[{email}] ✅ 额度可用")else:print(f"[{email}] ❌ Codex 登录失败,标记为 standby")update_account(email, status=STATUS_STANDBY)return exhausted_list6 unmodified linesresult = chatgpt_api._api_fetch("GET", path)if result["status"] != 200:print(f"[Team] 获取成员列表失败: {result['status']}")return Falsetry:data = json.loads(result["body"])members = data.get("items", data.get("users", data.get("members", [])))except Exception:print(f"[Team] 解析成员列表失败")return False# 找到对应邮箱的成员5 unmodified linesbreakif not target_user_id:print(f"[Team] 未在成员列表中找到 {email}")# 可能已经不在 team 了return True2 unmodified linesresult = chatgpt_api._api_fetch("DELETE", delete_path)if result["status"] in (200, 204):print(f"[Team] ✅ 已将 {email} 移出 Team")return Trueelse:print(f"[Team] ❌ 移除失败: {result['status']} {result['body'][:200]}")return False4 unmodified lineserrored = data.get("errored_emails", [])if errored:err_msg = errored[0].get("error", "unknown")print(f"[Team] 邀请 {email} 被拒绝: {err_msg}")# default 失败则尝试 usage_basedif seat_type == "default":print(f"[Team] 尝试 usage_based 方式...")return invite_to_team(chatgpt_api, email, seat_type="usage_based")return Falsereturn status == 2004 unmodified linesfrom autoteam.invite import register_with_invitefrom playwright.sync_api import sync_playwrightprint(f"开始注册 {email}...")with sync_playwright() as p:browser = p.chromium.launch(headless=False,8 unmodified linesbrowser.close()if not result:print(f"❌ 注册 {email} 失败")return None# Codex 登录1 unmodified lineif bundle:auth_file = save_auth_file(bundle)update_account(email, status=STATUS_ACTIVE, auth_file=auth_file, last_active_at=time.time())print(f"✅ 账号就绪: {email}")return emailelse:update_account(email, status=STATUS_ACTIVE)print(f"⚠️ 账号已加入 Team 但 Codex 登录失败: {email}")return email14 unmodified linesif not invites:return []print(f"\n[Pending] 发现 {len(invites)} 个待处理邀请:")completed = []for inv in invites:inv_email = inv.get("email_address", "")print(f" 检查 {inv_email} 是否已收到邮件...")# 从 CloudMail 搜索该邮箱的邀请邮件emails = mail_client.search_emails_by_recipient(inv_email, size=5)6 unmodified linesbreakif not invite_link:print(f" 未收到邮件,跳过")continueprint(f" 已收到邀请邮件,继续注册流程...")# 确保本地有账号记录acc = find_account(load_accounts(), inv_email)30 unmodified linesadd_account(email, password, cloudmail_account_id=account_id)# Step 3: 直接去 ChatGPT 注册页面print(f"\n[直接注册] {email}")signup_url = "https://chatgpt.com/auth/login"with sync_playwright() as p:15 unmodified lineshtml = page.content()[:2000].lower()if "verify you are human" not in html and "challenge" not in page.url:breakprint(f" 等待 Cloudflare... ({i*5}s)")time.sleep(5)screenshot(page, "direct_01_login_page.png")10 unmodified linesscreenshot(page, "direct_02_signup.png")# 输入邮箱print(f" 输入邮箱: {email}")email_input = page.locator('input[name="email"], input[type="email"]').firsttry:if email_input.is_visible(timeout=5000):10 unmodified linespwd_input = page.locator('input[type="password"]').firsttry:if pwd_input.is_visible(timeout=5000):print(f" 设置密码: {password}")pwd_input.fill(password)time.sleep(0.5)page.locator('button:has-text("Continue"), button:has-text("继续"), button[type="submit"]').first.click()14 unmodified linesif code_input:import reprint(f" 等待验证码...")verification_code = Nonestart_t = time.time()while time.time() - start_t < MAIL_TIMEOUT:11 unmodified linestime.sleep(3)if verification_code:print(f"\n 输入验证码: {verification_code}")code_input.fill(verification_code)time.sleep(0.5)page.locator('button:has-text("Continue"), button:has-text("继续"), button[type="submit"]').first.click()time.sleep(8)else:print(f"\n ❌ 未收到验证码")browser.close()return Nonescreenshot(page, "direct_05_after_code.png")print(f" 当前 URL: {page.url}")# 填写个人信息(全名 + 年龄/生日)name_input = page.locator('input[name="name"]').first15 unmodified linestime.sleep(0.2)page.keyboard.type(val, delay=80)time.sleep(0.3)print(" 填入生日: 1995/06/15")else:age_input = page.locator('input[name="age"]').firsttry:if age_input.is_visible(timeout=3000):age_input.fill("25")print(" 填入年龄: 25")except Exception:pass3 unmodified linespassscreenshot(page, "direct_06_after_profile.png")print(f" 当前 URL: {page.url}")# 可能需要选择 workspace 或自动加入try:10 unmodified linescurrent_url = page.urlsuccess = "chatgpt.com" in current_url and "auth" not in current_urlif success:print(f"\n ✅ 注册成功并已加入 workspace!")else:print(f"\n ⚠️ 注册可能未完成,URL: {current_url}")browser.close()5 unmodified linesif bundle:auth_file = save_auth_file(bundle)update_account(email, status=STATUS_ACTIVE, auth_file=auth_file, last_active_at=time.time())print(f"✅ 账号就绪: {email}")return emailelse:update_account(email, status=STATUS_ACTIVE)print(f"⚠️ 账号已加入 Team 但 Codex 登录失败: {email}")return email4 unmodified lines"""# 先检查 pending invitesif chatgpt_api and chatgpt_api.browser:print("\n[创建] 先检查 pending invites...")completed = _check_pending_invites(chatgpt_api, mail_client)if completed:print(f"\n从 pending invites 完成了 {len(completed)} 个账号")return completed[0]# 直接注册模式(不需要邀请)print("\n[创建] 使用直接注册模式...")if chatgpt_api and chatgpt_api.browser:chatgpt_api.stop()return create_account_direct(mail_client)10 unmodified linesemail = acc["email"]password = acc.get("password", "")print(f"\n[轮转] 恢复旧账号: {email}(直接登录)")# 关闭 ChatGPT API 浏览器避免冲突if chatgpt_api and chatgpt_api.browser:63 unmodified linesif code_input and mail_client:import reprint(" 等待登录验证码...")otp = Nonestart_t = time.time()while time.time() - start_t < 120:11 unmodified linesbreaktime.sleep(3)if otp:print(f" 输入验证码: {otp}")code_input.fill(otp)time.sleep(0.5)page.locator('button:has-text("Continue"), button:has-text("继续"), button[type="submit"]').first.click()time.sleep(5)screenshot(page, "reinvite_final.png")print(f" 当前 URL: {page.url}")browser.close()# 更新状态4 unmodified linesif bundle:auth_file = save_auth_file(bundle)update_account(email, auth_file=auth_file)print(f"✅ 旧账号已恢复: {email}")else:# 尝试用已有的 refresh_tokenauth_file = acc.get("auth_file")7 unmodified linesauth_data["refresh_token"] = new_tokens.get("refresh_token", rt)auth_data["last_refresh"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())Path(auth_file).write_text(json.dumps(auth_data, indent=2))print(f"✅ 旧账号已恢复(token 已刷新): {email}")return Trueprint(f"⚠️ 旧账号已登录但 Codex token 刷新失败: {email}")return True28 unmodified linesmail_client.login()return mail_clientprint("\n[1/5] 同步 Team 状态...")sync_account_states()print("[2/5] 检查额度...")exhausted = cmd_check()try:2 unmodified linesall_exhausted = [a for a in all_accounts if a["status"] == STATUS_EXHAUSTED]if all_exhausted:print(f"\n[3/5] 移出 {len(all_exhausted)} 个额度用完的账号...")ensure_chatgpt()for acc in all_exhausted:email = acc["email"]1 unmodified linechatgpt.start()if remove_from_team(chatgpt, email):update_account(email, status=STATUS_STANDBY)print(f" ✅ {email} → standby")else:print("[3/5] 无需移出账号")# 检查空缺if not chatgpt or not chatgpt.browser:2 unmodified linesvacancies = TARGET - current_countif vacancies <= 0:print(f"[4/5] Team 已满 ({current_count}/{TARGET})")sync_to_cpa()_print_status_table(load_accounts())returnprint(f"\n[4/5] 填补 {vacancies} 个空缺 (当前 {current_count}/{TARGET})...")# 优先复用旧账号filled = 01 unmodified linerecovered = [a for a in standby_list if a.get("_quota_recovered")]if recovered:print(f" 找到 {len(recovered)} 个额度已恢复的旧账号")for acc in recovered:if filled >= vacancies:breakemail = acc["email"]print(f" ♻️ 复用: {email}")if not chatgpt or not chatgpt.browser:ensure_chatgpt()reinvite_account(chatgpt, ensure_mail(), acc)1 unmodified lineremaining = vacancies - filledif remaining <= 0:print(f" 已用旧账号填满空缺")sync_to_cpa()_print_status_table(load_accounts())return5 unmodified linesnot_recovered = [a for a in standby_list if not a.get("_quota_recovered")]if not_recovered and active_with_quota:print(f"\n {len(not_recovered)} 个旧号等恢复中,Team 仍有 {len(active_with_quota)} 个可用,暂不创建")for a in not_recovered:rt = a.get("quota_resets_at")if rt:mins = max(0, int((rt - time.time()) / 60))print(f" {a['email']} → {mins} 分钟后恢复")sync_to_cpa()_print_status_table(load_accounts())return# 必须创建新号print(f"\n[5/5] 创建 {remaining} 个新账号...")for i in range(remaining):print(f"\n --- 第 {i+1}/{remaining} 个 ---")if not chatgpt or not chatgpt.browser:ensure_chatgpt()create_new_account(chatgpt, ensure_mail())2 unmodified linesif chatgpt and chatgpt.browser:chatgpt.stop()print("\n✅ 轮转完成")sync_to_cpa()_print_status_table(load_accounts())8 unmodified linestry:result = create_new_account(chatgpt, mail_client) # 内部会 stop chatgptif result:print(f"\n✅ 新账号添加成功: {result}")sync_to_cpa()else:print(f"\n❌ 添加失败")finally:if chatgpt.browser:chatgpt.stop()20 unmodified linestry:current = get_team_member_count(chatgpt)if current < 0:print("❌ 获取成员列表失败")returnprint(f"\n当前 Team 成员数: {current},目标: {target}")need = target - currentif need <= 0:print(f"成员数已满足({current} >= {target}),无需添加")returnprint(f"需要添加 {need} 个账号\n")for i in range(need):print(f"\n{'='*50}")print(f" 添加第 {i+1}/{need} 个账号")print(f"{'='*50}")# 优先复用 standby 中额度已恢复的旧账号reusable = get_next_reusable_account()if reusable and reusable.get("_quota_recovered"):email = reusable["email"]print(f"复用旧账号: {email}")# 确保 chatgpt 浏览器可用if not chatgpt.browser:chatgpt.start()reinvite_account(chatgpt, mail_client, reusable)else:# 创建新账号print("创建新账号...")if not chatgpt.browser:chatgpt.start()create_new_account(chatgpt, mail_client)3 unmodified lineschatgpt.start()new_count = get_team_member_count(chatgpt)if new_count >= 0:print(f"\n当前成员数: {new_count}/{target}")print(f"\n{'='*50}")print(f" 填充完成")print(f"{'='*50}")sync_to_cpa()cmd_status()8 unmodified lineslocal_emails = {a["email"].lower() for a in accounts}if not local_emails:print("本地无管理的账号,无需清理")returnchatgpt = ChatGPTTeamAPI()5 unmodified linesresult = chatgpt._api_fetch("GET", path)if result["status"] != 200:print(f"❌ 获取成员列表失败: {result['status']}")returndata = json.loads(result["body"])members = data.get("items", data.get("users", data.get("members", [])))total = len(members)print(f"\n当前 Team 成员数: {total}")# 区分:本地管理的 vs 手动添加的local_members = []5 unmodified lineselse:external_members.append(m)print(f" 手动添加的成员: {len(external_members)}")for m in external_members:print(f" {m.get('email'):<45} ({m.get('role')})")print(f" 本地管理的成员: {len(local_members)}")for m in local_members:print(f" {m.get('email'):<45} ({m.get('role')})")# 确定要移除的数量if max_seats is None:max_seats = len(external_members) + 2 # 保留外部成员 + 2 个本地席位to_remove_count = total - max_seatsif to_remove_count <= 0:print(f"\n成员数 {total} 未超过上限 {max_seats},无需清理")return# 从本地管理的账号中选择要移除的(优先移除额度已用完的)7 unmodified lines))to_remove = removable[:to_remove_count]print(f"\n需要移除 {len(to_remove)} 个本地账号:")for m in to_remove:print(f" {m.get('email')}")# 执行移除for m in to_remove:4 unmodified linesresult = chatgpt._api_fetch("DELETE", delete_path)if result["status"] in (200, 204):print(f" ✅ 已移除 {email}")update_account(email, status=STATUS_STANDBY)else:print(f" ❌ 移除 {email} 失败: {result['status']}")# 取消 pending invites 中本地管理的inv_result = chatgpt._api_fetch("GET", f"/backend-api/accounts/{CHATGPT_ACCOUNT_ID}/invites")7 unmodified linesdel_result = chatgpt._api_fetch("DELETE",f"/backend-api/accounts/{CHATGPT_ACCOUNT_ID}/invites/{inv_id}")if del_result["status"] in (200, 204):print(f" ✅ 已取消邀请 {inv_email}")print(f"\n清理完成")sync_to_cpa()finally:20 unmodified lines2122232425262711 unmodified lines394041424344454661 unmodified lines10810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121227 unmodified lines24024124224324424524624724824925025125225325425525617 unmodified lines2742752762772782792801 unmodified line2822832842852862872886 unmodified lines2952962972982993003013023033043053063073083091 unmodified line3113123133143153163173183193203213223233243253263273283293303313323333343353363373383393404 unmodified lines3453463473483493503513523533543556 unmodified lines3623633643653663673683693703713723733743755 unmodified lines3813823833843853863872 unmodified lines3903913923933943953963973983994 unmodified lines4044054064074084094104114124134 unmodified lines4184194204214224234248 unmodified lines4334344354364374384391 unmodified line44144244344444544644744844945045114 unmodified lines4664674684694704714724734744754764776 unmodified lines48448548648748848949049149249330 unmodified lines52452552652752852953015 unmodified lines54654754854955055155210 unmodified lines56356456556656756856910 unmodified lines58058158258358458558614 unmodified lines60160260360460560660711 unmodified lines61962062162262362462562662762862963063163263363463563615 unmodified lines6526536546556566576586596606616626636643 unmodified lines66866967067167267367410 unmodified lines6856866876886896906916926935 unmodified lines6997007017027037047057067077087094 unmodified lines71471571671771871972072172272372472572672710 unmodified lines73873974074174274374463 unmodified lines80880981081181281381411 unmodified lines8268278288298308318328338348358368378388394 unmodified lines8448458468478488498507 unmodified lines85885986086186286386486586628 unmodified lines8958968978988999009019029039042 unmodified lines9079089099109119129131 unmodified line9159169179189199209219229232 unmodified lines9269279289299309319329339349359369371 unmodified line9399409419429439449459469479489499509511 unmodified line9539549559569579589595 unmodified lines9659669679689699709719729739749759769779789799809819829839849852 unmodified lines9889899909919929939948 unmodified lines100310041005100610071008100910101011101220 unmodified lines1033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410653 unmodified lines1069107010711072107310741075107610778 unmodified lines10861087108810891090109110925 unmodified lines109810991100110111021103110411051106110711081109111011115 unmodified lines11171118111911201121112211231124112511261127112811291130113111321133113411357 unmodified lines1143114411451146114711481149115011514 unmodified lines11561157115811591160116111621163116411657 unmodified lines11731174117511761177117811791180118120 unmodified linesimport sysimport osimport jsonimport loggingimport timefrom pathlib import Path11 unmodified linesfrom autoteam.config import CHATGPT_ACCOUNT_IDfrom autoteam.cpa_sync import sync_to_cpalogger = logging.getLogger(__name__)MAIL_TIMEOUT = int(os.environ.get("MAIL_TIMEOUT", "180"))61 unmodified lines"last_active_at": None,})changed = Truelogger.info("[同步] 发现 Team 中新成员: %s(已添加到本地)", email)if changed:save_accounts(accounts)def _print_status_table(accounts, quota_cache=None):"""打印账号状态表格(使用 rich)"""from rich.console import Consolefrom rich.table import Tablefrom rich.text import Textif quota_cache is None:quota_cache = {}console = Console(width=120)table = Table(title="AutoTeam 账号状态",show_header=True,header_style="bold cyan",border_style="dim",title_style="bold white",padding=(0, 1),expand=True,)table.add_column("#", style="dim", width=3, justify="right")table.add_column("邮箱", style="white", no_wrap=True)table.add_column("状态", justify="center", width=10)table.add_column("5h 剩余", justify="right", width=8)table.add_column("周 剩余", justify="right", width=8)table.add_column("5h 重置", justify="center", width=12)table.add_column("周 重置", justify="center", width=12)STATUS_STYLE = {STATUS_ACTIVE: ("bold green", "● active"),STATUS_EXHAUSTED: ("bold red", "✗ used up"),STATUS_STANDBY: ("yellow", "○ standby"),STATUS_PENDING: ("dim", "… pending"),}for idx, acc in enumerate(accounts, 1):email = acc["email"]qi = quota_cache.get(email) or acc.get("last_quota")status = acc["status"]style, status_label = STATUS_STYLE.get(status, ("dim", status))status_text = Text(status_label, style=style)if qi:p_val = 100 - qi.get("primary_pct", 0)w_val = 100 - qi.get("weekly_pct", 0)p_pct = Text(f"{p_val}%", style="green" if p_val > 30 else "yellow" if p_val > 0 else "red")w_pct = Text(f"{w_val}%", style="green" if w_val > 30 else "yellow" if w_val > 0 else "red")p_reset = time.strftime("%m-%d %H:%M", time.localtime(qi["primary_resets_at"])) if qi.get("primary_resets_at") else "-"w_reset = time.strftime("%m-%d %H:%M", time.localtime(qi["weekly_resets_at"])) if qi.get("weekly_resets_at") else "-"else:p_pct = Text("-", style="dim")w_pct = Text("-", style="dim")p_reset = "-"w_reset = "-"table.add_row(str(idx), email, status_text,p_pct, w_pct,Text(p_reset, style="dim"), Text(w_reset, style="dim"),)console.print()console.print(table)# 统计摘要active = sum(1 for a in accounts if a["status"] == STATUS_ACTIVE)standby = sum(1 for a in accounts if a["status"] == STATUS_STANDBY)exhausted = sum(1 for a in accounts if a["status"] == STATUS_EXHAUSTED)console.print(f" [green]● 活跃 {active}[/] "f"[yellow]○ 待命 {standby}[/] "f"[red]✗ 用完 {exhausted}[/] "f"[dim]总计 {len(accounts)}[/]",)def cmd_status():"""显示所有账号状态(先同步 Team 实际状态,active 账号实时��询额度)"""logger.info("[状态] 同步 Team 实际状态...")sync_account_states()accounts = load_accounts()if not accounts:logger.info("[状态] 暂无账号")return# active 账号实时查询额度quota_cache = {}active_count = sum(1 for a in accounts if a["status"] == STATUS_ACTIVE and a.get("auth_file") and Path(a["auth_file"]).exists())if active_count:logger.info("[状态] 查询 %d 个 active 账号额度...", active_count)for acc in accounts:if acc["status"] == STATUS_ACTIVE and acc.get("auth_file") and Path(acc["auth_file"]).exists():auth_data = json.loads(Path(acc["auth_file"]).read_text())27 unmodified lines# token 过期,尝试刷新if status == "auth_error" and rt:logger.info("[%s] token 过期,尝试刷新...", email)new_tokens = refresh_access_token(rt)if new_tokens:auth_data["access_token"] = new_tokens["access_token"]auth_data["refresh_token"] = new_tokens.get("refresh_token", rt)auth_data["last_refresh"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())Path(auth_file).write_text(json.dumps(auth_data, indent=2))logger.info("[%s] token 已刷新,重新检查额度...", email)status, info = check_codex_quota(new_tokens["access_token"])else:logger.error("[%s] token 刷新失败", email)return status, info17 unmodified linesno_auth_list.append(a)if not active_with_auth and not no_auth_list:logger.info("[检查] 没有可检查的 active 账号")return []# 检查有认证文件的账号额度1 unmodified lineauth_error_list = []if active_with_auth:logger.info("[检查] 检查 %d 个 active 账号的额度...", len(active_with_auth))for acc in active_with_auth:email = acc["email"]status_str, info = _check_and_refresh(acc)6 unmodified linesw_reset = info.get("weekly_resets_at", 0)p_time = time.strftime("%m-%d %H:%M", time.localtime(p_reset)) if p_reset else "?"w_time = time.strftime("%m-%d %H:%M", time.localtime(w_reset)) if w_reset else "?"logger.info("[%s] 额度可用 - 5h剩余: %d%% (重置 %s) | 周剩余: %d%% (重置 %s)",email, p_remain, p_time, w_remain, w_time)# 保存最新额度快照,供 status 离线展示update_account(email, last_quota=info)else:logger.info("[%s] 额度可用", email)elif status_str == "exhausted":resets_at = infologger.warning("[%s] 额度已用完", email)update_account(email,status=STATUS_EXHAUSTED,quota_exhausted_at=time.time(),1 unmodified line)exhausted_list.append(acc)elif status_str == "auth_error":logger.warning("[%s] 认证失败,需要重新登录 Codex", email)auth_error_list.append(acc)# 无认证文件的 active 账号也需要重新登录if no_auth_list:logger.info("[检查] 发现 %d 个 active 账号无认证文件,需要登录 Codex:", len(no_auth_list))for a in no_auth_list:logger.info("[检查] %s", a['email'])auth_error_list.extend(no_auth_list)# auth_error + 无认证文件的统一重新登录 Codexif auth_error_list:logger.info("[检查] 重新登录 %d 个 token 失效的账号...", len(auth_error_list))mail_client = CloudMailClient()mail_client.login()for acc in auth_error_list:email = acc["email"]password = acc.get("password", "")logger.info("[%s] 重新 Codex 登录...", email)bundle = login_codex_via_browser(email, password, mail_client=mail_client)if bundle:auth_file = save_auth_file(bundle)update_account(email, auth_file=auth_file)logger.info("[%s] token 已更新", email)# 重新检查额度status_str, info = _check_and_refresh(find_account(load_accounts(), email))4 unmodified linesquota_resets_at=info,)exhausted_list.append(acc)logger.warning("[%s] 额度已用完", email)elif status_str == "ok":logger.info("[%s] 额度可用", email)else:logger.error("[%s] Codex 登录失败,标记为 standby", email)update_account(email, status=STATUS_STANDBY)return exhausted_list6 unmodified linesresult = chatgpt_api._api_fetch("GET", path)if result["status"] != 200:logger.error("[Team] 获取成员列表失败: %d", result['status'])return Falsetry:data = json.loads(result["body"])members = data.get("items", data.get("users", data.get("members", [])))except Exception:logger.error("[Team] 解析成员列表失败")return False# 找到对应邮箱的成员5 unmodified linesbreakif not target_user_id:logger.info("[Team] 未在成员列表中找到 %s(可能已移出)", email)# 可能已经不在 team 了return True2 unmodified linesresult = chatgpt_api._api_fetch("DELETE", delete_path)if result["status"] in (200, 204):logger.info("[Team] 已将 %s 移出 Team", email)return Trueelse:logger.error("[Team] 移除 %s 失败: %d %s", email, result['status'], result['body'][:200])return False4 unmodified lineserrored = data.get("errored_emails", [])if errored:err_msg = errored[0].get("error", "unknown")logger.warning("[Team] 邀请 %s 被拒绝: %s", email, err_msg)# default 失败则尝试 usage_basedif seat_type == "default":logger.info("[Team] 尝试 usage_based 方式...")return invite_to_team(chatgpt_api, email, seat_type="usage_based")return Falsereturn status == 2004 unmodified linesfrom autoteam.invite import register_with_invitefrom playwright.sync_api import sync_playwrightlogger.info("[注册] 开始注册 %s...", email)with sync_playwright() as p:browser = p.chromium.launch(headless=False,8 unmodified linesbrowser.close()if not result:logger.error("[注册] 注册 %s 失败", email)return None# Codex 登录1 unmodified lineif bundle:auth_file = save_auth_file(bundle)update_account(email, status=STATUS_ACTIVE, auth_file=auth_file, last_active_at=time.time())logger.info("[注册] 账号就绪: %s", email)return emailelse:update_account(email, status=STATUS_ACTIVE)logger.warning("[注册] 账号已加入 Team 但 Codex 登录失败: %s", email)return email14 unmodified linesif not invites:return []logger.info("[Pending] 发现 %d 个待处理邀请", len(invites))completed = []for inv in invites:inv_email = inv.get("email_address", "")logger.info("[Pending] 检查 %s 是否已收到邮件...", inv_email)# 从 CloudMail 搜索该邮箱的邀请邮件emails = mail_client.search_emails_by_recipient(inv_email, size=5)6 unmodified linesbreakif not invite_link:logger.info("[Pending] %s 未收到邮件,跳过", inv_email)continuelogger.info("[Pending] %s 已收到邀请邮件,继续注册流程...", inv_email)# 确保本地有账号记录acc = find_account(load_accounts(), inv_email)30 unmodified linesadd_account(email, password, cloudmail_account_id=account_id)# Step 3: 直接去 ChatGPT 注册页面logger.info("[直接注册] %s", email)signup_url = "https://chatgpt.com/auth/login"with sync_playwright() as p:15 unmodified lineshtml = page.content()[:2000].lower()if "verify you are human" not in html and "challenge" not in page.url:breaklogger.info("[直接注册] 等待 Cloudflare... (%ds)", i * 5)time.sleep(5)screenshot(page, "direct_01_login_page.png")10 unmodified linesscreenshot(page, "direct_02_signup.png")# 输入邮箱logger.info("[直接注册] 输入邮箱: %s", email)email_input = page.locator('input[name="email"], input[type="email"]').firsttry:if email_input.is_visible(timeout=5000):10 unmodified linespwd_input = page.locator('input[type="password"]').firsttry:if pwd_input.is_visible(timeout=5000):logger.info("[直接注册] 设置密码")pwd_input.fill(password)time.sleep(0.5)page.locator('button:has-text("Continue"), button:has-text("继续"), button[type="submit"]').first.click()14 unmodified linesif code_input:import relogger.info("[直接注册] 等待验证码...")verification_code = Nonestart_t = time.time()while time.time() - start_t < MAIL_TIMEOUT:11 unmodified linestime.sleep(3)if verification_code:logger.info("[直接注册] 输入验证码: %s", verification_code)code_input.fill(verification_code)time.sleep(0.5)page.locator('button:has-text("Continue"), button:has-text("继续"), button[type="submit"]').first.click()time.sleep(8)else:logger.error("[直接注册] 未收到验证码")browser.close()return Nonescreenshot(page, "direct_05_after_code.png")logger.info("[直接注册] 当前 URL: %s", page.url)# 填写个人信息(全名 + 年龄/生日)name_input = page.locator('input[name="name"]').first15 unmodified linestime.sleep(0.2)page.keyboard.type(val, delay=80)time.sleep(0.3)logger.info("[直接注册] 填入生日: 1995/06/15")else:age_input = page.locator('input[name="age"]').firsttry:if age_input.is_visible(timeout=3000):age_input.fill("25")logger.info("[直接注册] 填入年龄: 25")except Exception:pass3 unmodified linespassscreenshot(page, "direct_06_after_profile.png")logger.info("[直接注册] 当前 URL: %s", page.url)# 可能需要选择 workspace 或自动加入try:10 unmodified linescurrent_url = page.urlsuccess = "chatgpt.com" in current_url and "auth" not in current_urlif success:logger.info("[直接注册] 注册成功并已加入 workspace!")else:logger.warning("[直接注册] 注册可能未完成,URL: %s", current_url)browser.close()5 unmodified linesif bundle:auth_file = save_auth_file(bundle)update_account(email, status=STATUS_ACTIVE, auth_file=auth_file, last_active_at=time.time())logger.info("[直接注册] 账号就绪: %s", email)return emailelse:update_account(email, status=STATUS_ACTIVE)logger.warning("[直接注册] 账号已加入 Team 但 Codex 登录失败: %s", email)return email4 unmodified lines"""# 先检查 pending invitesif chatgpt_api and chatgpt_api.browser:logger.info("[创建] 先检查 pending invites...")completed = _check_pending_invites(chatgpt_api, mail_client)if completed:logger.info("[创建] 从 pending invites 完成了 %d 个账号", len(completed))return completed[0]# 直接注册模式(不需要邀请)logger.info("[创建] 使用直接注册模式...")if chatgpt_api and chatgpt_api.browser:chatgpt_api.stop()return create_account_direct(mail_client)10 unmodified linesemail = acc["email"]password = acc.get("password", "")logger.info("[轮转] 恢复旧账号: %s(直接登录)", email)# 关闭 ChatGPT API 浏览器避免冲突if chatgpt_api and chatgpt_api.browser:63 unmodified linesif code_input and mail_client:import relogger.info("[轮转] 等待登录验证码...")otp = Nonestart_t = time.time()while time.time() - start_t < 120:11 unmodified linesbreaktime.sleep(3)if otp:logger.info("[轮转] 输入验证码: %s", otp)code_input.fill(otp)time.sleep(0.5)page.locator('button:has-text("Continue"), button:has-text("继续"), button[type="submit"]').first.click()time.sleep(5)screenshot(page, "reinvite_final.png")logger.info("[轮转] 当前 URL: %s", page.url)browser.close()# 更新状态4 unmodified linesif bundle:auth_file = save_auth_file(bundle)update_account(email, auth_file=auth_file)logger.info("[轮转] 旧账号已恢复: %s", email)else:# 尝试用已有的 refresh_tokenauth_file = acc.get("auth_file")7 unmodified linesauth_data["refresh_token"] = new_tokens.get("refresh_token", rt)auth_data["last_refresh"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())Path(auth_file).write_text(json.dumps(auth_data, indent=2))logger.info("[轮转] 旧账号已恢复(token 已刷新): %s", email)return Truelogger.warning("[轮转] 旧账号已登录但 Codex token 刷新失败: %s", email)return True28 unmodified linesmail_client.login()return mail_clientlogger.info("[1/5] 同步 Team 状态...")sync_account_states()logger.info("[2/5] 检查额度...")exhausted = cmd_check()try:2 unmodified linesall_exhausted = [a for a in all_accounts if a["status"] == STATUS_EXHAUSTED]if all_exhausted:logger.info("[3/5] 移出 %d 个���度用完的账号...", len(all_exhausted))ensure_chatgpt()for acc in all_exhausted:email = acc["email"]1 unmodified linechatgpt.start()if remove_from_team(chatgpt, email):update_account(email, status=STATUS_STANDBY)logger.info("[3/5] %s → standby", email)else:logger.info("[3/5] 无需移出账号")# 检查空缺if not chatgpt or not chatgpt.browser:2 unmodified linesvacancies = TARGET - current_countif vacancies <= 0:logger.info("[4/5] Team 已满 (%d/%d)", current_count, TARGET)sync_to_cpa()_print_status_table(load_accounts())returnlogger.info("[4/5] 填补 %d 个空缺 (当前 %d/%d)...", vacancies, current_count, TARGET)# 优先复用旧账号filled = 01 unmodified linerecovered = [a for a in standby_list if a.get("_quota_recovered")]if recovered:logger.info("[4/5] 找到 %d 个额度已恢复的旧账号", len(recovered))for acc in recovered:if filled >= vacancies:breakemail = acc["email"]logger.info("[4/5] 复用: %s", email)if not chatgpt or not chatgpt.browser:ensure_chatgpt()reinvite_account(chatgpt, ensure_mail(), acc)1 unmodified lineremaining = vacancies - filledif remaining <= 0:logger.info("[4/5] 已用旧账号填满空缺")sync_to_cpa()_print_status_table(load_accounts())return5 unmodified linesnot_recovered = [a for a in standby_list if not a.get("_quota_recovered")]if not_recovered and active_with_quota:logger.info("[4/5] %d 个旧号等恢复中,Team 仍有 %d 个可用,暂不创建",len(not_recovered), len(active_with_quota))for a in not_recovered:rt = a.get("quota_resets_at")if rt:mins = max(0, int((rt - time.time()) / 60))logger.info("[4/5] %s → %d 分钟后恢复", a['email'], mins)sync_to_cpa()_print_status_table(load_accounts())return# 必须创建新号logger.info("[5/5] 创建 %d 个新账号...", remaining)for i in range(remaining):logger.info("[5/5] 创建第 %d/%d 个...", i + 1, remaining)if not chatgpt or not chatgpt.browser:ensure_chatgpt()create_new_account(chatgpt, ensure_mail())2 unmodified linesif chatgpt and chatgpt.browser:chatgpt.stop()logger.info("[轮转] 轮转完成")sync_to_cpa()_print_status_table(load_accounts())8 unmodified linestry:result = create_new_account(chatgpt, mail_client) # 内部会 stop chatgptif result:logger.info("[添加] 新账号添加成功: %s", result)sync_to_cpa()else:logger.error("[添加] 添加失败")finally:if chatgpt.browser:chatgpt.stop()20 unmodified linestry:current = get_team_member_count(chatgpt)if current < 0:logger.error("[填充] 获取成员列表失败")returnlogger.info("[填充] 当前 Team 成员数: %d,目标: %d", current, target)need = target - currentif need <= 0:logger.info("[填充] 成员数已满足(%d >= %d)���无需添加", current, target)returnlogger.info("[填充] 需要添加 %d 个账号", need)for i in range(need):logger.info("[填充] 添加第 %d/%d 个账号...", i + 1, need)# 优先复用 standby 中额度已恢复的旧账号reusable = get_next_reusable_account()if reusable and reusable.get("_quota_recovered"):email = reusable["email"]logger.info("[填充] 复用旧账号: %s", email)# 确保 chatgpt 浏览器可用if not chatgpt.browser:chatgpt.start()reinvite_account(chatgpt, mail_client, reusable)else:# 创建新账号logger.info("[填充] 创建新账号...")if not chatgpt.browser:chatgpt.start()create_new_account(chatgpt, mail_client)3 unmodified lineschatgpt.start()new_count = get_team_member_count(chatgpt)if new_count >= 0:logger.info("[填充] 当前成员数: %d/%d", new_count, target)logger.info("[填充] 填充完成")sync_to_cpa()cmd_status()8 unmodified lineslocal_emails = {a["email"].lower() for a in accounts}if not local_emails:logger.info("[清理] 本地无管理的账号,无需清理")returnchatgpt = ChatGPTTeamAPI()5 unmodified linesresult = chatgpt._api_fetch("GET", path)if result["status"] != 200:logger.error("[清理] 获取成员列表失败: %d", result['status'])returndata = json.loads(result["body"])members = data.get("items", data.get("users", data.get("members", [])))total = len(members)logger.info("[清理] 当前 Team 成员数: %d", total)# 区分:本地管理的 vs 手动添加的local_members = []5 unmodified lineselse:external_members.append(m)logger.info("[清理] 手动添加的成员: %d", len(external_members))for m in external_members:logger.info("[清理] %s (%s)", m.get('email'), m.get('role'))logger.info("[清理] 本地管理的成员: %d", len(local_members))for m in local_members:logger.info("[清理] %s (%s)", m.get('email'), m.get('role'))# 确定要移除的数量if max_seats is None:max_seats = len(external_members) + 2 # 保留外部成员 + 2 个本地席位to_remove_count = total - max_seatsif to_remove_count <= 0:logger.info("[清理] 成员数 %d 未超过上限 %d,无需清理", total, max_seats)return# 从本地管理的账号中选择要移除的(优先移除额度已用完的)7 unmodified lines))to_remove = removable[:to_remove_count]logger.info("[清理] 需要移除 %d 个本地账号:", len(to_remove))for m in to_remove:logger.info("[清理] %s", m.get('email'))# 执行移除for m in to_remove:4 unmodified linesresult = chatgpt._api_fetch("DELETE", delete_path)if result["status"] in (200, 204):logger.info("[清理] 已移除 %s", email)update_account(email, status=STATUS_STANDBY)else:logger.error("[清理] 移除 %s 失败: %d", email, result['status'])# 取消 pending invites 中本地管理的inv_result = chatgpt._api_fetch("GET", f"/backend-api/accounts/{CHATGPT_ACCOUNT_ID}/invites")7 unmodified linesdel_result = chatgpt._api_fetch("DELETE",f"/backend-api/accounts/{CHATGPT_ACCOUNT_ID}/invites/{inv_id}")if del_result["status"] in (200, 204):logger.info("[清理] 已取消邀请 %s", inv_email)logger.info("[清理] 清理完成")sync_to_cpa()finally:
8 unmodified lines910111213141 unmodified line161718192021186 unmodified lines20820921021121221325 unmodified lines2392402412422432449 unmodified lines2542552562572582598 unmodified linesdependencies = [{ name = "playwright" },{ name = "requests" },{ name = "xvfbwrapper" },]1 unmodified linerequires-dist = [{ name = "playwright", specifier = ">=1.40.0" },{ name = "requests", specifier = ">=2.28.0" },{ name = "xvfbwrapper", specifier = ">=0.2.9" },]186 unmodified lines{ url = "https://files.pythonhosted.org/packages/0e/61/66938bbb5fc52dbdf84594873d5b51fb1f7c7794e9c0f5bd885f30bc507b/idna-3.11-py3-none-any.whl", hash = "sha256:771a87f49d9defaf64091e6e6fe9c18d4833f140bd19464795bc32d966ca37ea", size = 71008, upload-time = "2025-10-12T14:55:18.883Z" },][[package]]name = "playwright"version = "1.58.0"25 unmodified lines{ url = "https://files.pythonhosted.org/packages/a0/c4/b4d4827c93ef43c01f599ef31453ccc1c132b353284fc6c87d535c233129/pyee-13.0.1-py3-none-any.whl", hash = "sha256:af2f8fede4171ef667dfded53f96e2ed0d6e6bd7ee3bb46437f77e3b57689228", size = 15659, upload-time = "2026-02-14T21:12:26.263Z" },][[package]]name = "requests"version = "2.33.1"9 unmodified lines{ url = "https://files.pythonhosted.org/packages/d7/8e/7540e8a2036f79a125c1d2ebadf69ed7901608859186c856fa0388ef4197/requests-2.33.1-py3-none-any.whl", hash = "sha256:4e6d1ef462f3626a1f0a0a9c42dd93c63bad33f9f1c1937509b8c5c8718ab56a", size = 64947, upload-time = "2026-03-30T16:09:13.83Z" },][[package]]name = "typing-extensions"version = "4.15.0"8 unmodified lines91011121314151 unmodified line17181920212223186 unmodified lines21021121221321421521621721821922022122222322422522622722822923023123223323423523625 unmodified lines2622632642652662672682692702712722732742752769 unmodified lines2862872882892902912922932942952962972982993003013023033048 unmodified linesdependencies = [{ name = "playwright" },{ name = "requests" },{ name = "rich" },{ name = "xvfbwrapper" },]1 unmodified linerequires-dist = [{ name = "playwright", specifier = ">=1.40.0" },{ name = "requests", specifier = ">=2.28.0" },{ name = "rich", specifier = ">=14.3.4" },{ name = "xvfbwrapper", specifier = ">=0.2.9" },]186 unmodified lines{ url = "https://files.pythonhosted.org/packages/0e/61/66938bbb5fc52dbdf84594873d5b51fb1f7c7794e9c0f5bd885f30bc507b/idna-3.11-py3-none-any.whl", hash = "sha256:771a87f49d9defaf64091e6e6fe9c18d4833f140bd19464795bc32d966ca37ea", size = 71008, upload-time = "2025-10-12T14:55:18.883Z" },][[package]]name = "markdown-it-py"version = "4.0.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "mdurl" },]sdist = { url = "https://files.pythonhosted.org/packages/5b/f5/4ec618ed16cc4f8fb3b701563655a69816155e79e24a17b651541804721d/markdown_it_py-4.0.0.tar.gz", hash = "sha256:cb0a2b4aa34f932c007117b194e945bd74e0ec24133ceb5bac59009cda1cb9f3", size = 73070, upload-time = "2025-08-11T12:57:52.854Z" }wheels = [{ url = "https://files.pythonhosted.org/packages/94/54/e7d793b573f298e1c9013b8c4dade17d481164aa517d1d7148619c2cedbf/markdown_it_py-4.0.0-py3-none-any.whl", hash = "sha256:87327c59b172c5011896038353a81343b6754500a08cd7a4973bb48c6d578147", size = 87321, upload-time = "2025-08-11T12:57:51.923Z" },][[package]]name = "mdurl"version = "0.1.2"source = { registry = "https://pypi.org/simple" }sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" }wheels = [{ url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" },][[package]]name = "playwright"version = "1.58.0"25 unmodified lines{ url = "https://files.pythonhosted.org/packages/a0/c4/b4d4827c93ef43c01f599ef31453ccc1c132b353284fc6c87d535c233129/pyee-13.0.1-py3-none-any.whl", hash = "sha256:af2f8fede4171ef667dfded53f96e2ed0d6e6bd7ee3bb46437f77e3b57689228", size = 15659, upload-time = "2026-02-14T21:12:26.263Z" },][[package]]name = "pygments"version = "2.20.0"source = { registry = "https://pypi.org/simple" }sdist = { url = "https://files.pythonhosted.org/packages/c3/b2/bc9c9196916376152d655522fdcebac55e66de6603a76a02bca1b6414f6c/pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", size = 4955991, upload-time = "2026-03-29T13:29:33.898Z" }wheels = [{ url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" },][[package]]name = "requests"version = "2.33.1"9 unmodified lines{ url = "https://files.pythonhosted.org/packages/d7/8e/7540e8a2036f79a125c1d2ebadf69ed7901608859186c856fa0388ef4197/requests-2.33.1-py3-none-any.whl", hash = "sha256:4e6d1ef462f3626a1f0a0a9c42dd93c63bad33f9f1c1937509b8c5c8718ab56a", size = 64947, upload-time = "2026-03-30T16:09:13.83Z" },][[package]]name = "rich"version = "14.3.4"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "markdown-it-py" },{ name = "pygments" },]sdist = { url = "https://files.pythonhosted.org/packages/e9/67/cae617f1351490c25a4b8ac3b8b63a4dda609295d8222bad12242dfdc629/rich-14.3.4.tar.gz", hash = "sha256:817e02727f2b25b40ef56f5aa2217f400c8489f79ca8f46ea2b70dd5e14558a9", size = 230524, upload-time = "2026-04-11T02:57:45.419Z" }wheels = [{ url = "https://files.pythonhosted.org/packages/b3/76/6d163cfac87b632216f71879e6b2cf17163f773ff59c00b5ff4900a80fa3/rich-14.3.4-py3-none-any.whl", hash = "sha256:07e7adb4690f68864777b1450859253bed81a99a31ac321ac1817b2313558952", size = 310480, upload-time = "2026-04-11T02:57:47.484Z" },][[package]]name = "typing-extensions"version = "4.15.0"
pyproject.toml+1
src/autoteam/__init__.py+10
src/autoteam/chatgpt_api.py+22-19
src/autoteam/cloudmail.py+11-8
src/autoteam/codex_auth.py+40-37
src/autoteam/cpa_sync.py+14-13
src/autoteam/display.py+3
src/autoteam/invite.py+38-44
src/autoteam/manager.py+176-124
uv.lock+45