This repository has been archived on 2024-07-28. You can view files and clone it, but cannot push or open issues or pull requests.
moderator-bot/utils/parse_timedelta.py

33 lines
1016 B
Python
Raw Normal View History

2022-08-07 04:45:35 -04:00
import re
from typing import Optional
2022-08-07 04:45:35 -04:00
2022-12-01 05:54:32 -05:00
import datetime
from load import types
def parse_timedelta(value: str) -> Optional[datetime.timedelta]:
2023-01-22 05:27:20 -05:00
regex = r'(?:(\d+)(?:d|д))?(?:(\d+)(?:h|ч))?(?:(\d+)(?:m|м))?(?:(\d+)(?:s|с))?'
2022-12-01 05:54:32 -05:00
specification = value.strip().replace(' ', '')
2023-01-22 05:27:20 -05:00
match = re.fullmatch(regex, specification)
2022-08-07 04:45:35 -04:00
if match:
units = [(0 if i is None else int(i)) for i in match.groups()]
2023-01-22 05:27:20 -05:00
return datetime.timedelta(
days=units[0],
hours=units[1],
minutes=units[2],
seconds=units[3]
)
2022-12-01 05:54:32 -05:00
def parse_timedelta_from_message(message: types.Message) -> Optional[datetime.timedelta]:
2023-01-22 05:27:20 -05:00
_, *args = message.text.split()
2022-12-01 05:54:32 -05:00
2023-01-22 05:27:20 -05:00
if args:
duration = re.findall(r"(\d+d|\d+h|\d+m|\d+s)", ''.join(message.text))
if duration:
2022-12-01 05:54:32 -05:00
duration = " ".join(duration)
duration = parse_timedelta(duration)
2023-01-22 05:27:20 -05:00
if not duration:
duration = datetime.timedelta(0, 0, 0)
return duration