Skip to content

Commit 75dffc0

Browse files
committed
Implemented aliases
1 parent 23082cf commit 75dffc0

File tree

4 files changed

+74
-33
lines changed

4 files changed

+74
-33
lines changed

dico_command/bot.py

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import dico
77
from .command import Command
88
from .context import Context
9-
from .exception import InvalidArgument, InvalidModule, MissingLoadFunction, MissingUnloadFunction, ModuleNotLoaded
9+
from .exception import *
1010
from .utils import smart_split, is_coro
1111

1212
if typing.TYPE_CHECKING:
@@ -25,6 +25,7 @@ def __init__(self,
2525
super().__init__(token, intents=intents, default_allowed_mentions=default_allowed_mentions, loop=loop, cache=cache)
2626
self.prefixes = [prefix] if not isinstance(prefix, list) else prefix
2727
self.commands = {}
28+
self.aliases = {}
2829
self.logger = logging.Logger("dico_command")
2930
self.on("MESSAGE_CREATE", self.execute_handler)
3031
self.addons: typing.List[Addon] = []
@@ -48,10 +49,10 @@ async def execute_handler(self, message: dico.Message):
4849
raw_ipt = cont[len(prefix_result):]
4950
ipt = raw_ipt.split(maxsplit=1)
5051
name = ipt[0]
51-
cmd = self.commands.get(name)
52+
cmd = self.commands.get(self.aliases.get(name, name))
5253
if not cmd:
5354
return
54-
context = Context.from_message(message, prefix_result, cmd)
55+
context = Context.from_message(message, prefix_result, cmd, name)
5556
try:
5657
try:
5758
args, kwargs = smart_split(ipt[1] if len(ipt) > 1 else "", cmd.args_data)
@@ -64,18 +65,25 @@ async def execute_handler(self, message: dico.Message):
6465

6566
def add_command(self, command: Command):
6667
if command.name in self.commands:
67-
raise
68+
raise CommandAlreadyExists(name=command.name)
6869
self.commands[command.name] = command
70+
for x in command.aliases:
71+
if x in self.aliases:
72+
raise CommandAlreadyExists(name=x)
73+
self.aliases[x] = command.name
6974
return command
7075

7176
def remove_command(self, name: str):
7277
if name not in self.commands:
73-
raise
74-
del self.commands[name]
78+
return
79+
command = self.commands.pop(name)
80+
for x in command.aliases:
81+
if x in self.aliases:
82+
del self.aliases[x]
7583

76-
def command(self, name: str = None):
84+
def command(self, name: typing.Optional[str] = None, *, aliases: typing.Optional[typing.List[str]] = None):
7785
def wrap(func):
78-
cmd = Command(func, name or func.__name__)
86+
cmd = Command(func, name or func.__name__, aliases=aliases)
7987
self.add_command(cmd)
8088
return cmd
8189
return wrap
@@ -89,7 +97,7 @@ def handle_command_error(self, context, ex):
8997
def load_addons(self, *addons: typing.Type["Addon"]):
9098
for x in addons:
9199
if x.name in self.addon_names:
92-
raise
100+
raise AddonAlreadyLoaded(name=x.name)
93101
self.addon_names.append(x.name)
94102
loaded = x(self)
95103
self.addons.append(loaded)
@@ -130,13 +138,15 @@ def load_module(self, import_path: str):
130138
try:
131139
module = importlib.import_module(import_path)
132140
importlib.reload(module)
141+
if module.__name__ in self.modules:
142+
raise ModuleAlreadyLoaded(path=import_path)
133143
self.modules.append(module.__name__)
134144
if hasattr(module, "load"):
135145
module.load(self)
136146
else:
137-
raise MissingLoadFunction
147+
raise MissingLoadFunction(path=import_path)
138148
except ImportError:
139-
raise InvalidModule
149+
raise InvalidModule(path=import_path)
140150

141151
def unload_module(self, import_path: str):
142152
try:
@@ -146,11 +156,11 @@ def unload_module(self, import_path: str):
146156
module.unload(self)
147157
self.modules.remove(module.__name__)
148158
else:
149-
raise MissingUnloadFunction
159+
raise MissingUnloadFunction(path=import_path)
150160
else:
151-
raise ModuleNotLoaded
161+
raise ModuleNotLoaded(path=import_path)
152162
except ImportError:
153-
raise InvalidModule
163+
raise InvalidModule(path=import_path)
154164

155165
def reload_module(self, import_path: str):
156166
self.unload_module(import_path)

dico_command/command.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,12 @@ class Command:
88
def __init__(self,
99
func,
1010
name: str,
11-
checks: typing.List[typing.Callable[[Context], bool]] = None):
11+
checks: typing.Optional[typing.List[typing.Callable[[Context], bool]]] = None,
12+
aliases: typing.Optional[typing.List[str]] = None):
1213
self.func = func
1314
self.name = name
1415
self.checks = checks or []
16+
self.aliases = aliases or []
1517

1618
self.args_data = read_function(self.func)
1719
if hasattr(func, "_checks"):
@@ -32,7 +34,7 @@ async def invoke(self, ctx: Context, *args, **kwargs):
3234
return await self.func(*init_args, *args, **kwargs)
3335

3436

35-
def command(name: str = None):
37+
def command(name: typing.Optional[str] = None, *, aliases: typing.Optional[typing.List[str]] = None):
3638
def wrap(func):
37-
return Command(func, name)
39+
return Command(func, name, aliases=aliases)
3840
return wrap

dico_command/context.py

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
1-
import io
21
import typing
3-
import pathlib
4-
from dico import Message, Embed, AllowedMentions, MessageReference
2+
from dico import Message, Embed, AllowedMentions, MessageReference, Component
3+
from dico.model.extras import FILE_TYPE
54

65

76
class Context(Message):
8-
def __init__(self, client, resp, prefix, command, **kwargs):
7+
def __init__(self, client, resp, prefix, command, name_used, **kwargs):
98
super().__init__(client, resp, **kwargs)
109
self.prefix = prefix
1110
self.command = command
11+
self.name_used = name_used
1212

1313
@classmethod
14-
def from_message(cls, message: Message, prefix, command):
15-
return cls(message.client, message.raw, prefix, command)
14+
def from_message(cls, message: Message, prefix, command, name_used):
15+
return cls(message.client, message.raw, prefix, command, name_used)
1616

1717
@property
1818
def bot(self):
@@ -22,9 +22,22 @@ def send(self,
2222
content: str = None,
2323
*,
2424
embed: typing.Union[Embed, dict] = None,
25-
file: typing.Union[io.FileIO, pathlib.Path, str] = None,
26-
files: typing.List[typing.Union[io.FileIO, pathlib.Path, str]] = None,
25+
embeds: typing.List[typing.Union[Embed, dict]] = None,
26+
file: FILE_TYPE = None,
27+
files: typing.List[FILE_TYPE] = None,
2728
tts: bool = False,
2829
allowed_mentions: typing.Union[AllowedMentions, dict] = None,
29-
message_reference: typing.Union[Message, MessageReference, dict] = None):
30-
return self.client.create_message(self.channel, content, embed=embed, file=file, files=files, tts=tts, allowed_mentions=allowed_mentions, message_reference=message_reference)
30+
message_reference: typing.Union[Message, MessageReference, dict] = None,
31+
component: typing.Union[dict, Component] = None,
32+
components: typing.List[typing.Union[dict, Component]] = None):
33+
return self.client.create_message(self.channel,
34+
content,
35+
embed=embed,
36+
embeds=embeds,
37+
file=file,
38+
files=files,
39+
tts=tts,
40+
allowed_mentions=allowed_mentions,
41+
message_reference=message_reference,
42+
component=component,
43+
components=components)

dico_command/exception.py

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,16 @@
33

44
class CommandException(DicoException):
55
"""Base exception for dico-command."""
6-
def __init__(self, *args):
7-
super().__init__(*args or [self.__doc__])
6+
def __init__(self, *args, **fmt):
7+
super().__init__(*args or [self.__doc__.format(**fmt)])
8+
9+
10+
class CommandAlreadyExists(CommandException):
11+
"""Command {name} already exists."""
12+
13+
14+
class CommandNotExists(CommandException):
15+
"""Command {name} doesn't exist."""
816

917

1018
class InvalidArgument(CommandException):
@@ -16,16 +24,24 @@ class CheckFailed(CommandException):
1624

1725

1826
class InvalidModule(CommandException):
19-
"""Unable to find module. Check if path is correct."""
27+
"""Unable to find module {path}. Check if path is correct."""
28+
29+
30+
class ModuleAlreadyLoaded(CommandException):
31+
"""Module {path} is already loaded."""
2032

2133

2234
class ModuleNotLoaded(CommandException):
23-
"""This module is never loaded."""
35+
"""Module {path} is never loaded."""
2436

2537

2638
class MissingLoadFunction(CommandException):
27-
"""This module is missing "load" function."""
39+
"""Module {path} is missing "load" function."""
2840

2941

3042
class MissingUnloadFunction(CommandException):
31-
"""This module is missing "unload" function."""
43+
"""Module {path} is missing "unload" function."""
44+
45+
46+
class AddonAlreadyLoaded(CommandException):
47+
"""Addon {name} is already loaded."""

0 commit comments

Comments
 (0)