From 40a14d1cf0806df9a1f50e61668211485f822657 Mon Sep 17 00:00:00 2001 From: samuelfirst Date: Wed, 10 Mar 2021 23:10:45 +0300 Subject: [PATCH] Add "forever" keyword for !ro and !ban #10 --- app/handlers/simple_admin.py | 25 +++++++++++++++++-------- app/utils/timedelta.py | 6 ++++-- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/app/handlers/simple_admin.py b/app/handlers/simple_admin.py index bd40d62..205b4f2 100644 --- a/app/handlers/simple_admin.py +++ b/app/handlers/simple_admin.py @@ -1,4 +1,5 @@ import asyncio +import datetime from contextlib import suppress from typing import List @@ -43,12 +44,16 @@ async def cmd_ro(message: types.Message, chat: Chat): logger.error("Failed to restrict chat member: {error!r}", error=e) return False + if duration >= datetime.timedelta(days=367): + duration = "forever" + else: + duration = format_timedelta( + duration, locale=chat.language, granularity="seconds", format="short" + ) + await message.reply_to_message.answer( _("Read-only activated for user {user}. Duration: {duration}").format( - user=message.reply_to_message.from_user.get_mention(), - duration=format_timedelta( - duration, locale=chat.language, granularity="seconds", format="short" - ), + user=message.reply_to_message.from_user.get_mention(), duration=duration ) ) return True @@ -78,12 +83,16 @@ async def cmd_ban(message: types.Message, chat: Chat): logger.error("Failed to kick chat member: {error!r}", error=e) return False + if duration >= datetime.timedelta(days=367): + duration = "forever" + else: + duration = format_timedelta( + duration, locale=chat.language, granularity="seconds", format="short" + ) + await message.reply_to_message.answer( _("User {user} banned for {duration}").format( - user=message.reply_to_message.from_user.get_mention(), - duration=format_timedelta( - duration, locale=chat.language, granularity="seconds", format="short" - ), + user=message.reply_to_message.from_user.get_mention(), duration=duration ) ) return True diff --git a/app/utils/timedelta.py b/app/utils/timedelta.py index 3dcbc85..3646e7d 100644 --- a/app/utils/timedelta.py +++ b/app/utils/timedelta.py @@ -4,8 +4,8 @@ from aiogram import types -PATTERN = re.compile(r"(?P\d+)(?P[wdhms])") -LINE_PATTERN = re.compile(r"^(\d+[wdhms]){1,}$") +PATTERN = re.compile(r"(?P\d+)(?P[wdhms])|^(?Pforever)$") +LINE_PATTERN = re.compile(r"^(\d+[wdhms])+$|^(forever)$") MODIFIERS = { "w": datetime.timedelta(weeks=1), @@ -26,6 +26,8 @@ def parse_timedelta(value: str) -> datetime.timedelta: raise TimedeltaParseError("Invalid time format") try: + if PATTERN.match(value).group("keyword"): + return datetime.timedelta(days=367) result = datetime.timedelta() for match in PATTERN.finditer(value): value, modifier = match.groups()