Skip to content

Commit

Permalink
[commands] Raise error when a cog name is already registered
Browse files Browse the repository at this point in the history
  • Loading branch information
SebbyLaw authored Apr 9, 2021
1 parent 9da2f34 commit 4134a17
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions discord/ext/commands/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -489,29 +489,49 @@ def decorator(func):

# cogs

def add_cog(self, cog):
def add_cog(self, cog: Cog, *, override: bool = False) -> None:
"""Adds a "cog" to the bot.
A cog is a class that has its own event listeners and commands.
.. versionchanged:: 2.0
:exc:`.ClientException` is raised when a cog with the same name
is already loaded.
Parameters
-----------
cog: :class:`.Cog`
The cog to register to the bot.
override: :class:`bool`
If a previously loaded cog with the same name should be ejected
instead of raising an error.
.. versionadded:: 2.0
Raises
-------
TypeError
The cog does not inherit from :class:`.Cog`.
CommandError
An error happened during loading.
.ClientException
A cog with the same name is already loaded.
"""

if not isinstance(cog, Cog):
raise TypeError('cogs must derive from Cog')

cog_name = cog.__cog_name__
existing = self.__cogs.get(cog_name)

if existing is not None:
if not override:
raise discord.ClientException(f'Cog named {cog_name!r} already loaded')
self.remove_cog(cog_name)

cog = cog._inject(self)
self.__cogs[cog.__cog_name__] = cog
self.__cogs[cog_name] = cog

def get_cog(self, name):
"""Gets the cog instance requested.
Expand Down

0 comments on commit 4134a17

Please sign in to comment.