Files
ASF-Control-Bot/bot/ui/formatters.py
T

221 lines
6.6 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.
import html
import json
from datetime import datetime, timezone
from bot.api.asf import get_asf_status
from bot.config import ADMIN_ID
from bot.constants import GAMES
def get_currency_name(currency_id: int) -> str:
if currency_id == 1:
return "USD"
if currency_id == 3:
return "EUR"
if currency_id == 5:
return "RUB"
if currency_id == 18:
return "UAH"
if currency_id == 6:
return "PLN"
if currency_id == 0:
return ""
return "???"
def get_inventory_icon(desc: dict) -> str:
tags = desc.get("tags", [])
for tag in tags:
category = tag.get("category", "")
name = tag.get("localized_tag_name", "")
if category == "item_class":
if "Trading Card" in name:
return "🎏"
elif "Emoticon" in name:
return "😀"
elif "Profile Background" in name:
return "🖼"
elif "Booster Pack" in name:
return "📦"
elif "Steam Gems" in name:
return "💎"
if "Gift" in name:
return "🎁"
item_type = desc.get("type", "").lower()
if "knife" in item_type:
return "🔪"
elif "pistol" in item_type:
return "🔫"
elif "rifle" in item_type:
return "🎯"
elif "graffiti" in item_type:
return "🎨"
elif "music kit" in item_type:
return "🎵"
return "📦"
def get_uptime(start_time_str: str) -> str:
start_time_str = start_time_str[:26] + "Z"
start_time = datetime.fromisoformat(start_time_str.replace("Z", "+00:00"))
now = datetime.now(timezone.utc)
delta = now - start_time
days = delta.days
hours, remainder = divmod(delta.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
days_measure = f"{days}д" if days > 0 else ""
hours_measure = f" {hours}ч" if hours > 0 else ""
minutes_measure = f" {minutes}м" if minutes > 0 else ""
seconds_measure = f" {seconds}с" if seconds > 0 else ""
return f"{days_measure}{hours_measure}{minutes_measure}{seconds_measure}"
def format_asf(data: dict, user_id: int) -> str:
result = data.get("Result", {})
current_version = result.get("Version")
latest_version = result.get("LatestVersion", current_version)
lines = [f"Версия ASF: {current_version}"]
if user_id == ADMIN_ID:
if current_version != latest_version:
lines.append(f"Доступно обновление: {latest_version}")
memory_kb = result.get("MemoryUsage", 0)
memory_mb = memory_kb / 1024
lines.append(f"Используется памяти: {memory_mb:.2f} MB")
lines.append(f"Работает: {get_uptime(result.get('ProcessStartTime'))}")
return "\n".join(lines)
def get_bot_status_icon(bot: dict) -> str:
online = bot.get("IsConnectedAndLoggedOn", False)
farming = bot.get("CardsFarmer", {}).get("NowFarming", False)
idle_games = bot.get("BotConfig", {}).get("GamesPlayedWhileIdle", [])
loaded = bool(bot.get("BotName")) and bool(bot.get("SteamID"))
if not loaded:
return "🔄"
if farming:
return "🎴"
if idle_games and online:
return ""
if online:
return "🟢"
return "🔴"
def format_bot_ui(bot: dict) -> str:
online = get_bot_status_icon(bot)
now_farming = bot.get("CardsFarmer", {}).get("NowFarming")
status_line = "🎴 Идет фарм карточек" if now_farming else "🎴 Карточки не фармятся"
time = bot.get("CardsFarmer", {}).get("TimeRemaining", "00:00:00")
games_to_farm = len(bot.get("CardsFarmer", {}).get("GamesToFarm", []))
twofa = "есть" if bot.get("HasMobileAuthenticator") else "нет"
balance = bot.get("WalletBalance", 0) / 100
currency = get_currency_name(bot.get("WalletCurrency", 0))
steam_id = bot.get("SteamID")
nickname = html.escape(str(bot.get("Nickname") or ""))
redeem = bot.get("GamesToRedeemInBackgroundCount", 0)
profile_url = f"https://steamcommunity.com/profiles/{steam_id}"
text = (
f"{online} {bot.get('BotName') or 'Загрузка...'}"
f' (<a href="{profile_url}">{nickname}</a>)\n'
f"{status_line}\n"
)
idle_games = bot.get("BotConfig", {}).get("GamesPlayedWhileIdle", [])
if idle_games:
names = [GAMES.get(game, str(game)) for game in idle_games]
if bot.get("IsConnectedAndLoggedOn"):
idle_text = f"⌚ Накрутка часов: включена ({', '.join(names)})"
else:
idle_text = (
f"⌚ Накрутка часов: включена ({', '.join(names)}) "
"применится после запуска"
)
text += f"{idle_text}\n"
else:
text += "⌚ Накрутка часов: выключена\n"
text += (
f"🆔: <code>{steam_id}</code>\n"
f"🔐 2FA: {twofa}\n\n"
f"💰 Баланс: {balance:.2f} {currency}\n"
)
if redeem > 0:
text += f"\nКлючей в очереди: {redeem}\n"
if now_farming:
text += f"\nОсталось: {time}\n"
if games_to_farm > 0:
text += f"В очереди игр: {games_to_farm}\n"
return text
def get_asf_status_text(user_id: int) -> str:
response = get_asf_status()
if response.status_code != 200:
return f"Ошибка API: {response.status_code}"
data = response.json()
if not data.get("Success"):
return "ASF вернул ошибку"
return f"<b>💻 Панель управления ASF</b>\n\n{format_asf(data, user_id)}"
def get_farm_summary(bots: dict) -> str:
total_games = 0
total_time_seconds = 0
for bot in bots.values():
farmer = bot.get("CardsFarmer", {})
if farmer.get("NowFarming"):
games = farmer.get("CurrentGamesFarming", [])
total_games += len(games)
time_str = farmer.get("TimeRemaining", "00:00:00")
hours, minutes, seconds = map(int, time_str.split(":"))
total_time_seconds += hours * 3600 + minutes * 60 + seconds
if total_games == 0:
return "На аккаунтах нечего фармить"
hours = total_time_seconds // 3600
minutes = (total_time_seconds % 3600) // 60
return (
f"Игр фармится: {total_games}\n"
f"Осталось времени: {hours}ч {minutes}м\n"
f"Карт осталось: ~{total_games * 3}"
)
def format_bot(bot_data: dict) -> str:
return json.dumps(bot_data, indent=2, ensure_ascii=False)