FEATURE 14: autoreaction

- если фулл_нейм пустой то будет сообщение о нарушении правила, само сообщение юзера будет удалено
- добавлена правка по спаму
- немного рефакторинга
- если сообщение содержит только слово из констант привет(полное совпадение) то выдаем правило непривет
This commit is contained in:
kotolex
2023-12-26 16:58:27 +05:00
parent 77e34681ec
commit 92bb50dd49
7 changed files with 99 additions and 39 deletions
+5 -15
View File
@@ -78,9 +78,7 @@ async def enable_stan(message: types.Message):
add_chat(message.chat.id, message.chat.title)
await bot.send_message(
message.chat.id,
f"""Группа "{message.chat.title}" добавлена в БД.
/get_group_info - узнать текущие настройки""",
)
f'Группа "{message.chat.title}" добавлена в БД.\n/get_group_info - узнать текущие настройки')
else:
await bot.send_message(message.chat.id, "Отказ. Группа уже включена")
@@ -119,7 +117,7 @@ async def get_quotes(message: types.Message):
logging.info(f"[{message.chat.id}] {message.from_user.first_name} {message.text}.")
quotes = all_chat_quotes(message.chat.id)
if quotes:
text = f"Количество цитат: {len(quotes)}\n\Последние добавленные\n\n"
text = f"Количество цитат: {len(quotes)}\n\nПоследние добавленные:\n\n"
text += "\n".join(f"· {quote}" for quote in quotes[-10:])
await bot.send_message(message.chat.id, f"{text}")
else:
@@ -132,17 +130,9 @@ async def get_group_info(message: types.Message):
if group:
await bot.send_message(
message.chat.id,
f"""Группа: {group.title}
ID группы: {group.chat_id}
Количество цитат: {len(group.quotes)}
Последние добавленные: /get_quotes
Текущие настройки:
Антиспам: {group.antispam}
Ежедневные отчёты: {group.report}
Праздники: {group.reminder}""",
)
f"Группа: {group.title}\nID группы: {group.chat_id}\n\nКоличество цитат: {len(group.quotes)}\n"
f"Последние добавленные: /get_quotes\n\nТекущие настройки:\n Антиспам: {group.antispam}\n "
f"Ежедневные отчёты: {group.report}\n Праздники: {group.reminder}")
else:
await bot.send_message(message.chat.id, "Группа не включена. Включить: /enable_stan")
+26 -9
View File
@@ -6,7 +6,7 @@ from telebot import types
from .admin_commands import bot
from .constants import (LOG_COMM, FAQ, LIB, RULES, RUS, RUS_ENG_TABLE, ENG_RUS_TABLE, PYTHONCHATRU, ZEN, LUTZ_ID,
BDMTSS_ID)
from .filters import in_spam_list, in_caption_spam_list, in_delete_list
from .filters import in_spam_list, in_caption_spam_list, in_delete_list, is_hello_text, is_empty_name
from .helpers import represent_as_get, detect_args, is_admin, fetch_rule
from .report import update_stats, increment
from .stan import act, speak
@@ -19,6 +19,16 @@ async def send_or_reply(message: types.Message, answer, **kwargs):
await bot.send_message(message.chat.id, answer, **kwargs)
async def _neprivet(message: types.Message, forced_reply: bool = False):
markup = types.InlineKeyboardMarkup()
markup.add(types.InlineKeyboardButton("👋 Непривет", url="https://neprivet.com/"), row_width=1)
text = "Пожалуйста, не пишите просто «Привет» в чате."
if forced_reply:
await bot.reply_to(message, text, reply_markup=markup)
else:
await send_or_reply(message, text, reply_markup=markup)
""" [ ANTISPAM ] """
@@ -66,11 +76,7 @@ async def send_rules(message: types.Message):
logging.info(LOG_COMM % (message.chat.title, message.from_user.id, message.from_user.first_name, message.text))
if len(args) > 1 and args[-1].isdigit():
index = int(args[-1])
await send_or_reply(
message,
f"<b>Правило {args[-1]}</b>\n<i>{fetch_rule(index)}</i>",
reply_markup=markup,
)
await send_or_reply(message, f"<b>Правило {index}</b>\n<i>{fetch_rule(index)}</i>", reply_markup=markup)
else:
await send_or_reply(message, "Читай...", reply_markup=markup)
await bot.delete_message(message.chat.id, message.id)
@@ -225,9 +231,7 @@ async def send_neprivet(message: types.Message):
message.text,
)
)
markup = types.InlineKeyboardMarkup()
markup.add(types.InlineKeyboardButton("👋 Непривет", url="https://neprivet.com/"), row_width=1)
await send_or_reply(message, "Пожалуйста, не пишите просто «Привет» в чате.", reply_markup=markup)
await _neprivet(message)
await bot.delete_message(message.chat.id, message.id)
@@ -348,6 +352,19 @@ async def default_query(inline_query):
await bot.answer_inline_query(inline_query.id, zen, cache_time=1200)
@bot.message_handler(func=is_empty_name, chat_types=["supergroup", "group"])
async def handle_hello(message: types.Message):
await bot.delete_message(message.chat.id, message.id)
nick_rule = 6
await bot.send_message(message.chat.id, f"@{message.from_user.username}\n"
f"Напоминаем правило: {fetch_rule(nick_rule)}")
@bot.message_handler(func=is_hello_text, chat_types=["supergroup", "group"])
async def handle_hello(message: types.Message):
await _neprivet(message, forced_reply=True)
""" [ COUNTER ] """
+2 -1
View File
@@ -35,6 +35,7 @@ ALLOWED_WORDS = [
"support",
"jetbrains",
]
HELLO_EXAMPLES = ('привет', 'привет всем', 'ку', 'здравствуйте', 'прив', 'всем прив', 'ребята всем привет', 'прива')
ONLY_RUS_LETTERS = "ёйцукенгшщзхъфывапролджэячсмитьбю"
ONLY_ENG_LETTERS = string.ascii_lowercase
@@ -59,7 +60,7 @@ SPAM = {"me.sv/", "tg.sv/", "goo.by/", "go.sv/", "intim.video/", "uclck.ru/", '
'P2P', 'Идет набор', 'в лс', 'нaбop', 'комaндy', 'kpuпт', 'бupж', '💰', 'пишитe', '💸',
'$ в неделю', 'обучаю с нуля', 'доходы для всех', 'по трейдингу', 'фальшивые рубли', '‼️',
'зароботку', 'Набuраю', 'цuфр', 'Обучу вас', 'прuб', 'остались курсы', 'Crypt', 'kр', 'рu',
'в лc', "в личные сообщения"}
'в лc', "в личные сообще"}
NON_GRATA = {"дудар", "хауди", "dudar"}
BAN_WORDS = {"GREEN"}
+11 -2
View File
@@ -3,8 +3,8 @@ import logging.handlers
from telebot import types
from .config import WHITEIDS
from .constants import LOG_COMM, ALLOWED_WORDS, URL_RX
from .helpers import is_spam, is_in_not_allowed, is_ban_words_in_caption
from .constants import LOG_COMM, ALLOWED_WORDS, URL_RX, HELLO_EXAMPLES
from .helpers import is_spam, is_in_not_allowed, is_ban_words_in_caption, cleaned_text, remove_spaces
from .models import is_antispam_enabled
@@ -45,3 +45,12 @@ def in_delete_list(message: types.Message) -> bool:
def is_white_id(message: types.Message) -> bool:
return message.from_user.id in WHITEIDS
def is_hello_text(message: types.Message) -> bool:
text = remove_spaces(cleaned_text(message.text))
return any(hello == text for hello in HELLO_EXAMPLES)
def is_empty_name(message: types.Message) -> bool:
return message.from_user.full_name.strip() == ''
+10 -3
View File
@@ -30,9 +30,8 @@ def is_mixed(text: str) -> bool:
Разбивает текст на слова и проверяет на смешанный алфавит, спамеры используют его. Слово допускается только
полностью на русском или русский + знаки пунктуации
"""
cleaned_text = ''.join(letter if letter not in SYMBOLS else ' ' for letter in text)
for word in cleaned_text.split():
word = word.strip().lower()
for word in cleaned_text(text).split():
word = word.strip()
if not word:
continue
if any(e in ONLY_RUS_LETTERS for e in word) and any(e in ONLY_ENG_LETTERS for e in word):
@@ -40,6 +39,14 @@ def is_mixed(text: str) -> bool:
return False
def cleaned_text(text: str) -> str:
return ''.join(letter.lower() if letter not in SYMBOLS else ' ' for letter in text)
def remove_spaces(text: str) -> str:
return ' '.join(word.strip() for word in text.split() if word.strip())
def is_in_not_allowed(word_list: list, msg: str) -> bool:
for word in word_list:
if word in msg.casefold():