Files
jev-decision-hub/auto_register.py
T

289 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""JEV auto-register — бесплатные ключи на автомате.
Регистрация на jev-ai.pro через magic-link: БЕЗ пароля и БЕЗ капчи.
Нужен только любой IMAP-ящик (Gmail + app password, или свой домен с catch-all).
Настройка (2 способа):
1) cp config.example.json config.json -> вписать свой IMAP
2) или env: JEV_IMAP_HOST / JEV_IMAP_USER / JEV_IMAP_PASS
Gmail: включить IMAP, создать app password (Google Account -> Security -> 2-Step -> App passwords).
Режимы почты:
"alias" — ящик поддерживает +теги (Gmail, Outlook): user+tag@domain
"catchall" — свой домен ловит всё: random@yourdomain.com
Команды:
python auto_register.py reg 5 # зарегистрировать 5 аккаунтов -> ключи в keys.txt
python auto_register.py checkin # daily check-in по всем аккаунтам (+1-3 кредита)
python auto_register.py status # аккаунты, ключи, кредиты
python auto_register.py daily # checkin + 2 новых реги (для cron)
Каждый аккаунт: welcome-кредиты + ежедневный check-in. Кредиты живут 30 дней.
Ключи пишутся в keys.txt (для jev_client.py / dashboard.py) и accounts.jsonl (куки для checkin).
Welcome-бонус (20 кредитов) дают только ~2 аккаунтам в день с одного IP.
Чтобы фармить больше — укажи "proxies_file" в config.json (текстовый файл, http://ip:port построчно):
каждая регистрация пойдёт через свежий прокси и получит свои welcome-20.
AlStack: https://t.me/AlStack
"""
import json, os, re, sys, time, random, string
import urllib.request, http.cookiejar
import imaplib, email
BASE = 'https://jev-ai.pro'
HERE = os.path.dirname(os.path.abspath(__file__))
KEYS_FILE = os.path.join(HERE, 'keys.txt')
ACC_FILE = os.path.join(HERE, 'accounts.jsonl')
CFG_FILE = os.path.join(HERE, 'config.json')
HDRS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
'Accept': '*/*', 'Accept-Language': 'en-US,en;q=0.9',
'Origin': BASE, 'Referer': BASE + '/jev-api',
'Sec-Ch-Ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
'Sec-Ch-Ua-Mobile': '?0', 'Sec-Ch-Ua-Platform': '"Windows"',
'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-origin',
}
def cfg():
c = {'imap_host': os.environ.get('JEV_IMAP_HOST', ''),
'imap_user': os.environ.get('JEV_IMAP_USER', ''),
'imap_pass': os.environ.get('JEV_IMAP_PASS', ''),
'email_mode': os.environ.get('JEV_EMAIL_MODE', 'alias'),
'email_domain': os.environ.get('JEV_EMAIL_DOMAIN', ''),
'proxies_file': os.environ.get('JEV_PROXIES_FILE', '')}
if os.path.exists(CFG_FILE):
c.update({k: v for k, v in json.load(open(CFG_FILE, encoding='utf-8')).items() if v})
if not (c['imap_host'] and c['imap_user'] and c['imap_pass']):
raise SystemExit('нет IMAP-конфига: cp config.example.json config.json и заполни (или env JEV_IMAP_*)')
if c['email_mode'] == 'catchall' and not c['email_domain']:
raise SystemExit('для catchall нужен email_domain')
return c
def load_proxies(c):
"""Опциональный файл прокси (http://ip:port построчно). Welcome-бонус ~2 акка/IP/день —
со свежим IP через прокси снова дают 20 кредитов. Пусто = прямые запросы."""
pf = c.get('proxies_file') or ''
if pf and os.path.exists(pf):
pxs = [l.strip() for l in open(pf, encoding='utf-8')
if l.strip() and not l.startswith('#') and '://' in l]
random.shuffle(pxs)
return pxs
return []
def proxy_alive(px):
"""Быстрый CONNECT-тест: большинство бесплатных прокси мертвы, не тратить на них реги."""
ph = urllib.request.ProxyHandler({'http': px, 'https': px})
op = urllib.request.build_opener(ph)
op.addheaders = [('User-Agent', HDRS['User-Agent'])]
try:
return op.open(BASE + '/login', timeout=15).status == 200
except Exception:
return False
def make_email(c):
tag = 'jv' + ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))
if c['email_mode'] == 'catchall':
return f'{tag}@{c["email_domain"]}'
local = c['imap_user'].split('@')[0]
domain = c['imap_user'].split('@')[1] if '@' in c['imap_user'] else c['email_domain']
return f'{local}+{tag}@{domain}'
def http_call(op, method, url, body=None, cookie_str=None):
h = dict(HDRS)
if body is not None:
h['Content-Type'] = 'application/json'
if cookie_str:
h['Cookie'] = cookie_str
req = urllib.request.Request(url, data=json.dumps(body).encode() if body is not None else None,
headers=h, method=method)
try:
r = op.open(req, timeout=45)
return r.status, r.read().decode('utf-8', 'ignore')
except urllib.error.HTTPError as ex:
return ex.code, ex.read().decode('utf-8', 'ignore')
def opener(proxy=None):
cj = http.cookiejar.CookieJar()
handlers = [urllib.request.HTTPCookieProcessor(cj)]
if proxy:
handlers.append(urllib.request.ProxyHandler({'http': proxy, 'https': proxy}))
op = urllib.request.build_opener(*handlers)
op.addheaders = list(HDRS.items())
return op, cj
def wait_magic_token(c, mail_to, tries=18):
"""Ждём письмо с magic-ссылкой. ВАЖНО: m.noop() каждый цикл — иначе IMAP не видит новые письма."""
m = imaplib.IMAP4_SSL(c['imap_host'])
m.login(c['imap_user'], c['imap_pass'])
m.select('INBOX')
local = mail_to.split('@')[0].lower()
url = None
for _ in range(tries):
m.noop()
typ, data = m.search(None, '(FROM "no-reply@jev-ai.pro")')
ids = data[0].split()
for i in ids[::-1][:15]:
typ, msg = m.fetch(i, '(RFC822)')
e = email.message_from_bytes(msg[0][1])
to = str(e.get('To', '')).lower()
# alias: точный тег в To; catchall: весь local-part
needle = local.split('+')[-1] if '+' in local else local
if needle not in to:
continue
html = ''
for p in e.walk():
if p.get_content_type() == 'text/html':
html = (p.get_payload(decode=True) or b'').decode('utf-8', 'ignore')
mm = re.search(r'href="(https://jev-ai\.pro/auth/magic-link\?token=[^"]+)"', html)
if mm:
url = mm.group(1)
break
if url:
break
time.sleep(6)
m.logout()
return url
def register_one(c, proxy=None):
mail = make_email(c)
op, cj = opener(proxy)
s, b = http_call(op, 'POST', BASE + '/api/auth/magic-link', {'email': mail, 'callbackUrl': '/'})
if s != 200:
return {'email': mail, 'error': f'magic-link {s} {b[:100]}'}
url = wait_magic_token(c, mail)
if not url:
return {'email': mail, 'error': 'письмо не пришло за ~2 мин'}
s, b = http_call(op, 'GET', url)
if s != 200:
return {'email': mail, 'error': f'verify {s}'}
ck = '; '.join(f'{k.name}={k.value}' for k in cj)
name = 'k' + ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))
s, b = http_call(op, 'POST', BASE + '/api/api-keys', {'name': name}, cookie_str=ck)
if s != 200:
return {'email': mail, 'error': f'apikey {s} {b[:100]}'}
d = json.loads(b)
rec = {'email': mail, 'secret': d['key']['secret'], 'key_id': d['key']['id'],
'cookie': ck, 'proxy': proxy or '', 'created': time.time()}
with open(ACC_FILE, 'a', encoding='utf-8') as f:
f.write(json.dumps(rec) + '\n')
with open(KEYS_FILE, 'a', encoding='utf-8') as f:
f.write(d['key']['secret'] + '\n')
return rec
def load_accounts():
if not os.path.exists(ACC_FILE):
return []
return [json.loads(l) for l in open(ACC_FILE, encoding='utf-8') if l.strip()]
def balance_of(a):
h = dict(HDRS)
h['Cookie'] = a.get('cookie', '')
h.pop('Origin', None)
req = urllib.request.Request(BASE + '/api/credit-balance', headers=h)
try:
r = urllib.request.urlopen(req, timeout=30)
return json.loads(r.read().decode()).get('balance')
except Exception:
return '?'
def cmd_reg(n):
c = cfg()
pxs = load_proxies(c)
ok = 0
pi = 0
n = int(n)
for i in range(n):
rec = None
# до 3 попыток: каждая со своим прокси (или direct если пула нет)
for attempt in range(3):
px = None
if pxs:
# берём следующий прокси, скипая мёртвые (до 6 проверок)
for _ in range(6):
cand = pxs[pi % len(pxs)]
pi += 1
if proxy_alive(cand):
px = cand
break
if not px:
print(f'[{i+1}/{n}] нет живых прокси в пуле')
continue
try:
rec = register_one(c, proxy=px)
except Exception as e:
rec = {'error': f'EXC {str(e)[:60]} (proxy {px})'}
if 'secret' in rec:
break
if not pxs:
break # direct-режим: без пула не ротировать
if rec and 'secret' in rec:
ok += 1
cr = balance_of(rec)
print(f'[{i+1}/{n}] OK {rec["email"]} key={rec["secret"][:12]}... credits={cr} proxy={rec.get("proxy") or "direct"}')
else:
print(f'[{i+1}/{n}] FAIL {rec}')
time.sleep(random.uniform(3, 7))
print(f'готово: {ok}/{n} аккаунтов, ключи в keys.txt')
def cmd_checkin():
total = 0
for a in load_accounts():
h = dict(HDRS)
h['Cookie'] = a.get('cookie', '')
h['Content-Type'] = 'application/json'
req = urllib.request.Request(BASE + '/api/daily-checkin', data=b'{}', headers=h, method='POST')
try:
r = urllib.request.urlopen(req, timeout=30)
got = json.loads(r.read().decode()).get('creditsAwarded', '?')
total += 1
print(f'{a["email"]}: +{got}')
except urllib.error.HTTPError as ex:
print(f'{a["email"]}: {ex.code} (уже заклеймлено сегодня)' if ex.code == 409 else f'{a["email"]}: {ex.code}')
except Exception as ex:
print(f'{a["email"]}: ERR {ex}')
print(f'check-in: {total} аккаунтов')
def cmd_status():
accs = load_accounts()
tot = 0
for a in accs:
b = balance_of(a)
if isinstance(b, int):
tot += b
print(f'{a["email"]} | key {a["secret"][:12]}... | credits {b}')
print(f'ИТОГО: {len(accs)} аккаунтов, {tot} кредитов')
def cmd_daily():
cmd_checkin()
cmd_reg(2)
cmd_status()
if __name__ == '__main__':
cmd = sys.argv[1] if len(sys.argv) > 1 else 'status'
if cmd == 'reg':
cmd_reg(sys.argv[2] if len(sys.argv) > 2 else 1)
elif cmd == 'checkin':
cmd_checkin()
elif cmd == 'status':
cmd_status()
elif cmd == 'daily':
cmd_daily()
else:
print(__doc__)