Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import asyncio
- import html
- import logging
- import os
- import sqlite3
- from contextlib import suppress
- import re
- from aiogram import Bot, Dispatcher, F
- from aiogram.enums import ParseMode
- from aiogram.filters import Command
- from aiogram.fsm.context import FSMContext
- from aiogram.fsm.state import State, StatesGroup
- from aiogram.fsm.storage.memory import MemoryStorage
- from aiogram.types import (
- CallbackQuery,
- InlineKeyboardButton,
- InlineKeyboardMarkup,
- KeyboardButton,
- Message,
- ReplyKeyboardMarkup,
- ReplyKeyboardRemove,
- )
- # ================== НАСТРОЙКИ ==================
- BOT_TOKEN = ""
- ADMIN_ID = int(os.getenv("ADMIN_ID", "6803061349"))
- DB_PATH = os.getenv("DB_PATH", "teamfinder.db")
- if not BOT_TOKEN:
- raise RuntimeError("BOT_TOKEN is empty. Set it in environment variables.")
- logging.basicConfig(level=logging.INFO)
- bot = Bot(token=BOT_TOKEN)
- dp = Dispatcher(storage=MemoryStorage())
- # ================== БАЗА ДАННЫХ ==================
- conn = sqlite3.connect(DB_PATH, check_same_thread=False)
- conn.row_factory = sqlite3.Row
- cursor = conn.cursor()
- def init_db() -> None:
- cursor.execute("""
- CREATE TABLE IF NOT EXISTS users (
- user_id INTEGER PRIMARY KEY,
- username TEXT,
- full_name TEXT,
- game TEXT,
- game_key TEXT DEFAULT '',
- rank TEXT,
- role TEXT,
- about TEXT,
- looking_for TEXT,
- is_active INTEGER DEFAULT 1,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
- )
- """)
- cursor.execute("""
- CREATE TABLE IF NOT EXISTS likes (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- from_user INTEGER,
- to_user INTEGER,
- is_like INTEGER,
- viewed INTEGER DEFAULT 0,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- UNIQUE(from_user, to_user)
- )
- """)
- cursor.execute("""
- CREATE TABLE IF NOT EXISTS matches (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- user1 INTEGER,
- user2 INTEGER,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- UNIQUE(user1, user2)
- )
- """)
- conn.commit()
- GAME_CHOICES = {
- "Dota 2": "dota 2",
- "CS2": "cs2",
- "PUBG": "pubg",
- "Valorant": "valorant",
- }
- GAME_ALIASES = {
- "dota": "dota 2",
- "dota 2": "dota 2",
- "dota2": "dota 2",
- "cs2": "cs2",
- "cs 2": "cs2",
- "counter strike 2": "cs2",
- "counter-strike 2": "cs2",
- "csgo": "cs2",
- "pubg": "pubg",
- "playerunknowns battlegrounds": "pubg",
- "playerunknown's battlegrounds": "pubg",
- "valorant": "valorant",
- }
- def game_choice_keyboard():
- return ReplyKeyboardMarkup(
- keyboard=[
- [KeyboardButton(text="Dota 2"), KeyboardButton(text="CS2")],
- [KeyboardButton(text="PUBG"), KeyboardButton(text="Valorant")],
- [KeyboardButton(text="Другое")],
- ],
- resize_keyboard=True,
- one_time_keyboard=True,
- )
- def normalize_game(value: str) -> str:
- value = "" if value is None else str(value)
- value = value.lower().replace("ё", "е")
- value = value.replace("—", "-").replace("–", "-")
- value = re.sub(r"[^\w\s-]+", " ", value)
- value = re.sub(r"\s+", " ", value).strip()
- return GAME_ALIASES.get(value, value)
- def migrate_db() -> None:
- cursor.execute("PRAGMA table_info(users)")
- columns = {row["name"] for row in cursor.fetchall()}
- if "game_key" not in columns:
- cursor.execute("ALTER TABLE users ADD COLUMN game_key TEXT DEFAULT ''")
- conn.commit()
- cursor.execute("""
- SELECT user_id, game
- FROM users
- WHERE COALESCE(game_key, '') = '' AND COALESCE(game, '') <> ''
- """)
- rows = cursor.fetchall()
- for row in rows:
- cursor.execute(
- "UPDATE users SET game_key = ? WHERE user_id = ?",
- (normalize_game(row["game"]), row["user_id"]),
- )
- conn.commit()
- init_db()
- migrate_db()
- # ================== СОСТОЯНИЯ ==================
- class ProfileForm(StatesGroup):
- game = State()
- custom_game = State()
- rank = State()
- role = State()
- about = State()
- looking_for = State()
- class SearchFlow(StatesGroup):
- browsing = State()
- class BroadcastFlow(StatesGroup):
- waiting_text = State()
- # ================== УТИЛИТЫ ==================
- def esc(value) -> str:
- return html.escape("" if value is None else str(value))
- def save_profile(user_id, username, full_name, game, game_key, rank, role, about, looking_for):
- with conn:
- cursor.execute(
- """
- INSERT INTO users (
- user_id, username, full_name, game, game_key, rank, role, about, looking_for, is_active
- )
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
- ON CONFLICT(user_id) DO UPDATE SET
- username=excluded.username,
- full_name=excluded.full_name,
- game=excluded.game,
- game_key=excluded.game_key,
- rank=excluded.rank,
- role=excluded.role,
- about=excluded.about,
- looking_for=excluded.looking_for,
- is_active=1
- """,
- (user_id, username, full_name, game, game_key, rank, role, about, looking_for),
- )
- def get_profile(user_id):
- cursor.execute("SELECT * FROM users WHERE user_id = ?", (user_id,))
- return cursor.fetchone()
- def get_candidate_ids(user_id, game_filter: str = ""):
- game_filter = normalize_game(game_filter)
- cursor.execute(
- """
- SELECT u.user_id
- FROM users u
- WHERE u.is_active = 1
- AND u.user_id != ?
- AND COALESCE(u.game_key, '') != ''
- AND (? = '' OR u.game_key = ?)
- AND NOT EXISTS (
- SELECT 1
- FROM likes l
- WHERE l.from_user = ?
- AND l.to_user = u.user_id
- )
- AND NOT EXISTS (
- SELECT 1
- FROM matches m
- WHERE (m.user1 = ? AND m.user2 = u.user_id)
- OR (m.user2 = ? AND m.user1 = u.user_id)
- )
- ORDER BY u.created_at DESC
- """,
- (user_id, game_filter, game_filter, user_id, user_id, user_id),
- )
- return [row["user_id"] for row in cursor.fetchall()]
- def add_like(from_user: int, to_user: int, is_like: int) -> bool:
- """
- Returns True if a match has been created.
- """
- with conn:
- cursor.execute(
- """
- INSERT INTO likes (from_user, to_user, is_like, viewed)
- VALUES (?, ?, ?, 0)
- ON CONFLICT(from_user, to_user) DO UPDATE SET
- is_like=excluded.is_like,
- viewed=0,
- created_at=CURRENT_TIMESTAMP
- """,
- (from_user, to_user, is_like),
- )
- if is_like == 1:
- cursor.execute(
- """
- SELECT 1
- FROM likes
- WHERE from_user = ? AND to_user = ? AND is_like = 1
- """,
- (to_user, from_user),
- )
- if cursor.fetchone():
- cursor.execute(
- """
- INSERT OR IGNORE INTO matches (user1, user2)
- VALUES (?, ?)
- """,
- (min(from_user, to_user), max(from_user, to_user)),
- )
- return True
- return False
- def get_new_likes(user_id: int):
- cursor.execute(
- """
- SELECT from_user
- FROM likes
- WHERE to_user = ? AND viewed = 0 AND is_like = 1
- ORDER BY created_at DESC
- """,
- (user_id,),
- )
- rows = cursor.fetchall()
- with conn:
- cursor.execute(
- """
- UPDATE likes
- SET viewed = 1
- WHERE to_user = ? AND viewed = 0 AND is_like = 1
- """,
- (user_id,),
- )
- return [row["from_user"] for row in rows]
- def get_matches(user_id: int):
- cursor.execute(
- """
- SELECT user1, user2, created_at
- FROM matches
- WHERE user1 = ? OR user2 = ?
- ORDER BY created_at DESC
- """,
- (user_id, user_id),
- )
- return cursor.fetchall()
- def main_menu(is_admin=False):
- keyboard = [
- [KeyboardButton(text="👤 Мой профиль")],
- [KeyboardButton(text="🔍 Искать"), KeyboardButton(text="❤️ Лайки")],
- [KeyboardButton(text="💕 Мэтчи"), KeyboardButton(text="✏️ Анкета")]
- ]
- if is_admin:
- keyboard.append([KeyboardButton(text="👑 Админ")])
- return ReplyKeyboardMarkup(
- keyboard=keyboard,
- resize_keyboard=True
- )
- def admin_menu():
- return ReplyKeyboardMarkup(
- keyboard=[
- [KeyboardButton(text="📊 Статистика")],
- [KeyboardButton(text="📢 Рассылка"), KeyboardButton(text="👥 Пользователи")],
- [KeyboardButton(text="🔙 Выход")]
- ],
- resize_keyboard=True
- )
- def search_buttons(target_id: int):
- return InlineKeyboardMarkup(
- inline_keyboard=[
- [
- InlineKeyboardButton(text="❤️ Лайк", callback_data=f"like:{target_id}"),
- InlineKeyboardButton(text="❌ Скип", callback_data=f"skip:{target_id}"),
- ]
- ]
- )
- def build_profile_card(profile) -> str:
- username = f"@{esc(profile['username'])}" if profile["username"] else f"ID: {profile['user_id']}"
- return (
- f"🎮 <b>Поиск тиммейта</b>\n\n"
- f"👤 {esc(profile['full_name'])}\n"
- f"{username}\n\n"
- f"🎮 Игра: {esc(profile['game'])}\n"
- f"🏆 Ранг: {esc(profile['rank'])}\n"
- f"⚡ Роль: {esc(profile['role'])}\n"
- f"📝 О себе: {esc(profile['about'])}\n"
- f"🔍 Ищет: {esc(profile['looking_for'])}"
- )
- async def safe_edit_or_send(message: Message, text: str, reply_markup=None):
- with suppress(Exception):
- await message.edit_text(text, reply_markup=reply_markup)
- return
- await message.answer(text, reply_markup=reply_markup)
- async def show_next_candidate(callback: CallbackQuery, state: FSMContext):
- data = await state.get_data()
- candidates = data.get("candidates", [])
- index = int(data.get("index", 0)) + 1
- while index < len(candidates):
- next_id = candidates[index]
- profile = get_profile(next_id)
- if profile and profile["is_active"]:
- await state.update_data(index=index, current_id=next_id)
- await safe_edit_or_send(
- callback.message,
- build_profile_card(profile),
- reply_markup=search_buttons(next_id),
- )
- return
- index += 1
- await state.clear()
- await safe_edit_or_send(
- callback.message,
- "🏁 Поиск закончен! Больше нет анкет.",
- reply_markup=None,
- )
- await callback.message.answer(
- "Что дальше?",
- reply_markup=main_menu(is_admin=(callback.from_user.id == ADMIN_ID))
- )
- # ================== START ==================
- @dp.message(Command("start"))
- async def start(message: Message, state: FSMContext):
- await state.clear()
- user_id = message.from_user.id
- profile = get_profile(user_id)
- if user_id == ADMIN_ID:
- if not profile or not profile["game"]:
- await message.answer(
- "👑 Ты вошёл как админ.\n\n"
- "Ты можешь создать свою анкету или открыть админ-панель через кнопку «👑 Админ».",
- reply_markup=main_menu(is_admin=True)
- )
- else:
- await message.answer(
- f"👑 <b>Добро пожаловать, {esc(message.from_user.first_name)}!</b>\n\n"
- "Ты можешь пользоваться ботом как обычный пользователь или открыть админ-панель.",
- parse_mode=ParseMode.HTML,
- reply_markup=main_menu(is_admin=True)
- )
- return
- if not profile or not profile["game"]:
- await state.set_state(ProfileForm.game)
- await message.answer(
- "🎮 <b>Создание анкеты</b>\n\n"
- "1️⃣ Выбери игру кнопкой ниже:",
- parse_mode=ParseMode.HTML,
- reply_markup=game_choice_keyboard(),
- )
- else:
- await message.answer(
- f"🎮 <b>С возвращением, {esc(message.from_user.first_name)}!</b>",
- parse_mode=ParseMode.HTML,
- reply_markup=main_menu()
- )
- @dp.message(Command("cancel"))
- async def cancel(message: Message, state: FSMContext):
- await state.clear()
- if message.from_user.id == ADMIN_ID:
- await message.answer("Действие отменено.", reply_markup=admin_menu())
- else:
- await message.answer("Действие отменено.", reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)))
- # ================== АНКЕТА ==================
- @dp.message(F.text == "✏️ Анкета")
- async def fill_anketa(message: Message, state: FSMContext):
- await state.clear()
- await state.set_state(ProfileForm.game)
- await message.answer(
- "📝 <b>Заполни анкету заново</b>\n\n"
- "1️⃣ Выбери игру кнопкой ниже:",
- parse_mode=ParseMode.HTML,
- reply_markup=game_choice_keyboard(),
- )
- @dp.message(ProfileForm.game, F.text)
- async def form_game(message: Message, state: FSMContext):
- choice = (message.text or "").strip()
- if choice == "Другое":
- await state.set_state(ProfileForm.custom_game)
- await message.answer(
- "Введите название игры вручную:",
- reply_markup=ReplyKeyboardRemove(),
- )
- return
- if choice not in GAME_CHOICES:
- await message.answer(
- "Пожалуйста, выбери игру кнопкой ниже.",
- reply_markup=game_choice_keyboard(),
- )
- return
- await state.update_data(game=choice, game_key=GAME_CHOICES[choice])
- await state.set_state(ProfileForm.rank)
- await message.answer(
- "2️⃣ Какой у тебя ранг/звание?\n(Пример: Легенда, Gold Nova, 2500 MMR)",
- reply_markup=ReplyKeyboardRemove(),
- )
- @dp.message(ProfileForm.rank, F.text)
- async def form_rank(message: Message, state: FSMContext):
- await state.update_data(rank=message.text.strip())
- await state.set_state(ProfileForm.role)
- await message.answer("3️⃣ Твоя роль?\n(Пример: Керри, Саппорт, Entry Fragger)")
- @dp.message(ProfileForm.role, F.text)
- async def form_role(message: Message, state: FSMContext):
- await state.update_data(role=message.text.strip())
- await state.set_state(ProfileForm.about)
- await message.answer("4️⃣ Расскажи о себе\n(Пример: Играю вечерами, есть микрофон, не токсичный)")
- @dp.message(ProfileForm.custom_game, F.text)
- async def form_custom_game(message: Message, state: FSMContext):
- raw_game = message.text or ""
- cleaned_game = re.sub(r"\s+", " ", raw_game).strip()
- if not cleaned_game:
- await message.answer("Название игры не должно быть пустым. Введите ещё раз.")
- return
- await state.update_data(
- game=cleaned_game,
- game_key=normalize_game(cleaned_game),
- )
- await state.set_state(ProfileForm.rank)
- await message.answer(
- "2️⃣ Какой у тебя ранг/звание?\n(Пример: Легенда, Gold Nova, 2500 MMR)"
- )
- @dp.message(ProfileForm.about, F.text)
- async def form_about(message: Message, state: FSMContext):
- await state.update_data(about=message.text.strip())
- await state.set_state(ProfileForm.looking_for)
- await message.answer("5️⃣ Кого ищешь?\n(Пример: Для каток в рейтинг, просто поиграть)")
- @dp.message(ProfileForm.looking_for, F.text)
- async def form_looking_for(message: Message, state: FSMContext):
- data = await state.get_data()
- save_profile(
- user_id=message.from_user.id,
- username=message.from_user.username or "",
- full_name=message.from_user.full_name,
- game=data.get("game", ""),
- game_key=data.get("game_key", normalize_game(data.get("game", ""))),
- rank=data.get("rank", ""),
- role=data.get("role", ""),
- about=data.get("about", ""),
- looking_for=message.text.strip(),
- )
- await state.clear()
- await message.answer(
- f"✅ <b>Анкета готова!</b>\n\n"
- f"🎮 Игра: {esc(data.get('game', ''))}\n"
- f"🏆 Ранг: {esc(data.get('rank', ''))}\n"
- f"⚡ Роль: {esc(data.get('role', ''))}\n"
- f"📝 О себе: {esc(data.get('about', ''))}\n"
- f"🔍 Ищет: {esc(message.text)}\n\n"
- f"Теперь ты можешь искать тиммейтов!",
- parse_mode=ParseMode.HTML,
- reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)),
- )
- # ================== ПРОФИЛЬ ==================
- @dp.message(F.text == "👤 Мой профиль")
- async def my_profile(message: Message):
- profile = get_profile(message.from_user.id)
- if not profile or not profile["game"]:
- await message.answer(
- "❌ Сначала заполни анкету. Нажми «✏️ Анкета».",
- reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)),
- )
- return
- await message.answer(
- f"👤 <b>Твой профиль</b>\n\n"
- f"🎮 Игра: {esc(profile['game'])}\n"
- f"🏆 Ранг: {esc(profile['rank'])}\n"
- f"⚡ Роль: {esc(profile['role'])}\n"
- f"📝 О себе: {esc(profile['about'])}\n"
- f"🔍 Ищет: {esc(profile['looking_for'])}",
- parse_mode=ParseMode.HTML,
- reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)),
- )
- # ================== ПОИСК ==================
- @dp.message(F.text == "🔍 Искать")
- async def search(message: Message, state: FSMContext):
- user_id = message.from_user.id
- me = get_profile(user_id)
- if not me or not me["game_key"]:
- await message.answer(
- "❌ Сначала заполни анкету. Нажми «✏️ Анкета».",
- reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID))
- )
- return
- candidates = get_candidate_ids(user_id, me["game_key"])
- if not candidates:
- await message.answer(
- "😔 Пока нет подходящих игроков по этой игре. Зайди позже!",
- reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)),
- )
- return
- await state.set_state(SearchFlow.browsing)
- await state.update_data(
- candidates=candidates,
- index=0,
- current_id=candidates[0],
- )
- profile = get_profile(candidates[0])
- if not profile:
- await message.answer("❌ Профиль не найден",reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)))
- await state.clear()
- return
- await message.answer(
- build_profile_card(profile),
- parse_mode=ParseMode.HTML,
- reply_markup=search_buttons(candidates[0]),
- )
- @dp.callback_query(F.data.startswith("like:"))
- async def like(callback: CallbackQuery, state: FSMContext):
- user_id = callback.from_user.id
- target_id = int(callback.data.split(":", 1)[1])
- data = await state.get_data()
- candidates = data.get("candidates", [])
- index = int(data.get("index", 0))
- current_id = candidates[index] if candidates and index < len(candidates) else None
- if current_id != target_id:
- await callback.answer("Эта карточка уже устарела.")
- return
- is_match = add_like(user_id, target_id, 1)
- try:
- await bot.send_message(
- target_id,
- "❤️ Кто-то из игроков лайкнул твою анкету!",
- )
- except Exception:
- pass
- if is_match:
- me = callback.from_user.full_name
- try:
- await bot.send_message(
- target_id,
- f"💕 У тебя мэтч с {esc(me)}!\nОткрой бота, чтобы начать общение.",
- parse_mode=ParseMode.HTML,
- )
- except Exception:
- pass
- await callback.answer("💕 Это мэтч!")
- else:
- await callback.answer("❤️ Лайк отправлен!")
- await show_next_candidate(callback, state)
- @dp.callback_query(F.data.startswith("skip:"))
- async def skip(callback: CallbackQuery, state: FSMContext):
- target_id = int(callback.data.split(":", 1)[1])
- data = await state.get_data()
- candidates = data.get("candidates", [])
- index = int(data.get("index", 0))
- current_id = candidates[index] if candidates and index < len(candidates) else None
- if current_id != target_id:
- await callback.answer("Эта карточка уже устарела.")
- return
- add_like(callback.from_user.id, target_id, 0)
- await callback.answer("⏭️ Пропущено")
- await show_next_candidate(callback, state)
- # ================== ЛАЙКИ И МЭТЧИ ==================
- @dp.message(F.text == "❤️ Лайки")
- async def my_likes(message: Message):
- user_id = message.from_user.id
- likes = get_new_likes(user_id)
- if not likes:
- await message.answer("😔 Пока нет лайков", reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)))
- return
- text = "❤️ <b>Тебя лайкнули:</b>\n\n"
- for uid in likes[:10]:
- p = get_profile(uid)
- if p:
- name = esc(p["full_name"])
- handle = f"@{esc(p['username'])}" if p["username"] else f"ID: {uid}"
- text += f"• {name} ({handle})\n"
- await message.answer(text, parse_mode=ParseMode.HTML, reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)))
- @dp.message(F.text == "💕 Мэтчи")
- async def my_matches(message: Message):
- user_id = message.from_user.id
- matches = get_matches(user_id)
- if not matches:
- await message.answer("😔 Пока нет мэтчей", reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)))
- return
- text = "💕 <b>Твои мэтчи:</b>\n\n"
- for row in matches:
- other = row["user1"] if row["user2"] == user_id else row["user2"]
- p = get_profile(other)
- if p:
- name = esc(p["full_name"])
- handle = f"@{esc(p['username'])}" if p["username"] else f"ID: {other}"
- text += f"• {name} ({handle})\n"
- await message.answer(text, parse_mode=ParseMode.HTML, reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID)))
- # ================== АДМИН-ПАНЕЛЬ ==================
- @dp.message(F.text == "👑 Админ")
- async def open_admin_panel(message: Message, state: FSMContext):
- if message.from_user.id != ADMIN_ID:
- return
- await state.clear()
- await message.answer(
- "👑 <b>Админ-панель</b>\n\nВыбери действие:",
- parse_mode=ParseMode.HTML,
- reply_markup=admin_menu()
- )
- @dp.message(F.text == "📊 Статистика")
- async def admin_stats(message: Message):
- if message.from_user.id != ADMIN_ID:
- return
- cursor.execute("SELECT COUNT(*) AS cnt FROM users")
- users_count = cursor.fetchone()["cnt"]
- cursor.execute("SELECT COUNT(*) AS cnt FROM matches")
- matches_count = cursor.fetchone()["cnt"]
- await message.answer(
- f"📊 <b>Статистика</b>\n\n"
- f"👥 Пользователей: {users_count}\n"
- f"💕 Мэтчей: {matches_count}",
- parse_mode=ParseMode.HTML,
- reply_markup=admin_menu(),
- )
- @dp.message(F.text == "👥 Пользователи")
- async def admin_users(message: Message):
- if message.from_user.id != ADMIN_ID:
- return
- cursor.execute(
- """
- SELECT user_id, username, full_name
- FROM users
- ORDER BY created_at DESC
- LIMIT 50
- """
- )
- users = cursor.fetchall()
- if not users:
- await message.answer("Нет пользователей", reply_markup=admin_menu())
- return
- text = "👥 <b>Пользователи:</b>\n\n"
- for u in users:
- name = esc(u["full_name"])
- handle = f"@{esc(u['username'])}" if u["username"] else "нет"
- text += f"• {name} ({handle}) - ID: {u['user_id']}\n"
- await message.answer(text, parse_mode=ParseMode.HTML, reply_markup=admin_menu())
- @dp.message(F.text == "📢 Рассылка")
- async def broadcast_start(message: Message, state: FSMContext):
- if message.from_user.id != ADMIN_ID:
- return
- await state.set_state(BroadcastFlow.waiting_text)
- await message.answer("📢 Отправь сообщение для рассылки:")
- @dp.message(BroadcastFlow.waiting_text, F.text)
- async def broadcast_send(message: Message, state: FSMContext):
- if message.from_user.id != ADMIN_ID:
- return
- cursor.execute("SELECT user_id FROM users WHERE is_active = 1")
- users = cursor.fetchall()
- success = 0
- broadcast_text = esc(message.text)
- for u in users:
- try:
- await bot.send_message(
- u["user_id"],
- f"📢 <b>Рассылка</b>\n\n{broadcast_text}",
- parse_mode=ParseMode.HTML,
- )
- success += 1
- except Exception:
- pass
- await state.clear()
- await message.answer(
- f"✅ Рассылка завершена! Отправлено {success} пользователям",
- reply_markup=admin_menu(),
- )
- @dp.message(F.text == "🔙 Выход")
- async def admin_exit(message: Message, state: FSMContext):
- if message.from_user.id != ADMIN_ID:
- return
- await state.clear()
- profile = get_profile(message.from_user.id)
- if profile and profile["game"]:
- await message.answer(
- "✅ Ты вернулся в режим обычного пользователя.",
- reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID))
- )
- else:
- await message.answer(
- "✅ Ты вернулся в режим обычного пользователя.\n"
- "Сначала можешь создать анкету через кнопку «✏️ Анкета».",
- reply_markup=main_menu(is_admin=(message.from_user.id == ADMIN_ID))
- )
- # ================== ЗАПУСК ==================
- async def main():
- print("🤖 Бот запущен!")
- await dp.start_polling(bot)
- if __name__ == "__main__":
- asyncio.run(main())
Advertisement