Files
new_lottery_bot/src/utils/utils.py
Trevor1985 3c1a6a02a5
All checks were successful
continuous-integration/drone/push Build is passing
Separate staff roles and protect message delivery with operator guides
2026-09-13 21:00:53 +09:00

115 lines
4.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.

#!/usr/bin/env python3
"""
Утилиты для управления ботом
"""
import asyncio
import sys
from sqlalchemy.ext.asyncio import AsyncSession
from ..core.database import async_session_maker, init_db
from ..core.services import UserService
from ..core.config import ADMIN_IDS
async def setup_admin_users():
"""Configured system admins already have access; never persist it as a second role."""
print(f"System administrators are loaded directly from ADMIN_IDS ({len(ADMIN_IDS)} configured).")
print("Use /staff in the bot to appoint ordinary administrators and cashiers.")
async def create_sample_lottery():
"""Создать пример розыгрыша для тестирования"""
from ..core.services import LotteryService
async with async_session_maker() as session:
# Берем первого администратора как создателя
if not ADMIN_IDS:
print("❌ Нет администраторов для создания розыгрыша")
return
admin_user = await UserService.get_user_by_telegram_id(session, ADMIN_IDS[0])
if not admin_user:
print("❌ Пользователь-администратор не найден в базе")
return
lottery = await LotteryService.create_lottery(
session,
title="🎉 Тестовый розыгрыш",
description="Это тестовый розыгрыш для демонстрации работы бота",
prizes=[
"🥇 Главный приз - 10,000 рублей",
"🥈 Второй приз - iPhone 15",
"🥉 Третий приз - AirPods Pro"
],
creator_id=admin_user.id
)
print(f"✅ Создан тестовый розыгрыш с ID: {lottery.id}")
print(f"📝 Название: {lottery.title}")
async def init_database():
"""Инициализация базы данных"""
print("🔄 Инициализация базы данных...")
await init_db()
print("✅ База данных инициализирована")
async def show_stats():
"""Показать статистику бота"""
from ..core.services import LotteryService, ParticipationService
from ..core.models import User, Lottery, Participation
from sqlalchemy import select, func
async with async_session_maker() as session:
# Количество пользователей
result = await session.execute(select(func.count(User.id)))
users_count = result.scalar()
# Количество розыгрышей
result = await session.execute(select(func.count(Lottery.id)))
lotteries_count = result.scalar()
# Количество активных розыгрышей
result = await session.execute(
select(func.count(Lottery.id))
.where(Lottery.is_active == True, Lottery.is_completed == False)
)
active_lotteries = result.scalar()
# Количество участий
result = await session.execute(select(func.count(Participation.id)))
participations_count = result.scalar()
print("\n📊 Статистика бота:")
print(f"👥 Всего пользователей: {users_count}")
print(f"🎲 Всего розыгрышей: {lotteries_count}")
print(f"🟢 Активных розыгрышей: {active_lotteries}")
print(f"🎫 Всего участий: {participations_count}")
def main():
"""Главная функция утилиты"""
if len(sys.argv) < 2:
print("Использование:")
print(" python utils.py init - Инициализация базы данных")
print(" python utils.py setup-admins - Установка прав администратора")
print(" python utils.py sample - Создание тестового розыгрыша")
print(" python utils.py stats - Показать статистику")
return
command = sys.argv[1]
if command == "init":
asyncio.run(init_database())
elif command == "setup-admins":
asyncio.run(setup_admin_users())
elif command == "sample":
asyncio.run(create_sample_lottery())
elif command == "stats":
asyncio.run(show_stats())
else:
print(f"❌ Неизвестная команда: {command}")
if __name__ == "__main__":
main()