Added comments

This commit is contained in:
2024-02-15 16:58:37 +03:00
parent 19cf282e08
commit dba5c60080
42 changed files with 388 additions and 11 deletions

View File

@@ -1,6 +1,7 @@
from aiogram import Bot
from handlers.handler import Handler
# Message handlers
from handlers.message_handlers.delete_command import DeleteCommand
from handlers.message_handlers.deleted_posts_command import DeletedPostsCommand
from handlers.message_handlers.edit_command import EditCommand
@@ -13,6 +14,7 @@ from handlers.message_handlers.reply_to_user import ReplyToUserCommand
from handlers.message_handlers.restore_command import RestoreCommand
from handlers.message_handlers.settings_command import SettingsCommand
from handlers.message_handlers.update_settings import UpdateSettingsCommand
# Middlewares
from handlers.middlewares.media_group import MediaGroupMiddleware
from handlers.middlewares.user import AdminMiddleware
from neuroapi.types import BotSettings as BotSettingsType
@@ -22,8 +24,9 @@ class AdminCommands(Handler):
settings: BotSettingsType
def __init__(self, bot: Bot) -> None:
"""Initialize the group of admin commands"""
super().__init__(bot)
self.router.message.middleware(AdminMiddleware())
self.router.message.middleware(AdminMiddleware()) # Admin checking
self.add_handlers([
InfoCommand,
@@ -33,7 +36,7 @@ class AdminCommands(Handler):
RestoreCommand,
SettingsCommand,
])
self.router.message.middleware(MediaGroupMiddleware())
self.router.message.middleware(MediaGroupMiddleware()) # Media group handling
self.add_handlers([
NewPostCommand,
NewPostSoloCommand,

View File

@@ -3,6 +3,7 @@ from aiogram.filters import Filter
class NewPostFilter(Filter):
"""Check if the message is in a media group of photos"""
async def __call__(self, message: types.Message) -> bool:
if message.media_group_id is None or message.content_type != 'photo':
return False
@@ -10,10 +11,12 @@ class NewPostFilter(Filter):
class NewSoloPostFilter(Filter):
"""Check if the message is /newpost command with photo"""
async def __call__(self, message: types.Message) -> bool:
return message.media_group_id is None and message.content_type == 'photo' and message.caption and message.caption.startswith('/newpost ')
class ChangePosts(Filter):
"""Change command filter"""
async def __call__(self, message: types.Message) -> bool:
return message.text and message.text.startswith("/change") and message.chat.type == 'private'

View File

@@ -3,6 +3,7 @@ from aiogram.filters import Filter
class ReplyToUser(Filter):
"""Replying to user filter"""
async def __call__(self, message: types.Message) -> bool:
if message.reply_to_message is None or message.chat.type != 'private':
return False

View File

@@ -9,10 +9,27 @@ from .message_handlers.handler import MessageHandlerABC
class NeuroApiRouter(Router):
bot: Bot
def __init__(self, *, name: str | None = None, bot: Bot) -> None:
"""
Initializes a new instance of the class with the provided name and bot.
Args:
name (str, optional): The name of the instance. Defaults to None.
bot (Bot): The bot instance.
Returns:
None
"""
super().__init__(name=name)
self.bot = bot
def add_message_handler(self, callback: MessageHandlerABC, *args: Any):
"""
Add a message handler to the bot.
:param callback: The message handler callback.
:param args: Additional arguments for the message handler.
:return: None
"""
handler = callback(self.bot, *args)
self.message.register(handler.handler, handler.filter)
@@ -23,6 +40,15 @@ class Handler:
router: NeuroApiRouter
def __init__(self, bot: Bot) -> None:
"""
Initializes the class with the given bot instance.
Args:
bot (Bot): The bot instance to be initialized with.
Returns:
None
"""
assert isinstance(bot, Bot)
self.bot = bot
self.router = NeuroApiRouter(bot=bot)
@@ -31,6 +57,15 @@ class Handler:
return self.router
def add_handlers(self, handlers: List[MessageHandlerABC] | List[Tuple[MessageHandlerABC] | Optional[Tuple[Any, ...]]]):
"""
Add multiple message handlers to the router.
Args:
handlers (List[MessageHandlerABC] | List[Tuple[MessageHandlerABC] | Optional[Tuple[Any, ...]]]): The list of message handlers to be added.
Returns:
None
"""
for handler in handlers:
if isinstance(handler, tuple):
args = handler[1:] if len(handler)>1 else []

View File

@@ -7,6 +7,7 @@ from .handler import MessageHandlerABC
class DeleteCommand(MessageHandlerABC):
"""Command to delete posts"""
filter = Command('delete')
async def _command(self, message: Message):
text = message.text.split()

View File

@@ -7,6 +7,7 @@ from .handler import MessageHandlerABC
class DeletedPostsCommand(MessageHandlerABC):
"""Command to show deleted posts"""
filter = Command('deleted')
async def _command(self, message: Message):
try:

View File

@@ -7,6 +7,7 @@ from .handler import MessageHandlerABC
class EditCommand(MessageHandlerABC):
"""Command to edit posts"""
filter = Command('edit')
async def _command(self, message: types.Message):

View File

@@ -11,6 +11,7 @@ from .handler import MessageHandlerABC
class ForwardMessageCommand(MessageHandlerABC):
"""Command to forward messages from users to admins. Also checking if they're in the channel"""
filter = F.chat.type == 'private'
async def _command(self, message: types.Message):
self.settings = BotSettings.get_instance()

View File

@@ -6,6 +6,7 @@ from aiogram.filters import Filter
class MessageHandlerABC(ABC):
"""Base class for all message handlers"""
bot: Bot
def __init__(self, bot: Bot, *args: Any, **kwargs: Dict[str, Any]) -> None:
@@ -14,13 +15,16 @@ class MessageHandlerABC(ABC):
@abstractmethod
def _command(self, *args, **kwargs):
"""Handler for the command"""
raise NotImplementedError
@property
def handler(self) -> Coroutine[None, None, None]:
"""Command handler method"""
return self._command
@property
@abstractmethod
def filter(self) -> Filter:
"""Filter for the command"""
raise NotImplementedError

View File

@@ -10,6 +10,7 @@ from .handler import MessageHandlerABC
class InfoCommand(MessageHandlerABC):
"""Command to show info about posts"""
filter = Command('info')
async def _command(self, message: types.Message):

View File

@@ -9,6 +9,7 @@ from .handler import MessageHandlerABC
class NewPostCommand(MessageHandlerABC):
"""Command to add new posts with media groups"""
filter = NewPostFilter()
async def _command(self, message: types.Message, album: List[types.Message]):
sorted_album = sorted(album, key=lambda x: x.message_id)
@@ -20,6 +21,7 @@ class NewPostCommand(MessageHandlerABC):
class NewPostSoloCommand(MessageHandlerABC):
"""Command to add new posts without media groups"""
filter = NewSoloPostFilter()
async def _command(self, message: types.Message):
await neuroapi.image.add(str(message.from_user.id), message.photo[-1].file_id, message.has_media_spoiler, message.message_id, message.caption, None, message.caption_entities, message)

View File

@@ -9,6 +9,7 @@ from .handler import MessageHandlerABC
class PostCommand(MessageHandlerABC):
"""Command to post posts manually or by timer"""
filter = Command('post')
async def _command(self, message: types.Message | None = None):
settings = neuroTypes.BotSettings.get_instance()

View File

@@ -9,6 +9,7 @@ from .handler import MessageHandlerABC
class PreviewCommand(MessageHandlerABC):
"""Command to preview posts like it posted to channel"""
filter = Command('preview')
async def _command(self, message: Message):
text = message.text.split()

View File

@@ -6,6 +6,7 @@ from .handler import MessageHandlerABC
class ReplyToUserCommand(MessageHandlerABC):
"""Send reply to user from admins"""
filter = ReplyToUser()
async def _command(self, message: types.Message):
if message.reply_to_message.forward_from is None:

View File

@@ -7,6 +7,7 @@ from .handler import MessageHandlerABC
class RestoreCommand(MessageHandlerABC):
"""Command to restore deleted posts"""
filter = Command('restore')
async def _command(self, message: Message):
try:

View File

@@ -7,6 +7,7 @@ from .handler import MessageHandlerABC
class SettingsCommand(MessageHandlerABC):
"""Command to show active settings"""
filter = Command('settings')
async def _command(self, message: types.Message):
self.settings = BotSettings.get_instance()

View File

@@ -5,6 +5,7 @@ from .handler import MessageHandlerABC
class StartCommand(MessageHandlerABC):
"""Command to get start message"""
filter = CommandStart()
async def _command(self, message: types.Message):

View File

@@ -14,21 +14,25 @@ from .handler import MessageHandlerABC
class UpdateSettingsCommand(MessageHandlerABC):
"""Command to update settings manually or by timer"""
settings: BotSettings
post: Coroutine
post: Coroutine # async post command method to post posts to channel by timer
filter = Command('update_settings')
async def settings_and_schedule_checker(self):
await self._auto_update_settings()
async def _auto_update_settings(self):
"""
An asynchronous function that updates settings and schedules jobs.
"""
self.settings = await neuroapi.bot_settings.get()
self.scheduler.remove_all_jobs()
self.scheduler.add_job(self._auto_update_settings, 'interval', seconds=60)
self.scheduler.add_job(self._auto_update_settings, 'interval', seconds=60) # Auto updating settings
# TODO: Сделать в бэке и в боте, чтоб дни тоже можно было в настройках хранить
for i in self.settings.message_times:
self.scheduler.add_job(self.post, 'cron', day_of_week='mon-sun', hour=i.split(':')[0], minute=i.split(':')[1])
self.scheduler.add_job(self.post, 'cron', day_of_week='mon-sun', hour=i.split(':')[0], minute=i.split(':')[1]) # Auto posting
logging.debug(self.scheduler.get_jobs())
def __init__(self, bot: Bot, post_command: Coroutine, *args) -> None:
@@ -41,6 +45,7 @@ class UpdateSettingsCommand(MessageHandlerABC):
self.scheduler.start()
async def _command(self, mes: types.Message):
"""Clearing server cache and returning actual settings"""
self.settings = await neuroapi.bot_settings.get_update()
await mes.answer('Настройки обновлены')

View File

@@ -7,6 +7,7 @@ from neuroapi import neuroapi
class AdminMiddleware(BaseMiddleware):
"""Checking admin rights"""
def __init__(self) -> None:
pass

View File

@@ -1,5 +1,6 @@
from aiogram.fsm.state import State, StatesGroup
#TODO: Use states somewhere
class ChangePost(StatesGroup):
Text = State()

View File

@@ -10,6 +10,7 @@ class UserCommands(Handler):
settings: BotSettingsType
def __init__(self, bot: Bot) -> None:
"""Initialize the group of user commands"""
super().__init__(bot)
self.add_handlers([