Skip to content

Commit 2787966

Browse files
committed
♻️ Extract name validation logic to helper method _validate_name_prefix
1 parent e127333 commit 2787966

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

discord/cog.py

+12-11
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,13 @@ def _name_filter(c: Any) -> str:
8787
)
8888

8989

90+
def _validate_name_prefix(base_class: type, name: str) -> None:
91+
if name.startswith(("cog_", "bot_")):
92+
raise TypeError(
93+
f"Commands or listeners must not start with cog_ or bot_ (in method {base_class}.{name})"
94+
)
95+
96+
9097
class CogMeta(type):
9198
"""A metaclass for defining a cog.
9299
@@ -176,10 +183,6 @@ def __new__(cls: type[CogMeta], *args: Any, **kwargs: Any) -> CogMeta:
176183

177184
commands = {}
178185
listeners = {}
179-
no_bot_cog = (
180-
"Commands or listeners must not start with cog_ or bot_ (in method"
181-
" {0.__name__}.{1})"
182-
)
183186

184187
new_cls = super().__new__(cls, name, bases, attrs, **kwargs)
185188

@@ -204,7 +207,8 @@ def __new__(cls: type[CogMeta], *args: Any, **kwargs: Any) -> CogMeta:
204207
if getattr(value, "parent", None) and isinstance(
205208
value, ApplicationCommand
206209
):
207-
# Skip commands if they are a part of a group
210+
# Skip application commands if they are a part of a group
211+
# Since they are already added when the group is added
208212
continue
209213

210214
is_static_method = isinstance(value, staticmethod)
@@ -216,8 +220,7 @@ def __new__(cls: type[CogMeta], *args: Any, **kwargs: Any) -> CogMeta:
216220
f"Command in method {base}.{elem!r} must not be"
217221
" staticmethod."
218222
)
219-
if elem.startswith(("cog_", "bot_")):
220-
raise TypeError(no_bot_cog.format(base, elem))
223+
_validate_name_prefix(base, elem)
221224
commands[elem] = value
222225

223226
if _is_bridge_command(value) and not value.parent:
@@ -226,8 +229,7 @@ def __new__(cls: type[CogMeta], *args: Any, **kwargs: Any) -> CogMeta:
226229
f"Command in method {base}.{elem!r} must not be"
227230
" staticmethod."
228231
)
229-
if elem.startswith(("cog_", "bot_")):
230-
raise TypeError(no_bot_cog.format(base, elem))
232+
_validate_name_prefix(base, elem)
231233

232234
commands[f"ext_{elem}"] = value.ext_variant
233235
commands[f"app_{elem}"] = value.slash_variant
@@ -243,8 +245,7 @@ def __new__(cls: type[CogMeta], *args: Any, **kwargs: Any) -> CogMeta:
243245
except AttributeError:
244246
continue
245247
else:
246-
if elem.startswith(("cog_", "bot_")):
247-
raise TypeError(no_bot_cog.format(base, elem))
248+
_validate_name_prefix(base, elem)
248249
listeners[elem] = value
249250

250251
new_cls.__cog_commands__ = list(commands.values())

0 commit comments

Comments
 (0)