From 0603ced4e36af07a5df6645dac38fc487f0bd2b9 Mon Sep 17 00:00:00 2001 From: kotolex Date: Tue, 26 Dec 2023 17:53:21 +0500 Subject: [PATCH] FEATURE 14.1: autoreaction on invalid nick MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - если фулл_нейм НЕ содержит букв английских или русских то считаем его невалидным, сообщение удаляем, юзеру пишем о правиле 6 --- src/commands.py | 4 ++-- src/filters.py | 9 ++++++--- src/helpers.py | 6 ++++++ tests/test_bot.py | 23 ++++++++++++++++++++--- tests/test_helpers.py | 17 ++++++++++++++++- 5 files changed, 50 insertions(+), 9 deletions(-) diff --git a/src/commands.py b/src/commands.py index 623c4e6..5c4b931 100644 --- a/src/commands.py +++ b/src/commands.py @@ -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, is_hello_text, is_empty_name +from .filters import in_spam_list, in_caption_spam_list, in_delete_list, is_hello_text, is_invalid_name from .helpers import represent_as_get, detect_args, is_admin, fetch_rule from .report import update_stats, increment from .stan import act, speak @@ -352,7 +352,7 @@ 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"]) +@bot.message_handler(func=is_invalid_name, chat_types=["supergroup", "group"]) async def handle_hello(message: types.Message): await bot.delete_message(message.chat.id, message.id) nick_rule = 6 diff --git a/src/filters.py b/src/filters.py index 2ca0be2..ac26c67 100644 --- a/src/filters.py +++ b/src/filters.py @@ -4,7 +4,7 @@ from telebot import types from .config import WHITEIDS 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 .helpers import is_spam, is_in_not_allowed, is_ban_words_in_caption, cleaned_text, remove_spaces, has_no_letters from .models import is_antispam_enabled @@ -52,5 +52,8 @@ def is_hello_text(message: types.Message) -> bool: return any(hello == text for hello in HELLO_EXAMPLES) -def is_empty_name(message: types.Message) -> bool: - return message.from_user.full_name.strip() == '' +def is_invalid_name(message: types.Message) -> bool: + name = message.from_user.full_name + if name is None or name.strip() == '': + return True + return has_no_letters(name) diff --git a/src/helpers.py b/src/helpers.py index c09bed5..252a0c7 100644 --- a/src/helpers.py +++ b/src/helpers.py @@ -69,6 +69,12 @@ def is_admin(message: types.Message) -> bool: return message.from_user.id == ADMIN_ID +def has_no_letters(text: str) -> bool: + text = text.lower() + letters = f'{ONLY_RUS_LETTERS}{ONLY_ENG_LETTERS}' + return not any(letter in text for letter in letters) + + def my_ip(): ip_service = "https://icanhazip.com" ip = urlopen(ip_service) diff --git a/tests/test_bot.py b/tests/test_bot.py index 35bbafd..e5d4ea6 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -18,7 +18,7 @@ from src import helpers helpers.is_url_reachable = lambda a: True from src.commands import bot from src.constants import BDMTSS_ID, LUTZ_ID, ADMIN_ID, HELLO_EXAMPLES -from src.filters import is_white_id +from src.filters import is_white_id, is_invalid_name # отключаем логи бота, в тестах они не нужны logger.setLevel(logging.ERROR) @@ -99,6 +99,23 @@ class TestOther(TestCase): m = MagicMock(from_user=MagicMock(id=text)) self.assertEqual(is_white_id(m), expected) + def test_is_invalid_name(self): + params = ( + (True, None), + (True, ''), + (True, ' '), + (True, '.'), + (True, '#!%%@$#@'), + (True, '⛔️ '), + (True, '212434343'), + (False, 'a212434343'), + (False, '212434343я'), + ) + for expected, text in params: + with self.subTest(f"check non-is_invalid_name({text})"): + m = MagicMock(from_user=MagicMock(full_name=text)) + self.assertEqual(is_invalid_name(m), expected) + class TestBot(IsolatedAsyncioTestCase): @@ -476,8 +493,8 @@ class TestBot(IsolatedAsyncioTestCase): self.assertEqual(expected, RESULTS[0][0]['text']) RESULTS.clear() - async def test_empty_name_user(self): - await self.bot.process_new_updates([get_update('новый текст', first_name='')]) + async def test_invalid_name_user(self): + await self.bot.process_new_updates([get_update('новый текст', first_name=None)]) self.assertEqual(RESULTS[0], ({'chat_id': 11, 'message_id': 1}, 'deleteMessage')) self.assertEqual(RESULTS[1][1], 'sendMessage') self.assertEqual(RESULTS[1][0]['text'], '@None\nНапоминаем правило: Твой ник должен быть читаемым и понятным') diff --git a/tests/test_helpers.py b/tests/test_helpers.py index 4fd6c15..15c4dce 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -2,7 +2,7 @@ from unittest import TestCase, main from unittest.mock import MagicMock from src.constants import SPAM, BAN_WORDS, ADMIN_ID, RULES_TEXT from src.helpers import is_spam, is_mixed, is_ban_words_in_caption, is_in_not_allowed, is_nongrata, is_admin, \ - fetch_rule, cleaned_text, remove_spaces + fetch_rule, cleaned_text, remove_spaces, has_no_letters CASES = ( "Оформим резидeнтствo ОАЭ без предoплаты за 5000 дирхам. Пoдробнoсти в лc", @@ -115,6 +115,21 @@ class TestOthers(TestCase): with self.subTest(f"remove_spaces {text}"): self.assertEqual(expected, remove_spaces(text)) + def test_has_no_letters(self): + params = ( + (False, 'f1 b2 print text '), + (True, ''), + (True, ' '), + (True, '12 @# &*'), + (False, '12 @# &* f'), + (False, '12 @# &* Z'), + (False, '12 @# &* я'), + (False, '12 @# &* Я'), + ) + for expected, text in params: + with self.subTest(f"has_no_letters {text}"): + self.assertEqual(expected, has_no_letters(text)) + if __name__ == '__main__': main()