Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
from typing import List
class CommandDecorator():
def __init__(self, name: str = None, description: str = '', aliases: List[str] = list):
self.name = name
self.description = description
self.aliases = aliases
self.func = None
def __call__(self, func):
self.func = func
return self.func
class CommandHandler():
def __init__(self):
self.commands = {}
def command(self, name: str = None, description: str = '', aliases: List[str] = list):
name = name or func.__name__
decorator = CommandDecorator(name, description, aliases)
self.commands[name] = decorator
return decorator
c = CommandHandler() # internal CommandHandler instance
class Commands():
@c.command(name="test", description="this is a test command", aliases=["test1", "test2"])
def test_command(self):
print("heya")
def call_commands(self, c):
for command in c.commands.values():
command.func(self)
commands_instance = Commands()
commands_instance.call_commands(c)
class CommandHandler:
def __init__(self, client: Client) -> None:
self.client = client
self.aliases = {}
self.commands = {}
def command(func: Callable, name: str = None, description: str = '', alternates: List[str] = []) -> Callable:
name = name or func.__name__
@wraps(func)
def wrapper(*args, **kwargs):
logger.info(f'Executing {name} command for Client {args[0].client.nickname}')
func(*args, **kwargs)
# Impossible code
for alias in alternates:
self.aliases[alias] = name
self.commands[name] = {'name': name, 'description': description, 'func': wrapper}
return wrapper
@command(name='Reroll', description='Change your color to a random color.')
def reroll(self) -> str:
"""
Randomly change the client's color to a different color.
"""
newColor = random.choice(constants.Colors.ALL)
newColorName = constants.Colors.ALL_NAMES[constants.Colors.ALL.index(newColor)]
self.client.color = newColor
return f'Changed your color to {newColorName} ({newColor})'
class Decorator():
def __init__(self, name, description):
self.name = name
self.description = description
def __call__(self, func):
@wraps(func)
def wrapper(*args, **kwargs):
logger.info(f'Executing {name} command for Client {args[0].client.nickname}')
func(*args, **kwargs)
return wrapper
class A():
def __init__(self, a):
self.a = a
def command(self, name="", description=""):
return Decorator(name, description)
a = A(5)
@a.command
def my_command():
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment