Добавление работы с конфликтными частями и исправление вайтлиста

This commit is contained in:
2026-02-25 17:50:11 +07:00
parent 6a4e56c367
commit 54125b82ac
15 changed files with 463 additions and 329 deletions

View File

@@ -44,6 +44,7 @@ class BanWordsManager:
"""Инициализирует базу данных и загружает кэш"""
await self.db.init()
await self.init_default_bot_settings() # ← добавлено
await self.init_default_words()
await self.refresh_cache()
logger.info("BanWordsManager инициализирован", log_type="DATABASE")
@@ -452,12 +453,13 @@ class BanWordsManager:
admins = await self.repo.get_admins()
return {
'substring': banwords.get(BanWordType.SUBSTRING, set()),
'word': banwords.get(BanWordType.WORD, set()),
'lemma': banwords.get(BanWordType.LEMMA, set()),
'part': banwords.get(BanWordType.PART, set()),
'conflict_substring': banwords.get(BanWordType.CONFLICT_SUBSTRING, set()),
'conflict_word': banwords.get(BanWordType.CONFLICT_WORD, set()),
'conflict_lemma': banwords.get(BanWordType.CONFLICT_LEMMA, set()),
'temp_substring': temp_banwords.get(BanWordType.SUBSTRING, set()),
'conflict_part': banwords.get(BanWordType.CONFLICT_PART, set()),
'temp_word': temp_banwords.get(BanWordType.WORD, set()),
'temp_lemma': temp_banwords.get(BanWordType.LEMMA, set()),
'whitelist': whitelist,
'admins': admins
@@ -516,6 +518,50 @@ class BanWordsManager:
)
return []
async def init_default_words(self) -> None:
"""
Добавляет базовые банворды и whitelist при первом запуске.
Ничего не перезаписывает, если уже существует.
"""
try:
from configs import settings
# --- Базовые слова ---
default_word = {"http", "t.me/"}
default_part = {"bot"}
default_lemma = {"скам", "мошенник"}
# Проверяем уже существующие
existing = await self.repo.get_all_banwords()
# word
for word in default_word:
if word not in existing.get(BanWordType.WORD, set()):
await self.repo.add_banword(word, BanWordType.WORD)
# PART
for word in default_part:
if word not in existing.get(BanWordType.PART, set()):
await self.repo.add_banword(word, BanWordType.PART)
# LEMMA
for word in default_lemma:
if word not in existing.get(BanWordType.LEMMA, set()):
await self.repo.add_banword(word, BanWordType.LEMMA)
# --- Добавляем username бота в whitelist ---
bot_username = settings.BOT_USERNAME
if bot_username:
whitelist = await self.repo.get_whitelist()
if bot_username.lower() not in whitelist:
await self.repo.add_whitelist(bot_username.lower())
logger.info("Базовые слова и whitelist инициализированы", log_type="DATABASE")
except Exception as e:
logger.error(f"Ошибка инициализации базовых слов: {e}", log_type="DATABASE")
async def cleanup_expired_temp_words(self) -> int:
"""
Удаляет истёкшие временные банворды.

View File

@@ -31,11 +31,12 @@ class Base(DeclarativeBase):
class BanWordType(str, PyEnum):
"""Типы банвордов"""
SUBSTRING = "substring"
WORD = "word"
LEMMA = "lemma"
PART = "part"
CONFLICT_SUBSTRING = "conflict_substring"
CONFLICT_WORD = "conflict_word"
CONFLICT_LEMMA = "conflict_lemma"
CONFLICT_PART = "conflict_part"
class SpamMode(str, PyEnum):
@@ -62,7 +63,11 @@ class BanWord(Base):
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
word: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
type: Mapped[BanWordType] = mapped_column(
Enum(BanWordType, native_enum=False),
Enum(
BanWordType,
native_enum=False,
values_callable=lambda enum: [e.value for e in enum]
),
nullable=False,
index=True
)
@@ -95,8 +100,13 @@ class TempBanWord(Base):
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
word: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
type: Mapped[BanWordType] = mapped_column(
Enum(BanWordType, native_enum=False),
nullable=False
Enum(
BanWordType,
native_enum=False,
values_callable=lambda enum: [e.value for e in enum]
),
nullable=False,
index=True
)
added_by: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
added_at: Mapped[datetime] = mapped_column(

View File

@@ -158,11 +158,12 @@ class BanWordsRepository:
async def get_all_banwords(self) -> dict[BanWordType, Set[str]]:
result = {
BanWordType.SUBSTRING: set(),
BanWordType.WORD: set(),
BanWordType.LEMMA: set(),
BanWordType.PART: set(),
BanWordType.CONFLICT_SUBSTRING: set(),
BanWordType.CONFLICT_WORD: set(),
BanWordType.CONFLICT_LEMMA: set(),
BanWordType.CONFLICT_PART: set(),
}
try:
async with self.db.get_session() as session:
@@ -335,7 +336,7 @@ class BanWordsRepository:
async def get_all_temp_banwords(self) -> dict[BanWordType, Set[str]]:
"""Получает все активные временные банворды по типам"""
result = {
BanWordType.SUBSTRING: set(),
BanWordType.WORD: set(),
BanWordType.LEMMA: set(),
}