You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
There comes a point in your bot's development when you want to organize a collection of commands, listeners, and some state into one class. Cogs allow you to do just that.
10
+
11
+
The gist:
12
+
13
+
- Each cog is a Python class that subclasses :class:`.Cog`.
14
+
- Every command is marked with the :func:`.command` decorator or the corresponding shortcut command decorator.
15
+
- Every listener is marked with the :meth:`.Cog.listener` decorator.
16
+
- Cogs are then registered with the :meth:`.Bot.add_cog` call.
17
+
- Cogs are subsequently removed with the :meth:`.Bot.remove_cog` call.
18
+
19
+
Quick Example
20
+
---------------
21
+
22
+
This example cog defines a ``Greetings`` category for your commands, with a single slash command named ``hello`` as well as a listener to listen to an :ref:`Event <discord-api-events>`.
if self._last_member is None or self._last_member.id != member.id:
42
+
await ctx.send(f'Hello {member.name}~')
43
+
else:
44
+
await ctx.send(f'Hello {member.name}... This feels familiar.')
45
+
self._last_member = member
46
+
47
+
A couple of technical notes to take into consideration:
48
+
49
+
- All listeners must be explicitly marked via decorator, :meth:`~.Cog.listener`.
50
+
- The name of the cog is automatically derived from the class name but can be overridden.
51
+
- All commands must now take a ``self`` parameter to allow usage of instance attributes that can be used to maintain state.
52
+
53
+
Cog Registration
54
+
-------------------
55
+
56
+
Once you have defined your cogs, you need to tell the bot to register the cogs to be used. We do this via the :meth:`~.Bot.add_cog` method.
57
+
58
+
.. code-block:: python3
59
+
60
+
bot.add_cog(Greetings(bot))
61
+
62
+
This binds the cog to the bot, adding all commands and listeners to the bot automatically.
63
+
64
+
Using Cogs
65
+
-------------
66
+
67
+
Just as we remove a cog by its name, we can also retrieve it by its name as well. This allows us to use a cog as an inter-command communication protocol to share data. For example:
0 commit comments