domovoy_bot/main.py

141 lines
6.1 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 logging
import asyncio
import sys
import os
from pathlib import Path
# Добавляем путь к проекту
BASE_DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(BASE_DIR))
# Добавляем путь к библиотекам роя
LIBS_DIR = BASE_DIR.parent.parent / "libs"
if LIBS_DIR.exists():
sys.path.insert(0, str(LIBS_DIR))
from aiogram import Bot, Dispatcher
from aiogram.enums import ParseMode
from aiogram.fsm.storage.memory import MemoryStorage
from config import BOT_TOKEN, ADMIN_USER_ID
from database.db import init_db
# Импортируем роутеры
from handlers import (
admin_router, users_router, verification_router, chat_monitor_router,
security_router, apartments_router, antimat_router, phones_router,
polls_router, antispam_router, ratelimit_router, schedule_router,
ads_router, payments_router, multicount_router, topics_router,
toxicity_router, profile_history_router, achievements_router,
thanks_router, events_router, initiative_group_router
)
from handlers.mutual_aid import router as mutual_aid_router
from services.scheduler import Scheduler
from services.alert_bridge import send_domovoy_alert
# Настройка логирования
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('logs/bot.log', encoding='utf-8'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
async def on_startup(bot: Bot):
await init_db()
scheduler = Scheduler(bot)
scheduler.start()
try:
from aiogram.types import (
BotCommand, BotCommandScopeDefault,
BotCommandScopeAllGroupChats, BotCommandScopeAllPrivateChats,
BotCommandScopeChat
)
# 1. Для всех групповых чатов (публичный чат дома) - только базовая справка, без админок
await bot.set_my_commands([
BotCommand(command="phones", description="📞 Экстренные службы (в ЛС)"),
BotCommand(command="help", description="❓ Справка (в ЛС)")
], scope=BotCommandScopeAllGroupChats())
# 2. Для всех личных чатов с жильцами
await bot.set_my_commands([
BotCommand(command="start", description="Главное меню дома"),
BotCommand(command="phones", description="📞 Экстренные службы"),
BotCommand(command="jurist", description="⚖️ Юрист & Разбор ЖК РФ"),
BotCommand(command="help", description="❓ Помощь и навигация")
], scope=BotCommandScopeAllPrivateChats())
# 3. Персонально для суперадмина дома (Александр Тырин)
if ADMIN_USER_ID:
try:
await bot.set_my_commands([
BotCommand(command="admin", description="🛡️ Админ-панель дома"),
BotCommand(command="start", description="Главное меню дома"),
BotCommand(command="phones", description="📞 Экстренные службы"),
BotCommand(command="jurist", description="⚖️ Юрист & Разбор ЖК РФ"),
BotCommand(command="stats", description="📊 Статистика дома"),
BotCommand(command="help", description="❓ Помощь и навигация")
], scope=BotCommandScopeChat(chat_id=ADMIN_USER_ID))
except Exception as admin_cmd_err:
logger.warning(f"Failed to set admin commands scope: {admin_cmd_err}")
# 4. Дефолтный fallback
await bot.set_my_commands([
BotCommand(command="start", description="Главное меню дома"),
BotCommand(command="phones", description="📞 Экстренные телефоны"),
BotCommand(command="help", description="❓ Помощь")
], scope=BotCommandScopeDefault())
logger.info("✅ Telegram BotCommand scopes successfully updated.")
except Exception as e:
logger.warning(f"Failed to set bot commands: {e}")
try:
await bot.send_message(ADMIN_USER_ID, '✅ <b>LKM37 CORE v4.3 АКТИВИРОВАН</b>')
await send_domovoy_alert("Сервис запущен", "Домовой МКД успешно запущен в автономном коммунальном режиме.")
except: pass
async def main():
from bot_instance import get_bot
bot = get_bot()
dp = Dispatcher(storage=MemoryStorage())
# Регистрация роутеров МКД (Юрист в наивысшем приоритете)
from handlers.legal_advisor import router as legal_advisor_router
from handlers.smart_broadcast import router as smart_broadcast_router
from handlers.digest import router as digest_router
dp.include_router(legal_advisor_router)
dp.include_router(admin_router)
dp.include_router(users_router)
other_routers = [
verification_router, chat_monitor_router, security_router,
apartments_router, antimat_router, phones_router, polls_router,
antispam_router, ratelimit_router, schedule_router, ads_router,
payments_router, multicount_router, topics_router, toxicity_router,
profile_history_router, achievements_router, thanks_router,
events_router, initiative_group_router, mutual_aid_router,
smart_broadcast_router, digest_router
]
for r in other_routers:
dp.include_router(r)
dp.startup.register(on_startup)
logger.info('🤖 Бот запускается...')
await dp.start_polling(bot)
if __name__ == '__main__':
try:
asyncio.run(main())
except KeyboardInterrupt:
logger.info('🛑 Остановка пользователем.')
except Exception as e:
logger.error(f'Критическая ошибка: {e}', exc_info=True)