14 changed files with 776 additions and 184 deletions
@ -0,0 +1,30 @@ |
|||
# -*- coding: utf-8 -*- |
|||
|
|||
""" |
|||
The MIT License (MIT) |
|||
|
|||
Copyright (c) 2015-2017 Rapptz |
|||
|
|||
Permission is hereby granted, free of charge, to any person obtaining a |
|||
copy of this software and associated documentation files (the "Software"), |
|||
to deal in the Software without restriction, including without limitation |
|||
the rights to use, copy, modify, merge, publish, distribute, sublicense, |
|||
and/or sell copies of the Software, and to permit persons to whom the |
|||
Software is furnished to do so, subject to the following conditions: |
|||
|
|||
The above copyright notice and this permission notice shall be included in |
|||
all copies or substantial portions of the Software. |
|||
|
|||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS |
|||
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
|||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
|||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
|||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
|||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER |
|||
DEALINGS IN THE SOFTWARE. |
|||
""" |
|||
|
|||
# This is merely a tag type to avoid circular import issues. |
|||
# Yes, this is a terrible solution but ultimately it is the only solution. |
|||
class _BaseCommand: |
|||
__slots__ = () |
@ -0,0 +1,325 @@ |
|||
# -*- coding: utf-8 -*- |
|||
|
|||
""" |
|||
The MIT License (MIT) |
|||
|
|||
Copyright (c) 2015-2017 Rapptz |
|||
|
|||
Permission is hereby granted, free of charge, to any person obtaining a |
|||
copy of this software and associated documentation files (the "Software"), |
|||
to deal in the Software without restriction, including without limitation |
|||
the rights to use, copy, modify, merge, publish, distribute, sublicense, |
|||
and/or sell copies of the Software, and to permit persons to whom the |
|||
Software is furnished to do so, subject to the following conditions: |
|||
|
|||
The above copyright notice and this permission notice shall be included in |
|||
all copies or substantial portions of the Software. |
|||
|
|||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS |
|||
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
|||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
|||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
|||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
|||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER |
|||
DEALINGS IN THE SOFTWARE. |
|||
""" |
|||
|
|||
import inspect |
|||
import copy |
|||
from ._types import _BaseCommand |
|||
|
|||
__all__ = ('CogMeta', 'Cog') |
|||
|
|||
class CogMeta(type): |
|||
"""A metaclass for defining a cog. |
|||
|
|||
Note that you should probably not use this directly. It is exposed |
|||
purely for documentation purposes along with making custom metaclasses to intermix |
|||
with other metaclasses such as the :class:`abc.ABCMeta` metaclass. |
|||
|
|||
For example, to create an abstract cog mixin class, the following would be done. |
|||
|
|||
.. code-block:: python3 |
|||
|
|||
import abc |
|||
|
|||
class CogABCMeta(commands.CogMeta, abc.ABCMeta): |
|||
pass |
|||
|
|||
class SomeMixin(metaclass=abc.ABCMeta): |
|||
pass |
|||
|
|||
class SomeCogMixin(SomeMixin, commands.Cog, metaclass=CogABCMeta): |
|||
pass |
|||
|
|||
.. note:: |
|||
|
|||
When passing an attribute of a metaclass that is documented below, note |
|||
that you must pass it as a keyword-only argument to the class creation |
|||
like the following example: |
|||
|
|||
.. code-block:: python3 |
|||
|
|||
class MyCog(commands.Cog, name='My Cog'): |
|||
pass |
|||
|
|||
Attributes |
|||
----------- |
|||
name: :class:`str` |
|||
The cog name. By default, it is the name of the class with no modification. |
|||
command_attrs: :class:`dict` |
|||
A list of attributes to apply to every command inside this cog. The dictionary |
|||
is passed into the :class:`Command` (or its subclass) options at ``__init__``. |
|||
If you specify attributes inside the command attribute in the class, it will |
|||
override the one specified inside this attribute. For example: |
|||
|
|||
.. code-block:: python3 |
|||
|
|||
class MyCog(commands.Cog, command_attrs=dict(hidden=True)): |
|||
@commands.command() |
|||
async def foo(self, ctx): |
|||
pass # hidden -> True |
|||
|
|||
@commands.command(hidden=False) |
|||
async def bar(self, ctx): |
|||
pass # hidden -> False |
|||
""" |
|||
|
|||
def __new__(cls, *args, **kwargs): |
|||
name, bases, attrs = args |
|||
attrs['__cog_name__'] = kwargs.pop('name', name) |
|||
attrs['__cog_settings__'] = command_attrs = kwargs.pop('command_attrs', {}) |
|||
|
|||
commands = [] |
|||
listeners = [] |
|||
|
|||
for elem, value in attrs.items(): |
|||
if isinstance(value, _BaseCommand): |
|||
commands.append(value) |
|||
elif inspect.iscoroutinefunction(value): |
|||
try: |
|||
is_listener = getattr(value, '__cog_listener__') |
|||
except AttributeError: |
|||
continue |
|||
else: |
|||
listeners.append((value.__cog_listener_name__, value.__name__)) |
|||
|
|||
attrs['__cog_commands__'] = commands # this will be copied in Cog.__new__ |
|||
attrs['__cog_listeners__'] = tuple(listeners) |
|||
return super().__new__(cls, name, bases, attrs) |
|||
|
|||
def __init__(self, *args, **kwargs): |
|||
super().__init__(*args) |
|||
|
|||
@classmethod |
|||
def qualified_name(cls): |
|||
return cls.__cog_name__ |
|||
|
|||
class Cog(metaclass=CogMeta): |
|||
"""The base class that all cogs must inherit from. |
|||
|
|||
A cog is a collection of commands, listeners, and optional state to |
|||
help group commands together. More information on them can be found on |
|||
the :ref:`ext_commands_cogs` page. |
|||
|
|||
When inheriting from this class, the options shown in :class:`CogMeta` |
|||
are equally valid here. |
|||
""" |
|||
|
|||
def __new__(cls, *args, **kwargs): |
|||
# For issue 426, we need to store a copy of the command objects |
|||
# since we modify them to inject `self` to them. |
|||
# To do this, we need to interfere with the Cog creation process. |
|||
self = super().__new__(cls) |
|||
cmd_attrs = cls.__cog_settings__ |
|||
|
|||
# Either update the command with the cog provided defaults or copy it. |
|||
self.__cog_commands__ = tuple(c._update_copy(cmd_attrs) for c in cls.__cog_commands__) |
|||
return self |
|||
|
|||
def get_commands(self): |
|||
r"""Returns a :class:`tuple` of :class:`.Command`\s and its subclasses that are |
|||
defined inside this cog. |
|||
""" |
|||
return self.__cog_commands__ |
|||
|
|||
def walk_commands(self): |
|||
"""An iterator that recursively walks through this cog's commands and subcommands.""" |
|||
from .core import GroupMixin |
|||
for command in self.__cog_commands__: |
|||
yield command |
|||
if isinstance(command, GroupMixin): |
|||
yield from command.walk_commands() |
|||
|
|||
def get_listeners(self): |
|||
"""Returns a :class:`list` of (name, function) listener pairs that are defined in this cog.""" |
|||
return [(name, getattr(self, method_name)) for name, method_name in self.__cog_listeners__] |
|||
|
|||
@classmethod |
|||
def _get_overridden_method(cls, method): |
|||
"""Return None if the method is not overridden. Otherwise returns the overridden method.""" |
|||
if method.__func__ is getattr(cls, method.__name__): |
|||
return None |
|||
return method |
|||
|
|||
@classmethod |
|||
def listener(cls, name=None): |
|||
"""A decorator that marks a function as a listener. |
|||
|
|||
This is the cog equivalent of :meth:`.Bot.listen`. |
|||
|
|||
Parameters |
|||
------------ |
|||
name: :class:`str` |
|||
The name of the event being listened to. If not provided, it |
|||
defaults to the function's name. |
|||
|
|||
Raises |
|||
-------- |
|||
TypeError |
|||
The function is not a coroutine function. |
|||
""" |
|||
|
|||
def decorator(func): |
|||
if not inspect.iscoroutinefunction(func): |
|||
raise TypeError('Listener function must be a coroutine function.') |
|||
func.__cog_listener__ = True |
|||
func.__cog_listener_name__ = name or func.__name__ |
|||
return func |
|||
return decorator |
|||
|
|||
def cog_unload(self): |
|||
"""A special method that is called when the cog gets removed. |
|||
|
|||
This function **cannot** be a coroutine. It must be a regular |
|||
function. |
|||
|
|||
Subclasses must replace this if they want special unloading behaviour. |
|||
""" |
|||
pass |
|||
|
|||
def bot_check_once(self, ctx): |
|||
"""A special method that registers as a :meth:`.Bot.check_once` |
|||
check. |
|||
|
|||
This function **can** be a coroutine and must take a sole parameter, |
|||
``ctx``, to represent the :class:`.Context`. |
|||
""" |
|||
return True |
|||
|
|||
def bot_check(self, ctx): |
|||
"""A special method that registers as a :meth:`.Bot.check` |
|||
check. |
|||
|
|||
This function **can** be a coroutine and must take a sole parameter, |
|||
``ctx``, to represent the :class:`.Context`. |
|||
""" |
|||
return True |
|||
|
|||
def cog_check(self, ctx): |
|||
"""A special method that registers as a :func:`commands.check` |
|||
for every command and subcommand in this cog. |
|||
|
|||
This function **can** be a coroutine and must take a sole parameter, |
|||
``ctx``, to represent the :class:`.Context`. |
|||
""" |
|||
return True |
|||
|
|||
def cog_command_error(self, ctx, error): |
|||
"""A special method that is called whenever an error |
|||
is dispatched inside this cog. |
|||
|
|||
This is similar to :func:`.on_command_error` except only applying |
|||
to the commands inside this cog. |
|||
|
|||
This function **can** be a coroutine. |
|||
|
|||
Parameters |
|||
----------- |
|||
ctx: :class:`.Context` |
|||
The invocation context where the error happened. |
|||
error: :class:`CommandError` |
|||
The error that happened. |
|||
""" |
|||
pass |
|||
|
|||
async def cog_before_invoke(self, ctx): |
|||
"""A special method that acts as a cog local pre-invoke hook. |
|||
|
|||
This is similar to :meth:`.Command.before_invoke`. |
|||
|
|||
This **must** be a coroutine. |
|||
|
|||
Parameters |
|||
----------- |
|||
ctx: :class:`.Context` |
|||
The invocation context. |
|||
""" |
|||
pass |
|||
|
|||
async def cog_after_invoke(self, ctx): |
|||
"""A special method that acts as a cog local post-invoke hook. |
|||
|
|||
This is similar to :meth:`.Command.after_invoke`. |
|||
|
|||
This **must** be a coroutine. |
|||
|
|||
Parameters |
|||
----------- |
|||
ctx: :class:`.Context` |
|||
The invocation context. |
|||
""" |
|||
pass |
|||
|
|||
def _inject(self, bot): |
|||
cls = self.__class__ |
|||
|
|||
# realistically, the only thing that can cause loading errors |
|||
# is essentially just the command loading, which raises if there are |
|||
# duplicates. When this condition is met, we want to undo all what |
|||
# we've added so far for some form of atomic loading. |
|||
for index, command in enumerate(self.__cog_commands__): |
|||
command.cog = self |
|||
if command.parent is None: |
|||
try: |
|||
bot.add_command(command) |
|||
except Exception as e: |
|||
# undo our additions |
|||
for to_undo in self.__cog_commands__[:index]: |
|||
bot.remove_command(to_undo) |
|||
raise e |
|||
|
|||
# check if we're overriding the default |
|||
if cls.bot_check is not Cog.bot_check: |
|||
bot.add_check(self.bot_check) |
|||
|
|||
if cls.bot_check_once is not Cog.bot_check_once: |
|||
bot.add_check(self.bot_check_once, call_once=True) |
|||
|
|||
# while Bot.add_listener can raise if it's not a coroutine, |
|||
# this precondition is already met by the listener decorator |
|||
# already, thus this should never raise. |
|||
# Outside of, memory errors and the like... |
|||
for name, method_name in self.__cog_listeners__: |
|||
bot.add_listener(getattr(self, method_name), name) |
|||
|
|||
return self |
|||
|
|||
def _eject(self, bot): |
|||
cls = self.__class__ |
|||
|
|||
try: |
|||
for command in self.__cog_commands__: |
|||
if command.parent is None: |
|||
bot.remove_command(command.name) |
|||
|
|||
for _, method_name in self.__cog_listeners__: |
|||
bot.remove_listener(getattr(self, method_name)) |
|||
|
|||
if cls.bot_check is not Cog.bot_check: |
|||
bot.remove_check(self.bot_check) |
|||
|
|||
if cls.bot_check_once is not Cog.bot_check_once: |
|||
bot.remove_check(self.bot_check_once) |
|||
finally: |
|||
self.cog_unload() |
@ -0,0 +1,159 @@ |
|||
.. currentmodule:: discord |
|||
|
|||
.. _ext_commands_cogs: |
|||
|
|||
Cogs |
|||
====== |
|||
|
|||
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. |
|||
|
|||
The gist: |
|||
|
|||
- Each cog is a Python class that subclasses :class:`.commands.Cog`. |
|||
- Every command is marked with the :func:`.commands.command` decorator. |
|||
- Every listener is marked with the :meth:`.commands.Cog.listener` decorator. |
|||
- Cogs are then registered with the :meth:`.Bot.add_cog` call. |
|||
- Cogs are subsequently removed with the :meth:`.Bot.remove_cog` call. |
|||
|
|||
It should be noted that cogs are typically used alongside with :ref:`ext_commands_extensions`. |
|||
|
|||
Quick Example |
|||
--------------- |
|||
|
|||
This example cog defines a ``Greetings`` category for your commands, with a single :ref:`command <ext_commands_commands>` named ``hello`` as well as a listener to listen to an :ref:`Event <discord-api-events>`. |
|||
|
|||
.. code-block:: python3 |
|||
|
|||
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('Welcome {0.mention}.'.format(member)) |
|||
|
|||
@commands.command() |
|||
async def hello(self, ctx, *, member: discord.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('Hello {0.name}~'.format(member)) |
|||
else: |
|||
await ctx.send('Hello {0.name}... This feels familiar.'.format(member)) |
|||
self._last_member = member |
|||
|
|||
A couple of technical notes to take into consideration: |
|||
|
|||
- All listeners must be explicitly marked via decorator, :meth:`~.commands.Cog.listener`. |
|||
- The name of the cog is automatically derived from the class name but can be overridden. See :ref:`ext_commands_cogs_meta_options`. |
|||
- All commands must now take a ``self`` parameter to allow usage of instance attributes that can be used to maintain state. |
|||
|
|||
Cog Registration |
|||
------------------- |
|||
|
|||
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:`~.commands.Bot.add_cog` method. |
|||
|
|||
.. code-block:: python3 |
|||
|
|||
bot.add_cog(Greetings(bot)) |
|||
|
|||
This binds the cog to the bot, adding all commands and listeners to the bot automatically. |
|||
|
|||
Note that we reference the cog by name, which we can override through :ref:`ext_commands_cogs_meta_options`. So if we ever want to remove the cog eventually, we would have to do the following. |
|||
|
|||
.. code-block:: python3 |
|||
|
|||
bot.remove_cog('Greetings') |
|||
|
|||
Using Cogs |
|||
------------- |
|||
|
|||
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: |
|||
|
|||
.. code-block:: python3 |
|||
:emphasize-lines: 22,24 |
|||
|
|||
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) |
|||
|
|||
.. _ext_commands_cogs_special_methods: |
|||
|
|||
Special Methods |
|||
----------------- |
|||
|
|||
As cogs get more complicated and have more commands, there comes a point where we want to customise the behaviour of the entire cog or bot. |
|||
|
|||
They are as follows: |
|||
|
|||
- :meth:`.Cog.cog_unload` |
|||
- :meth:`.Cog.cog_check` |
|||
- :meth:`.Cog.cog_command_error` |
|||
- :meth:`.Cog.cog_before_invoke` |
|||
- :meth:`.Cog.cog_after_invoke` |
|||
- :meth:`.Cog.bot_check` |
|||
- :meth:`.Cog.bot_check_once` |
|||
|
|||
You can visit the reference to get more detail. |
|||
|
|||
.. _ext_commands_cogs_meta_options: |
|||
|
|||
Meta Options |
|||
-------------- |
|||
|
|||
At the heart of a cog resides a metaclass, :class:`.commands.CogMeta`, which can take various options to customise some of the behaviour. To do this, we pass keyword arguments to the class definition line. For example, to change the cog name we can pass the ``name`` keyword argument as follows: |
|||
|
|||
.. code-block:: python3 |
|||
|
|||
class MyCog(commands.Cog, name='My Cog'): |
|||
pass |
|||
|
|||
To see more options that you can set, see the documentation of :class:`.commands.CogMeta`. |
|||
|
|||
Inspection |
|||
------------ |
|||
|
|||
Since cogs ultimately are classes, we have some tools to help us inspect certain properties of the cog. |
|||
|
|||
|
|||
To get a :class:`tuple` of commands, we can use :meth:`.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 well, we can use the :meth:`.Cog.walk_commands` generator. :: |
|||
|
|||
>>> print([c.qualified_name for c in cog.walk_commands()]) |
|||
|
|||
To do the same with listeners, we can query them with :meth:`.Cog.get_listeners`. This returns a list of tuples -- the first element being the listener name and the second one being the actual function itself. :: |
|||
|
|||
>>> for name, func in cog.get_listeners(): |
|||
... print(name, '->', func) |
|||
|
@ -0,0 +1,65 @@ |
|||
.. currentmodule:: discord |
|||
|
|||
.. _ext_commands_extensions: |
|||
|
|||
Extensions |
|||
============= |
|||
|
|||
There comes a time in the bot development when you want to extend the bot functionality at run-time and quickly unload and reload code (also called hot-reloading). The command framework comes with this ability built-in, with a concept called **extensions**. |
|||
|
|||
Primer |
|||
-------- |
|||
|
|||
An extension at its core is a python file with an entry point called ``setup``. This setup must be a plain Python function (not a coroutine). It takes a single parameter -- the :class:`~.commands.Bot` that loads the extension. |
|||
|
|||
An example extension looks like this: |
|||
|
|||
.. code-block:: python3 |
|||
:caption: hello.py |
|||
:emphasize-lines: 7,8 |
|||
|
|||
from discord.ext import commands |
|||
|
|||
@commands.command() |
|||
async def hello(ctx): |
|||
await ctx.send('Hello {0.display_name}.'.format(ctx.author)) |
|||
|
|||
def setup(bot): |
|||
bot.add_command(hello) |
|||
|
|||
In this example we define a simple command, and when the extension is loaded this command is added to the bot. Now the final step to this is loading the extension, which we do by calling :meth:`.commands.Bot.load_extension`. To load this extension we call ``bot.load_extension('hello')``. |
|||
|
|||
.. admonition:: Cogs |
|||
:class: helpful |
|||
|
|||
Extensions are usually used in conjunction with cogs. To read more about them, check out the documentation, :ref:`ext_commands_cogs`. |
|||
|
|||
.. note:: |
|||
|
|||
Extension paths are ultimately similar to the import mechanism. What this means is that if there is a folder, then it must be dot-qualified. For example to load an extension in ``plugins/hello.py`` then we use the string ``plugins.hello``. |
|||
|
|||
Reloading |
|||
----------- |
|||
|
|||
The act of reloading an extension is actually quite simple -- it is as simple as unloading it and then reloading it. |
|||
|
|||
.. code-block:: python3 |
|||
|
|||
>>> bot.unload_extension('hello') |
|||
>>> bot.load_extension('hello') |
|||
|
|||
Once we remove and load the extension, any changes that we did will be applied upon load. This is useful if we want to add or remove functionality without restarting our bot. |
|||
|
|||
Cleaning Up |
|||
------------- |
|||
|
|||
Although rare, sometimes an extension needs to clean-up or know when it's being unloaded. For cases like these, there is another entry point named ``teardown`` which is similar to ``setup`` except called when the extension is unloaded. |
|||
|
|||
.. code-block:: python3 |
|||
:caption: basic_ext.py |
|||
|
|||
def setup(bot): |
|||
print('I am being loaded!') |
|||
|
|||
def teardown(bot): |
|||
print('I am being unloaded!') |
Loading…
Reference in new issue