FEATURE 14.1: autoreaction on invalid nick

- если фулл_нейм НЕ содержит букв английских или русских то считаем его невалидным, сообщение удаляем, юзеру пишем о правиле 6
This commit is contained in:
kotolex
2023-12-26 17:53:21 +05:00
parent 800870f9a9
commit 0603ced4e3
5 changed files with 50 additions and 9 deletions
+2 -2
View File
@@ -6,7 +6,7 @@ from telebot import types
from .admin_commands import bot from .admin_commands import bot
from .constants import (LOG_COMM, FAQ, LIB, RULES, RUS, RUS_ENG_TABLE, ENG_RUS_TABLE, PYTHONCHATRU, ZEN, LUTZ_ID, from .constants import (LOG_COMM, FAQ, LIB, RULES, RUS, RUS_ENG_TABLE, ENG_RUS_TABLE, PYTHONCHATRU, ZEN, LUTZ_ID,
BDMTSS_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 .helpers import represent_as_get, detect_args, is_admin, fetch_rule
from .report import update_stats, increment from .report import update_stats, increment
from .stan import act, speak 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) 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): async def handle_hello(message: types.Message):
await bot.delete_message(message.chat.id, message.id) await bot.delete_message(message.chat.id, message.id)
nick_rule = 6 nick_rule = 6
+6 -3
View File
@@ -4,7 +4,7 @@ from telebot import types
from .config import WHITEIDS from .config import WHITEIDS
from .constants import LOG_COMM, ALLOWED_WORDS, URL_RX, HELLO_EXAMPLES 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 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) return any(hello == text for hello in HELLO_EXAMPLES)
def is_empty_name(message: types.Message) -> bool: def is_invalid_name(message: types.Message) -> bool:
return message.from_user.full_name.strip() == '' name = message.from_user.full_name
if name is None or name.strip() == '':
return True
return has_no_letters(name)
+6
View File
@@ -69,6 +69,12 @@ def is_admin(message: types.Message) -> bool:
return message.from_user.id == ADMIN_ID 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(): def my_ip():
ip_service = "https://icanhazip.com" ip_service = "https://icanhazip.com"
ip = urlopen(ip_service) ip = urlopen(ip_service)
+20 -3
View File
@@ -18,7 +18,7 @@ from src import helpers
helpers.is_url_reachable = lambda a: True helpers.is_url_reachable = lambda a: True
from src.commands import bot from src.commands import bot
from src.constants import BDMTSS_ID, LUTZ_ID, ADMIN_ID, HELLO_EXAMPLES 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) logger.setLevel(logging.ERROR)
@@ -99,6 +99,23 @@ class TestOther(TestCase):
m = MagicMock(from_user=MagicMock(id=text)) m = MagicMock(from_user=MagicMock(id=text))
self.assertEqual(is_white_id(m), expected) 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): class TestBot(IsolatedAsyncioTestCase):
@@ -476,8 +493,8 @@ class TestBot(IsolatedAsyncioTestCase):
self.assertEqual(expected, RESULTS[0][0]['text']) self.assertEqual(expected, RESULTS[0][0]['text'])
RESULTS.clear() RESULTS.clear()
async def test_empty_name_user(self): async def test_invalid_name_user(self):
await self.bot.process_new_updates([get_update('новый текст', first_name='')]) 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[0], ({'chat_id': 11, 'message_id': 1}, 'deleteMessage'))
self.assertEqual(RESULTS[1][1], 'sendMessage') self.assertEqual(RESULTS[1][1], 'sendMessage')
self.assertEqual(RESULTS[1][0]['text'], '@None\nНапоминаем правило: Твой ник должен быть читаемым и понятным') self.assertEqual(RESULTS[1][0]['text'], '@None\nНапоминаем правило: Твой ник должен быть читаемым и понятным')
+16 -1
View File
@@ -2,7 +2,7 @@ from unittest import TestCase, main
from unittest.mock import MagicMock from unittest.mock import MagicMock
from src.constants import SPAM, BAN_WORDS, ADMIN_ID, RULES_TEXT 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, \ 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 = ( CASES = (
"Оформим резидeнтствo ОАЭ без предoплаты за 5000 дирхам. Пoдробнoсти в лc", "Оформим резидeнтствo ОАЭ без предoплаты за 5000 дирхам. Пoдробнoсти в лc",
@@ -115,6 +115,21 @@ class TestOthers(TestCase):
with self.subTest(f"remove_spaces {text}"): with self.subTest(f"remove_spaces {text}"):
self.assertEqual(expected, 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__': if __name__ == '__main__':
main() main()