Advertisement
Guest User

Untitled

a guest
Apr 4th, 2020
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.39 KB | None | 0 0
  1. from abc import ABC
  2. from enum import Enum
  3. from vkbottle import Bot, Message
  4. from vbml import Patcher, Pattern
  5.  
  6. import typing
  7. import asyncio
  8. import json
  9.  
  10.  
  11. async def send_msg(
  12.         bot: Bot,
  13.         message: str,
  14.         attachment: str,
  15.         keyboard: json,
  16.         disable_mentions: bool = True,
  17.         **kwargs
  18. ):
  19.     await bot.api.messages.send(**locals())
  20.  
  21.  
  22. class CommandException(Exception):
  23.     def __init__(self, command: str, msg: str):
  24.         self.error_command = command
  25.         self.error_msg = msg
  26.  
  27.  
  28. class CommandTypeException(Exception):
  29.     def __init__(self, error_msg: str):
  30.         self.error_msg = error_msg
  31.  
  32.  
  33. class CommandType(Enum):
  34.     ONLY_CHATS = "only_chats"
  35.     ONLY_SELF = "only_self"
  36.     ALL = "all"
  37.  
  38.  
  39. class AbstractCommandManager(ABC):
  40.     def __init__(
  41.             self,
  42.             bot: Bot,
  43.             command: str,
  44.             pattern: typing.Union[typing.List[Pattern], Pattern],
  45.             loop: asyncio.AbstractEventLoop or None,
  46.             patcher: Patcher = None,
  47.             description: str = None,
  48.             example: str = None,
  49.             kind: str = "all"
  50.     ):
  51.         self.bot = bot
  52.         self.command = command
  53.         self.patcher: Patcher = patcher
  54.         self.patterns: typing.List[Pattern] = pattern
  55.         self.description = description or "Undefined"
  56.         self.example = example or ""
  57.         self.kind: CommandType = CommandType(kind)
  58.  
  59.         if isinstance(pattern, Pattern):
  60.             self.patterns = [pattern]
  61.  
  62.         self.__loop = loop or asyncio.get_event_loop()
  63.  
  64.     async def __call__(self, message: Message):
  65.         try:
  66.             await self.parse_arguments(message)
  67.             kwargs: dict = await self.parse_arguments(message)
  68.             self.__loop.create_task(self.start(message, **kwargs))
  69.         except (CommandTypeException, CommandException) as e:
  70.             await self.response(message, str(e))
  71.  
  72.     async def parse_arguments(self, message: Message):
  73.         kwargs = {}
  74.         for pattern in self.patterns:
  75.             result = self.patcher.check(message.text, pattern)
  76.             if result is not None:
  77.                 if result == {}:
  78.                     pass
  79.                 else:
  80.                     kwargs.update(result)
  81.  
  82.         if kwargs:
  83.             raise CommandException(
  84.                 self.command, f"Недостаточно аргументов для команды.\n{self.example}"
  85.             )
  86.  
  87.     async def property_check(self, message: Message) -> bool:
  88.         """ Тщательная проверка перед отправлением.
  89.        :param message: Объект сообщения
  90.        :return: -> boolean
  91.        """
  92.         if self.kind is CommandType.ONLY_SELF:
  93.             if message.peer_id != message.from_id:
  94.                 raise CommandTypeException("Команда доступна только в ЛС бота.")
  95.             return True
  96.  
  97.         # Тут можно добавить еще много проверов: Пример: Проверка на админа, доступ и т.д
  98.  
  99.     async def start(self, message: Message, **kwargs):
  100.         """ Запуск обработчика команды.
  101.        Метод должен быть переписан!
  102.        :param message: Объект сообщения
  103.        :param kwargs: Аргументы команды
  104.        :return:
  105.        """
  106.         pass
  107.  
  108.     @staticmethod
  109.     async def response(
  110.         message: Message,
  111.         text: str,
  112.         attachment: str = None,
  113.         keyboard: json = None
  114.     ):
  115.         """ Отправка результата команды.
  116.        :param message: Объект сообщения
  117.        :param text: Тут всё понятно.
  118.        :param attachment: Тут всё понятно.
  119.        :param keyboard: Тут всё понятно.
  120.        :return:
  121.        """
  122.         await send_msg(**locals())
  123.  
  124.  
  125. class RegisterCommand:
  126.     def __init__(self, patcher: Patcher):
  127.         self.commands: typing.List[AbstractCommandManager] = []
  128.         self.patcher: Patcher = patcher
  129.        
  130.     def new_command(self, handler: AbstractCommandManager):
  131.         handler.patcher = self.patcher
  132.         self.commands.append(handler)
  133.         print("Registered new command: ", handler.command)
  134.    
  135.     def get_commands(self) -> list:
  136.         return [i.command for i in self.commands]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement