拿到token
This commit is contained in:
143
main.py
143
main.py
@@ -4,6 +4,7 @@ OpenAI 账号自动注册系统 - 主程序入口
|
||||
|
||||
功能:
|
||||
- 异步并发执行多个注册任务
|
||||
- 账号登录获取 access_token
|
||||
- 代理池轮换
|
||||
- 结果保存和统计
|
||||
- 错误日志记录
|
||||
@@ -26,6 +27,109 @@ from utils.logger import logger, setup_logger
|
||||
import random
|
||||
|
||||
|
||||
async def login_account(
|
||||
config,
|
||||
email: str,
|
||||
password: str,
|
||||
task_id: int = 1
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
单个账号登录任务
|
||||
|
||||
参数:
|
||||
config: AppConfig 配置对象
|
||||
email: 登录邮箱
|
||||
password: 登录密码
|
||||
task_id: 任务 ID(用于日志标识)
|
||||
|
||||
返回:
|
||||
登录结果字典
|
||||
"""
|
||||
# 选择代理
|
||||
proxy = config.proxy.get_next_proxy()
|
||||
if proxy:
|
||||
logger.info(f"[Login {task_id}] Using proxy: {_mask_proxy(proxy)}")
|
||||
else:
|
||||
logger.info(f"[Login {task_id}] No proxy configured, using direct connection")
|
||||
|
||||
session = None
|
||||
try:
|
||||
session = OAISession(
|
||||
proxy=proxy,
|
||||
impersonate=config.tls_impersonate
|
||||
)
|
||||
|
||||
logger.info(f"[Login {task_id}] Starting login for {email}")
|
||||
result = await session.login(email, password)
|
||||
|
||||
result["task_id"] = task_id
|
||||
result["proxy"] = _mask_proxy(proxy) if proxy else "none"
|
||||
|
||||
if result["status"] == "success":
|
||||
logger.success(
|
||||
f"[Login {task_id}] ✅ Login successful: {email}"
|
||||
)
|
||||
# 保存 token 到文件
|
||||
await save_token(result, config)
|
||||
else:
|
||||
logger.error(
|
||||
f"[Login {task_id}] ❌ Login failed: {result.get('error', 'Unknown error')}"
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
logger.exception(f"[Login {task_id}] Unexpected error in login task")
|
||||
return {
|
||||
"task_id": task_id,
|
||||
"email": email,
|
||||
"status": "failed",
|
||||
"error": str(e),
|
||||
"message": f"Task exception: {type(e).__name__}"
|
||||
}
|
||||
|
||||
finally:
|
||||
if session:
|
||||
try:
|
||||
session.close()
|
||||
except Exception as e:
|
||||
logger.warning(f"[Login {task_id}] Error closing session: {e}")
|
||||
|
||||
|
||||
async def save_token(result: Dict[str, Any], config):
|
||||
"""
|
||||
保存登录 token 到文件
|
||||
|
||||
参数:
|
||||
result: 登录结果字典
|
||||
config: 配置对象
|
||||
"""
|
||||
output_path = Path("tokens.txt")
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
email = result.get("email", "unknown")
|
||||
access_token = result.get("access_token", "")
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
# 格式: email | access_token | timestamp
|
||||
line = f"{email} | {access_token[:50]}... | {timestamp}\n"
|
||||
|
||||
async with asyncio.Lock():
|
||||
with open(output_path, "a", encoding="utf-8") as f:
|
||||
f.write(line)
|
||||
|
||||
# 同时保存完整 token 到单独文件
|
||||
token_file = Path(f"tokens/{email.replace('@', '_at_')}.txt")
|
||||
token_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(token_file, "w", encoding="utf-8") as f:
|
||||
f.write(f"Email: {email}\n")
|
||||
f.write(f"Access Token: {access_token}\n")
|
||||
f.write(f"Session Token: {result.get('session_token', 'N/A')}\n")
|
||||
f.write(f"Timestamp: {timestamp}\n")
|
||||
|
||||
logger.debug(f"Token saved for {email}")
|
||||
|
||||
|
||||
async def register_account(
|
||||
config,
|
||||
task_id: int,
|
||||
@@ -115,6 +219,8 @@ async def save_account(result: Dict[str, Any], output_file: str):
|
||||
result: 注册结果字典
|
||||
output_file: 输出文件路径
|
||||
"""
|
||||
import json
|
||||
|
||||
# 确保目录存在
|
||||
output_path = Path(output_file)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -122,17 +228,44 @@ async def save_account(result: Dict[str, Any], output_file: str):
|
||||
# 构建保存内容
|
||||
email = result.get("email", "unknown")
|
||||
password = result.get("password", "unknown")
|
||||
access_token = result.get("access_token", "")
|
||||
status = result.get("status", "unknown")
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
# 格式: email:password | status | timestamp
|
||||
line = f"{email}:{password} | {status} | {timestamp}\n"
|
||||
# 保存到 JSON 文件
|
||||
json_file = Path("accounts.json")
|
||||
|
||||
# 异步写入文件(避免阻塞)
|
||||
# 读取现有数据
|
||||
accounts = []
|
||||
if json_file.exists():
|
||||
try:
|
||||
with open(json_file, "r", encoding="utf-8") as f:
|
||||
accounts = json.load(f)
|
||||
except (json.JSONDecodeError, Exception):
|
||||
accounts = []
|
||||
|
||||
# 添加新账号
|
||||
account_data = {
|
||||
"email": email,
|
||||
"password": password,
|
||||
"access_token": access_token,
|
||||
"oai_did": result.get("oai_did", ""),
|
||||
"status": status,
|
||||
"timestamp": timestamp
|
||||
}
|
||||
accounts.append(account_data)
|
||||
|
||||
# 写入 JSON
|
||||
async with asyncio.Lock():
|
||||
with open(output_path, "a", encoding="utf-8") as f:
|
||||
f.write(line)
|
||||
with open(json_file, "w", encoding="utf-8") as f:
|
||||
json.dump(accounts, f, indent=2, ensure_ascii=False)
|
||||
|
||||
# 同时保存到 txt(兼容旧格式)
|
||||
line = f"{email}:{password} | {status} | {timestamp}\n"
|
||||
with open(output_path, "a", encoding="utf-8") as f:
|
||||
f.write(line)
|
||||
|
||||
logger.info(f"Account saved to accounts.json: {email}")
|
||||
logger.debug(f"Account saved to {output_file}: {email}")
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user