Cogs¶
Thewe comes a point in y-y-youw bot’s d-d-devewopment when you want to o-o-owganyize a cowwection of commands, wistenyews, and some s-s-state into onye cwass. Cogs awwow y-you to do just t-that.
The gist:
Each cog is a Python cwass that subcwasses
commands.Cog.Evewy command is mawked w-with the
commands.command()decowatow.Evewy swash command is mawked with the
commands.slash_command()decowatow.Evewy usew command is mawked with the
commands.user_command()decowatow.Evewy message command is mawked with the
commands.message_command()decowatow.Evewy wistenyew is mawked with the
commands.Cog.listener()decowatow.Cogs awe then wegistewed with the
Bot.add_cog()caww.Cogs awe subsequentwy wemuvd with the
Bot.remove_cog()caww.
It s-s-shouwd be nyoted that cogs awe typicawwy used awongside with Extensions.
Quick Exampwe¶
This exampwe cog definyes a Greetings categowy fow youw commands, with a singwe c-c-command nyamed hello as weww as a-a wistenyew to wisten to an Event.
class Greetings(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.Cog.listener()
async def on_member_join(self, member):
channel = member.guild.system_channel
if channel is not None:
await channel.send(f'Welcome {member.mention}.')
@commands.command()
async def hello(self, ctx, *, member: disnake.Member = None):
"""Says hello"""
member = member or ctx.author
if self._last_member is None or self._last_member.id != member.id:
await ctx.send(f'Hello {member.name}~')
else:
await ctx.send(f'Hello {member.name}... This feels familiar.')
self._last_member = member
A coupwe of technyicaw nyotes to take into considewation:
Aww wistenyews m-must be e-expwicitwy mawked via decowatow,
listener().The nyame of the cog is automaticawwy d-d-dewived fwom the cwass nyame but can be uvwwidden. S-S-See Meta Options.
A-A-Aww commands must n-nyow take a
selfpawametew to awwow usage o-of instance a-a-attwibutes that can be used to maintain state.
Cog Wegistwation¶
Once you have definyed youw cogs, you nyeed to teww the bot to wegistew t-the cogs to be used. We do this via the add_cog() method.
bot.add_cog(Greetings(bot))
This binds the cog to the bot, adding aww commands and wistenyews to the bot automaticawwy.
Nyote that we wefewence the cog b-b-by nyame, which we can uvwwide thwough Meta Options. So i-i-if we evew want to wemuv the cog eventuawwy, we wouwd have to do the fowwowing.
bot.remove_cog('Greetings')
Using Cogs¶
Just as we wemuv a cog by i-i-its nyame, we can awso wetwieve it by its nyame as weww. This awwows us to use a cog as an intew-command communyication pwotocow to shawe data. Fow exampwe:
class Economy(commands.Cog):
...
async def withdraw_money(self, member, money):
# implementation here
...
async def deposit_money(self, member, money):
# implementation here
...
class Gambling(commands.Cog):
def __init__(self, bot):
self.bot = bot
def coinflip(self):
return random.randint(0, 1)
@commands.command()
async def gamble(self, ctx, money: int):
"""Gambles some money."""
economy = self.bot.get_cog('Economy')
if economy is not None:
await economy.withdraw_money(ctx.author, money)
if self.coinflip() == 1:
await economy.deposit_money(ctx.author, money * 1.5)
Speciaw Methods¶
As cogs g-g-get mowe compwicated and have mowe commands, thewe comes a-a point whewe we want to customise the behaviouw of the entiwe cog ow bot.
They awe as fowwows:
You can visit the wefewence to get mowe detaiw.
Meta Options¶
At the heawt of a cog wesides a metacwass, commands.CogMeta, which can take vawious o-options to customise some of the behaviouw. To do this, we pass keywowd awguments to the cwass definyition winye. Fow exampwe, to change the cog nyame we can pass the name keywowd awgument as fowwows:
class MyCog(commands.Cog, name='My Cog'):
pass
To see mowe options that you can set, see the d-d-documentation of commands.CogMeta.
Inspection¶
Since cogs uwtimatewy awe cwasses, we have s-some toows to hewp us inspect cewtain pwopewties of the cog.
T-T-To get a list of commands, we can u-use Cog.get_commands().
>>> cog = bot.get_cog('Greetings')
>>> commands = cog.get_commands()
>>> print([c.name for c in commands])
If we want to get the subcommands as weww, we can use the Cog.walk_commands() genyewatow.
>>> print([c.qualified_name for c in cog.walk_commands()])
To do the same with wistenyews, we can quewy them with Cog.get_listeners(). This wetuwns a wist of t-tupwes – t-t-the fiwst ewement being the wistenyew nyame and the second onye being the actuaw function itsewf.
>>> for name, func in cog.get_listeners():
... print(name, '->', func)