from typing import Optional, Union
from datetime import datetime, timedelta
from aiogram.dispatcher.filters import BoundFilter
from aiogram import types
from app.services.users import UserService
class LimitRequest(BoundFilter):
key = 'limit'
datetime_limit = datetime.now() + timedelta(days=1)
limit_dict: dict[str, int] = {}
msg_datetime: datetime
def __init__(self, limit: Optional[bool] = None):
self.limit = limit
@staticmethod
async def _get_limit_count(call: types.CallbackQuery) -> int:
async with UserService(call.from_user.id) as us:
user_db = await us.get()
limit_count = user_db['limit_count']
return limit_count
@staticmethod
async def _get_limit(call: types.CallbackQuery) -> bool:
async with UserService(call.from_user.id) as us:
user_db = await us.get()
is_limit = user_db['limit']
return is_limit
async def _check_update_datetime(self, call: types.CallbackQuery):
self.msg_datetime = call.message.date
if self.msg_datetime >= self.datetime_limit:
return False
return True
async def check(self, call: types.CallbackQuery) -> Optional[bool]:
is_limit = await self._get_limit(call)
limit_count = await self._get_limit_count(call)
if self.limit is None or not isinstance(is_limit, bool):
return False
if is_limit:
if call.from_user.id not in self.limit_dict:
self.limit_dict[call.from_user.id] = 0
return True
elif not await self._check_update_datetime(call):
self.datetime_limit = self.msg_datetime
self.limit_dict[call.from_user.id] = 0
return True
else:
self.limit_dict[call.from_user.id] += 1
if self.limit_dict[call.from_user.id] >= limit_count:
self.limit_dict[call.from_user.id] = limit_count
await call.message.answer('Превышен суточный лимит действий.\n'
'Вы можете отключить лимит, если пригласите 2-х друзей.')
return False
return True