Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # morington
- # t.me/dev_survival
- # ================== commands.yaml
- """
- USER:
- start:
- description: Press to start
- help: The start command provokes the bot to start.
- help:
- description: Press to help
- help: We can use help to get more information on the commands.
- ADMIN:
- start:
- description: Press to start
- help: You don't need it, go to work )
- """
- # ================== BotCommands
- import structlog
- from pathlib import Path
- from yaml import safe_load
- from aiogram.types import BotCommand
- from src.application.exceptions import (
- FileNotFound,
- FileIncorrectExtension,
- RoleNotFound,
- CommandNotFound
- )
- from src.application.database.models.user_model import UserRole
- logger = structlog.get_logger(__name__)
- class BotCommands:
- def __init__(self, command_path: str) -> None:
- self.command_path = command_path
- self.initCommands()
- @property
- def command_path(self) -> str: return self._command_path
- @command_path.setter
- def command_path(self, file_path: str):
- path: Path = Path(file_path)
- if not path.exists():
- raise FileNotFound("The passed path for the configuration file does not exist.")
- if path.suffix != '.yaml':
- raise FileIncorrectExtension(f"The configuration file must have the extension 'yaml' for configuration, and passed '{path.suffix}'.")
- self._command_path: str = file_path
- def initCommands(self):
- with open(self.command_path, 'r', encoding='utf-8') as file:
- self.commands = safe_load(file)
- def generate_commands(self, role: UserRole) -> list[BotCommand]:
- if role not in self.commands:
- raise RoleNotFound(f"The role '{role}' was not found.")
- return [
- BotCommand(
- command=command,
- description=other.get("description")
- )
- for command, other in self.commands.get(role).items()
- ]
- def get_help(self, role: UserRole, command: str) -> str:
- if role not in self.commands:
- raise RoleNotFound(f"The role '{role}' was not found.")
- if command not in self.commands.get(role):
- raise CommandNotFound(f"The role '{role}' was not found.")
- return self.commands[role][command]["help"]
- def __str__(self) -> str:
- return f'<{__class__.__name__} command_path:{self._command_path}>'
- def __repr__(self) -> str: return self.__str__()
- bot_commands = BotCommands("commands.yaml")
- logger.debug(
- bot_commands.generate_commands(role=UserRole.USER)
- )
- """
- Output:
- >>> 2023-08-12 20:32:12 [debug ] [BotCommand(command='start', description='Press to start'), BotCommand(command='help', description='Press to help')]
- """
- logger.debug(
- bot_commands.get_help(role=UserRole.ADMIN, command="start")
- )
- """
- Output:
- >>> You don't need it, go to work )
- """
Advertisement
Add Comment
Please, Sign In to add comment