import asyncio
import sqlite3
from aiogram import Bot, Dispatcher, types
from aiogram.filters import Command
from aiogram.types import Message
import logging
from datetime import datetime
BOT_TOKEN = "ВАШ_BOT_TOKEN"
ADMIN_IDS = [123456789] # Список ID адміністраторів
bot = Bot(token=BOT_TOKEN)
dp = Dispatcher()
# Ініціалізація бази даних
def init_db():
conn = sqlite3.connect('bot_users.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
username TEXT,
first_name TEXT,
joined_date TIMESTAMP,
is_active INTEGER DEFAULT 1
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS announcements (
id INTEGER PRIMARY KEY AUTOINCREMENT,
text TEXT,
sent_date TIMESTAMP,
success_count INTEGER,
fail_count INTEGER
)
''')
conn.commit()
conn.close()
# Додавання користувача
def add_user(user_id, username, first_name):
conn = sqlite3.connect('bot_users.db')
cursor = conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO users (user_id, username, first_name, joined_date)
VALUES (?, ?, ?, ?)
''', (user_id, username, first_name, datetime.now()))
conn.commit()
conn.close()
# Отримання активних користувачів
def get_active_users():
conn = sqlite3.connect('bot_users.db')
cursor = conn.cursor()
cursor.execute('SELECT user_id FROM users WHERE is_active = 1')
users = [row[0] for row in cursor.fetchall()]
conn.close()
return users
@dp.message(Command("start"))
async def start_handler(message: Message):
user = message.from_user
add_user(user.id, user.username, user.first_name)
await message.reply(
"Вітаю! Ви підписалися на оголошення.\n"
"Використовуйте /stop щоб відписатися."
)
@dp.message(Command("stop"))
async def stop_handler(message: Message):
conn = sqlite3.connect('bot_users.db')
cursor = conn.cursor()
cursor.execute(
'UPDATE users SET is_active = 0 WHERE user_id = ?',
(message.from_user.id,)
)
conn.commit()
conn.close()
await message.reply("Ви відписалися від оголошень.")
@dp.message()
async def announcement_handler(message: Message):
if message.chat.type not in ["group", "supergroup"]:
return
if message.from_user.id not in ADMIN_IDS:
return
if not message.text or not message.text.startswith("!О "):
return
announcement_text = message.text[3:]
active_users = get_active_users()
await message.reply("🔄 Починаю розсилку...")
success_count = 0
fail_count = 0
for user_id in active_users:
try:
await bot.send_message(
user_id,
f"📢 <b>Оголошення</b>\n\n{announcement_text}\n\n"
f"<i>Від: {message.from_user.full_name}</i>",
parse_mode="HTML"
)
success_count += 1
await asyncio.sleep(0.1)
except Exception as e:
fail_count += 1
logging.error(f"Помилка для {user_id}: {e}")
# Зберігаємо статистику
conn = sqlite3.connect('bot_users.db')
cursor = conn.cursor()
cursor.execute('''
INSERT INTO announcements (text, sent_date, success_count, fail_count)
VALUES (?, ?, ?, ?)
''', (announcement_text, datetime.now(), success_count, fail_count))
conn.commit()
conn.close()
await message.reply(
f"✅ Розсилку завершено!\n\n"
f"📨 Надіслано: {success_count}\n"
f"❌ Помилки: {fail_count}\n"
f"👥 Всього активних: {len(active_users)}"
)
# Команда статистики для адмінів
@dp.message(Command("stats"))
async def stats_handler(message: Message):
if message.from_user.id not in ADMIN_IDS:
return
conn = sqlite3.connect('bot_users.db')
cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM users WHERE is_active = 1')
active_count = cursor.fetchone()[0]
cursor.execute('SELECT COUNT(*) FROM users')
total_count = cursor.fetchone()[0]
conn.close()
await message.reply(
f"📊 <b>Статистика бота</b>\n\n"
f"👥 Всього користувачів: {total_count}\n"
f"✅ Активних: {active_count}\n"
f"❌ Неактивних: {total_count - active_count}",
parse_mode="HTML"
)
async def main():
logging.basicConfig(level=logging.INFO)
init_db()
await dp.start_polling(bot)
if __name__ == "__main__":
asyncio.run(main())