Archived
refactor(logging): logging and rename token env
This commit is contained in:
+52
-3
@@ -1,27 +1,53 @@
|
||||
import asyncio
|
||||
|
||||
from bot.api.asf import get_all_bots, get_bot, save_bot_config, send_command
|
||||
from bot.logging_utils import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def is_bot_playing(bot_name: str) -> bool:
|
||||
logger.info("Проверка, играет ли бот: bot=%s", bot_name)
|
||||
response = get_all_bots()
|
||||
if response.status_code != 200:
|
||||
logger.warning(
|
||||
"Не удалось проверить состояние игры бота: bot=%s status=%s",
|
||||
bot_name,
|
||||
response.status_code,
|
||||
)
|
||||
return False
|
||||
|
||||
data = response.json()
|
||||
bot = data.get("Result", {}).get(bot_name, {})
|
||||
return bool(bot.get("PlayingBlocked", False)) or bool(
|
||||
playing = bool(bot.get("PlayingBlocked", False)) or bool(
|
||||
bot.get("CurrentGamesPlayed", [])
|
||||
)
|
||||
logger.info("Состояние игры бота определено: bot=%s playing=%s", bot_name, playing)
|
||||
return playing
|
||||
|
||||
|
||||
def is_idle_enabled(bot_name: str, app_id: int) -> bool:
|
||||
logger.info("Проверка статуса idle-игры: bot=%s app_id=%s", bot_name, app_id)
|
||||
response = get_bot(bot_name)
|
||||
if response.status_code != 200:
|
||||
logger.warning(
|
||||
"Не удалось получить конфиг бота для проверки idle: bot=%s status=%s",
|
||||
bot_name,
|
||||
response.status_code,
|
||||
)
|
||||
return False
|
||||
|
||||
data = response.json()
|
||||
bot = data.get("Result", {}).get(bot_name, {})
|
||||
config = bot.get("BotConfig", {})
|
||||
return app_id in config.get("GamesPlayedWhileIdle", [])
|
||||
enabled = app_id in config.get("GamesPlayedWhileIdle", [])
|
||||
logger.info(
|
||||
"Статус idle-игры определен: bot=%s app_id=%s enabled=%s",
|
||||
bot_name,
|
||||
app_id,
|
||||
enabled,
|
||||
)
|
||||
return enabled
|
||||
|
||||
|
||||
def toggle_idle_game(config: dict, app_id: int) -> tuple[dict, bool]:
|
||||
@@ -38,22 +64,45 @@ def toggle_idle_game(config: dict, app_id: int) -> tuple[dict, bool]:
|
||||
|
||||
async def reload_bot(bot_name: str) -> None:
|
||||
try:
|
||||
logger.info("Отправка команды перезагрузки бота: bot=%s", bot_name)
|
||||
send_command(f"!reload {bot_name}")
|
||||
except Exception:
|
||||
pass
|
||||
logger.exception(
|
||||
"Не удалось отправить команду перезагрузки бота: bot=%s", bot_name
|
||||
)
|
||||
|
||||
|
||||
async def update_idle_game(bot_name: str, app_id: int) -> tuple[bool, str, bool]:
|
||||
logger.info("Изменение настройки idle-игры: bot=%s app_id=%s", bot_name, app_id)
|
||||
response = get_bot(bot_name)
|
||||
if response.status_code != 200:
|
||||
logger.warning(
|
||||
"Не удалось загрузить конфиг бота для idle: bot=%s status=%s",
|
||||
bot_name,
|
||||
response.status_code,
|
||||
)
|
||||
return False, "Ошибка API", False
|
||||
|
||||
data = response.json()
|
||||
bot_data = data.get("Result", {}).get(bot_name, {})
|
||||
config = bot_data.get("BotConfig", {})
|
||||
config, enabled = toggle_idle_game(config, app_id)
|
||||
save = save_bot_config(bot_name, config)
|
||||
if save.status_code != 200:
|
||||
logger.warning(
|
||||
"Не удалось сохранить конфиг idle-игры: bot=%s app_id=%s status=%s",
|
||||
bot_name,
|
||||
app_id,
|
||||
save.status_code,
|
||||
)
|
||||
return False, "Ошибка сохранения", enabled
|
||||
|
||||
asyncio.create_task(reload_bot(bot_name))
|
||||
action = "Idle включен" if enabled else "Idle выключен"
|
||||
logger.info(
|
||||
"Настройка idle-игры изменена: bot=%s app_id=%s enabled=%s",
|
||||
bot_name,
|
||||
app_id,
|
||||
enabled,
|
||||
)
|
||||
return True, action, enabled
|
||||
|
||||
+48
-11
@@ -1,10 +1,14 @@
|
||||
from bot.api.asf import get_bot_inventory
|
||||
from bot.constants import PAGE_SIZE
|
||||
from bot.logging_utils import get_logger
|
||||
from bot.ui.formatters import get_inventory_icon
|
||||
from bot.ui.keyboards import inventory_menu_keyboard, inventory_page_keyboard
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
async def build_inventory_menu(bot_name: str) -> tuple[str, object]:
|
||||
logger.info("Формирование меню инвентаря: bot=%s", bot_name)
|
||||
cs2_inventory = await get_bot_inventory(bot_name, 730, 2)
|
||||
steam_inventory = await get_bot_inventory(bot_name, 753, 6)
|
||||
cs2_assets = []
|
||||
@@ -12,13 +16,23 @@ async def build_inventory_menu(bot_name: str) -> tuple[str, object]:
|
||||
try:
|
||||
cs2_assets = cs2_inventory.get(bot_name, {}).get("Assets", []) # type: ignore[union-attr]
|
||||
except Exception:
|
||||
pass
|
||||
logger.exception("Ошибка чтения CS2-инвентаря: bot=%s", bot_name)
|
||||
try:
|
||||
steam_assets = steam_inventory.get(bot_name, {}).get("Assets", []) # type: ignore[union-attr]
|
||||
except Exception:
|
||||
pass
|
||||
logger.exception("Ошибка чтения Steam-инвентаря: bot=%s", bot_name)
|
||||
if not cs2_assets and not steam_assets:
|
||||
return f"📦 Инвентарь {bot_name} пуст", inventory_menu_keyboard(bot_name, 0, 0)
|
||||
logger.info("Инвентарь пуст: bot=%s", bot_name)
|
||||
return (
|
||||
f"📦 Инвентарь {bot_name} пуст",
|
||||
inventory_menu_keyboard(bot_name, 0, 0),
|
||||
)
|
||||
logger.info(
|
||||
"Меню инвентаря сформировано: bot=%s cs2_items=%s steam_items=%s",
|
||||
bot_name,
|
||||
len(cs2_assets),
|
||||
len(steam_assets),
|
||||
)
|
||||
text = (
|
||||
f"📦 Инвентарь {bot_name}\n\n"
|
||||
"🔄 — можно трейдить\n"
|
||||
@@ -32,13 +46,28 @@ async def build_inventory_menu(bot_name: str) -> tuple[str, object]:
|
||||
async def render_inventory_page(
|
||||
bot_name: str, inventory_type: str, appid: int, contextid: int, page: int
|
||||
) -> tuple[str, object] | tuple[None, None]:
|
||||
logger.info(
|
||||
"Формирование страницы инвентаря: bot=%s type=%s appid=%s contextid=%s page=%s",
|
||||
bot_name,
|
||||
inventory_type,
|
||||
appid,
|
||||
contextid,
|
||||
page,
|
||||
)
|
||||
inventory = await get_bot_inventory(bot_name, appid, contextid)
|
||||
if not inventory:
|
||||
logger.warning(
|
||||
"Не удалось получить данные для страницы инвентаря: bot=%s type=%s page=%s",
|
||||
bot_name,
|
||||
inventory_type,
|
||||
page,
|
||||
)
|
||||
return None, None
|
||||
bot_inventory = inventory.get(bot_name, {})
|
||||
assets = bot_inventory.get("Assets", [])
|
||||
descriptions = bot_inventory.get("Descriptions", [])
|
||||
if not assets:
|
||||
logger.info("Инвентарь выбранного типа пуст: bot=%s type=%s", bot_name, inventory_type)
|
||||
return f"Инвентарь {bot_name} пуст", inventory_menu_keyboard(bot_name, 0, 0)
|
||||
desc_map = {}
|
||||
for desc in descriptions:
|
||||
@@ -67,7 +96,7 @@ async def render_inventory_page(
|
||||
marketable_count += 1
|
||||
if desc.get("tradable"):
|
||||
tradable_count += 1
|
||||
if icon == "🃏":
|
||||
if icon == "🎏":
|
||||
cards_count += amount
|
||||
elif icon == "😀":
|
||||
emotes_count += amount
|
||||
@@ -78,22 +107,30 @@ async def render_inventory_page(
|
||||
lines.append(f"{icon} {tradable}{marketable} {name} x{amount}")
|
||||
inv_name = "CS2" if appid == 730 else "Steam"
|
||||
stats = (
|
||||
f"📦 Items: {len(assets)}\n"
|
||||
f"💰 Marketable: {marketable_count}\n"
|
||||
f"🔄 Tradable: {tradable_count}"
|
||||
f"📦 Предметов: {len(assets)}\n"
|
||||
f"💰 Можно продать: {marketable_count}\n"
|
||||
f"🔄 Можно трейдить: {tradable_count}"
|
||||
)
|
||||
if appid == 753:
|
||||
stats += (
|
||||
f"\n🃏 Cards: {cards_count}"
|
||||
f"\n😀 Emotes: {emotes_count}"
|
||||
f"\n🖼 Backgrounds: {backgrounds_count}"
|
||||
f"\n💎 Gems: {gems_count}"
|
||||
f"\n🎏 Карточек: {cards_count}"
|
||||
f"\n😀 Смайлов: {emotes_count}"
|
||||
f"\n🖼 Фонов: {backgrounds_count}"
|
||||
f"\n💎 Самоцветов: {gems_count}"
|
||||
)
|
||||
text = (
|
||||
f"📦 {inv_name} Inventory {bot_name}\n"
|
||||
f"📄 Страница {page + 1}/{total_pages}\n\n"
|
||||
f"{stats}\n\n" + "\n".join(lines)
|
||||
)
|
||||
logger.info(
|
||||
"Страница инвентаря сформирована: bot=%s type=%s page=%s total_pages=%s items_on_page=%s",
|
||||
bot_name,
|
||||
inventory_type,
|
||||
page,
|
||||
total_pages,
|
||||
len(page_assets),
|
||||
)
|
||||
return text[:4000], inventory_page_keyboard(
|
||||
inventory_type, bot_name, page, total_pages
|
||||
)
|
||||
|
||||
+74
-1
@@ -2,13 +2,17 @@ import asyncio
|
||||
import re
|
||||
|
||||
from bot.api.asf import get_all_bots, redeem_key
|
||||
from bot.logging_utils import get_logger, mask_key
|
||||
|
||||
KEY_PATTERN = r"[A-Z0-9]{5}(?:-[A-Z0-9]{5}){2}"
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def extract_keys(text: str) -> list[str]:
|
||||
keys = re.findall(KEY_PATTERN, text.upper())
|
||||
return list(dict.fromkeys(keys))
|
||||
unique_keys = list(dict.fromkeys(keys))
|
||||
logger.info("Из текста извлечены ключи: count=%s", len(unique_keys))
|
||||
return unique_keys
|
||||
|
||||
|
||||
def parse_redeem_result(result: str, bot_name: str | None = None) -> str:
|
||||
@@ -18,6 +22,7 @@ def parse_redeem_result(result: str, bot_name: str | None = None) -> str:
|
||||
if f"<{bot_name.lower()}>" in line.lower():
|
||||
result_lower = line.lower()
|
||||
break
|
||||
|
||||
if "ok/nodetail" in result_lower or "ok/" in result_lower:
|
||||
return "success"
|
||||
if "ratelimited" in result_lower:
|
||||
@@ -34,17 +39,42 @@ def parse_redeem_result(result: str, bot_name: str | None = None) -> str:
|
||||
|
||||
|
||||
async def redeem_single_bot_keys(bot_name: str, keys: list[str]) -> str:
|
||||
logger.info(
|
||||
"Начата активация ключей для одного бота: bot=%s count=%s",
|
||||
bot_name,
|
||||
len(keys),
|
||||
)
|
||||
success_count = 0
|
||||
failed_count = 0
|
||||
results = []
|
||||
|
||||
for key in keys:
|
||||
logger.info(
|
||||
"Попытка активации ключа для одного бота: bot=%s key=%s",
|
||||
bot_name,
|
||||
mask_key(key),
|
||||
)
|
||||
success, result = await redeem_key(bot_name, key)
|
||||
await asyncio.sleep(2)
|
||||
|
||||
if not success or not result:
|
||||
failed_count += 1
|
||||
logger.warning(
|
||||
"Активация ключа завершилась ошибкой ASF/HTTP: bot=%s key=%s",
|
||||
bot_name,
|
||||
mask_key(key),
|
||||
)
|
||||
results.append(f"❌ {key}: ASF ERROR")
|
||||
continue
|
||||
|
||||
status = parse_redeem_result(result)
|
||||
logger.info(
|
||||
"Получен результат активации ключа: bot=%s key=%s status=%s",
|
||||
bot_name,
|
||||
mask_key(key),
|
||||
status,
|
||||
)
|
||||
|
||||
if status == "success":
|
||||
success_count += 1
|
||||
results.append(f"✅ {key}: активировано")
|
||||
@@ -66,31 +96,62 @@ async def redeem_single_bot_keys(bot_name: str, keys: list[str]) -> str:
|
||||
else:
|
||||
failed_count += 1
|
||||
results.append(f"❔ {key}: неизвестный ответ")
|
||||
|
||||
text = (
|
||||
f"Результат активации для <code>{bot_name}</code>\n\n"
|
||||
f"✅ Успешно: {success_count}\n"
|
||||
f"❌ Ошибок: {failed_count}\n\n" + "\n".join(results[:50])
|
||||
)
|
||||
logger.info(
|
||||
"Завершена активация ключей для одного бота: bot=%s success=%s failed=%s",
|
||||
bot_name,
|
||||
success_count,
|
||||
failed_count,
|
||||
)
|
||||
return text[:4000] + ("\n\n...обрезано" if len(text) > 4000 else "")
|
||||
|
||||
|
||||
async def redeem_all_bots_keys(keys: list[str]) -> str:
|
||||
logger.info("Начата активация ключей по всем ботам: count=%s", len(keys))
|
||||
response = get_all_bots()
|
||||
data = response.json()
|
||||
bots = list(data.get("Result", {}).keys())
|
||||
logger.info("Для массовой активации найдено ботов: count=%s", len(bots))
|
||||
success_count = 0
|
||||
failed_count = 0
|
||||
results = []
|
||||
|
||||
for key in keys:
|
||||
activated = False
|
||||
key_report = []
|
||||
logger.info("Начата обработка ключа по всем ботам: key=%s", mask_key(key))
|
||||
|
||||
for bot_name in bots:
|
||||
logger.info(
|
||||
"Попытка активации ключа на боте: bot=%s key=%s",
|
||||
bot_name,
|
||||
mask_key(key),
|
||||
)
|
||||
success, result = await redeem_key(bot_name, key)
|
||||
await asyncio.sleep(2)
|
||||
|
||||
if not success or not result:
|
||||
logger.warning(
|
||||
"Активация ключа завершилась ошибкой ASF/HTTP: bot=%s key=%s",
|
||||
bot_name,
|
||||
mask_key(key),
|
||||
)
|
||||
key_report.append(f"❌ {bot_name}: ASF ERROR")
|
||||
continue
|
||||
|
||||
status = parse_redeem_result(result, bot_name)
|
||||
logger.info(
|
||||
"Получен результат активации ключа: bot=%s key=%s status=%s",
|
||||
bot_name,
|
||||
mask_key(key),
|
||||
status,
|
||||
)
|
||||
|
||||
if status == "success":
|
||||
key_report.append(f"✅ {bot_name}: активировано")
|
||||
success_count += 1
|
||||
@@ -112,12 +173,24 @@ async def redeem_all_bots_keys(keys: list[str]) -> str:
|
||||
key_report.append(f"❌ {bot_name}: неверный ключ")
|
||||
break
|
||||
key_report.append(f"❔ {bot_name}: неизвестный ответ")
|
||||
|
||||
if not activated:
|
||||
failed_count += 1
|
||||
logger.warning(
|
||||
"Ключ не удалось активировать ни на одном боте: key=%s",
|
||||
mask_key(key),
|
||||
)
|
||||
|
||||
results.append(f"\n🔑 {key}\n" + "\n".join(key_report))
|
||||
|
||||
text = (
|
||||
"Результат активации\n\n"
|
||||
f"✅ Успешно: {success_count}\n"
|
||||
f"❌ Ошибок: {failed_count}\n\n" + "\n".join(results[:50])
|
||||
)
|
||||
logger.info(
|
||||
"Завершена массовая активация ключей: success=%s failed=%s",
|
||||
success_count,
|
||||
failed_count,
|
||||
)
|
||||
return text[:4000] + ("\n\n...обрезано" if len(text) > 4000 else "")
|
||||
|
||||
+42
-3
@@ -1,23 +1,37 @@
|
||||
import asyncio
|
||||
|
||||
from bot.api.asf import get_2fa_token, get_confirmations
|
||||
from bot.logging_utils import get_logger
|
||||
from bot.state import twofa_tasks
|
||||
from bot.ui.keyboards import twofa_keyboard
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
async def stop_twofa_task(message_id: int) -> None:
|
||||
task = twofa_tasks.pop(message_id, None)
|
||||
if task:
|
||||
logger.info(
|
||||
"Остановка фоновой задачи обновления 2FA: message_id=%s", message_id
|
||||
)
|
||||
task.cancel()
|
||||
try:
|
||||
await task
|
||||
except Exception:
|
||||
pass
|
||||
logger.exception(
|
||||
"Ошибка при завершении фоновой задачи обновления 2FA: message_id=%s",
|
||||
message_id,
|
||||
)
|
||||
|
||||
|
||||
async def auto_update_2fa(message, bot_name: str) -> None:
|
||||
last_code = None
|
||||
message_id = message.message_id
|
||||
logger.info(
|
||||
"Запуск фонового обновления 2FA: bot=%s message_id=%s",
|
||||
bot_name,
|
||||
message_id,
|
||||
)
|
||||
try:
|
||||
while True:
|
||||
code = await get_2fa_token(bot_name)
|
||||
@@ -30,12 +44,37 @@ async def auto_update_2fa(message, bot_name: str) -> None:
|
||||
reply_markup=twofa_keyboard(bot_name, bool(confirmations)),
|
||||
)
|
||||
last_code = code
|
||||
logger.info(
|
||||
"Сообщение 2FA обновлено: bot=%s message_id=%s confirmations=%s",
|
||||
bot_name,
|
||||
message_id,
|
||||
len(confirmations),
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Не удалось обновить сообщение 2FA: bot=%s message_id=%s",
|
||||
bot_name,
|
||||
message_id,
|
||||
)
|
||||
break
|
||||
await asyncio.sleep(15)
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
logger.info(
|
||||
"Фоновое обновление 2FA отменено: bot=%s message_id=%s",
|
||||
bot_name,
|
||||
message_id,
|
||||
)
|
||||
except Exception as error:
|
||||
print(f"2FA updater error: {error}")
|
||||
logger.exception(
|
||||
"Фоновое обновление 2FA завершилось ошибкой: bot=%s message_id=%s error=%s",
|
||||
bot_name,
|
||||
message_id,
|
||||
error,
|
||||
)
|
||||
finally:
|
||||
twofa_tasks.pop(message_id, None)
|
||||
logger.info(
|
||||
"Фоновая задача обновления 2FA завершена: bot=%s message_id=%s",
|
||||
bot_name,
|
||||
message_id,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user