Update banned users handling with async support and improved date parsing

- Modified `change_page` function in `callback_handlers.py` to use async methods for retrieving banned users and their buttons.
- Enhanced `get_banned_users_list` in `helper_func.py` to handle string timestamps and various date formats, ensuring robust date parsing.
- Added a new test case in `test_utils.py` to validate the handling of string timestamps in the banned users list retrieval.
This commit is contained in:
2025-09-08 23:19:19 +03:00
parent 5f6882d348
commit 31e29cdec0
3 changed files with 35 additions and 4 deletions

View File

@@ -219,14 +219,14 @@ async def change_page(
reply_markup=keyboard reply_markup=keyboard
) )
else: else:
message_user = get_banned_users_list(int(page_number) * 7 - 7, bot_db) message_user = await get_banned_users_list(int(page_number) * 7 - 7, bot_db)
await call.bot.edit_message_text( await call.bot.edit_message_text(
chat_id=call.message.chat.id, chat_id=call.message.chat.id,
message_id=call.message.message_id, message_id=call.message.message_id,
text=message_user text=message_user
) )
buttons = get_banned_users_buttons(bot_db) buttons = await get_banned_users_buttons(bot_db)
keyboard = create_keyboard_with_pagination(page_number, len(buttons), buttons, 'unlock') keyboard = create_keyboard_with_pagination(page_number, len(buttons), buttons, 'unlock')
await call.bot.edit_message_reply_markup( await call.bot.edit_message_reply_markup(
chat_id=call.message.chat.id, chat_id=call.message.chat.id,

View File

@@ -696,9 +696,22 @@ async def get_banned_users_list(offset: int, bot_db):
if isinstance(unban_date, (int, float)): if isinstance(unban_date, (int, float)):
unban_datetime = datetime.fromtimestamp(unban_date) unban_datetime = datetime.fromtimestamp(unban_date)
safe_unban_date = unban_datetime.strftime("%d-%m-%Y %H:%M") safe_unban_date = unban_datetime.strftime("%d-%m-%Y %H:%M")
else: elif isinstance(unban_date, str):
# Если это уже datetime объект # Если это строка, попытаемся её обработать
try:
# Попробуем преобразовать строку в timestamp
timestamp = int(unban_date)
unban_datetime = datetime.fromtimestamp(timestamp)
safe_unban_date = unban_datetime.strftime("%d-%m-%Y %H:%M")
except (ValueError, TypeError):
# Если не удалось, показываем как есть
safe_unban_date = html.escape(str(unban_date))
elif hasattr(unban_date, 'strftime'):
# Если это datetime объект
safe_unban_date = unban_date.strftime("%d-%m-%Y %H:%M") safe_unban_date = unban_date.strftime("%d-%m-%Y %H:%M")
else:
# Для всех остальных случаев
safe_unban_date = html.escape(str(unban_date))
except (ValueError, TypeError, OSError): except (ValueError, TypeError, OSError):
# В случае ошибки показываем исходное значение # В случае ошибки показываем исходное значение
safe_unban_date = html.escape(str(unban_date)) safe_unban_date = html.escape(str(unban_date))

View File

@@ -599,6 +599,24 @@ class TestUtilityFunctions:
assert "Spam" in result assert "Spam" in result
assert "Violation" in result assert "Violation" in result
@pytest.mark.asyncio
async def test_get_banned_users_list_with_string_timestamp(self):
"""Тест получения списка заблокированных пользователей со строковым timestamp"""
mock_db = AsyncMock()
mock_db.get_banned_users_from_db_with_limits.return_value = [
(123, "Spam", "1704067200"), # user_id, ban_reason, unban_date (string timestamp)
(456, "Violation", "1704153600")
]
mock_db.get_username.return_value = None
mock_db.get_full_name_by_id.return_value = "Test User"
result = await get_banned_users_list(0, mock_db)
assert "Список заблокированных пользователей:" in result
assert "Test User" in result
assert "Spam" in result
assert "Violation" in result
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_get_banned_users_buttons(self): async def test_get_banned_users_buttons(self):
"""Тест получения кнопок заблокированных пользователей""" """Тест получения кнопок заблокированных пользователей"""