1.0 버전으로 이전하기¶
1.0 버전은 전체적인 재설계로 인해 구버전과 크게 달라졌습니다.
모든 의도와 목적들을 위한 변경 점들은 매우 방대하고 기므로,이것은 완전히 새로운 라이브러리가 되었습니다.
재설계에는 여러 가지 요소들을 더 쉽게, 그리고 더 자연스럽게 만드는 것이 포함됩니다.이러한 작업은 어떤 일을 하기 위해 Client
의 객체를 요구하는 대신에 models 위에서 완료됩니다.
파이썬의 버전 변화¶
개발을 더 쉽게 만들기 위해, 그리고 우리가 의존하는 라이브러리들이3.7 이상의 버전들을 지원하는 것을 허락하기 위해 버전을 올리는 것을 허락하기 위해, discord.py는3.5.3 아래의 파이썬 버전들을 지원하지 않기로 했습니다. 이것은 본질적으로 파이썬 3.4버전을 지원하는 일이 취소되었음 을 의미합니다.
주요 모델 변화¶
아래는 1.0 버전에서 발생한 주요 모델들의 변경 점들입니다.
Snowflake는 정수형입니다.¶
1.0 이전 버전에서는, 모든 snowflake들은(id
특성) 문자열이었습니다. 이것은 int
로 변경되었습니다.
간단한 예제입니다:
# before
ch = client.get_channel('84319995256905728')
if message.author.id == '80528701850124288':
...
# after
ch = client.get_channel(84319995256905728)
if message.author.id == 80528701850124288:
...
이 변경 점은 ID를 따옴표로 감싸지 않게 만들어 공식 클라이언트에서 ID를 복사하는 기능을 사용했을 때 발생하는 오류의 수를 줄일 수 있게 합니다.또한, 이 변경 점은 내부적으로 JSON 대신 ETF가 사용될 수 있게 해 최적화를 했습니다.
Server는 이제 Guild입니다.¶
공식 API 문서는 《Server》의 개념을 《Guild》라고 부릅니다. API 문서와 더욱 일관되게 만들기 위해서, 이 모델은 Guild
로 개명되었고 이를 참조하는 모든 객체 또한 변경되었습니다.
아래는 변경된 항목들입니다.
이전 |
이후 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
모델들은¶
이전에 언급했듯이, 많은 기능이 Client
의 밖으로 이동해 각각의 model에 포함되었습니다.
변경된 항목들은 아래에 기재되어 있습니다.
이전 |
이후 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
제거됨 |
|
변화 없음 |
속성 변화¶
좀 더 일관되게 하려고, 속성으로 제공되던 특정 요소들은 메소드로 교체되었습니다.
다음과 같은 것들은 이제 속성이 아닌 메소드로 제공됩니다.
딕셔너리 값 변화¶
1.0 이전 버전에 모델들을 반환하던 총합 속성들은》딕셔너리 뷰》 객체를 반환하곤 했습니다.
그 결과, 딕셔너리가 당신이 그것을 반복하는 동안 크기를 바꾸면, 런타임에러가 발생해 작업을 충돌시킵니다. 이것을완화하기 위해, 《딕셔너리 뷰》 객체들은 리스트로 변경되었습니다.
The following views were changed to a list:
Client.users
(new in v1.0)Client.emojis
(new in v1.0)Guild.text_channels
(1.0버전에 새로 추가됨)Guild.voice_channels
(1.0버전에 새로 추가됨)
Voice State Changes¶
이전에, 0.11.0버전에서 VoiceState
클래스는 Member.voice
속성과 함께 음성 상태들을 참조하기 위해 추가되었습니다.
그러나, 이것은 사용자에게 잘 드러나지 않았습니다. 라이브러리가 메모리를 절약하도록 하기 위해, 음성 상태의 변화는 이제 더 가시적입니다.
The only way to access voice attributes is via the Member.voice
attribute. Note that if
the member does not have a voice state this attribute can be None
.
간단한 예제입니다:
# before
member.deaf
member.voice.voice_channel
# after
if member.voice: # can be None
member.voice.deaf
member.voice.channel
User and Member Type Split¶
In v1.0 to save memory, User
and Member
are no longer inherited. Instead, they are 《flattened》
by having equivalent properties that map out to the functional underlying User
. Thus, there is no functional
change in how they are used. However this breaks isinstance()
checks and thus is something to keep in mind.
These memory savings were accomplished by having a global User
cache, and as a positive consequence you
can now easily fetch a User
by their ID by using the new Client.get_user()
. You can also get a list
of all User
your client can see with Client.users
.
Channel Type Split¶
Prior to v1.0, channels were two different types, Channel
and PrivateChannel
with a is_private
property to help differentiate between them.
In order to save memory the channels have been split into 4 different types:
TextChannel
for guild text channels.VoiceChannel
for guild voice channels.DMChannel
for DM channels with members.GroupChannel
for Group DM channels with members.
With this split came the removal of the is_private
attribute. You should now use isinstance()
.
The types are split into two different Abstract Base Classes:
abc.GuildChannel
for guild channels.abc.PrivateChannel
for private channels (DMs and group DMs).
So to check if something is a guild channel you would do:
isinstance(channel, discord.abc.GuildChannel)
And to check if it’s a private channel you would do:
isinstance(channel, discord.abc.PrivateChannel)
Of course, if you’re looking for only a specific type you can pass that too, e.g.
isinstance(channel, discord.TextChannel)
With this type split also came event changes, which are enumerated in Event Changes.
Miscellaneous Model Changes¶
There were lots of other things added or removed in the models in general.
They will be enumerated here.
Removed
Client.login()
no longer accepts email and password logins.Use a token and
bot=False
.
Client.get_all_emojis
Use
Client.emojis
instead.
Client.messages
Use read-only
Client.cached_messages
instead.
Client.wait_for_message
andClient.wait_for_reaction
are gone.Use
Client.wait_for()
instead.
Channel.voice_members
Use
VoiceChannel.members
instead.
Channel.is_private
Use
isinstance
instead with one of the Abstract Base Classes instead.e.g.
isinstance(channel, discord.abc.GuildChannel)
will check if it isn’t a private channel.
Client.accept_invite
There is no replacement for this one. This functionality is deprecated API wise.
Guild.default_channel
/Server.default_channel
andChannel.is_default
The concept of a default channel was removed from Discord. See #329.
Message.edited_timestamp
Use
Message.edited_at
instead.
Message.timestamp
Use
Message.created_at
instead.
Colour.to_tuple()
Use
Colour.to_rgb()
instead.
Permissions.view_audit_logs
Use
Permissions.view_audit_log
instead.
Member.game
Use
Member.activities
instead.
Guild.role_hierarchy
/Server.role_hierarchy
Use
Guild.roles
instead. Note that while sorted, it is in the opposite order of what the oldGuild.role_hierarchy
used to be.
Changed
Member.avatar_url
andUser.avatar_url
now return the default avatar if a custom one is not set.Message.embeds
is now a list ofEmbed
instead ofdict
objects.Message.attachments
is now a list ofAttachment
instead ofdict
object.Guild.roles
is now sorted through hierarchy. The first element is always the@everyone
role.
Added
Attachment
to represent a discord attachment.CategoryChannel
to represent a channel category.VoiceChannel.members
for fetching members connected to a voice channel.TextChannel.members
for fetching members that can see the channel.Role.members
for fetching members that have the role.Guild.text_channels
for fetching text channels only.Guild.voice_channels
for fetching voice channels only.Guild.categories
for fetching channel categories only.TextChannel.category
andVoiceChannel.category
to get the category a channel belongs to.Guild.by_category()
to get channels grouped by their category.Guild.chunked
to check member chunking status.Guild.explicit_content_filter
to fetch the content filter.Guild.shard_id
to get a guild’s Shard ID if you’re sharding.Client.users
to get all visibleUser
instances.Client.get_user()
to get aUser
by ID.User.avatar_url_as()
to get an avatar in a specific size or format.Guild.vanity_invite()
to fetch the guild’s vanity invite.Guild.audit_logs()
to fetch the guild’s audit logs.Message.webhook_id
to fetch the message’s webhook ID.Message.activity
andMessage.application
for Rich Presence related information.TextChannel.is_nsfw()
to check if a text channel is NSFW.Colour.from_rgb()
to construct aColour
from RGB tuple.Guild.get_role()
to get a role by its ID.
Sending Messages¶
One of the changes that were done was the merger of the previous Client.send_message
and Client.send_file
functionality into a single method, send()
.
Basically:
# before
await client.send_message(channel, 'Hello')
# after
await channel.send('Hello')
This supports everything that the old send_message
supported such as embeds:
e = discord.Embed(title='foo')
await channel.send('Hello', embed=e)
There is a caveat with sending files however, as this functionality was expanded to support multiple
file attachments, you must now use a File
pseudo-namedtuple to upload a single file.
# before
await client.send_file(channel, 'cool.png', filename='testing.png', content='Hello')
# after
await channel.send('Hello', file=discord.File('cool.png', 'testing.png'))
This change was to facilitate multiple file uploads:
my_files = [
discord.File('cool.png', 'testing.png'),
discord.File(some_fp, 'cool_filename.png'),
]
await channel.send('Your images:', files=my_files)
Asynchronous Iterators¶
Prior to v1.0, certain functions like Client.logs_from
would return a different type if done in Python 3.4 or 3.5+.
In v1.0, this change has been reverted and will now return a singular type meeting an abstract concept called
AsyncIterator
.
This allows you to iterate over it like normal:
async for message in channel.history():
print(message)
Or turn it into a list:
messages = await channel.history().flatten()
for message in messages:
print(message)
A handy aspect of returning AsyncIterator
is that it allows you to chain functions together such as
AsyncIterator.map()
or AsyncIterator.filter()
:
async for m_id in channel.history().filter(lambda m: m.author == client.user).map(lambda m: m.id):
print(m_id)
The functions passed to AsyncIterator.map()
or AsyncIterator.filter()
can be either coroutines or regular
functions.
You can also get single elements a la discord.utils.find()
or discord.utils.get()
via
AsyncIterator.get()
or AsyncIterator.find()
:
my_last_message = await channel.history().get(author=client.user)
The following return AsyncIterator
:
Event Changes¶
A lot of events have gone through some changes.
Many events with server
in the name were changed to use guild
instead.
Before:
on_server_join
on_server_remove
on_server_update
on_server_role_create
on_server_role_delete
on_server_role_update
on_server_emojis_update
on_server_available
on_server_unavailable
After:
The on_voice_state_update()
event has received an argument change.
Before:
async def on_voice_state_update(before, after)
After:
async def on_voice_state_update(member, before, after)
Instead of two Member
objects, the new event takes one Member
object and two VoiceState
objects.
The on_guild_emojis_update()
event has received an argument change.
Before:
async def on_guild_emojis_update(before, after)
After:
async def on_guild_emojis_update(guild, before, after)
The first argument is now the Guild
that the emojis were updated from.
The on_member_ban()
event has received an argument change as well:
Before:
async def on_member_ban(member)
After:
async def on_member_ban(guild, user)
As part of the change, the event can either receive a User
or Member
. To help in the cases that have
User
, the Guild
is provided as the first parameter.
The on_channel_
events have received a type level split (see Channel Type Split).
Before:
on_channel_delete
on_channel_create
on_channel_update
After:
The on_guild_channel_
events correspond to abc.GuildChannel
being updated (i.e. TextChannel
and VoiceChannel
) and the on_private_channel_
events correspond to abc.PrivateChannel
being
updated (i.e. DMChannel
and GroupChannel
).
Voice Changes¶
Voice sending has gone through a complete redesign.
In particular:
Connection is done through
VoiceChannel.connect()
instead ofClient.join_voice_channel
.You no longer create players and operate on them (you no longer store them).
You instead request
VoiceClient
to play anAudioSource
viaVoiceClient.play()
.There are different built-in
AudioSource
s.FFmpegPCMAudio
is the equivalent ofcreate_ffmpeg_player
create_ffmpeg_player/create_stream_player/create_ytdl_player have all been removed.
The goal is to create
AudioSource
instead.
Using
VoiceClient.play()
will not return anAudioPlayer
.The
after
parameter now takes a single parameter (the error).
Basically:
Before:
vc = await client.join_voice_channel(channel)
player = vc.create_ffmpeg_player('testing.mp3', after=lambda: print('done'))
player.start()
player.is_playing()
player.pause()
player.resume()
player.stop()
# ...
After:
vc = await channel.connect()
vc.play(discord.FFmpegPCMAudio('testing.mp3'), after=lambda e: print('done', e))
vc.is_playing()
vc.pause()
vc.resume()
vc.stop()
# ...
With the changed AudioSource
design, you can now change the source that the VoiceClient
is
playing at runtime via VoiceClient.source
.
For example, you can add a PCMVolumeTransformer
to allow changing the volume:
vc.source = discord.PCMVolumeTransformer(vc.source)
vc.source.volume = 0.6
An added benefit of the redesign is that it will be much more resilient towards reconnections:
The voice websocket will now automatically re-connect and re-do the handshake when disconnected.
The initial connect handshake will now retry up to 5 times so you no longer get as many
asyncio.TimeoutError
.Audio will now stop and resume when a disconnect is found.
This includes changing voice regions etc.
Waiting For Events¶
Prior to v1.0, the machinery for waiting for an event outside of the event itself was done through two different
functions, Client.wait_for_message
and Client.wait_for_reaction
. One problem with one such approach is that it did
not allow you to wait for events outside of the ones provided by the library.
In v1.0 the concept of waiting for another event has been generalised to work with any event as Client.wait_for()
.
For example, to wait for a message:
# before
msg = await client.wait_for_message(author=message.author, channel=message.channel)
# after
def pred(m):
return m.author == message.author and m.channel == message.channel
msg = await client.wait_for('message', check=pred)
To facilitate multiple returns, Client.wait_for()
returns either a single argument, no arguments, or a tuple of
arguments.
For example, to wait for a reaction:
reaction, user = await client.wait_for('reaction_add', check=lambda r, u: u.id == 176995180300206080)
# use user and reaction
Since this function now can return multiple arguments, the timeout
parameter will now raise a asyncio.TimeoutError
when reached instead of setting the return to None
. For example:
def pred(m):
return m.author == message.author and m.channel == message.channel
try:
msg = await client.wait_for('message', check=pred, timeout=60.0)
except asyncio.TimeoutError:
await channel.send('You took too long...')
else:
await channel.send('You said {0.content}, {0.author}.'.format(msg))
Upgraded Dependencies¶
Following v1.0 of the library, we’ve updated our requirements to aiohttp v2.0 or higher.
Since this is a backwards incompatible change, it is recommended that you see the changes and the Migration to 2.x pages for details on the breaking changes in aiohttp.
Of the most significant for common users is the removal of helper functions such as:
aiohttp.get
aiohttp.post
aiohttp.delete
aiohttp.patch
aiohttp.head
aiohttp.put
aiohttp.request
It is recommended that you create a session instead:
async with aiohttp.ClientSession() as sess:
async with sess.get('url') as resp:
# work with resp
Since it is better to not create a session for every request, you should store it in a variable and then call
session.close
on it when it needs to be disposed.
Connection Improvements¶
In v1.0, the auto reconnection logic has been powered up significantly.
Client.connect()
has gained a new keyword argument, reconnect
that defaults to True
which controls
the reconnect logic. When enabled, the client will automatically reconnect in all instances of your internet going
offline or Discord going offline with exponential back-off.
Client.run()
and Client.start()
gains this keyword argument as well, but for most cases you will not
need to specify it unless turning it off.
Command Extension Changes¶
Due to the 모델들은 changes, some of the design of the extension module had to undergo some design changes as well.
Context Changes¶
In v1.0, the Context
has received a lot of changes with how it’s retrieved and used.
The biggest change is that pass_context=True
no longer exists, Context
is always passed. Ergo:
# before
@bot.command()
async def foo():
await bot.say('Hello')
# after
@bot.command()
async def foo(ctx):
await ctx.send('Hello')
The reason for this is because Context
now meets the requirements of abc.Messageable
. This
makes it have similar functionality to TextChannel
or DMChannel
. Using send()
will either DM the user in a DM context or send a message in the channel it was in, similar to the old bot.say
functionality. The old helpers have been removed in favour of the new abc.Messageable
interface. See
Removed Helpers for more information.
Since the Context
is now passed by default, several shortcuts have been added:
New Shortcuts
ctx.author
is a shortcut forctx.message.author
.ctx.guild
is a shortcut forctx.message.guild
.ctx.channel
is a shortcut forctx.message.channel
.ctx.me
is a shortcut forctx.message.guild.me
orctx.bot.user
.ctx.voice_client
is a shortcut forctx.message.guild.voice_client
.
New Functionality
Context.reinvoke()
to invoke a command again.This is useful for bypassing cooldowns.
Context.valid
to check if a context can be invoked withBot.invoke()
.Context.send_help()
to show the help command for an entity using the newHelpCommand
system.This is useful if you want to show the user help if they misused a command.
Subclassing Context¶
In v1.0, there is now the ability to subclass Context
and use it instead of the default
provided one.
For example, if you want to add some functionality to the context:
class MyContext(commands.Context):
@property
def secret(self):
return 'my secret here'
Then you can use get_context()
inside on_message()
with combination with
invoke()
to use your custom context:
class MyBot(commands.Bot):
async def on_message(self, message):
ctx = await self.get_context(message, cls=MyContext)
await self.invoke(ctx)
Now inside your commands you will have access to your custom context:
@bot.command()
async def secret(ctx):
await ctx.send(ctx.secret)
Removed Helpers¶
With the new Context
changes, a lot of message sending helpers have been removed.
For a full list of changes, see below:
이전 |
이후 |
|
|
|
|
|
|
|
|
|
No replacement. |
Command Changes¶
As mentioned earlier, the first command change is that pass_context=True
no longer
exists, so there is no need to pass this as a parameter.
Another change is the removal of no_pm=True
. Instead, use the new guild_only()
built-in
check.
The commands
attribute of Bot
and Group
have been changed from a
dictionary to a set that does not have aliases. To retrieve the previous dictionary behaviour, use all_commands
instead.
Command instances have gained new attributes and properties:
signature
to get the signature of the command.usage
, an attribute to override the default signature.root_parent
to get the root parent group of a subcommand.
For Group
and Bot
the following changed:
Changed
commands
to be aset
without aliases.Use
all_commands
to get the olddict
with all commands.
Check Changes¶
Prior to v1.0, check()
s could only be synchronous. As of v1.0 checks can now be coroutines.
Along with this change, a couple new checks were added.
guild_only()
replaces the oldno_pm=True
functionality.is_owner()
uses theClient.application_info()
endpoint by default to fetch owner ID.This is actually powered by a different function,
is_owner()
.You can set the owner ID yourself by setting
Bot.owner_id
.
is_nsfw()
checks if the channel the command is in is a NSFW channel.This is powered by the new
TextChannel.is_nsfw()
method.
Event Changes¶
All command extension events have changed.
Before:
on_command(command, ctx)
on_command_completion(command, ctx)
on_command_error(error, ctx)
After:
on_command(ctx)
on_command_completion(ctx)
on_command_error(ctx, error)
The extraneous command
parameter in on_command()
and on_command_completion()
have been removed. The Command
instance was not kept up-to date so it was incorrect. In order to get
the up to date Command
instance, use the Context.command
attribute.
The error handlers, either Command.error()
or on_command_error()
,
have been re-ordered to use the Context
as its first parameter to be consistent with other events
and commands.
HelpFormatter and Help Command Changes¶
The HelpFormatter
class has been removed. It has been replaced with a HelpCommand
class. This class now stores all the command handling and processing of the help command.
The help command is now stored in the Bot.help_command
attribute. As an added extension, you can disable the help command completely by assigning the attribute to None
or passing it at __init__
as help_command=None
.
The new interface allows the help command to be customised through special methods that can be overridden.
HelpCommand.send_bot_help()
Called when the user requested for help with the entire bot.
HelpCommand.send_cog_help()
Called when the user requested for help with a specific cog.
HelpCommand.send_group_help()
Called when the user requested for help with a
Group
HelpCommand.send_command_help()
Called when the user requested for help with a
Command
HelpCommand.get_destination()
Called to know where to send the help messages. Useful for deciding whether to DM or not.
HelpCommand.command_not_found()
A function (or coroutine) that returns a presentable no command found string.
HelpCommand.subcommand_not_found()
A function (or coroutine) that returns a string when a subcommand is not found.
HelpCommand.send_error_message()
A coroutine that gets passed the result of
HelpCommand.command_not_found()
andHelpCommand.subcommand_not_found()
.By default it just sends the message. But you can, for example, override it to put it in an embed.
HelpCommand.on_help_command_error()
The error handler for the help command if you want to add one.
HelpCommand.prepare_help_command()
A coroutine that is called right before the help command processing is done.
Certain subclasses can implement more customisable methods.
The old HelpFormatter
was replaced with DefaultHelpCommand
, which implements all of the logic of the old help command. The customisable methods can be found in the accompanying documentation.
The library now provides a new more minimalistic HelpCommand
implementation that doesn’t take as much space, MinimalHelpCommand
. The customisable methods can also be found in the accompanying documentation.
A frequent request was if you could associate a help command with a cog. The new design allows for dynamically changing of cog through binding it to the HelpCommand.cog
attribute. After this assignment the help command will pretend to be part of the cog and everything should work as expected. When the cog is unloaded then the help command will be 《unbound》 from the cog.
For example, to implement a HelpCommand
in a cog, the following snippet can be used.
class MyHelpCommand(commands.MinimalHelpCommand):
def get_command_signature(self, command):
return '{0.clean_prefix}{1.qualified_name} {1.signature}'.format(self, command)
class MyCog(commands.Cog):
def __init__(self, bot):
self._original_help_command = bot.help_command
bot.help_command = MyHelpCommand()
bot.help_command.cog = self
def cog_unload(self):
self.bot.help_command = self._original_help_command
For more information, check out the relevant documentation.
Cog Changes¶
Cogs have completely been revamped. They are documented in Cogs as well.
Cogs are now required to have a base class, Cog
for future proofing purposes. This comes with special methods to customise some behaviour.
Cog.cog_unload()
This is called when a cog needs to do some cleanup, such as cancelling a task.
Cog.bot_check_once()
This registers a
Bot.check_once()
check.
Cog.bot_check()
This registers a regular
Bot.check()
check.
Cog.cog_check()
This registers a check that applies to every command in the cog.
Cog.cog_command_error()
This is a special error handler that is called whenever an error happens inside the cog.
Cog.cog_before_invoke()
andCog.cog_after_invoke()
A special method that registers a cog before and after invoke hook. More information can be found in Before and After Invocation Hooks.
Those that were using listeners, such as on_message
inside a cog will now have to explicitly mark them as such using the commands.Cog.listener()
decorator.
Along with that, cogs have gained the ability to have custom names through specifying it in the class definition line. More options can be found in the metaclass that facilitates all this, commands.CogMeta
.
An example cog with every special method registered and a custom name is as follows:
class MyCog(commands.Cog, name='Example Cog'):
def cog_unload(self):
print('cleanup goes here')
def bot_check(self, ctx):
print('bot check')
return True
def bot_check_once(self, ctx):
print('bot check once')
return True
async def cog_check(self, ctx):
print('cog local check')
return await ctx.bot.is_owner(ctx.author)
async def cog_command_error(self, ctx, error):
print('Error in {0.command.qualified_name}: {1}'.format(ctx, error))
async def cog_before_invoke(self, ctx):
print('cog local before: {0.command.qualified_name}'.format(ctx))
async def cog_after_invoke(self, ctx):
print('cog local after: {0.command.qualified_name}'.format(ctx))
@commands.Cog.listener()
async def on_message(self, message):
pass
Before and After Invocation Hooks¶
Commands have gained new before and after invocation hooks that allow you to do an action before and after a command is run.
They take a single parameter, Context
and they must be a coroutine.
They are on a global, per-cog, or per-command basis.
Basically:
# global hooks:
@bot.before_invoke
async def before_any_command(ctx):
# do something before a command is called
pass
@bot.after_invoke
async def after_any_command(ctx):
# do something after a command is called
pass
The after invocation is hook always called, regardless of an error in the command. This makes it ideal for some error handling or clean up of certain resources such a database connection.
The per-command registration is as follows:
@bot.command()
async def foo(ctx):
await ctx.send('foo')
@foo.before_invoke
async def before_foo_command(ctx):
# do something before the foo command is called
pass
@foo.after_invoke
async def after_foo_command(ctx):
# do something after the foo command is called
pass
The special cog method for these is Cog.cog_before_invoke()
and Cog.cog_after_invoke()
, e.g.:
class MyCog(commands.Cog):
async def cog_before_invoke(self, ctx):
ctx.secret_cog_data = 'foo'
async def cog_after_invoke(self, ctx):
print('{0.command} is done...'.format(ctx))
@commands.command()
async def foo(self, ctx):
await ctx.send(ctx.secret_cog_data)
To check if a command failed in the after invocation hook, you can use
Context.command_failed
.
The invocation order is as follows:
Command local before invocation hook
Cog local before invocation hook
Global before invocation hook
The actual command
Command local after invocation hook
Cog local after invocation hook
Global after invocation hook
Converter Changes¶
Prior to v1.0, a converter was a type hint that could be a callable that could be invoked with a singular argument denoting the argument passed by the user as a string.
This system was eventually expanded to support a Converter
system to
allow plugging in the Context
and do more complicated conversions such
as the built-in 《discord》 converters.
In v1.0 this converter system was revamped to allow instances of Converter
derived
classes to be passed. For consistency, the convert()
method was changed to
always be a coroutine and will now take the two arguments as parameters.
Essentially, before:
class MyConverter(commands.Converter):
def convert(self):
return self.ctx.message.server.me
After:
class MyConverter(commands.Converter):
async def convert(self, ctx, argument):
return ctx.me
The command framework also got a couple new converters:
clean_content
this is akin toMessage.clean_content
which scrubs mentions.UserConverter
will now appropriately convertUser
only.ChannelConverter
is now split into two different converters.