Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from abc import ABC
- from enum import Enum
- from vkbottle import Bot, Message
- from vbml import Patcher, Pattern
- import typing
- import asyncio
- import json
- async def send_msg(
- bot: Bot,
- message: str,
- attachment: str,
- keyboard: json,
- disable_mentions: bool = True,
- **kwargs
- ):
- await bot.api.messages.send(**locals())
- class CommandException(Exception):
- def __init__(self, command: str, msg: str):
- self.error_command = command
- self.error_msg = msg
- class CommandTypeException(Exception):
- def __init__(self, error_msg: str):
- self.error_msg = error_msg
- class CommandType(Enum):
- ONLY_CHATS = "only_chats"
- ONLY_SELF = "only_self"
- ALL = "all"
- class AbstractCommandManager(ABC):
- def __init__(
- self,
- bot: Bot,
- command: str,
- pattern: typing.Union[typing.List[Pattern], Pattern],
- loop: asyncio.AbstractEventLoop or None,
- patcher: Patcher = None,
- description: str = None,
- example: str = None,
- kind: str = "all"
- ):
- self.bot = bot
- self.command = command
- self.patcher: Patcher = patcher
- self.patterns: typing.List[Pattern] = pattern
- self.description = description or "Undefined"
- self.example = example or ""
- self.kind: CommandType = CommandType(kind)
- if isinstance(pattern, Pattern):
- self.patterns = [pattern]
- self.__loop = loop or asyncio.get_event_loop()
- async def __call__(self, message: Message):
- try:
- await self.parse_arguments(message)
- kwargs: dict = await self.parse_arguments(message)
- self.__loop.create_task(self.start(message, **kwargs))
- except (CommandTypeException, CommandException) as e:
- await self.response(message, str(e))
- async def parse_arguments(self, message: Message):
- kwargs = {}
- for pattern in self.patterns:
- result = self.patcher.check(message.text, pattern)
- if result is not None:
- if result == {}:
- pass
- else:
- kwargs.update(result)
- if kwargs:
- raise CommandException(
- self.command, f"Недостаточно аргументов для команды.\n{self.example}"
- )
- async def property_check(self, message: Message) -> bool:
- """ Тщательная проверка перед отправлением.
- :param message: Объект сообщения
- :return: -> boolean
- """
- if self.kind is CommandType.ONLY_SELF:
- if message.peer_id != message.from_id:
- raise CommandTypeException("Команда доступна только в ЛС бота.")
- return True
- # Тут можно добавить еще много проверов: Пример: Проверка на админа, доступ и т.д
- async def start(self, message: Message, **kwargs):
- """ Запуск обработчика команды.
- Метод должен быть переписан!
- :param message: Объект сообщения
- :param kwargs: Аргументы команды
- :return:
- """
- pass
- @staticmethod
- async def response(
- message: Message,
- text: str,
- attachment: str = None,
- keyboard: json = None
- ):
- """ Отправка результата команды.
- :param message: Объект сообщения
- :param text: Тут всё понятно.
- :param attachment: Тут всё понятно.
- :param keyboard: Тут всё понятно.
- :return:
- """
- await send_msg(**locals())
- class RegisterCommand:
- def __init__(self, patcher: Patcher):
- self.commands: typing.List[AbstractCommandManager] = []
- self.patcher: Patcher = patcher
- def new_command(self, handler: AbstractCommandManager):
- handler.patcher = self.patcher
- self.commands.append(handler)
- print("Registered new command: ", handler.command)
- def get_commands(self) -> list:
- return [i.command for i in self.commands]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement