morington

Configuration of bot commands with HELP support

Aug 12th, 2023 (edited)
1,198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.95 KB | None | 0 0
  1. # morington
  2. # t.me/dev_survival
  3.  
  4. # ================== commands.yaml
  5. """
  6. USER:
  7.  start:
  8.    description: Press to start
  9.    help: The start command provokes the bot to start.
  10.  help:
  11.    description: Press to help
  12.    help: We can use help to get more information on the commands.
  13.    
  14. ADMIN:
  15.  start:
  16.    description: Press to start
  17.    help: You don't need it, go to work )
  18. """
  19.  
  20. # ================== BotCommands
  21. import structlog
  22. from pathlib import Path
  23.  
  24. from yaml import safe_load
  25. from aiogram.types import BotCommand
  26.  
  27. from src.application.exceptions import (
  28.     FileNotFound,
  29.     FileIncorrectExtension,
  30.     RoleNotFound,
  31.     CommandNotFound
  32. )
  33. from src.application.database.models.user_model import UserRole
  34.  
  35.  
  36. logger = structlog.get_logger(__name__)
  37.  
  38. class BotCommands:
  39.     def __init__(self, command_path: str) -> None:
  40.         self.command_path = command_path
  41.         self.initCommands()
  42.  
  43.  
  44.     @property
  45.     def command_path(self) -> str: return self._command_path
  46.    
  47.  
  48.     @command_path.setter
  49.     def command_path(self, file_path: str):
  50.         path: Path = Path(file_path)
  51.         if not path.exists():
  52.             raise FileNotFound("The passed path for the configuration file does not exist.")
  53.         if path.suffix != '.yaml':
  54.             raise FileIncorrectExtension(f"The configuration file must have the extension 'yaml' for configuration, and passed '{path.suffix}'.")
  55.         self._command_path: str = file_path
  56.  
  57.  
  58.     def initCommands(self):
  59.         with open(self.command_path, 'r', encoding='utf-8') as file:
  60.             self.commands = safe_load(file)
  61.  
  62.  
  63.     def generate_commands(self, role: UserRole) -> list[BotCommand]:
  64.         if role not in self.commands:
  65.             raise RoleNotFound(f"The role '{role}' was not found.")
  66.        
  67.         return [
  68.             BotCommand(
  69.                 command=command,
  70.                 description=other.get("description")
  71.             )
  72.             for command, other in self.commands.get(role).items()
  73.         ]
  74.    
  75.  
  76.     def get_help(self, role: UserRole, command: str) -> str:
  77.         if role not in self.commands:
  78.             raise RoleNotFound(f"The role '{role}' was not found.")
  79.         if command not in self.commands.get(role):
  80.             raise CommandNotFound(f"The role '{role}' was not found.")
  81.  
  82.         return self.commands[role][command]["help"]
  83.  
  84.    
  85.     def __str__(self) -> str:
  86.         return f'<{__class__.__name__} command_path:{self._command_path}>'
  87.  
  88.  
  89.     def __repr__(self) -> str: return self.__str__()
  90.  
  91.  
  92.  
  93. bot_commands = BotCommands("commands.yaml")
  94.  
  95. logger.debug(
  96.     bot_commands.generate_commands(role=UserRole.USER)
  97. )
  98. """
  99. Output:
  100. >>> 2023-08-12 20:32:12 [debug    ] [BotCommand(command='start', description='Press to start'), BotCommand(command='help', description='Press to help')]
  101. """
  102.  
  103. logger.debug(
  104.     bot_commands.get_help(role=UserRole.ADMIN, command="start")
  105. )
  106. """
  107. Output:
  108. >>> You don't need it, go to work )
  109. """
Advertisement
Add Comment
Please, Sign In to add comment