+ Кнопки разбана и проверка имени

parent 71ec1518
import asyncio
from aiogram import Bot, Dispatcher, Router
from aiogram.types import ChatMemberUpdated, Message
from aiogram.types import ChatMemberUpdated, Message, InlineKeyboardButton, InlineKeyboardMarkup
from aiogram.exceptions import AiogramError
from itertools import chain
import os
......@@ -24,6 +24,7 @@ bot_token = os.getenv("BOT_TOKEN")
log_chat_id = os.getenv("LOG_CHAT_ID")
main_chat_id = os.getenv("MAIN_CHAT_ID")
db_path = os.getenv("DB_PATH")
# Вызов функции для создания базы данных или подключения к существующей
create_db()
......@@ -92,6 +93,42 @@ tg_log_handler.setFormatter(formatter)
# Добавляем обработчик в логгер
logger.addHandler(tg_log_handler)
# Обработчик кнопки "Разбанить"
@router.callback_query(lambda c: c.data.startswith("unban_"))
async def unban_user(callback_query: types.CallbackQuery):
user_id = int(callback_query.data.split("_")[1])
try:
# Разбаниваем пользователя в чате
await bot.unban_chat_member(main_chat_id, user_id, only_if_banned=True)
# Удаляем пользователя из таблицы забаненных пользователей
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("DELETE FROM banned_users WHERE id = ?", (user_id,))
conn.commit()
conn.close()
# Ответ пользователю
await callback_query.answer("✅ User unbanned and removed from the banned list!")
# Сообщение в лог
await bot.send_message(
callback_query.message.chat.id,
f"✅ User <b>{user_id}</b> unbanned and removed from the banned list.",
parse_mode="HTML"
)
except AiogramError as e:
await callback_query.answer("Unbanning error.")
await bot.send_message(
callback_query.message.chat.id,
f"Error in unbanning {user_id}: {e}"
)
except Exception as e:
await callback_query.answer("An error occurred.")
logger.error(f"Error in unban_user callback: {e}")
@router.chat_member()
async def welcome_new_user(event: ChatMemberUpdated):
"""Обработчик новых участников группы."""
......@@ -117,13 +154,27 @@ async def welcome_new_user(event: ChatMemberUpdated):
add_user(new_user.id, new_user.first_name, new_user.last_name, new_user.username)
logger.info(f"User {new_user.first_name} ({new_user.id}) added to active users.", extra={"chat_id": event.chat.id})
# Проверка на спам в имени (например, на наличие спам-слов)
if any(spam_word in new_user.first_name.lower() for spam_word in SPAM_KEYWORDS):
try:
await bot.ban_chat_member(event.chat.id, new_user.id)
ban_user(new_user.id, new_user.first_name, new_user.last_name, new_user.username, "Spam detected in name")
logger.info(f"User {new_user.first_name} ({new_user.id}) banned due to spam detected in name.", extra={"chat_id": event.chat_id})
return
except AiogramError as e:
logger.error(f"Failed to ban user {new_user.id}. Error: {e}", extra={"chat_id": event.chat.id})
except Exception as e:
logger.error(f"Error banning user {new_user.id}: {e}", extra={"chat_id": event.chat.id})
return
# Проверка, если имя пользователя содержит арабские символы
if is_arabic_name(new_user.first_name):
try:
# Немедленно удаляем пользователя
await bot.ban_chat_member(event.chat.id, new_user.id)
ban_user(new_user.id, new_user.first_name, new_user.last_name, new_user.username, "Arabic name detected")
logger.info(f"User {new_user.first_name} ({new_user.id}) banned due to Arabic name.", extra={"chat_id": event.chat_id})
return # Прерываем дальнейшую обработку
return
except AiogramError as e:
logger.error(f"Failed to ban user {new_user.id}. Error: {e}", extra={"chat_id": event.chat.id})
......@@ -180,7 +231,21 @@ async def handle_message(message: Message):
user_id = message.from_user.id
ban_user(user_id, message.from_user.first_name, message.from_user.last_name, message.from_user.username, "Mixed layout detected")
await bot.ban_chat_member(chat_id, user_id)
logger.info(f"User {user_id} has been banned in the chat and moved to banned_users table due to mixed layout.", extra={"chat_id": chat_id})
# Создаем кнопку для разбанивания
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[InlineKeyboardButton(text="🔓 Разбанить", callback_data=f"unban_{user_id}")]
]
)
# Отправляем сообщение с кнопкой в группу логов
await bot.send_message(
chat_id=log_chat_id,
text=f"❌ User <b>{user_id}</b> has been banned for sending a massege with mixed layout.",
reply_markup=keyboard,
parse_mode="HTML"
)
#logger.info(f"User {user_id} has been banned in the chat and moved to banned_users table due to mixed layout.", extra={"chat_id": chat_id})
return
......@@ -197,7 +262,22 @@ async def handle_message(message: Message):
user_id = message.from_user.id
ban_user(user_id, message.from_user.first_name, message.from_user.last_name, message.from_user.username, "Spam in multimedia message")
await bot.ban_chat_member(chat_id, user_id)
logger.info(f"User {user_id} has been banned in the chat and moved to banned_users table due to spam in multimedia message.", extra={"chat_id": chat_id})
# Создаем кнопку для разбанивания
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[InlineKeyboardButton(text="🔓 Разбанить", callback_data=f"unban_{user_id}")]
]
)
# Отправляем сообщение с кнопкой в группу логов
await bot.send_message(
chat_id=log_chat_id,
text=f"❌ User <b>{user_id}</b> has been banned due to spam in multimedia message.",
reply_markup=keyboard,
parse_mode="HTML"
)
#logger.info(f"User {user_id} has been banned in the chat and moved to banned_users table due to spam in multimedia message.", extra={"chat_id": chat_id})
return
......@@ -219,7 +299,21 @@ async def handle_message(message: Message):
# Баним пользователя в чате
await bot.ban_chat_member(chat_id, user_id)
logger.info(f"User {user_id} has been banned in the chat and moved to banned_users table due to spam link/button.", extra={"chat_id": chat_id})
# Создаем кнопку для разбанивания
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[InlineKeyboardButton(text="🔓 Разбанить", callback_data=f"unban_{user_id}")]
]
)
# Отправляем сообщение с кнопкой в группу логов
await bot.send_message(
chat_id=log_chat_id,
text=f"❌ User <b>{user_id}</b> has been banned and moved to banned_users table due to spam link/button.",
reply_markup=keyboard,
parse_mode="HTML"
)
#logger.info(f"User {user_id} has been banned in the chat and moved to banned_users table due to spam link/button.", extra={"chat_id": chat_id})
return
......@@ -239,7 +333,22 @@ async def handle_message(message: Message):
# Баним пользователя в чате
await bot.ban_chat_member(chat_id, user_id)
logger.info(f"User {user_id} has been banned in the chat and moved to banned_users table due to spam button text.", extra={"chat_id": chat_id})
# Создаем кнопку для разбанивания
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[InlineKeyboardButton(text="🔓 Разбанить", callback_data=f"unban_{user_id}")]
]
)
# Отправляем сообщение с кнопкой в группу логов
await bot.send_message(
chat_id=log_chat_id,
text=f"❌ User <b>{user_id}</b> has been banned and moved to banned_users table due to spam button text.",
reply_markup=keyboard,
parse_mode="HTML"
)
#logger.info(f"User {user_id} has been banned in the chat and moved to banned_users table due to spam button text.", extra={"chat_id": chat_id})
return
......@@ -256,12 +365,26 @@ async def handle_message(message: Message):
# Добавляем пользователя в таблицу забаненных и удаляем из таблицы новых участников
ban_user(user_id, message.from_user.first_name, message.from_user.last_name, message.from_user.username, "Spam detected")
logger.info(f"User {user_id} has been banned and moved to banned_users table.", extra={"chat_id": chat_id})
#logger.info(f"User {user_id} has been banned and moved to banned_users table.", extra={"chat_id": chat_id})
# Бан пользователя в чате
await bot.ban_chat_member(chat_id, user_id)
logger.info(f"User {user_id} has been banned from the chat.", extra={"chat_id": chat_id})
#logger.info(f"User {user_id} has been banned from the chat.", extra={"chat_id": chat_id})
# Создаем кнопку для разбанивания
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[InlineKeyboardButton(text="🔓 Разбанить", callback_data=f"unban_{user_id}")]
]
)
# Отправляем сообщение с кнопкой в группу логов
await bot.send_message(
chat_id=log_chat_id,
text=f"❌ User <b>{user_id}</b> has been banned and moved to banned_users table due to spam button text.",
reply_markup=keyboard,
parse_mode="HTML"
)
except Exception as e:
logger.error(f"Error when banning user {user_id}. Error: {e}", extra={"chat_id": chat_id})
else:
......
......@@ -30,7 +30,7 @@ SPAM_KEYWORDS = [
"лотерея", "быстрый выигрыш", "выигрыш", "приз", "деньги", "халява", "прибыль", "заработок", "зп", "подработка", "легкий заработок",
"мгновенно", "доход", "доход онлайн", "как заработать", "схема заработка",
"пассивный доход", "быстро заработать", "богатство", "всего за", "инвестировать", "инвестиция",
"биткоин", "криптовалюта", "forex", "деньги на карта", "СБП", "18+", "дивиденд", "процент", "депозит", "выплата", "невероятный доход", "статус","гарантированный доход", "секрет богатство", "без риск",
"биткоин", "криптовалюта", "forex", "деньги на карта", "СБП", "18+","порно", "порн", "дивиденд", "процент", "депозит", "выплата", "невероятный доход", "статус","гарантированный доход", "секрет богатство", "без риск",
# Психология, манипуляции и самопомощь
"гипноз", "секрет уверенность", "как стать успешный", "формула успех", "коуч", "коучинг", "психотренинг", "управление человек", "контроль над разум", "манипуляция", "техника влияния", "мгновенный успех",
......
File added
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment