Files

145 lines
5.6 KiB
Python

from aiogram import Router
from aiogram.types import CallbackQuery, Message
from bot.api.asf import get_all_bots
from bot.logging_utils import get_logger
from bot.services.bot_accounts import (
ensure_admin_compatibility,
get_owned_bot,
list_user_bot_accounts,
)
from bot.config import ADMIN_ID
from bot.services.twofa import stop_twofa_task
from bot.ui.formatters import format_bot_ui, get_farm_summary
from bot.ui.keyboards import bot_details_keyboard, bots_keyboard, games_keyboard
from bot.services.bots import is_bot_reloading, is_idle_enabled, update_idle_game
router = Router()
logger = get_logger(__name__)
async def owned_callback_bot(callback: CallbackQuery, prefix: str):
try:
account_id = int((callback.data or "").removeprefix(prefix))
except ValueError:
return None
return await get_owned_bot(callback.from_user.id, account_id)
async def send_bots_menu(message: Message, user_id: int) -> None:
"""Отправляет отдельное сообщение со списком ботов пользователя."""
response = get_all_bots()
if response.status_code != 200 or not response.json().get("Success"):
await message.answer("Не удалось загрузить список ботов")
return
asf_bots = response.json().get("Result", {})
if user_id == ADMIN_ID:
await ensure_admin_compatibility(list(asf_bots))
accounts = await list_user_bot_accounts(user_id)
rows = [
(account.id, account.bot_name, asf_bots.get(account.bot_name, {}))
for account in accounts
]
await message.answer(
f"<b>🤖 Ваших ботов:</b> {len(rows)}\n\n{get_farm_summary({name: bot for _, name, bot in rows})}",
reply_markup=bots_keyboard(rows),
)
@router.callback_query(lambda c: c.data == "bot_loading")
async def bot_loading_handler(callback: CallbackQuery) -> None:
await callback.answer(
"Аккаунт ещё загружается. Попробуйте через несколько секунд.", show_alert=True
)
@router.callback_query(lambda c: c.data == "bots")
async def bots_handler(callback: CallbackQuery) -> None:
await stop_twofa_task(callback.message.message_id)
await callback.answer()
response = get_all_bots()
if response.status_code != 200 or not response.json().get("Success"):
await callback.message.edit_text("Не удалось загрузить список ботов")
return
asf_bots = response.json().get("Result", {})
if callback.from_user.id == ADMIN_ID:
await ensure_admin_compatibility(list(asf_bots))
accounts = await list_user_bot_accounts(callback.from_user.id)
rows = [
(account.id, account.bot_name, asf_bots.get(account.bot_name, {}))
for account in accounts
]
await callback.message.edit_text(
f"<b>🤖 Ваших ботов:</b> {len(rows)}\n\n{get_farm_summary({name: bot for _, name, bot in rows})}",
reply_markup=bots_keyboard(rows),
)
@router.callback_query(
lambda c: c.data and c.data.startswith("bot_") and c.data != "bot_loading"
)
async def bot_selected(callback: CallbackQuery) -> None:
account = await owned_callback_bot(callback, "bot_")
if account is None:
await callback.answer("Бот не найден или вам не принадлежит", show_alert=True)
return
await stop_twofa_task(callback.message.message_id)
if is_bot_reloading(account.bot_name):
await callback.answer(
"Аккаунт перезагружается. Попробуйте позже.", show_alert=True
)
return
bot = get_all_bots().json().get("Result", {}).get(account.bot_name)
if not bot or not bot.get("BotName") or not bot.get("SteamID"):
await callback.answer(
"Аккаунт ещё загружается. Попробуйте позже.", show_alert=True
)
return
await callback.answer()
await callback.message.edit_text(
format_bot_ui(bot),
disable_web_page_preview=True,
reply_markup=bot_details_keyboard(
account.id, bool(bot.get("HasMobileAuthenticator"))
),
)
@router.callback_query(lambda c: c.data and c.data.startswith("games_"))
async def games(callback: CallbackQuery) -> None:
account = await owned_callback_bot(callback, "games_")
if account is None:
await callback.answer("Бот не найден или вам не принадлежит", show_alert=True)
return
await callback.answer()
enabled = is_idle_enabled(account.bot_name, 730)
await callback.message.edit_text(
"⌚ Выберите игру для накрутки часов",
reply_markup=games_keyboard(account.id, enabled),
)
@router.callback_query(lambda c: c.data and c.data.startswith("farm|"))
async def farm_game(callback: CallbackQuery) -> None:
try:
_, account_id, app_id = (callback.data or "").split("|")
account = await get_owned_bot(callback.from_user.id, int(account_id))
app_id = int(app_id)
except (ValueError, TypeError):
account = None
if account is None:
await callback.answer("Бот не найден или вам не принадлежит", show_alert=True)
return
success, text, enabled = await update_idle_game(account.bot_name, app_id)
await callback.answer(text, show_alert=True)
if success:
await callback.message.edit_text(
"⌚ Выберите игру для накрутки часов",
reply_markup=games_keyboard(account.id, enabled),
)