Hasli4

Untitled

Apr 15th, 2026
86
0
Never
8
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 27.63 KB | None | 0 0
  1. import asyncio
  2. import html
  3. import logging
  4. import os
  5. import sqlite3
  6. from contextlib import suppress
  7. import re
  8.  
  9. from aiogram import Bot, Dispatcher, F
  10. from aiogram.enums import ParseMode
  11. from aiogram.filters import Command
  12. from aiogram.fsm.context import FSMContext
  13. from aiogram.fsm.state import State, StatesGroup
  14. from aiogram.fsm.storage.memory import MemoryStorage
  15. from aiogram.types import (
  16.     CallbackQuery,
  17.     InlineKeyboardButton,
  18.     InlineKeyboardMarkup,
  19.     KeyboardButton,
  20.     Message,
  21.     ReplyKeyboardMarkup,
  22.     ReplyKeyboardRemove,
  23. )
  24.  
  25. # ================== НАСТРОЙКИ ==================
  26. BOT_TOKEN = ""
  27. ADMIN_ID = int(os.getenv("ADMIN_ID", "6803061349"))
  28. DB_PATH = os.getenv("DB_PATH", "teamfinder.db")
  29.  
  30. if not BOT_TOKEN:
  31.     raise RuntimeError("BOT_TOKEN is empty. Set it in environment variables.")
  32.  
  33. logging.basicConfig(level=logging.INFO)
  34.  
  35. bot = Bot(token=BOT_TOKEN)
  36. dp = Dispatcher(storage=MemoryStorage())
  37.  
  38. # ================== БАЗА ДАННЫХ ==================
  39. conn = sqlite3.connect(DB_PATH, check_same_thread=False)
  40. conn.row_factory = sqlite3.Row
  41. cursor = conn.cursor()
  42.  
  43.  
  44. def init_db() -> None:
  45.     cursor.execute("""
  46.    CREATE TABLE IF NOT EXISTS users (
  47.        user_id INTEGER PRIMARY KEY,
  48.        username TEXT,
  49.        full_name TEXT,
  50.        game TEXT,
  51.        game_key TEXT DEFAULT '',
  52.        rank TEXT,
  53.        role TEXT,
  54.        about TEXT,
  55.        looking_for TEXT,
  56.        is_active INTEGER DEFAULT 1,
  57.        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  58.    )
  59.    """)
  60.  
  61.     cursor.execute("""
  62.    CREATE TABLE IF NOT EXISTS likes (
  63.        id INTEGER PRIMARY KEY AUTOINCREMENT,
  64.        from_user INTEGER,
  65.        to_user INTEGER,
  66.        is_like INTEGER,
  67.        viewed INTEGER DEFAULT 0,
  68.        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  69.        UNIQUE(from_user, to_user)
  70.    )
  71.    """)
  72.  
  73.     cursor.execute("""
  74.    CREATE TABLE IF NOT EXISTS matches (
  75.        id INTEGER PRIMARY KEY AUTOINCREMENT,
  76.        user1 INTEGER,
  77.        user2 INTEGER,
  78.        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  79.        UNIQUE(user1, user2)
  80.    )
  81.    """)
  82.  
  83.     conn.commit()
  84.  
  85.  
  86. GAME_CHOICES = {
  87.     "Dota 2": "dota 2",
  88.     "CS2": "cs2",
  89.     "PUBG": "pubg",
  90.     "Valorant": "valorant",
  91. }
  92.  
  93. GAME_ALIASES = {
  94.     "dota": "dota 2",
  95.     "dota 2": "dota 2",
  96.     "dota2": "dota 2",
  97.     "cs2": "cs2",
  98.     "cs 2": "cs2",
  99.     "counter strike 2": "cs2",
  100.     "counter-strike 2": "cs2",
  101.     "csgo": "cs2",
  102.     "pubg": "pubg",
  103.     "playerunknowns battlegrounds": "pubg",
  104.     "playerunknown's battlegrounds": "pubg",
  105.     "valorant": "valorant",
  106. }
  107.  
  108.  
  109. def game_choice_keyboard():
  110.     return ReplyKeyboardMarkup(
  111.         keyboard=[
  112.             [KeyboardButton(text="Dota 2"), KeyboardButton(text="CS2")],
  113.             [KeyboardButton(text="PUBG"), KeyboardButton(text="Valorant")],
  114.             [KeyboardButton(text="Другое")],
  115.         ],
  116.         resize_keyboard=True,
  117.         one_time_keyboard=True,
  118.     )
  119.  
  120. def normalize_game(value: str) -> str:
  121.     value = "" if value is None else str(value)
  122.     value = value.lower().replace("ё", "е")
  123.     value = value.replace("—", "-").replace("–", "-")
  124.     value = re.sub(r"[^\w\s-]+", " ", value)
  125.     value = re.sub(r"\s+", " ", value).strip()
  126.     return GAME_ALIASES.get(value, value)
  127.  
  128.  
  129. def migrate_db() -> None:
  130.     cursor.execute("PRAGMA table_info(users)")
  131.     columns = {row["name"] for row in cursor.fetchall()}
  132.  
  133.     if "game_key" not in columns:
  134.         cursor.execute("ALTER TABLE users ADD COLUMN game_key TEXT DEFAULT ''")
  135.         conn.commit()
  136.  
  137.     cursor.execute("""
  138.        SELECT user_id, game
  139.        FROM users
  140.        WHERE COALESCE(game_key, '') = '' AND COALESCE(game, '') <> ''
  141.    """)
  142.     rows = cursor.fetchall()
  143.  
  144.     for row in rows:
  145.         cursor.execute(
  146.             "UPDATE users SET game_key = ? WHERE user_id = ?",
  147.             (normalize_game(row["game"]), row["user_id"]),
  148.         )
  149.  
  150.     conn.commit()
  151.  
  152.  
  153.  
  154. init_db()
  155. migrate_db()
  156.  
  157.  
  158. # ================== СОСТОЯНИЯ ==================
  159. class ProfileForm(StatesGroup):
  160.     game = State()
  161.     custom_game = State()
  162.     rank = State()
  163.     role = State()
  164.     about = State()
  165.     looking_for = State()
  166.  
  167.  
  168. class SearchFlow(StatesGroup):
  169.     browsing = State()
  170.  
  171.  
  172. class BroadcastFlow(StatesGroup):
  173.     waiting_text = State()
  174.  
  175.  
  176. # ================== УТИЛИТЫ ==================
  177. def esc(value) -> str:
  178.     return html.escape("" if value is None else str(value))
  179.  
  180.  
  181. def save_profile(user_id, username, full_name, game, game_key, rank, role, about, looking_for):
  182.     with conn:
  183.         cursor.execute(
  184.             """
  185.            INSERT INTO users (
  186.                user_id, username, full_name, game, game_key, rank, role, about, looking_for, is_active
  187.            )
  188.            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
  189.            ON CONFLICT(user_id) DO UPDATE SET
  190.                username=excluded.username,
  191.                full_name=excluded.full_name,
  192.                game=excluded.game,
  193.                game_key=excluded.game_key,
  194.                rank=excluded.rank,
  195.                role=excluded.role,
  196.                about=excluded.about,
  197.                looking_for=excluded.looking_for,
  198.                is_active=1
  199.            """,
  200.             (user_id, username, full_name, game, game_key, rank, role, about, looking_for),
  201.         )
  202.  
  203. def get_profile(user_id):
  204.     cursor.execute("SELECT * FROM users WHERE user_id = ?", (user_id,))
  205.     return cursor.fetchone()
  206.  
  207.  
  208.  
  209. def get_candidate_ids(user_id, game_filter: str = ""):
  210.     game_filter = normalize_game(game_filter)
  211.  
  212.     cursor.execute(
  213.         """
  214.        SELECT u.user_id
  215.        FROM users u
  216.        WHERE u.is_active = 1
  217.          AND u.user_id != ?
  218.          AND COALESCE(u.game_key, '') != ''
  219.          AND (? = '' OR u.game_key = ?)
  220.          AND NOT EXISTS (
  221.              SELECT 1
  222.              FROM likes l
  223.              WHERE l.from_user = ?
  224.                AND l.to_user = u.user_id
  225.          )
  226.          AND NOT EXISTS (
  227.              SELECT 1
  228.              FROM matches m
  229.              WHERE (m.user1 = ? AND m.user2 = u.user_id)
  230.                 OR (m.user2 = ? AND m.user1 = u.user_id)
  231.          )
  232.        ORDER BY u.created_at DESC
  233.        """,
  234.         (user_id, game_filter, game_filter, user_id, user_id, user_id),
  235.     )
  236.     return [row["user_id"] for row in cursor.fetchall()]
  237.  
  238. def add_like(from_user: int, to_user: int, is_like: int) -> bool:
  239.     """
  240.    Returns True if a match has been created.
  241.    """
  242.     with conn:
  243.         cursor.execute(
  244.             """
  245.            INSERT INTO likes (from_user, to_user, is_like, viewed)
  246.            VALUES (?, ?, ?, 0)
  247.            ON CONFLICT(from_user, to_user) DO UPDATE SET
  248.                is_like=excluded.is_like,
  249.                viewed=0,
  250.                created_at=CURRENT_TIMESTAMP
  251.            """,
  252.             (from_user, to_user, is_like),
  253.         )
  254.  
  255.         if is_like == 1:
  256.             cursor.execute(
  257.                 """
  258.                SELECT 1
  259.                FROM likes
  260.                WHERE from_user = ? AND to_user = ? AND is_like = 1
  261.                """,
  262.                 (to_user, from_user),
  263.             )
  264.             if cursor.fetchone():
  265.                 cursor.execute(
  266.                     """
  267.                    INSERT OR IGNORE INTO matches (user1, user2)
  268.                    VALUES (?, ?)
  269.                    """,
  270.                     (min(from_user, to_user), max(from_user, to_user)),
  271.                 )
  272.                 return True
  273.  
  274.     return False
  275.  
  276.  
  277. def get_new_likes(user_id: int):
  278.     cursor.execute(
  279.         """
  280.        SELECT from_user
  281.        FROM likes
  282.        WHERE to_user = ? AND viewed = 0 AND is_like = 1
  283.        ORDER BY created_at DESC
  284.        """,
  285.         (user_id,),
  286.     )
  287.     rows = cursor.fetchall()
  288.  
  289.     with conn:
  290.         cursor.execute(
  291.             """
  292.            UPDATE likes
  293.            SET viewed = 1
  294.            WHERE to_user = ? AND viewed = 0 AND is_like = 1
  295.            """,
  296.             (user_id,),
  297.         )
  298.  
  299.     return [row["from_user"] for row in rows]
  300.  
  301.  
  302. def get_matches(user_id: int):
  303.     cursor.execute(
  304.         """
  305.        SELECT user1, user2, created_at
  306.        FROM matches
  307.        WHERE user1 = ? OR user2 = ?
  308.        ORDER BY created_at DESC
  309.        """,
  310.         (user_id, user_id),
  311.     )
  312.     return cursor.fetchall()
  313.  
  314.  
  315. def main_menu(is_admin=False):
  316.     keyboard = [
  317.         [KeyboardButton(text="👤 Мой профиль")],
  318.         [KeyboardButton(text="🔍 Искать"), KeyboardButton(text="❤️ Лайки")],
  319.         [KeyboardButton(text="💕 Мэтчи"), KeyboardButton(text="✏️ Анкета")]
  320.     ]
  321.  
  322.     if is_admin:
  323.         keyboard.append([KeyboardButton(text="👑 Админ")])
  324.  
  325.     return ReplyKeyboardMarkup(
  326.         keyboard=keyboard,
  327.         resize_keyboard=True
  328.     )
  329.  
  330. def admin_menu():
  331.     return ReplyKeyboardMarkup(
  332.         keyboard=[
  333.             [KeyboardButton(text="📊 Статистика")],
  334.             [KeyboardButton(text="📢 Рассылка"), KeyboardButton(text="👥 Пользователи")],
  335.             [KeyboardButton(text="🔙 Выход")]
  336.         ],
  337.         resize_keyboard=True
  338.     )
  339.  
  340. def search_buttons(target_id: int):
  341.     return InlineKeyboardMarkup(
  342.         inline_keyboard=[
  343.             [
  344.                 InlineKeyboardButton(text="❤️ Лайк", callback_data=f"like:{target_id}"),
  345.                 InlineKeyboardButton(text="❌ Скип", callback_data=f"skip:{target_id}"),
  346.             ]
  347.         ]
  348.     )
  349.  
  350.  
  351. def build_profile_card(profile) -> str:
  352.     username = f"@{esc(profile['username'])}" if profile["username"] else f"ID: {profile['user_id']}"
  353.     return (
  354.         f"🎮 <b>Поиск тиммейта</b>\n\n"
  355.         f"👤 {esc(profile['full_name'])}\n"
  356.         f"{username}\n\n"
  357.         f"🎮 Игра: {esc(profile['game'])}\n"
  358.         f"🏆 Ранг: {esc(profile['rank'])}\n"
  359.         f"⚡ Роль: {esc(profile['role'])}\n"
  360.         f"📝 О себе: {esc(profile['about'])}\n"
  361.         f"🔍 Ищет: {esc(profile['looking_for'])}"
  362.     )
  363.  
  364.  
  365. async def safe_edit_or_send(message: Message, text: str, reply_markup=None):
  366.     with suppress(Exception):
  367.         await message.edit_text(text, reply_markup=reply_markup)
  368.         return
  369.     await message.answer(text, reply_markup=reply_markup)
  370.  
  371.  
  372. async def show_next_candidate(callback: CallbackQuery, state: FSMContext):
  373.     data = await state.get_data()
  374.     candidates = data.get("candidates", [])
  375.     index = int(data.get("index", 0)) + 1
  376.  
  377.     while index < len(candidates):
  378.         next_id = candidates[index]
  379.         profile = get_profile(next_id)
  380.         if profile and profile["is_active"]:
  381.             await state.update_data(index=index, current_id=next_id)
  382.             await safe_edit_or_send(
  383.                 callback.message,
  384.                 build_profile_card(profile),
  385.                 reply_markup=search_buttons(next_id),
  386.             )
  387.             return
  388.         index += 1
  389.  
  390.     await state.clear()
  391.     await safe_edit_or_send(
  392.         callback.message,
  393.         "🏁 Поиск закончен! Больше нет анкет.",
  394.         reply_markup=None,
  395.     )
  396.     await callback.message.answer(
  397.         "Что дальше?",
  398.         reply_markup=main_menu(is_admin=(callback.from_user.id == ADMIN_ID))
  399.     )
  400.  
  401.  
  402. # ================== START ==================
  403. @dp.message(Command("start"))
  404. async def start(message: Message, state: FSMContext):
  405.     await state.clear()
  406.  
  407.     user_id = message.from_user.id
  408.     profile = get_profile(user_id)
  409.  
  410.     if user_id == ADMIN_ID:
  411.         if not profile or not profile["game"]:
  412.             await message.answer(
  413.                 "👑 Ты вошёл как админ.\n\n"
  414.                 "Ты можешь создать свою анкету или открыть админ-панель через кнопку «👑 Админ».",
  415.                 reply_markup=main_menu(is_admin=True)
  416.             )
  417.         else:
  418.             await message.answer(
  419.                 f"👑 <b>Добро пожаловать, {esc(message.from_user.first_name)}!</b>\n\n"
  420.                 "Ты можешь пользоваться ботом как обычный пользователь или открыть админ-панель.",
  421.                 parse_mode=ParseMode.HTML,
  422.                 reply_markup=main_menu(is_admin=True)
  423.             )
  424.         return
  425.  
  426.     if not profile or not profile["game"]:
  427.         await state.set_state(ProfileForm.game)
  428.         await message.answer(
  429.             "🎮 <b>Создание анкеты</b>\n\n"
  430.             "1️⃣ Выбери игру кнопкой ниже:",
  431.             parse_mode=ParseMode.HTML,
  432.             reply_markup=game_choice_keyboard(),
  433.         )
  434.     else:
  435.         await message.answer(
  436.             f"🎮 <b>С возвращением, {esc(message.from_user.first_name)}!</b>",
  437.             parse_mode=ParseMode.HTML,
  438.             reply_markup=main_menu()
  439.         )
  440.  
  441. @dp.message(Command("cancel"))
  442. async def cancel(message: Message, state: FSMContext):
  443.     await state.clear()
  444.     if message.from_user.id == ADMIN_ID:
  445.         await message.answer("Действие отменено.", reply_markup=admin_menu())
  446.     else:
  447.         await message.answer("Действие отменено.", reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)))
  448.  
  449.  
  450. # ================== АНКЕТА ==================
  451. @dp.message(F.text == "✏️ Анкета")
  452. async def fill_anketa(message: Message, state: FSMContext):
  453.     await state.clear()
  454.     await state.set_state(ProfileForm.game)
  455.     await message.answer(
  456.         "📝 <b>Заполни анкету заново</b>\n\n"
  457.         "1️⃣ Выбери игру кнопкой ниже:",
  458.         parse_mode=ParseMode.HTML,
  459.         reply_markup=game_choice_keyboard(),
  460.     )
  461.  
  462.  
  463. @dp.message(ProfileForm.game, F.text)
  464. async def form_game(message: Message, state: FSMContext):
  465.     choice = (message.text or "").strip()
  466.  
  467.     if choice == "Другое":
  468.         await state.set_state(ProfileForm.custom_game)
  469.         await message.answer(
  470.             "Введите название игры вручную:",
  471.             reply_markup=ReplyKeyboardRemove(),
  472.         )
  473.         return
  474.  
  475.     if choice not in GAME_CHOICES:
  476.         await message.answer(
  477.             "Пожалуйста, выбери игру кнопкой ниже.",
  478.             reply_markup=game_choice_keyboard(),
  479.         )
  480.         return
  481.  
  482.     await state.update_data(game=choice, game_key=GAME_CHOICES[choice])
  483.     await state.set_state(ProfileForm.rank)
  484.     await message.answer(
  485.         "2️⃣ Какой у тебя ранг/звание?\n(Пример: Легенда, Gold Nova, 2500 MMR)",
  486.         reply_markup=ReplyKeyboardRemove(),
  487.     )
  488. @dp.message(ProfileForm.rank, F.text)
  489. async def form_rank(message: Message, state: FSMContext):
  490.     await state.update_data(rank=message.text.strip())
  491.     await state.set_state(ProfileForm.role)
  492.     await message.answer("3️⃣ Твоя роль?\n(Пример: Керри, Саппорт, Entry Fragger)")
  493.  
  494.  
  495. @dp.message(ProfileForm.role, F.text)
  496. async def form_role(message: Message, state: FSMContext):
  497.     await state.update_data(role=message.text.strip())
  498.     await state.set_state(ProfileForm.about)
  499.     await message.answer("4️⃣ Расскажи о себе\n(Пример: Играю вечерами, есть микрофон, не токсичный)")
  500.  
  501. @dp.message(ProfileForm.custom_game, F.text)
  502. async def form_custom_game(message: Message, state: FSMContext):
  503.     raw_game = message.text or ""
  504.     cleaned_game = re.sub(r"\s+", " ", raw_game).strip()
  505.  
  506.     if not cleaned_game:
  507.         await message.answer("Название игры не должно быть пустым. Введите ещё раз.")
  508.         return
  509.  
  510.     await state.update_data(
  511.         game=cleaned_game,
  512.         game_key=normalize_game(cleaned_game),
  513.     )
  514.     await state.set_state(ProfileForm.rank)
  515.     await message.answer(
  516.         "2️⃣ Какой у тебя ранг/звание?\n(Пример: Легенда, Gold Nova, 2500 MMR)"
  517.     )
  518.  
  519. @dp.message(ProfileForm.about, F.text)
  520. async def form_about(message: Message, state: FSMContext):
  521.     await state.update_data(about=message.text.strip())
  522.     await state.set_state(ProfileForm.looking_for)
  523.     await message.answer("5️⃣ Кого ищешь?\n(Пример: Для каток в рейтинг, просто поиграть)")
  524.  
  525.  
  526. @dp.message(ProfileForm.looking_for, F.text)
  527. async def form_looking_for(message: Message, state: FSMContext):
  528.     data = await state.get_data()
  529.  
  530.     save_profile(
  531.         user_id=message.from_user.id,
  532.         username=message.from_user.username or "",
  533.         full_name=message.from_user.full_name,
  534.         game=data.get("game", ""),
  535.         game_key=data.get("game_key", normalize_game(data.get("game", ""))),
  536.         rank=data.get("rank", ""),
  537.         role=data.get("role", ""),
  538.         about=data.get("about", ""),
  539.         looking_for=message.text.strip(),
  540.     )
  541.  
  542.     await state.clear()
  543.  
  544.     await message.answer(
  545.         f"✅ <b>Анкета готова!</b>\n\n"
  546.         f"🎮 Игра: {esc(data.get('game', ''))}\n"
  547.         f"🏆 Ранг: {esc(data.get('rank', ''))}\n"
  548.         f"⚡ Роль: {esc(data.get('role', ''))}\n"
  549.         f"📝 О себе: {esc(data.get('about', ''))}\n"
  550.         f"🔍 Ищет: {esc(message.text)}\n\n"
  551.         f"Теперь ты можешь искать тиммейтов!",
  552.         parse_mode=ParseMode.HTML,
  553.         reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)),
  554.     )
  555.  
  556.  
  557. # ================== ПРОФИЛЬ ==================
  558. @dp.message(F.text == "👤 Мой профиль")
  559. async def my_profile(message: Message):
  560.     profile = get_profile(message.from_user.id)
  561.  
  562.     if not profile or not profile["game"]:
  563.         await message.answer(
  564.             "❌ Сначала заполни анкету. Нажми «✏️ Анкета».",
  565.             reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)),
  566.         )
  567.         return
  568.  
  569.     await message.answer(
  570.         f"👤 <b>Твой профиль</b>\n\n"
  571.         f"🎮 Игра: {esc(profile['game'])}\n"
  572.         f"🏆 Ранг: {esc(profile['rank'])}\n"
  573.         f"⚡ Роль: {esc(profile['role'])}\n"
  574.         f"📝 О себе: {esc(profile['about'])}\n"
  575.         f"🔍 Ищет: {esc(profile['looking_for'])}",
  576.         parse_mode=ParseMode.HTML,
  577.         reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)),
  578.     )
  579.  
  580.  
  581. # ================== ПОИСК ==================
  582. @dp.message(F.text == "🔍 Искать")
  583. async def search(message: Message, state: FSMContext):
  584.     user_id = message.from_user.id
  585.     me = get_profile(user_id)
  586.  
  587.     if not me or not me["game_key"]:
  588.         await message.answer(
  589.             "❌ Сначала заполни анкету. Нажми «✏️ Анкета».",
  590.             reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID))
  591.         )
  592.         return
  593.  
  594.     candidates = get_candidate_ids(user_id, me["game_key"])
  595.  
  596.     if not candidates:
  597.         await message.answer(
  598.             "😔 Пока нет подходящих игроков по этой игре. Зайди позже!",
  599.             reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)),
  600.         )
  601.         return
  602.  
  603.     await state.set_state(SearchFlow.browsing)
  604.     await state.update_data(
  605.         candidates=candidates,
  606.         index=0,
  607.         current_id=candidates[0],
  608.     )
  609.  
  610.     profile = get_profile(candidates[0])
  611.     if not profile:
  612.         await message.answer("❌ Профиль не найден",reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)))
  613.         await state.clear()
  614.         return
  615.  
  616.     await message.answer(
  617.         build_profile_card(profile),
  618.         parse_mode=ParseMode.HTML,
  619.         reply_markup=search_buttons(candidates[0]),
  620.     )
  621.  
  622.  
  623. @dp.callback_query(F.data.startswith("like:"))
  624. async def like(callback: CallbackQuery, state: FSMContext):
  625.     user_id = callback.from_user.id
  626.     target_id = int(callback.data.split(":", 1)[1])
  627.  
  628.     data = await state.get_data()
  629.     candidates = data.get("candidates", [])
  630.     index = int(data.get("index", 0))
  631.     current_id = candidates[index] if candidates and index < len(candidates) else None
  632.  
  633.     if current_id != target_id:
  634.         await callback.answer("Эта карточка уже устарела.")
  635.         return
  636.  
  637.     is_match = add_like(user_id, target_id, 1)
  638.  
  639.     try:
  640.         await bot.send_message(
  641.             target_id,
  642.             "❤️ Кто-то из игроков лайкнул твою анкету!",
  643.         )
  644.     except Exception:
  645.         pass
  646.  
  647.     if is_match:
  648.         me = callback.from_user.full_name
  649.         try:
  650.             await bot.send_message(
  651.                 target_id,
  652.                 f"💕 У тебя мэтч с {esc(me)}!\nОткрой бота, чтобы начать общение.",
  653.                 parse_mode=ParseMode.HTML,
  654.             )
  655.         except Exception:
  656.             pass
  657.  
  658.         await callback.answer("💕 Это мэтч!")
  659.     else:
  660.         await callback.answer("❤️ Лайк отправлен!")
  661.  
  662.     await show_next_candidate(callback, state)
  663.  
  664.  
  665. @dp.callback_query(F.data.startswith("skip:"))
  666. async def skip(callback: CallbackQuery, state: FSMContext):
  667.     target_id = int(callback.data.split(":", 1)[1])
  668.  
  669.     data = await state.get_data()
  670.     candidates = data.get("candidates", [])
  671.     index = int(data.get("index", 0))
  672.     current_id = candidates[index] if candidates and index < len(candidates) else None
  673.  
  674.     if current_id != target_id:
  675.         await callback.answer("Эта карточка уже устарела.")
  676.         return
  677.  
  678.     add_like(callback.from_user.id, target_id, 0)
  679.     await callback.answer("⏭️ Пропущено")
  680.     await show_next_candidate(callback, state)
  681.  
  682.  
  683. # ================== ЛАЙКИ И МЭТЧИ ==================
  684. @dp.message(F.text == "❤️ Лайки")
  685. async def my_likes(message: Message):
  686.     user_id = message.from_user.id
  687.     likes = get_new_likes(user_id)
  688.  
  689.     if not likes:
  690.         await message.answer("😔 Пока нет лайков", reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)))
  691.         return
  692.  
  693.     text = "❤️ <b>Тебя лайкнули:</b>\n\n"
  694.     for uid in likes[:10]:
  695.         p = get_profile(uid)
  696.         if p:
  697.             name = esc(p["full_name"])
  698.             handle = f"@{esc(p['username'])}" if p["username"] else f"ID: {uid}"
  699.             text += f"• {name} ({handle})\n"
  700.  
  701.     await message.answer(text, parse_mode=ParseMode.HTML, reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)))
  702.  
  703.  
  704. @dp.message(F.text == "💕 Мэтчи")
  705. async def my_matches(message: Message):
  706.     user_id = message.from_user.id
  707.     matches = get_matches(user_id)
  708.  
  709.     if not matches:
  710.         await message.answer("😔 Пока нет мэтчей", reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)))
  711.         return
  712.  
  713.     text = "💕 <b>Твои мэтчи:</b>\n\n"
  714.     for row in matches:
  715.         other = row["user1"] if row["user2"] == user_id else row["user2"]
  716.         p = get_profile(other)
  717.         if p:
  718.             name = esc(p["full_name"])
  719.             handle = f"@{esc(p['username'])}" if p["username"] else f"ID: {other}"
  720.             text += f"• {name} ({handle})\n"
  721.  
  722.     await message.answer(text, parse_mode=ParseMode.HTML, reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)))
  723.  
  724.  
  725. # ================== АДМИН-ПАНЕЛЬ ==================
  726.  
  727. @dp.message(F.text == "👑 Админ")
  728. async def open_admin_panel(message: Message, state: FSMContext):
  729.     if message.from_user.id != ADMIN_ID:
  730.         return
  731.  
  732.     await state.clear()
  733.     await message.answer(
  734.         "👑 <b>Админ-панель</b>\n\nВыбери действие:",
  735.         parse_mode=ParseMode.HTML,
  736.         reply_markup=admin_menu()
  737.     )
  738. @dp.message(F.text == "📊 Статистика")
  739. async def admin_stats(message: Message):
  740.     if message.from_user.id != ADMIN_ID:
  741.         return
  742.  
  743.     cursor.execute("SELECT COUNT(*) AS cnt FROM users")
  744.     users_count = cursor.fetchone()["cnt"]
  745.  
  746.     cursor.execute("SELECT COUNT(*) AS cnt FROM matches")
  747.     matches_count = cursor.fetchone()["cnt"]
  748.  
  749.     await message.answer(
  750.         f"📊 <b>Статистика</b>\n\n"
  751.         f"👥 Пользователей: {users_count}\n"
  752.         f"💕 Мэтчей: {matches_count}",
  753.         parse_mode=ParseMode.HTML,
  754.         reply_markup=admin_menu(),
  755.     )
  756.  
  757.  
  758. @dp.message(F.text == "👥 Пользователи")
  759. async def admin_users(message: Message):
  760.     if message.from_user.id != ADMIN_ID:
  761.         return
  762.  
  763.     cursor.execute(
  764.         """
  765.        SELECT user_id, username, full_name
  766.        FROM users
  767.        ORDER BY created_at DESC
  768.        LIMIT 50
  769.        """
  770.     )
  771.     users = cursor.fetchall()
  772.  
  773.     if not users:
  774.         await message.answer("Нет пользователей", reply_markup=admin_menu())
  775.         return
  776.     text = "👥 <b>Пользователи:</b>\n\n"
  777.     for u in users:
  778.         name = esc(u["full_name"])
  779.         handle = f"@{esc(u['username'])}" if u["username"] else "нет"
  780.         text += f"• {name} ({handle}) - ID: {u['user_id']}\n"
  781.  
  782.     await message.answer(text, parse_mode=ParseMode.HTML, reply_markup=admin_menu())
  783.  
  784.  
  785. @dp.message(F.text == "📢 Рассылка")
  786. async def broadcast_start(message: Message, state: FSMContext):
  787.     if message.from_user.id != ADMIN_ID:
  788.         return
  789.  
  790.     await state.set_state(BroadcastFlow.waiting_text)
  791.     await message.answer("📢 Отправь сообщение для рассылки:")
  792.  
  793.  
  794. @dp.message(BroadcastFlow.waiting_text, F.text)
  795. async def broadcast_send(message: Message, state: FSMContext):
  796.     if message.from_user.id != ADMIN_ID:
  797.         return
  798.  
  799.     cursor.execute("SELECT user_id FROM users WHERE is_active = 1")
  800.     users = cursor.fetchall()
  801.  
  802.     success = 0
  803.     broadcast_text = esc(message.text)
  804.  
  805.     for u in users:
  806.         try:
  807.             await bot.send_message(
  808.                 u["user_id"],
  809.                 f"📢 <b>Рассылка</b>\n\n{broadcast_text}",
  810.                 parse_mode=ParseMode.HTML,
  811.             )
  812.             success += 1
  813.         except Exception:
  814.             pass
  815.  
  816.     await state.clear()
  817.     await message.answer(
  818.         f"✅ Рассылка завершена! Отправлено {success} пользователям",
  819.         reply_markup=admin_menu(),
  820.     )
  821.  
  822.  
  823. @dp.message(F.text == "🔙 Выход")
  824. async def admin_exit(message: Message, state: FSMContext):
  825.     if message.from_user.id != ADMIN_ID:
  826.         return
  827.  
  828.     await state.clear()
  829.  
  830.     profile = get_profile(message.from_user.id)
  831.  
  832.     if profile and profile["game"]:
  833.         await message.answer(
  834.             "✅ Ты вернулся в режим обычного пользователя.",
  835.             reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID))
  836.         )
  837.     else:
  838.         await message.answer(
  839.             "✅ Ты вернулся в режим обычного пользователя.\n"
  840.             "Сначала можешь создать анкету через кнопку «✏️ Анкета».",
  841.             reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID))
  842.         )
  843.  
  844. # ================== ЗАПУСК ==================
  845. async def main():
  846.     print("🤖 Бот запущен!")
  847.     await dp.start_polling(bot)
  848.  
  849.  
  850. if __name__ == "__main__":
  851.     asyncio.run(main())
Advertisement
Comments
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
Add Comment
Please, Sign In to add comment