diff --git a/docs/Python/doctrees/api.doctree b/docs/Python/doctrees/api.doctree new file mode 100644 index 00000000..d6d2bfac Binary files /dev/null and b/docs/Python/doctrees/api.doctree differ diff --git a/docs/Python/doctrees/discord.doctree b/docs/Python/doctrees/discord.doctree new file mode 100644 index 00000000..9361755b Binary files /dev/null and b/docs/Python/doctrees/discord.doctree differ diff --git a/docs/Python/doctrees/environment.pickle b/docs/Python/doctrees/environment.pickle new file mode 100644 index 00000000..b1ba9882 Binary files /dev/null and b/docs/Python/doctrees/environment.pickle differ diff --git a/docs/Python/doctrees/ext/commands/api.doctree b/docs/Python/doctrees/ext/commands/api.doctree new file mode 100644 index 00000000..ea4be0b4 Binary files /dev/null and b/docs/Python/doctrees/ext/commands/api.doctree differ diff --git a/docs/Python/doctrees/ext/commands/cogs.doctree b/docs/Python/doctrees/ext/commands/cogs.doctree new file mode 100644 index 00000000..89b581f2 Binary files /dev/null and b/docs/Python/doctrees/ext/commands/cogs.doctree differ diff --git a/docs/Python/doctrees/ext/commands/commands.doctree b/docs/Python/doctrees/ext/commands/commands.doctree new file mode 100644 index 00000000..2112459f Binary files /dev/null and b/docs/Python/doctrees/ext/commands/commands.doctree differ diff --git a/docs/Python/doctrees/ext/commands/extensions.doctree b/docs/Python/doctrees/ext/commands/extensions.doctree new file mode 100644 index 00000000..07fe1beb Binary files /dev/null and b/docs/Python/doctrees/ext/commands/extensions.doctree differ diff --git a/docs/Python/doctrees/ext/commands/index.doctree b/docs/Python/doctrees/ext/commands/index.doctree new file mode 100644 index 00000000..8fd81b26 Binary files /dev/null and b/docs/Python/doctrees/ext/commands/index.doctree differ diff --git a/docs/Python/doctrees/ext/commands/slash-commands.doctree b/docs/Python/doctrees/ext/commands/slash-commands.doctree new file mode 100644 index 00000000..dd303288 Binary files /dev/null and b/docs/Python/doctrees/ext/commands/slash-commands.doctree differ diff --git a/docs/Python/doctrees/ext/tasks/index.doctree b/docs/Python/doctrees/ext/tasks/index.doctree new file mode 100644 index 00000000..1200a86f Binary files /dev/null and b/docs/Python/doctrees/ext/tasks/index.doctree differ diff --git a/docs/Python/doctrees/faq.doctree b/docs/Python/doctrees/faq.doctree new file mode 100644 index 00000000..32560c6a Binary files /dev/null and b/docs/Python/doctrees/faq.doctree differ diff --git a/docs/Python/doctrees/index.doctree b/docs/Python/doctrees/index.doctree new file mode 100644 index 00000000..98b96f32 Binary files /dev/null and b/docs/Python/doctrees/index.doctree differ diff --git a/docs/Python/doctrees/intents.doctree b/docs/Python/doctrees/intents.doctree new file mode 100644 index 00000000..f86e908a Binary files /dev/null and b/docs/Python/doctrees/intents.doctree differ diff --git a/docs/Python/doctrees/intro.doctree b/docs/Python/doctrees/intro.doctree new file mode 100644 index 00000000..88dab010 Binary files /dev/null and b/docs/Python/doctrees/intro.doctree differ diff --git a/docs/Python/doctrees/logging.doctree b/docs/Python/doctrees/logging.doctree new file mode 100644 index 00000000..4d88fc36 Binary files /dev/null and b/docs/Python/doctrees/logging.doctree differ diff --git a/docs/Python/doctrees/migrating.doctree b/docs/Python/doctrees/migrating.doctree new file mode 100644 index 00000000..6c83a2f8 Binary files /dev/null and b/docs/Python/doctrees/migrating.doctree differ diff --git a/docs/Python/doctrees/migrating_to_async.doctree b/docs/Python/doctrees/migrating_to_async.doctree new file mode 100644 index 00000000..0627713a Binary files /dev/null and b/docs/Python/doctrees/migrating_to_async.doctree differ diff --git a/docs/Python/doctrees/quickstart.doctree b/docs/Python/doctrees/quickstart.doctree new file mode 100644 index 00000000..680c7246 Binary files /dev/null and b/docs/Python/doctrees/quickstart.doctree differ diff --git a/docs/Python/doctrees/version_guarantees.doctree b/docs/Python/doctrees/version_guarantees.doctree new file mode 100644 index 00000000..92b8e223 Binary files /dev/null and b/docs/Python/doctrees/version_guarantees.doctree differ diff --git a/docs/Python/doctrees/whats_new.doctree b/docs/Python/doctrees/whats_new.doctree new file mode 100644 index 00000000..136fa355 Binary files /dev/null and b/docs/Python/doctrees/whats_new.doctree differ diff --git a/docs/Python/html/_images/snake.svg b/docs/Python/html/_images/snake.svg new file mode 100644 index 00000000..aa741440 --- /dev/null +++ b/docs/Python/html/_images/snake.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + diff --git a/docs/Python/html/_images/snake_dark.svg b/docs/Python/html/_images/snake_dark.svg new file mode 100644 index 00000000..12022af4 --- /dev/null +++ b/docs/Python/html/_images/snake_dark.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + diff --git a/docs/Python/html/_sources/api.rst.txt b/docs/Python/html/_sources/api.rst.txt new file mode 100644 index 00000000..76468601 --- /dev/null +++ b/docs/Python/html/_sources/api.rst.txt @@ -0,0 +1,4242 @@ +.. currentmodule:: discord + +API Reference +=============== + +The following section outlines the API of discord.py. + +.. note:: + + This module uses the Python logging module to log diagnostic and errors + in an output independent way. If the logging module is not configured, + these logs will not be output anywhere. See :ref:`logging_setup` for + more information on how to set up and use the logging module with + discord.py. + +Version Related Info +--------------------- + +There are two main ways to query version information about the library. For guarantees, check :ref:`version_guarantees`. + +.. data:: version_info + + A named tuple that is similar to :obj:`py:sys.version_info`. + + Just like :obj:`py:sys.version_info` the valid values for ``releaselevel`` are + 'alpha', 'beta', 'candidate' and 'final'. + +.. data:: __version__ + + A string representation of the version. e.g. ``'1.0.0rc1'``. This is based + off of :pep:`440`. + +Clients +-------- + +Client +~~~~~~~ + +.. attributetable:: Client + +.. autoclass:: Client + :members: + :exclude-members: fetch_guilds, event + + .. automethod:: Client.event() + :decorator: + + .. automethod:: Client.fetch_guilds + :async-for: + +AutoShardedClient +~~~~~~~~~~~~~~~~~~ + +.. attributetable:: AutoShardedClient + +.. autoclass:: AutoShardedClient + :members: + +Application Info +------------------ + +AppInfo +~~~~~~~~ + +.. attributetable:: AppInfo + +.. autoclass:: AppInfo() + :members: + +PartialAppInfo +~~~~~~~~~~~~~~~ + +.. attributetable:: PartialAppInfo + +.. autoclass:: PartialAppInfo() + :members: + +Team +~~~~~ + +.. attributetable:: Team + +.. autoclass:: Team() + :members: + +TeamMember +~~~~~~~~~~~ + +.. attributetable:: TeamMember + +.. autoclass:: TeamMember() + :members: + +Voice Related +--------------- + +VoiceClient +~~~~~~~~~~~~ + +.. attributetable:: VoiceClient + +.. autoclass:: VoiceClient() + :members: + :exclude-members: connect, on_voice_state_update, on_voice_server_update + +VoiceProtocol +~~~~~~~~~~~~~~~ + +.. attributetable:: VoiceProtocol + +.. autoclass:: VoiceProtocol + :members: + +AudioSource +~~~~~~~~~~~~ + +.. attributetable:: AudioSource + +.. autoclass:: AudioSource + :members: + +PCMAudio +~~~~~~~~~ + +.. attributetable:: PCMAudio + +.. autoclass:: PCMAudio + :members: + +FFmpegAudio +~~~~~~~~~~~~ + +.. attributetable:: FFmpegAudio + +.. autoclass:: FFmpegAudio + :members: + +FFmpegPCMAudio +~~~~~~~~~~~~~~~ + +.. attributetable:: FFmpegPCMAudio + +.. autoclass:: FFmpegPCMAudio + :members: + +FFmpegOpusAudio +~~~~~~~~~~~~~~~~ + +.. attributetable:: FFmpegOpusAudio + +.. autoclass:: FFmpegOpusAudio + :members: + +PCMVolumeTransformer +~~~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: PCMVolumeTransformer + +.. autoclass:: PCMVolumeTransformer + :members: + +Opus Library +~~~~~~~~~~~~~ + +.. autofunction:: discord.opus.load_opus + +.. autofunction:: discord.opus.is_loaded + +.. _discord-api-events: + +Event Reference +--------------- + +This section outlines the different types of events listened by :class:`Client`. + +There are two ways to register an event, the first way is through the use of +:meth:`Client.event`. The second way is through subclassing :class:`Client` and +overriding the specific events. For example: :: + + import discord + + class MyClient(discord.Client): + async def on_message(self, message): + if message.author == self.user: + return + + if message.content.startswith('$hello'): + await message.channel.send('Hello World!') + + +If an event handler raises an exception, :func:`on_error` will be called +to handle it, which defaults to print a traceback and ignoring the exception. + +.. warning:: + + All the events must be a |coroutine_link|_. If they aren't, then you might get unexpected + errors. In order to turn a function into a coroutine they must be ``async def`` + functions. + +Networking +~~~~~~~~~~~ + +.. function:: on_connect() + + Called when the client has successfully connected to Discord. This is not + the same as the client being fully prepared, see :func:`on_ready` for that. + + The warnings on :func:`on_ready` also apply. + +.. function:: on_shard_connect(shard_id) + + Similar to :func:`on_connect` except used by :class:`AutoShardedClient` + to denote when a particular shard ID has connected to Discord. + + .. versionadded:: 1.4 + + :param shard_id: The shard ID that has connected. + :type shard_id: :class:`int` + +.. function:: on_disconnect() + + Called when the client has disconnected from Discord, or a connection attempt to Discord has failed. + This could happen either through the internet being disconnected, explicit calls to close, + or Discord terminating the connection one way or the other. + + This function can be called many times without a corresponding :func:`on_connect` call. + +.. function:: on_shard_disconnect(shard_id) + + Similar to :func:`on_disconnect` except used by :class:`AutoShardedClient` + to denote when a particular shard ID has disconnected from Discord. + + .. versionadded:: 1.4 + + :param shard_id: The shard ID that has disconnected. + :type shard_id: :class:`int` + +.. function:: on_ready() + + Called when the client is done preparing the data received from Discord. Usually after login is successful + and the :attr:`Client.guilds` and co. are filled up. + + .. warning:: + + This function is not guaranteed to be the first event called. + Likewise, this function is **not** guaranteed to only be called + once. This library implements reconnection logic and thus will + end up calling this event whenever a RESUME request fails. + +.. function:: on_shard_ready(shard_id) + + Similar to :func:`on_ready` except used by :class:`AutoShardedClient` + to denote when a particular shard ID has become ready. + + :param shard_id: The shard ID that is ready. + :type shard_id: :class:`int` + +.. function:: on_resumed() + + Called when the client has resumed a session. + +.. function:: on_shard_resumed(shard_id) + + Similar to :func:`on_resumed` except used by :class:`AutoShardedClient` + to denote when a particular shard ID has resumed a session. + + .. versionadded:: 1.4 + + :param shard_id: The shard ID that has resumed. + :type shard_id: :class:`int` + +.. function:: on_error(event, *args, **kwargs) + + Usually when an event raises an uncaught exception, a traceback is + printed to stderr and the exception is ignored. If you want to + change this behaviour and handle the exception for whatever reason + yourself, this event can be overridden. Which, when done, will + suppress the default action of printing the traceback. + + The information of the exception raised and the exception itself can + be retrieved with a standard call to :func:`sys.exc_info`. + + If you want exception to propagate out of the :class:`Client` class + you can define an ``on_error`` handler consisting of a single empty + :ref:`raise statement `. Exceptions raised by ``on_error`` will not be + handled in any way by :class:`Client`. + + .. note:: + + ``on_error`` will only be dispatched to :meth:`Client.event`. + + It will not be received by :meth:`Client.wait_for`, or, if used, + :ref:`ext_commands_api_bot` listeners such as + :meth:`~ext.commands.Bot.listen` or :meth:`~ext.commands.Cog.listener`. + + :param event: The name of the event that raised the exception. + :type event: :class:`str` + + :param args: The positional arguments for the event that raised the + exception. + :param kwargs: The keyword arguments for the event that raised the + exception. + +.. function:: on_socket_event_type(event_type) + + Called whenever a websocket event is received from the WebSocket. + + This is mainly useful for logging how many events you are receiving + from the Discord gateway. + + .. versionadded:: 2.0 + + :param event_type: The event type from Discord that is received, e.g. ``'READY'``. + :type event_type: :class:`str` + +.. function:: on_socket_raw_receive(msg) + + Called whenever a message is completely received from the WebSocket, before + it's processed and parsed. This event is always dispatched when a + complete message is received and the passed data is not parsed in any way. + + This is only really useful for grabbing the WebSocket stream and + debugging purposes. + + This requires setting the ``enable_debug_events`` setting in the :class:`Client`. + + .. note:: + + This is only for the messages received from the client + WebSocket. The voice WebSocket will not trigger this event. + + :param msg: The message passed in from the WebSocket library. + :type msg: :class:`str` + +.. function:: on_socket_raw_send(payload) + + Called whenever a send operation is done on the WebSocket before the + message is sent. The passed parameter is the message that is being + sent to the WebSocket. + + This is only really useful for grabbing the WebSocket stream and + debugging purposes. + + This requires setting the ``enable_debug_events`` setting in the :class:`Client`. + + .. note:: + + This is only for the messages sent from the client + WebSocket. The voice WebSocket will not trigger this event. + + :param payload: The message that is about to be passed on to the + WebSocket library. It can be :class:`bytes` to denote a binary + message or :class:`str` to denote a regular text message. + +.. function:: on_typing(channel, user, when) + + Called when someone begins typing a message. + + The ``channel`` parameter can be a :class:`abc.Messageable` instance. + Which could either be :class:`TextChannel`, :class:`GroupChannel`, or + :class:`DMChannel`. + + If the ``channel`` is a :class:`TextChannel` then the ``user`` parameter + is a :class:`Member`, otherwise it is a :class:`User`. + + This requires :attr:`Intents.typing` to be enabled. + + :param channel: The location where the typing originated from. + :type channel: :class:`abc.Messageable` + :param user: The user that started typing. + :type user: Union[:class:`User`, :class:`Member`] + :param when: When the typing started as an aware datetime in UTC. + :type when: :class:`datetime.datetime` + +.. function:: on_raw_typing(payload) + + Called when someone begins typing a message. Unlike :func:`on_typing`, this is + called regardless if the user can be found or not. This most often happens + when a user types in DMs. + + This requires :attr:`Intents.typing` to be enabled. + + :param payload: The raw typing payload. + :type payload: :class:`RawTypingEvent` + +Messages +~~~~~~~~~ + +.. function:: on_message(message) + + Called when a :class:`Message` is created and sent. + + This requires :attr:`Intents.messages` to be enabled. + + .. warning:: + + Your bot's own messages and private messages are sent through this + event. This can lead cases of 'recursion' depending on how your bot was + programmed. If you want the bot to not reply to itself, consider + checking the user IDs. Note that :class:`~ext.commands.Bot` does not + have this problem. + + :param message: The current message. + :type message: :class:`Message` + +.. function:: on_message_delete(message) + + Called when a message is deleted. If the message is not found in the + internal message cache, then this event will not be called. + Messages might not be in cache if the message is too old + or the client is participating in high traffic guilds. + + If this occurs increase the :class:`max_messages ` parameter + or use the :func:`on_raw_message_delete` event instead. + + This requires :attr:`Intents.messages` to be enabled. + + :param message: The deleted message. + :type message: :class:`Message` + +.. function:: on_bulk_message_delete(messages) + + Called when messages are bulk deleted. If none of the messages deleted + are found in the internal message cache, then this event will not be called. + If individual messages were not found in the internal message cache, + this event will still be called, but the messages not found will not be included in + the messages list. Messages might not be in cache if the message is too old + or the client is participating in high traffic guilds. + + If this occurs increase the :class:`max_messages ` parameter + or use the :func:`on_raw_bulk_message_delete` event instead. + + This requires :attr:`Intents.messages` to be enabled. + + :param messages: The messages that have been deleted. + :type messages: List[:class:`Message`] + +.. function:: on_raw_message_delete(payload) + + Called when a message is deleted. Unlike :func:`on_message_delete`, this is + called regardless of the message being in the internal message cache or not. + + If the message is found in the message cache, + it can be accessed via :attr:`RawMessageDeleteEvent.cached_message` + + This requires :attr:`Intents.messages` to be enabled. + + :param payload: The raw event payload data. + :type payload: :class:`RawMessageDeleteEvent` + +.. function:: on_raw_bulk_message_delete(payload) + + Called when a bulk delete is triggered. Unlike :func:`on_bulk_message_delete`, this is + called regardless of the messages being in the internal message cache or not. + + If the messages are found in the message cache, + they can be accessed via :attr:`RawBulkMessageDeleteEvent.cached_messages` + + This requires :attr:`Intents.messages` to be enabled. + + :param payload: The raw event payload data. + :type payload: :class:`RawBulkMessageDeleteEvent` + +.. function:: on_message_edit(before, after) + + Called when a :class:`Message` receives an update event. If the message is not found + in the internal message cache, then these events will not be called. + Messages might not be in cache if the message is too old + or the client is participating in high traffic guilds. + + If this occurs increase the :class:`max_messages ` parameter + or use the :func:`on_raw_message_edit` event instead. + + The following non-exhaustive cases trigger this event: + + - A message has been pinned or unpinned. + - The message content has been changed. + - The message has received an embed. + + - For performance reasons, the embed server does not do this in a "consistent" manner. + + - The message's embeds were suppressed or unsuppressed. + - A call message has received an update to its participants or ending time. + + This requires :attr:`Intents.messages` to be enabled. + + :param before: The previous version of the message. + :type before: :class:`Message` + :param after: The current version of the message. + :type after: :class:`Message` + +.. function:: on_raw_message_edit(payload) + + Called when a message is edited. Unlike :func:`on_message_edit`, this is called + regardless of the state of the internal message cache. + + If the message is found in the message cache, + it can be accessed via :attr:`RawMessageUpdateEvent.cached_message`. The cached message represents + the message before it has been edited. For example, if the content of a message is modified and + triggers the :func:`on_raw_message_edit` coroutine, the :attr:`RawMessageUpdateEvent.cached_message` + will return a :class:`Message` object that represents the message before the content was modified. + + Due to the inherently raw nature of this event, the data parameter coincides with + the raw data given by the `gateway `_. + + Since the data payload can be partial, care must be taken when accessing stuff in the dictionary. + One example of a common case of partial data is when the ``'content'`` key is inaccessible. This + denotes an "embed" only edit, which is an edit in which only the embeds are updated by the Discord + embed server. + + This requires :attr:`Intents.messages` to be enabled. + + :param payload: The raw event payload data. + :type payload: :class:`RawMessageUpdateEvent` + +.. function:: on_reaction_add(reaction, user) + + Called when a message has a reaction added to it. Similar to :func:`on_message_edit`, + if the message is not found in the internal message cache, then this + event will not be called. Consider using :func:`on_raw_reaction_add` instead. + + .. note:: + + To get the :class:`Message` being reacted, access it via :attr:`Reaction.message`. + + This requires :attr:`Intents.reactions` to be enabled. + + .. note:: + + This doesn't require :attr:`Intents.members` within a guild context, + but due to Discord not providing updated user information in a direct message + it's required for direct messages to receive this event. + Consider using :func:`on_raw_reaction_add` if you need this and do not otherwise want + to enable the members intent. + + :param reaction: The current state of the reaction. + :type reaction: :class:`Reaction` + :param user: The user who added the reaction. + :type user: Union[:class:`Member`, :class:`User`] + +.. function:: on_raw_reaction_add(payload) + + Called when a message has a reaction added. Unlike :func:`on_reaction_add`, this is + called regardless of the state of the internal message cache. + + This requires :attr:`Intents.reactions` to be enabled. + + :param payload: The raw event payload data. + :type payload: :class:`RawReactionActionEvent` + +.. function:: on_reaction_remove(reaction, user) + + Called when a message has a reaction removed from it. Similar to on_message_edit, + if the message is not found in the internal message cache, then this event + will not be called. + + .. note:: + + To get the message being reacted, access it via :attr:`Reaction.message`. + + This requires both :attr:`Intents.reactions` and :attr:`Intents.members` to be enabled. + + .. note:: + + Consider using :func:`on_raw_reaction_remove` if you need this and do not want + to enable the members intent. + + :param reaction: The current state of the reaction. + :type reaction: :class:`Reaction` + :param user: The user who added the reaction. + :type user: Union[:class:`Member`, :class:`User`] + +.. function:: on_raw_reaction_remove(payload) + + Called when a message has a reaction removed. Unlike :func:`on_reaction_remove`, this is + called regardless of the state of the internal message cache. + + This requires :attr:`Intents.reactions` to be enabled. + + :param payload: The raw event payload data. + :type payload: :class:`RawReactionActionEvent` + +.. function:: on_reaction_clear(message, reactions) + + Called when a message has all its reactions removed from it. Similar to :func:`on_message_edit`, + if the message is not found in the internal message cache, then this event + will not be called. Consider using :func:`on_raw_reaction_clear` instead. + + This requires :attr:`Intents.reactions` to be enabled. + + :param message: The message that had its reactions cleared. + :type message: :class:`Message` + :param reactions: The reactions that were removed. + :type reactions: List[:class:`Reaction`] + +.. function:: on_raw_reaction_clear(payload) + + Called when a message has all its reactions removed. Unlike :func:`on_reaction_clear`, + this is called regardless of the state of the internal message cache. + + This requires :attr:`Intents.reactions` to be enabled. + + :param payload: The raw event payload data. + :type payload: :class:`RawReactionClearEvent` + +.. function:: on_reaction_clear_emoji(reaction) + + Called when a message has a specific reaction removed from it. Similar to :func:`on_message_edit`, + if the message is not found in the internal message cache, then this event + will not be called. Consider using :func:`on_raw_reaction_clear_emoji` instead. + + This requires :attr:`Intents.reactions` to be enabled. + + .. versionadded:: 1.3 + + :param reaction: The reaction that got cleared. + :type reaction: :class:`Reaction` + +.. function:: on_raw_reaction_clear_emoji(payload) + + Called when a message has a specific reaction removed from it. Unlike :func:`on_reaction_clear_emoji` this is called + regardless of the state of the internal message cache. + + This requires :attr:`Intents.reactions` to be enabled. + + .. versionadded:: 1.3 + + :param payload: The raw event payload data. + :type payload: :class:`RawReactionClearEmojiEvent` + +.. function:: on_interaction(interaction) + + Called when an interaction happened. + + This currently happens due to slash command invocations or components being used. + + .. warning:: + + This is a low level function that is not generally meant to be used. + If you are working with components, consider using the callbacks associated + with the :class:`~discord.ui.View` instead as it provides a nicer user experience. + + .. versionadded:: 2.0 + + :param interaction: The interaction data. + :type interaction: :class:`Interaction` + +.. function:: on_private_channel_update(before, after) + + Called whenever a private group DM is updated. e.g. changed name or topic. + + This requires :attr:`Intents.messages` to be enabled. + + :param before: The updated group channel's old info. + :type before: :class:`GroupChannel` + :param after: The updated group channel's new info. + :type after: :class:`GroupChannel` + +.. function:: on_private_channel_pins_update(channel, last_pin) + + Called whenever a message is pinned or unpinned from a private channel. + + :param channel: The private channel that had its pins updated. + :type channel: :class:`abc.PrivateChannel` + :param last_pin: The latest message that was pinned as an aware datetime in UTC. Could be ``None``. + :type last_pin: Optional[:class:`datetime.datetime`] + +.. function:: on_guild_channel_delete(channel) + on_guild_channel_create(channel) + + Called whenever a guild channel is deleted or created. + + Note that you can get the guild from :attr:`~abc.GuildChannel.guild`. + + This requires :attr:`Intents.guilds` to be enabled. + + :param channel: The guild channel that got created or deleted. + :type channel: :class:`abc.GuildChannel` + +.. function:: on_guild_channel_update(before, after) + + Called whenever a guild channel is updated. e.g. changed name, topic, permissions. + + This requires :attr:`Intents.guilds` to be enabled. + + :param before: The updated guild channel's old info. + :type before: :class:`abc.GuildChannel` + :param after: The updated guild channel's new info. + :type after: :class:`abc.GuildChannel` + +.. function:: on_guild_channel_pins_update(channel, last_pin) + + Called whenever a message is pinned or unpinned from a guild channel. + + This requires :attr:`Intents.guilds` to be enabled. + + :param channel: The guild channel that had its pins updated. + :type channel: Union[:class:`abc.GuildChannel`, :class:`Thread`] + :param last_pin: The latest message that was pinned as an aware datetime in UTC. Could be ``None``. + :type last_pin: Optional[:class:`datetime.datetime`] + +.. function:: on_thread_join(thread) + + Called whenever a thread is joined or created. Note that from the API's perspective there is no way to + differentiate between a thread being created or the bot joining a thread. + + Note that you can get the guild from :attr:`Thread.guild`. + + This requires :attr:`Intents.guilds` to be enabled. + + .. versionadded:: 2.0 + + :param thread: The thread that got joined. + :type thread: :class:`Thread` + +.. function:: on_thread_remove(thread) + + Called whenever a thread is removed. This is different from a thread being deleted. + + Note that you can get the guild from :attr:`Thread.guild`. + + This requires :attr:`Intents.guilds` to be enabled. + + .. warning:: + + Due to technical limitations, this event might not be called + as soon as one expects. Since the library tracks thread membership + locally, the API only sends updated thread membership status upon being + synced by joining a thread. + + .. versionadded:: 2.0 + + :param thread: The thread that got removed. + :type thread: :class:`Thread` + +.. function:: on_thread_delete(thread) + + Called whenever a thread is deleted. + + Note that you can get the guild from :attr:`Thread.guild`. + + This requires :attr:`Intents.guilds` to be enabled. + + .. versionadded:: 2.0 + + :param thread: The thread that got deleted. + :type thread: :class:`Thread` + +.. function:: on_thread_member_join(member) + on_thread_member_remove(member) + + Called when a :class:`ThreadMember` leaves or joins a :class:`Thread`. + + You can get the thread a member belongs in by accessing :attr:`ThreadMember.thread`. + + This requires :attr:`Intents.members` to be enabled. + + .. versionadded:: 2.0 + + :param member: The member who joined or left. + :type member: :class:`ThreadMember` + +.. function:: on_thread_update(before, after) + + Called whenever a thread is updated. + + This requires :attr:`Intents.guilds` to be enabled. + + .. versionadded:: 2.0 + + :param before: The updated thread's old info. + :type before: :class:`Thread` + :param after: The updated thread's new info. + :type after: :class:`Thread` + +.. function:: on_guild_integrations_update(guild) + + Called whenever an integration is created, modified, or removed from a guild. + + This requires :attr:`Intents.integrations` to be enabled. + + .. versionadded:: 1.4 + + :param guild: The guild that had its integrations updated. + :type guild: :class:`Guild` + +.. function:: on_integration_create(integration) + + Called when an integration is created. + + This requires :attr:`Intents.integrations` to be enabled. + + .. versionadded:: 2.0 + + :param integration: The integration that was created. + :type integration: :class:`Integration` + +.. function:: on_integration_update(integration) + + Called when an integration is updated. + + This requires :attr:`Intents.integrations` to be enabled. + + .. versionadded:: 2.0 + + :param integration: The integration that was created. + :type integration: :class:`Integration` + +.. function:: on_raw_integration_delete(payload) + + Called when an integration is deleted. + + This requires :attr:`Intents.integrations` to be enabled. + + .. versionadded:: 2.0 + + :param payload: The raw event payload data. + :type payload: :class:`RawIntegrationDeleteEvent` + +.. function:: on_webhooks_update(channel) + + Called whenever a webhook is created, modified, or removed from a guild channel. + + This requires :attr:`Intents.webhooks` to be enabled. + + :param channel: The channel that had its webhooks updated. + :type channel: :class:`abc.GuildChannel` + +.. function:: on_member_join(member) + on_member_remove(member) + + Called when a :class:`Member` leaves or joins a :class:`Guild`. + + This requires :attr:`Intents.members` to be enabled. + + :param member: The member who joined or left. + :type member: :class:`Member` + +.. function:: on_member_update(before, after) + + Called when a :class:`Member` updates their profile. + + This is called when one or more of the following things change: + + - nickname + - roles + - pending + + This requires :attr:`Intents.members` to be enabled. + + :param before: The updated member's old info. + :type before: :class:`Member` + :param after: The updated member's updated info. + :type after: :class:`Member` + +.. function:: on_presence_update(before, after) + + Called when a :class:`Member` updates their presence. + + This is called when one or more of the following things change: + + - status + - activity + + This requires :attr:`Intents.presences` and :attr:`Intents.members` to be enabled. + + .. versionadded:: 2.0 + + :param before: The updated member's old info. + :type before: :class:`Member` + :param after: The updated member's updated info. + :type after: :class:`Member` + +.. function:: on_user_update(before, after) + + Called when a :class:`User` updates their profile. + + This is called when one or more of the following things change: + + - avatar + - username + - discriminator + + This requires :attr:`Intents.members` to be enabled. + + :param before: The updated user's old info. + :type before: :class:`User` + :param after: The updated user's updated info. + :type after: :class:`User` + +.. function:: on_guild_join(guild) + + Called when a :class:`Guild` is either created by the :class:`Client` or when the + :class:`Client` joins a guild. + + This requires :attr:`Intents.guilds` to be enabled. + + :param guild: The guild that was joined. + :type guild: :class:`Guild` + +.. function:: on_guild_remove(guild) + + Called when a :class:`Guild` is removed from the :class:`Client`. + + This happens through, but not limited to, these circumstances: + + - The client got banned. + - The client got kicked. + - The client left the guild. + - The client or the guild owner deleted the guild. + + In order for this event to be invoked then the :class:`Client` must have + been part of the guild to begin with. (i.e. it is part of :attr:`Client.guilds`) + + This requires :attr:`Intents.guilds` to be enabled. + + :param guild: The guild that got removed. + :type guild: :class:`Guild` + +.. function:: on_guild_update(before, after) + + Called when a :class:`Guild` updates, for example: + + - Changed name + - Changed AFK channel + - Changed AFK timeout + - etc + + This requires :attr:`Intents.guilds` to be enabled. + + :param before: The guild prior to being updated. + :type before: :class:`Guild` + :param after: The guild after being updated. + :type after: :class:`Guild` + +.. function:: on_guild_role_create(role) + on_guild_role_delete(role) + + Called when a :class:`Guild` creates or deletes a new :class:`Role`. + + To get the guild it belongs to, use :attr:`Role.guild`. + + This requires :attr:`Intents.guilds` to be enabled. + + :param role: The role that was created or deleted. + :type role: :class:`Role` + +.. function:: on_guild_role_update(before, after) + + Called when a :class:`Role` is changed guild-wide. + + This requires :attr:`Intents.guilds` to be enabled. + + :param before: The updated role's old info. + :type before: :class:`Role` + :param after: The updated role's updated info. + :type after: :class:`Role` + +.. function:: on_guild_emojis_update(guild, before, after) + + Called when a :class:`Guild` adds or removes :class:`Emoji`. + + This requires :attr:`Intents.emojis_and_stickers` to be enabled. + + :param guild: The guild who got their emojis updated. + :type guild: :class:`Guild` + :param before: A list of emojis before the update. + :type before: Sequence[:class:`Emoji`] + :param after: A list of emojis after the update. + :type after: Sequence[:class:`Emoji`] + +.. function:: on_guild_stickers_update(guild, before, after) + + Called when a :class:`Guild` updates its stickers. + + This requires :attr:`Intents.emojis_and_stickers` to be enabled. + + .. versionadded:: 2.0 + + :param guild: The guild who got their stickers updated. + :type guild: :class:`Guild` + :param before: A list of stickers before the update. + :type before: Sequence[:class:`GuildSticker`] + :param after: A list of stickers after the update. + :type after: Sequence[:class:`GuildSticker`] + +.. function:: on_guild_available(guild) + on_guild_unavailable(guild) + + Called when a guild becomes available or unavailable. The guild must have + existed in the :attr:`Client.guilds` cache. + + This requires :attr:`Intents.guilds` to be enabled. + + :param guild: The :class:`Guild` that has changed availability. + +.. function:: on_voice_state_update(member, before, after) + + Called when a :class:`Member` changes their :class:`VoiceState`. + + The following, but not limited to, examples illustrate when this event is called: + + - A member joins a voice or stage channel. + - A member leaves a voice or stage channel. + - A member is muted or deafened by their own accord. + - A member is muted or deafened by a guild administrator. + + This requires :attr:`Intents.voice_states` to be enabled. + + :param member: The member whose voice states changed. + :type member: :class:`Member` + :param before: The voice state prior to the changes. + :type before: :class:`VoiceState` + :param after: The voice state after the changes. + :type after: :class:`VoiceState` + +.. function:: on_stage_instance_create(stage_instance) + on_stage_instance_delete(stage_instance) + + Called when a :class:`StageInstance` is created or deleted for a :class:`StageChannel`. + + .. versionadded:: 2.0 + + :param stage_instance: The stage instance that was created or deleted. + :type stage_instance: :class:`StageInstance` + +.. function:: on_stage_instance_update(before, after) + + Called when a :class:`StageInstance` is updated. + + The following, but not limited to, examples illustrate when this event is called: + + - The topic is changed. + - The privacy level is changed. + + .. versionadded:: 2.0 + + :param before: The stage instance before the update. + :type before: :class:`StageInstance` + :param after: The stage instance after the update. + :type after: :class:`StageInstance` + +.. function:: on_member_ban(guild, user) + + Called when user gets banned from a :class:`Guild`. + + This requires :attr:`Intents.bans` to be enabled. + + :param guild: The guild the user got banned from. + :type guild: :class:`Guild` + :param user: The user that got banned. + Can be either :class:`User` or :class:`Member` depending if + the user was in the guild or not at the time of removal. + :type user: Union[:class:`User`, :class:`Member`] + +.. function:: on_member_unban(guild, user) + + Called when a :class:`User` gets unbanned from a :class:`Guild`. + + This requires :attr:`Intents.bans` to be enabled. + + :param guild: The guild the user got unbanned from. + :type guild: :class:`Guild` + :param user: The user that got unbanned. + :type user: :class:`User` + +.. function:: on_invite_create(invite) + + Called when an :class:`Invite` is created. + You must have the :attr:`~Permissions.manage_channels` permission to receive this. + + .. versionadded:: 1.3 + + .. note:: + + There is a rare possibility that the :attr:`Invite.guild` and :attr:`Invite.channel` + attributes will be of :class:`Object` rather than the respective models. + + This requires :attr:`Intents.invites` to be enabled. + + :param invite: The invite that was created. + :type invite: :class:`Invite` + +.. function:: on_invite_delete(invite) + + Called when an :class:`Invite` is deleted. + You must have the :attr:`~Permissions.manage_channels` permission to receive this. + + .. versionadded:: 1.3 + + .. note:: + + There is a rare possibility that the :attr:`Invite.guild` and :attr:`Invite.channel` + attributes will be of :class:`Object` rather than the respective models. + + Outside of those two attributes, the only other attribute guaranteed to be + filled by the Discord gateway for this event is :attr:`Invite.code`. + + This requires :attr:`Intents.invites` to be enabled. + + :param invite: The invite that was deleted. + :type invite: :class:`Invite` + +.. function:: on_group_join(channel, user) + on_group_remove(channel, user) + + Called when someone joins or leaves a :class:`GroupChannel`. + + :param channel: The group that the user joined or left. + :type channel: :class:`GroupChannel` + :param user: The user that joined or left. + :type user: :class:`User` + +.. _discord-api-utils: + +Utility Functions +----------------- + +.. autofunction:: discord.utils.find + +.. autofunction:: discord.utils.get + +.. autofunction:: discord.utils.snowflake_time + +.. autofunction:: discord.utils.oauth_url + +.. autofunction:: discord.utils.remove_markdown + +.. autofunction:: discord.utils.escape_markdown + +.. autofunction:: discord.utils.escape_mentions + +.. autofunction:: discord.utils.resolve_invite + +.. autofunction:: discord.utils.resolve_template + +.. autofunction:: discord.utils.sleep_until + +.. autofunction:: discord.utils.utcnow + +.. autofunction:: discord.utils.format_dt + +.. autofunction:: discord.utils.as_chunks + +.. _discord-api-enums: + +Enumerations +------------- + +The API provides some enumerations for certain types of strings to avoid the API +from being stringly typed in case the strings change in the future. + +All enumerations are subclasses of an internal class which mimics the behaviour +of :class:`enum.Enum`. + +.. class:: ChannelType + + Specifies the type of channel. + + .. attribute:: text + + A text channel. + .. attribute:: voice + + A voice channel. + .. attribute:: private + + A private text channel. Also called a direct message. + .. attribute:: group + + A private group text channel. + .. attribute:: category + + A category channel. + .. attribute:: news + + A guild news channel. + + .. attribute:: store + + A guild store channel. + + .. attribute:: stage_voice + + A guild stage voice channel. + + .. versionadded:: 1.7 + + .. attribute:: news_thread + + A news thread + + .. versionadded:: 2.0 + + .. attribute:: public_thread + + A public thread + + .. versionadded:: 2.0 + + .. attribute:: private_thread + + A private thread + + .. versionadded:: 2.0 + +.. class:: MessageType + + Specifies the type of :class:`Message`. This is used to denote if a message + is to be interpreted as a system message or a regular message. + + .. container:: operations + + .. describe:: x == y + + Checks if two messages are equal. + .. describe:: x != y + + Checks if two messages are not equal. + + .. attribute:: default + + The default message type. This is the same as regular messages. + .. attribute:: recipient_add + + The system message when a user is added to a group private + message or a thread. + .. attribute:: recipient_remove + + The system message when a user is removed from a group private + message or a thread. + .. attribute:: call + + The system message denoting call state, e.g. missed call, started call, + etc. + .. attribute:: channel_name_change + + The system message denoting that a channel's name has been changed. + .. attribute:: channel_icon_change + + The system message denoting that a channel's icon has been changed. + .. attribute:: pins_add + + The system message denoting that a pinned message has been added to a channel. + .. attribute:: new_member + + The system message denoting that a new member has joined a Guild. + + .. attribute:: premium_guild_subscription + + The system message denoting that a member has "nitro boosted" a guild. + .. attribute:: premium_guild_tier_1 + + The system message denoting that a member has "nitro boosted" a guild + and it achieved level 1. + .. attribute:: premium_guild_tier_2 + + The system message denoting that a member has "nitro boosted" a guild + and it achieved level 2. + .. attribute:: premium_guild_tier_3 + + The system message denoting that a member has "nitro boosted" a guild + and it achieved level 3. + .. attribute:: channel_follow_add + + The system message denoting that an announcement channel has been followed. + + .. versionadded:: 1.3 + .. attribute:: guild_stream + + The system message denoting that a member is streaming in the guild. + + .. versionadded:: 1.7 + .. attribute:: guild_discovery_disqualified + + The system message denoting that the guild is no longer eligible for Server + Discovery. + + .. versionadded:: 1.7 + .. attribute:: guild_discovery_requalified + + The system message denoting that the guild has become eligible again for Server + Discovery. + + .. versionadded:: 1.7 + .. attribute:: guild_discovery_grace_period_initial_warning + + The system message denoting that the guild has failed to meet the Server + Discovery requirements for one week. + + .. versionadded:: 1.7 + .. attribute:: guild_discovery_grace_period_final_warning + + The system message denoting that the guild has failed to meet the Server + Discovery requirements for 3 weeks in a row. + + .. versionadded:: 1.7 + .. attribute:: thread_created + + The system message denoting that a thread has been created. This is only + sent if the thread has been created from an older message. The period of time + required for a message to be considered old cannot be relied upon and is up to + Discord. + + .. versionadded:: 2.0 + .. attribute:: reply + + The system message denoting that the author is replying to a message. + + .. versionadded:: 2.0 + .. attribute:: application_command + + The system message denoting that an application (or "slash") command was executed. + + .. versionadded:: 2.0 + .. attribute:: guild_invite_reminder + + The system message sent as a reminder to invite people to the guild. + + .. versionadded:: 2.0 + .. attribute:: thread_starter_message + + The system message denoting the message in the thread that is the one that started the + thread's conversation topic. + + .. versionadded:: 2.0 + +.. class:: UserFlags + + Represents Discord User flags. + + .. attribute:: staff + + The user is a Discord Employee. + .. attribute:: partner + + The user is a Discord Partner. + .. attribute:: hypesquad + + The user is a HypeSquad Events member. + .. attribute:: bug_hunter + + The user is a Bug Hunter. + .. attribute:: mfa_sms + + The user has SMS recovery for Multi Factor Authentication enabled. + .. attribute:: premium_promo_dismissed + + The user has dismissed the Discord Nitro promotion. + .. attribute:: hypesquad_bravery + + The user is a HypeSquad Bravery member. + .. attribute:: hypesquad_brilliance + + The user is a HypeSquad Brilliance member. + .. attribute:: hypesquad_balance + + The user is a HypeSquad Balance member. + .. attribute:: early_supporter + + The user is an Early Supporter. + .. attribute:: team_user + + The user is a Team User. + .. attribute:: system + + The user is a system user (i.e. represents Discord officially). + .. attribute:: has_unread_urgent_messages + + The user has an unread system message. + .. attribute:: bug_hunter_level_2 + + The user is a Bug Hunter Level 2. + .. attribute:: verified_bot + + The user is a Verified Bot. + .. attribute:: verified_bot_developer + + The user is an Early Verified Bot Developer. + .. attribute:: discord_certified_moderator + + The user is a Discord Certified Moderator. + +.. class:: ActivityType + + Specifies the type of :class:`Activity`. This is used to check how to + interpret the activity itself. + + .. attribute:: unknown + + An unknown activity type. This should generally not happen. + .. attribute:: playing + + A "Playing" activity type. + .. attribute:: streaming + + A "Streaming" activity type. + .. attribute:: listening + + A "Listening" activity type. + .. attribute:: watching + + A "Watching" activity type. + .. attribute:: custom + + A custom activity type. + .. attribute:: competing + + A competing activity type. + + .. versionadded:: 1.5 + +.. class:: InteractionType + + Specifies the type of :class:`Interaction`. + + .. versionadded:: 2.0 + + .. attribute:: ping + + Represents Discord pinging to see if the interaction response server is alive. + .. attribute:: application_command + + Represents a slash command interaction. + .. attribute:: component + + Represents a component based interaction, i.e. using the Discord Bot UI Kit. + +.. class:: InteractionResponseType + + Specifies the response type for the interaction. + + .. versionadded:: 2.0 + + .. attribute:: pong + + Pongs the interaction when given a ping. + + See also :meth:`InteractionResponse.pong` + .. attribute:: channel_message + + Respond to the interaction with a message. + + See also :meth:`InteractionResponse.send_message` + .. attribute:: deferred_channel_message + + Responds to the interaction with a message at a later time. + + See also :meth:`InteractionResponse.defer` + .. attribute:: deferred_message_update + + Acknowledges the component interaction with a promise that + the message will update later (though there is no need to actually update the message). + + See also :meth:`InteractionResponse.defer` + .. attribute:: message_update + + Responds to the interaction by editing the message. + + See also :meth:`InteractionResponse.edit_message` + +.. class:: ComponentType + + Represents the component type of a component. + + .. versionadded:: 2.0 + + .. attribute:: action_row + + Represents the group component which holds different components in a row. + .. attribute:: button + + Represents a button component. + .. attribute:: select + + Represents a select component. + + +.. class:: ButtonStyle + + Represents the style of the button component. + + .. versionadded:: 2.0 + + .. attribute:: primary + + Represents a blurple button for the primary action. + .. attribute:: secondary + + Represents a grey button for the secondary action. + .. attribute:: success + + Represents a green button for a successful action. + .. attribute:: danger + + Represents a red button for a dangerous action. + .. attribute:: link + + Represents a link button. + + .. attribute:: blurple + + An alias for :attr:`primary`. + .. attribute:: grey + + An alias for :attr:`secondary`. + .. attribute:: gray + + An alias for :attr:`secondary`. + .. attribute:: green + + An alias for :attr:`success`. + .. attribute:: red + + An alias for :attr:`danger`. + .. attribute:: url + + An alias for :attr:`link`. + +.. class:: VoiceRegion + + Specifies the region a voice server belongs to. + + .. attribute:: amsterdam + + The Amsterdam region. + .. attribute:: brazil + + The Brazil region. + .. attribute:: dubai + + The Dubai region. + + .. versionadded:: 1.3 + + .. attribute:: eu_central + + The EU Central region. + .. attribute:: eu_west + + The EU West region. + .. attribute:: europe + + The Europe region. + + .. versionadded:: 1.3 + + .. attribute:: frankfurt + + The Frankfurt region. + .. attribute:: hongkong + + The Hong Kong region. + .. attribute:: india + + The India region. + + .. versionadded:: 1.2 + + .. attribute:: japan + + The Japan region. + .. attribute:: london + + The London region. + .. attribute:: russia + + The Russia region. + .. attribute:: singapore + + The Singapore region. + .. attribute:: southafrica + + The South Africa region. + .. attribute:: south_korea + + The South Korea region. + .. attribute:: sydney + + The Sydney region. + .. attribute:: us_central + + The US Central region. + .. attribute:: us_east + + The US East region. + .. attribute:: us_south + + The US South region. + .. attribute:: us_west + + The US West region. + .. attribute:: vip_amsterdam + + The Amsterdam region for VIP guilds. + .. attribute:: vip_us_east + + The US East region for VIP guilds. + .. attribute:: vip_us_west + + The US West region for VIP guilds. + +.. class:: VerificationLevel + + Specifies a :class:`Guild`\'s verification level, which is the criteria in + which a member must meet before being able to send messages to the guild. + + .. container:: operations + + .. versionadded:: 2.0 + + .. describe:: x == y + + Checks if two verification levels are equal. + .. describe:: x != y + + Checks if two verification levels are not equal. + .. describe:: x > y + + Checks if a verification level is higher than another. + .. describe:: x < y + + Checks if a verification level is lower than another. + .. describe:: x >= y + + Checks if a verification level is higher or equal to another. + .. describe:: x <= y + + Checks if a verification level is lower or equal to another. + + .. attribute:: none + + No criteria set. + .. attribute:: low + + Member must have a verified email on their Discord account. + .. attribute:: medium + + Member must have a verified email and be registered on Discord for more + than five minutes. + .. attribute:: high + + Member must have a verified email, be registered on Discord for more + than five minutes, and be a member of the guild itself for more than + ten minutes. + .. attribute:: highest + + Member must have a verified phone on their Discord account. + +.. class:: NotificationLevel + + Specifies whether a :class:`Guild` has notifications on for all messages or mentions only by default. + + .. container:: operations + + .. versionadded:: 2.0 + + .. describe:: x == y + + Checks if two notification levels are equal. + .. describe:: x != y + + Checks if two notification levels are not equal. + .. describe:: x > y + + Checks if a notification level is higher than another. + .. describe:: x < y + + Checks if a notification level is lower than another. + .. describe:: x >= y + + Checks if a notification level is higher or equal to another. + .. describe:: x <= y + + Checks if a notification level is lower or equal to another. + + .. attribute:: all_messages + + Members receive notifications for every message regardless of them being mentioned. + .. attribute:: only_mentions + + Members receive notifications for messages they are mentioned in. + +.. class:: ContentFilter + + Specifies a :class:`Guild`\'s explicit content filter, which is the machine + learning algorithms that Discord uses to detect if an image contains + pornography or otherwise explicit content. + + .. container:: operations + + .. versionadded:: 2.0 + + .. describe:: x == y + + Checks if two content filter levels are equal. + .. describe:: x != y + + Checks if two content filter levels are not equal. + .. describe:: x > y + + Checks if a content filter level is higher than another. + .. describe:: x < y + + Checks if a content filter level is lower than another. + .. describe:: x >= y + + Checks if a content filter level is higher or equal to another. + .. describe:: x <= y + + Checks if a content filter level is lower or equal to another. + + .. attribute:: disabled + + The guild does not have the content filter enabled. + .. attribute:: no_role + + The guild has the content filter enabled for members without a role. + .. attribute:: all_members + + The guild has the content filter enabled for every member. + +.. class:: Status + + Specifies a :class:`Member` 's status. + + .. attribute:: online + + The member is online. + .. attribute:: offline + + The member is offline. + .. attribute:: idle + + The member is idle. + .. attribute:: dnd + + The member is "Do Not Disturb". + .. attribute:: do_not_disturb + + An alias for :attr:`dnd`. + .. attribute:: invisible + + The member is "invisible". In reality, this is only used in sending + a presence a la :meth:`Client.change_presence`. When you receive a + user's presence this will be :attr:`offline` instead. + + +.. class:: AuditLogAction + + Represents the type of action being done for a :class:`AuditLogEntry`\, + which is retrievable via :meth:`Guild.audit_logs`. + + .. attribute:: guild_update + + The guild has updated. Things that trigger this include: + + - Changing the guild vanity URL + - Changing the guild invite splash + - Changing the guild AFK channel or timeout + - Changing the guild voice server region + - Changing the guild icon, banner, or discovery splash + - Changing the guild moderation settings + - Changing things related to the guild widget + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Guild`. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.afk_channel` + - :attr:`~AuditLogDiff.system_channel` + - :attr:`~AuditLogDiff.afk_timeout` + - :attr:`~AuditLogDiff.default_message_notifications` + - :attr:`~AuditLogDiff.explicit_content_filter` + - :attr:`~AuditLogDiff.mfa_level` + - :attr:`~AuditLogDiff.name` + - :attr:`~AuditLogDiff.owner` + - :attr:`~AuditLogDiff.splash` + - :attr:`~AuditLogDiff.discovery_splash` + - :attr:`~AuditLogDiff.icon` + - :attr:`~AuditLogDiff.banner` + - :attr:`~AuditLogDiff.vanity_url_code` + + .. attribute:: channel_create + + A new channel was created. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + either a :class:`abc.GuildChannel` or :class:`Object` with an ID. + + A more filled out object in the :class:`Object` case can be found + by using :attr:`~AuditLogEntry.after`. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.name` + - :attr:`~AuditLogDiff.type` + - :attr:`~AuditLogDiff.overwrites` + + .. attribute:: channel_update + + A channel was updated. Things that trigger this include: + + - The channel name or topic was changed + - The channel bitrate was changed + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`abc.GuildChannel` or :class:`Object` with an ID. + + A more filled out object in the :class:`Object` case can be found + by using :attr:`~AuditLogEntry.after` or :attr:`~AuditLogEntry.before`. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.name` + - :attr:`~AuditLogDiff.type` + - :attr:`~AuditLogDiff.position` + - :attr:`~AuditLogDiff.overwrites` + - :attr:`~AuditLogDiff.topic` + - :attr:`~AuditLogDiff.bitrate` + - :attr:`~AuditLogDiff.rtc_region` + - :attr:`~AuditLogDiff.video_quality_mode` + - :attr:`~AuditLogDiff.default_auto_archive_duration` + + .. attribute:: channel_delete + + A channel was deleted. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + an :class:`Object` with an ID. + + A more filled out object can be found by using the + :attr:`~AuditLogEntry.before` object. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.name` + - :attr:`~AuditLogDiff.type` + - :attr:`~AuditLogDiff.overwrites` + + .. attribute:: overwrite_create + + A channel permission overwrite was created. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`abc.GuildChannel` or :class:`Object` with an ID. + + When this is the action, the type of :attr:`~AuditLogEntry.extra` is + either a :class:`Role` or :class:`Member`. If the object is not found + then it is a :class:`Object` with an ID being filled, a name, and a + ``type`` attribute set to either ``'role'`` or ``'member'`` to help + dictate what type of ID it is. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.deny` + - :attr:`~AuditLogDiff.allow` + - :attr:`~AuditLogDiff.id` + - :attr:`~AuditLogDiff.type` + + .. attribute:: overwrite_update + + A channel permission overwrite was changed, this is typically + when the permission values change. + + See :attr:`overwrite_create` for more information on how the + :attr:`~AuditLogEntry.target` and :attr:`~AuditLogEntry.extra` fields + are set. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.deny` + - :attr:`~AuditLogDiff.allow` + - :attr:`~AuditLogDiff.id` + - :attr:`~AuditLogDiff.type` + + .. attribute:: overwrite_delete + + A channel permission overwrite was deleted. + + See :attr:`overwrite_create` for more information on how the + :attr:`~AuditLogEntry.target` and :attr:`~AuditLogEntry.extra` fields + are set. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.deny` + - :attr:`~AuditLogDiff.allow` + - :attr:`~AuditLogDiff.id` + - :attr:`~AuditLogDiff.type` + + .. attribute:: kick + + A member was kicked. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`User` who got kicked. + + When this is the action, :attr:`~AuditLogEntry.changes` is empty. + + .. attribute:: member_prune + + A member prune was triggered. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + set to ``None``. + + When this is the action, the type of :attr:`~AuditLogEntry.extra` is + set to an unspecified proxy object with two attributes: + + - ``delete_members_days``: An integer specifying how far the prune was. + - ``members_removed``: An integer specifying how many members were removed. + + When this is the action, :attr:`~AuditLogEntry.changes` is empty. + + .. attribute:: ban + + A member was banned. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`User` who got banned. + + When this is the action, :attr:`~AuditLogEntry.changes` is empty. + + .. attribute:: unban + + A member was unbanned. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`User` who got unbanned. + + When this is the action, :attr:`~AuditLogEntry.changes` is empty. + + .. attribute:: member_update + + A member has updated. This triggers in the following situations: + + - A nickname was changed + - They were server muted or deafened (or it was undo'd) + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Member` or :class:`User` who got updated. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.nick` + - :attr:`~AuditLogDiff.mute` + - :attr:`~AuditLogDiff.deaf` + + .. attribute:: member_role_update + + A member's role has been updated. This triggers when a member + either gains a role or loses a role. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Member` or :class:`User` who got the role. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.roles` + + .. attribute:: member_move + + A member's voice channel has been updated. This triggers when a + member is moved to a different voice channel. + + When this is the action, the type of :attr:`~AuditLogEntry.extra` is + set to an unspecified proxy object with two attributes: + + - ``channel``: A :class:`TextChannel` or :class:`Object` with the channel ID where the members were moved. + - ``count``: An integer specifying how many members were moved. + + .. versionadded:: 1.3 + + .. attribute:: member_disconnect + + A member's voice state has changed. This triggers when a + member is force disconnected from voice. + + When this is the action, the type of :attr:`~AuditLogEntry.extra` is + set to an unspecified proxy object with one attribute: + + - ``count``: An integer specifying how many members were disconnected. + + .. versionadded:: 1.3 + + .. attribute:: bot_add + + A bot was added to the guild. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Member` or :class:`User` which was added to the guild. + + .. versionadded:: 1.3 + + .. attribute:: role_create + + A new role was created. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Role` or a :class:`Object` with the ID. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.colour` + - :attr:`~AuditLogDiff.mentionable` + - :attr:`~AuditLogDiff.hoist` + - :attr:`~AuditLogDiff.name` + - :attr:`~AuditLogDiff.permissions` + + .. attribute:: role_update + + A role was updated. This triggers in the following situations: + + - The name has changed + - The permissions have changed + - The colour has changed + - Its hoist/mentionable state has changed + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Role` or a :class:`Object` with the ID. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.colour` + - :attr:`~AuditLogDiff.mentionable` + - :attr:`~AuditLogDiff.hoist` + - :attr:`~AuditLogDiff.name` + - :attr:`~AuditLogDiff.permissions` + + .. attribute:: role_delete + + A role was deleted. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Role` or a :class:`Object` with the ID. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.colour` + - :attr:`~AuditLogDiff.mentionable` + - :attr:`~AuditLogDiff.hoist` + - :attr:`~AuditLogDiff.name` + - :attr:`~AuditLogDiff.permissions` + + .. attribute:: invite_create + + An invite was created. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Invite` that was created. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.max_age` + - :attr:`~AuditLogDiff.code` + - :attr:`~AuditLogDiff.temporary` + - :attr:`~AuditLogDiff.inviter` + - :attr:`~AuditLogDiff.channel` + - :attr:`~AuditLogDiff.uses` + - :attr:`~AuditLogDiff.max_uses` + + .. attribute:: invite_update + + An invite was updated. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Invite` that was updated. + + .. attribute:: invite_delete + + An invite was deleted. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Invite` that was deleted. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.max_age` + - :attr:`~AuditLogDiff.code` + - :attr:`~AuditLogDiff.temporary` + - :attr:`~AuditLogDiff.inviter` + - :attr:`~AuditLogDiff.channel` + - :attr:`~AuditLogDiff.uses` + - :attr:`~AuditLogDiff.max_uses` + + .. attribute:: webhook_create + + A webhook was created. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Object` with the webhook ID. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.channel` + - :attr:`~AuditLogDiff.name` + - :attr:`~AuditLogDiff.type` (always set to ``1`` if so) + + .. attribute:: webhook_update + + A webhook was updated. This trigger in the following situations: + + - The webhook name changed + - The webhook channel changed + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Object` with the webhook ID. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.channel` + - :attr:`~AuditLogDiff.name` + - :attr:`~AuditLogDiff.avatar` + + .. attribute:: webhook_delete + + A webhook was deleted. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Object` with the webhook ID. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.channel` + - :attr:`~AuditLogDiff.name` + - :attr:`~AuditLogDiff.type` (always set to ``1`` if so) + + .. attribute:: emoji_create + + An emoji was created. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Emoji` or :class:`Object` with the emoji ID. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.name` + + .. attribute:: emoji_update + + An emoji was updated. This triggers when the name has changed. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Emoji` or :class:`Object` with the emoji ID. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.name` + + .. attribute:: emoji_delete + + An emoji was deleted. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Object` with the emoji ID. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.name` + + .. attribute:: message_delete + + A message was deleted by a moderator. Note that this + only triggers if the message was deleted by someone other than the author. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Member` or :class:`User` who had their message deleted. + + When this is the action, the type of :attr:`~AuditLogEntry.extra` is + set to an unspecified proxy object with two attributes: + + - ``count``: An integer specifying how many messages were deleted. + - ``channel``: A :class:`TextChannel` or :class:`Object` with the channel ID where the message got deleted. + + .. attribute:: message_bulk_delete + + Messages were bulk deleted by a moderator. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`TextChannel` or :class:`Object` with the ID of the channel that was purged. + + When this is the action, the type of :attr:`~AuditLogEntry.extra` is + set to an unspecified proxy object with one attribute: + + - ``count``: An integer specifying how many messages were deleted. + + .. versionadded:: 1.3 + + .. attribute:: message_pin + + A message was pinned in a channel. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Member` or :class:`User` who had their message pinned. + + When this is the action, the type of :attr:`~AuditLogEntry.extra` is + set to an unspecified proxy object with two attributes: + + - ``channel``: A :class:`TextChannel` or :class:`Object` with the channel ID where the message was pinned. + - ``message_id``: the ID of the message which was pinned. + + .. versionadded:: 1.3 + + .. attribute:: message_unpin + + A message was unpinned in a channel. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Member` or :class:`User` who had their message unpinned. + + When this is the action, the type of :attr:`~AuditLogEntry.extra` is + set to an unspecified proxy object with two attributes: + + - ``channel``: A :class:`TextChannel` or :class:`Object` with the channel ID where the message was unpinned. + - ``message_id``: the ID of the message which was unpinned. + + .. versionadded:: 1.3 + + .. attribute:: integration_create + + A guild integration was created. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Object` with the integration ID of the integration which was created. + + .. versionadded:: 1.3 + + .. attribute:: integration_update + + A guild integration was updated. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Object` with the integration ID of the integration which was updated. + + .. versionadded:: 1.3 + + .. attribute:: integration_delete + + A guild integration was deleted. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Object` with the integration ID of the integration which was deleted. + + .. versionadded:: 1.3 + + .. attribute:: stage_instance_create + + A stage instance was started. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`StageInstance` or :class:`Object` with the ID of the stage + instance which was created. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.topic` + - :attr:`~AuditLogDiff.privacy_level` + + .. versionadded:: 2.0 + + .. attribute:: stage_instance_update + + A stage instance was updated. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`StageInstance` or :class:`Object` with the ID of the stage + instance which was updated. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.topic` + - :attr:`~AuditLogDiff.privacy_level` + + .. versionadded:: 2.0 + + .. attribute:: stage_instance_delete + + A stage instance was ended. + + .. versionadded:: 2.0 + + .. attribute:: sticker_create + + A sticker was created. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`GuildSticker` or :class:`Object` with the ID of the sticker + which was updated. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.name` + - :attr:`~AuditLogDiff.emoji` + - :attr:`~AuditLogDiff.type` + - :attr:`~AuditLogDiff.format_type` + - :attr:`~AuditLogDiff.description` + - :attr:`~AuditLogDiff.available` + + .. versionadded:: 2.0 + + .. attribute:: sticker_update + + A sticker was updated. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`GuildSticker` or :class:`Object` with the ID of the sticker + which was updated. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.name` + - :attr:`~AuditLogDiff.emoji` + - :attr:`~AuditLogDiff.type` + - :attr:`~AuditLogDiff.format_type` + - :attr:`~AuditLogDiff.description` + - :attr:`~AuditLogDiff.available` + + .. versionadded:: 2.0 + + .. attribute:: sticker_delete + + A sticker was deleted. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`GuildSticker` or :class:`Object` with the ID of the sticker + which was updated. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.name` + - :attr:`~AuditLogDiff.emoji` + - :attr:`~AuditLogDiff.type` + - :attr:`~AuditLogDiff.format_type` + - :attr:`~AuditLogDiff.description` + - :attr:`~AuditLogDiff.available` + + .. versionadded:: 2.0 + + .. attribute:: thread_create + + A thread was created. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Thread` or :class:`Object` with the ID of the thread which + was created. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.name` + - :attr:`~AuditLogDiff.archived` + - :attr:`~AuditLogDiff.locked` + - :attr:`~AuditLogDiff.auto_archive_duration` + + .. versionadded:: 2.0 + + .. attribute:: thread_update + + A thread was updated. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Thread` or :class:`Object` with the ID of the thread which + was updated. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.name` + - :attr:`~AuditLogDiff.archived` + - :attr:`~AuditLogDiff.locked` + - :attr:`~AuditLogDiff.auto_archive_duration` + + .. versionadded:: 2.0 + + .. attribute:: thread_delete + + A thread was deleted. + + When this is the action, the type of :attr:`~AuditLogEntry.target` is + the :class:`Thread` or :class:`Object` with the ID of the thread which + was deleted. + + Possible attributes for :class:`AuditLogDiff`: + + - :attr:`~AuditLogDiff.name` + - :attr:`~AuditLogDiff.archived` + - :attr:`~AuditLogDiff.locked` + - :attr:`~AuditLogDiff.auto_archive_duration` + + .. versionadded:: 2.0 + +.. class:: AuditLogActionCategory + + Represents the category that the :class:`AuditLogAction` belongs to. + + This can be retrieved via :attr:`AuditLogEntry.category`. + + .. attribute:: create + + The action is the creation of something. + + .. attribute:: delete + + The action is the deletion of something. + + .. attribute:: update + + The action is the update of something. + +.. class:: TeamMembershipState + + Represents the membership state of a team member retrieved through :func:`Client.application_info`. + + .. versionadded:: 1.3 + + .. attribute:: invited + + Represents an invited member. + + .. attribute:: accepted + + Represents a member currently in the team. + +.. class:: WebhookType + + Represents the type of webhook that can be received. + + .. versionadded:: 1.3 + + .. attribute:: incoming + + Represents a webhook that can post messages to channels with a token. + + .. attribute:: channel_follower + + Represents a webhook that is internally managed by Discord, used for following channels. + + .. attribute:: application + + Represents a webhook that is used for interactions or applications. + + .. versionadded:: 2.0 + +.. class:: ExpireBehaviour + + Represents the behaviour the :class:`Integration` should perform + when a user's subscription has finished. + + There is an alias for this called ``ExpireBehavior``. + + .. versionadded:: 1.4 + + .. attribute:: remove_role + + This will remove the :attr:`StreamIntegration.role` from the user + when their subscription is finished. + + .. attribute:: kick + + This will kick the user when their subscription is finished. + +.. class:: DefaultAvatar + + Represents the default avatar of a Discord :class:`User` + + .. attribute:: blurple + + Represents the default avatar with the color blurple. + See also :attr:`Colour.blurple` + .. attribute:: grey + + Represents the default avatar with the color grey. + See also :attr:`Colour.greyple` + .. attribute:: gray + + An alias for :attr:`grey`. + .. attribute:: green + + Represents the default avatar with the color green. + See also :attr:`Colour.green` + .. attribute:: orange + + Represents the default avatar with the color orange. + See also :attr:`Colour.orange` + .. attribute:: red + + Represents the default avatar with the color red. + See also :attr:`Colour.red` + +.. class:: StickerType + + Represents the type of sticker. + + .. versionadded:: 2.0 + + .. attribute:: standard + + Represents a standard sticker that all Nitro users can use. + + .. attribute:: guild + + Represents a custom sticker created in a guild. + +.. class:: StickerFormatType + + Represents the type of sticker images. + + .. versionadded:: 1.6 + + .. attribute:: png + + Represents a sticker with a png image. + + .. attribute:: apng + + Represents a sticker with an apng image. + + .. attribute:: lottie + + Represents a sticker with a lottie image. + +.. class:: InviteTarget + + Represents the invite type for voice channel invites. + + .. versionadded:: 2.0 + + .. attribute:: unknown + + The invite doesn't target anyone or anything. + + .. attribute:: stream + + A stream invite that targets a user. + + .. attribute:: embedded_application + + A stream invite that targets an embedded application. + +.. class:: VideoQualityMode + + Represents the camera video quality mode for voice channel participants. + + .. versionadded:: 2.0 + + .. attribute:: auto + + Represents auto camera video quality. + + .. attribute:: full + + Represents full camera video quality. + +.. class:: StagePrivacyLevel + + Represents a stage instance's privacy level. + + .. versionadded:: 2.0 + + .. attribute:: public + + The stage instance can be joined by external users. + + .. attribute:: closed + + The stage instance can only be joined by members of the guild. + + .. attribute:: guild_only + + Alias for :attr:`.closed` + +.. class:: NSFWLevel + + Represents the NSFW level of a guild. + + .. versionadded:: 2.0 + + .. container:: operations + + .. describe:: x == y + + Checks if two NSFW levels are equal. + .. describe:: x != y + + Checks if two NSFW levels are not equal. + .. describe:: x > y + + Checks if a NSFW level is higher than another. + .. describe:: x < y + + Checks if a NSFW level is lower than another. + .. describe:: x >= y + + Checks if a NSFW level is higher or equal to another. + .. describe:: x <= y + + Checks if a NSFW level is lower or equal to another. + + .. attribute:: default + + The guild has not been categorised yet. + + .. attribute:: explicit + + The guild contains NSFW content. + + .. attribute:: safe + + The guild does not contain any NSFW content. + + .. attribute:: age_restricted + + The guild may contain NSFW content. + +Async Iterator +---------------- + +Some API functions return an "async iterator". An async iterator is something that is +capable of being used in an :ref:`async for statement `. + +These async iterators can be used as follows: :: + + async for elem in channel.history(): + # do stuff with elem here + +Certain utilities make working with async iterators easier, detailed below. + +.. class:: AsyncIterator + + Represents the "AsyncIterator" concept. Note that no such class exists, + it is purely abstract. + + .. container:: operations + + .. describe:: async for x in y + + Iterates over the contents of the async iterator. + + + .. method:: next() + :async: + + |coro| + + Advances the iterator by one, if possible. If no more items are found + then this raises :exc:`NoMoreItems`. + + .. method:: get(**attrs) + :async: + + |coro| + + Similar to :func:`utils.get` except run over the async iterator. + + Getting the last message by a user named 'Dave' or ``None``: :: + + msg = await channel.history().get(author__name='Dave') + + .. method:: find(predicate) + :async: + + |coro| + + Similar to :func:`utils.find` except run over the async iterator. + + Unlike :func:`utils.find`\, the predicate provided can be a + |coroutine_link|_. + + Getting the last audit log with a reason or ``None``: :: + + def predicate(event): + return event.reason is not None + + event = await guild.audit_logs().find(predicate) + + :param predicate: The predicate to use. Could be a |coroutine_link|_. + :return: The first element that returns ``True`` for the predicate or ``None``. + + .. method:: flatten() + :async: + + |coro| + + Flattens the async iterator into a :class:`list` with all the elements. + + :return: A list of every element in the async iterator. + :rtype: list + + .. method:: chunk(max_size) + + Collects items into chunks of up to a given maximum size. + Another :class:`AsyncIterator` is returned which collects items into + :class:`list`\s of a given size. The maximum chunk size must be a positive integer. + + .. versionadded:: 1.6 + + Collecting groups of users: :: + + async for leader, *users in reaction.users().chunk(3): + ... + + .. warning:: + + The last chunk collected may not be as large as ``max_size``. + + :param max_size: The size of individual chunks. + :rtype: :class:`AsyncIterator` + + .. method:: map(func) + + This is similar to the built-in :func:`map ` function. Another + :class:`AsyncIterator` is returned that executes the function on + every element it is iterating over. This function can either be a + regular function or a |coroutine_link|_. + + Creating a content iterator: :: + + def transform(message): + return message.content + + async for content in channel.history().map(transform): + message_length = len(content) + + :param func: The function to call on every element. Could be a |coroutine_link|_. + :rtype: :class:`AsyncIterator` + + .. method:: filter(predicate) + + This is similar to the built-in :func:`filter ` function. Another + :class:`AsyncIterator` is returned that filters over the original + async iterator. This predicate can be a regular function or a |coroutine_link|_. + + Getting messages by non-bot accounts: :: + + def predicate(message): + return not message.author.bot + + async for elem in channel.history().filter(predicate): + ... + + :param predicate: The predicate to call on every element. Could be a |coroutine_link|_. + :rtype: :class:`AsyncIterator` + +.. _discord-api-audit-logs: + +Audit Log Data +---------------- + +Working with :meth:`Guild.audit_logs` is a complicated process with a lot of machinery +involved. The library attempts to make it easy to use and friendly. In order to accomplish +this goal, it must make use of a couple of data classes that aid in this goal. + +AuditLogEntry +~~~~~~~~~~~~~~~ + +.. attributetable:: AuditLogEntry + +.. autoclass:: AuditLogEntry + :members: + +AuditLogChanges +~~~~~~~~~~~~~~~~~ + +.. attributetable:: AuditLogChanges + +.. class:: AuditLogChanges + + An audit log change set. + + .. attribute:: before + + The old value. The attribute has the type of :class:`AuditLogDiff`. + + Depending on the :class:`AuditLogActionCategory` retrieved by + :attr:`~AuditLogEntry.category`\, the data retrieved by this + attribute differs: + + +----------------------------------------+---------------------------------------------------+ + | Category | Description | + +----------------------------------------+---------------------------------------------------+ + | :attr:`~AuditLogActionCategory.create` | All attributes are set to ``None``. | + +----------------------------------------+---------------------------------------------------+ + | :attr:`~AuditLogActionCategory.delete` | All attributes are set the value before deletion. | + +----------------------------------------+---------------------------------------------------+ + | :attr:`~AuditLogActionCategory.update` | All attributes are set the value before updating. | + +----------------------------------------+---------------------------------------------------+ + | ``None`` | No attributes are set. | + +----------------------------------------+---------------------------------------------------+ + + .. attribute:: after + + The new value. The attribute has the type of :class:`AuditLogDiff`. + + Depending on the :class:`AuditLogActionCategory` retrieved by + :attr:`~AuditLogEntry.category`\, the data retrieved by this + attribute differs: + + +----------------------------------------+--------------------------------------------------+ + | Category | Description | + +----------------------------------------+--------------------------------------------------+ + | :attr:`~AuditLogActionCategory.create` | All attributes are set to the created value | + +----------------------------------------+--------------------------------------------------+ + | :attr:`~AuditLogActionCategory.delete` | All attributes are set to ``None`` | + +----------------------------------------+--------------------------------------------------+ + | :attr:`~AuditLogActionCategory.update` | All attributes are set the value after updating. | + +----------------------------------------+--------------------------------------------------+ + | ``None`` | No attributes are set. | + +----------------------------------------+--------------------------------------------------+ + +AuditLogDiff +~~~~~~~~~~~~~ + +.. attributetable:: AuditLogDiff + +.. class:: AuditLogDiff + + Represents an audit log "change" object. A change object has dynamic + attributes that depend on the type of action being done. Certain actions + map to certain attributes being set. + + Note that accessing an attribute that does not match the specified action + will lead to an attribute error. + + To get a list of attributes that have been set, you can iterate over + them. To see a list of all possible attributes that could be set based + on the action being done, check the documentation for :class:`AuditLogAction`, + otherwise check the documentation below for all attributes that are possible. + + .. container:: operations + + .. describe:: iter(diff) + + Returns an iterator over (attribute, value) tuple of this diff. + + .. attribute:: name + + A name of something. + + :type: :class:`str` + + .. attribute:: icon + + A guild's icon. See also :attr:`Guild.icon`. + + :type: :class:`Asset` + + .. attribute:: splash + + The guild's invite splash. See also :attr:`Guild.splash`. + + :type: :class:`Asset` + + .. attribute:: discovery_splash + + The guild's discovery splash. See also :attr:`Guild.discovery_splash`. + + :type: :class:`Asset` + + .. attribute:: banner + + The guild's banner. See also :attr:`Guild.banner`. + + :type: :class:`Asset` + + .. attribute:: owner + + The guild's owner. See also :attr:`Guild.owner` + + :type: Union[:class:`Member`, :class:`User`] + + .. attribute:: region + + The guild's voice region. See also :attr:`Guild.region`. + + :type: :class:`VoiceRegion` + + .. attribute:: afk_channel + + The guild's AFK channel. + + If this could not be found, then it falls back to a :class:`Object` + with the ID being set. + + See :attr:`Guild.afk_channel`. + + :type: Union[:class:`VoiceChannel`, :class:`Object`] + + .. attribute:: system_channel + + The guild's system channel. + + If this could not be found, then it falls back to a :class:`Object` + with the ID being set. + + See :attr:`Guild.system_channel`. + + :type: Union[:class:`TextChannel`, :class:`Object`] + + + .. attribute:: rules_channel + + The guild's rules channel. + + If this could not be found then it falls back to a :class:`Object` + with the ID being set. + + See :attr:`Guild.rules_channel`. + + :type: Union[:class:`TextChannel`, :class:`Object`] + + + .. attribute:: public_updates_channel + + The guild's public updates channel. + + If this could not be found then it falls back to a :class:`Object` + with the ID being set. + + See :attr:`Guild.public_updates_channel`. + + :type: Union[:class:`TextChannel`, :class:`Object`] + + .. attribute:: afk_timeout + + The guild's AFK timeout. See :attr:`Guild.afk_timeout`. + + :type: :class:`int` + + .. attribute:: mfa_level + + The guild's MFA level. See :attr:`Guild.mfa_level`. + + :type: :class:`int` + + .. attribute:: widget_enabled + + The guild's widget has been enabled or disabled. + + :type: :class:`bool` + + .. attribute:: widget_channel + + The widget's channel. + + If this could not be found then it falls back to a :class:`Object` + with the ID being set. + + :type: Union[:class:`TextChannel`, :class:`Object`] + + .. attribute:: verification_level + + The guild's verification level. + + See also :attr:`Guild.verification_level`. + + :type: :class:`VerificationLevel` + + .. attribute:: default_notifications + + The guild's default notification level. + + See also :attr:`Guild.default_notifications`. + + :type: :class:`NotificationLevel` + + .. attribute:: explicit_content_filter + + The guild's content filter. + + See also :attr:`Guild.explicit_content_filter`. + + :type: :class:`ContentFilter` + + .. attribute:: default_message_notifications + + The guild's default message notification setting. + + :type: :class:`int` + + .. attribute:: vanity_url_code + + The guild's vanity URL. + + See also :meth:`Guild.vanity_invite` and :meth:`Guild.edit`. + + :type: :class:`str` + + .. attribute:: position + + The position of a :class:`Role` or :class:`abc.GuildChannel`. + + :type: :class:`int` + + .. attribute:: type + + The type of channel or sticker. + + :type: Union[:class:`ChannelType`, :class:`StickerType`] + + .. attribute:: topic + + The topic of a :class:`TextChannel` or :class:`StageChannel`. + + See also :attr:`TextChannel.topic` or :attr:`StageChannel.topic`. + + :type: :class:`str` + + .. attribute:: bitrate + + The bitrate of a :class:`VoiceChannel`. + + See also :attr:`VoiceChannel.bitrate`. + + :type: :class:`int` + + .. attribute:: overwrites + + A list of permission overwrite tuples that represents a target and a + :class:`PermissionOverwrite` for said target. + + The first element is the object being targeted, which can either + be a :class:`Member` or :class:`User` or :class:`Role`. If this object + is not found then it is a :class:`Object` with an ID being filled and + a ``type`` attribute set to either ``'role'`` or ``'member'`` to help + decide what type of ID it is. + + :type: List[Tuple[target, :class:`PermissionOverwrite`]] + + .. attribute:: privacy_level + + The privacy level of the stage instance. + + :type: :class:`StagePrivacyLevel` + + .. attribute:: roles + + A list of roles being added or removed from a member. + + If a role is not found then it is a :class:`Object` with the ID and name being + filled in. + + :type: List[Union[:class:`Role`, :class:`Object`]] + + .. attribute:: nick + + The nickname of a member. + + See also :attr:`Member.nick` + + :type: Optional[:class:`str`] + + .. attribute:: deaf + + Whether the member is being server deafened. + + See also :attr:`VoiceState.deaf`. + + :type: :class:`bool` + + .. attribute:: mute + + Whether the member is being server muted. + + See also :attr:`VoiceState.mute`. + + :type: :class:`bool` + + .. attribute:: permissions + + The permissions of a role. + + See also :attr:`Role.permissions`. + + :type: :class:`Permissions` + + .. attribute:: colour + color + + The colour of a role. + + See also :attr:`Role.colour` + + :type: :class:`Colour` + + .. attribute:: hoist + + Whether the role is being hoisted or not. + + See also :attr:`Role.hoist` + + :type: :class:`bool` + + .. attribute:: mentionable + + Whether the role is mentionable or not. + + See also :attr:`Role.mentionable` + + :type: :class:`bool` + + .. attribute:: code + + The invite's code. + + See also :attr:`Invite.code` + + :type: :class:`str` + + .. attribute:: channel + + A guild channel. + + If the channel is not found then it is a :class:`Object` with the ID + being set. In some cases the channel name is also set. + + :type: Union[:class:`abc.GuildChannel`, :class:`Object`] + + .. attribute:: inviter + + The user who created the invite. + + See also :attr:`Invite.inviter`. + + :type: Optional[:class:`User`] + + .. attribute:: max_uses + + The invite's max uses. + + See also :attr:`Invite.max_uses`. + + :type: :class:`int` + + .. attribute:: uses + + The invite's current uses. + + See also :attr:`Invite.uses`. + + :type: :class:`int` + + .. attribute:: max_age + + The invite's max age in seconds. + + See also :attr:`Invite.max_age`. + + :type: :class:`int` + + .. attribute:: temporary + + If the invite is a temporary invite. + + See also :attr:`Invite.temporary`. + + :type: :class:`bool` + + .. attribute:: allow + deny + + The permissions being allowed or denied. + + :type: :class:`Permissions` + + .. attribute:: id + + The ID of the object being changed. + + :type: :class:`int` + + .. attribute:: avatar + + The avatar of a member. + + See also :attr:`User.avatar`. + + :type: :class:`Asset` + + .. attribute:: slowmode_delay + + The number of seconds members have to wait before + sending another message in the channel. + + See also :attr:`TextChannel.slowmode_delay`. + + :type: :class:`int` + + .. attribute:: rtc_region + + The region for the voice channel’s voice communication. + A value of ``None`` indicates automatic voice region detection. + + See also :attr:`VoiceChannel.rtc_region`. + + :type: :class:`VoiceRegion` + + .. attribute:: video_quality_mode + + The camera video quality for the voice channel's participants. + + See also :attr:`VoiceChannel.video_quality_mode`. + + :type: :class:`VideoQualityMode` + + .. attribute:: format_type + + The format type of a sticker being changed. + + See also :attr:`GuildSticker.format` + + :type: :class:`StickerFormatType` + + .. attribute:: emoji + + The name of the emoji that represents a sticker being changed. + + See also :attr:`GuildSticker.emoji` + + :type: :class:`str` + + .. attribute:: description + + The description of a sticker being changed. + + See also :attr:`GuildSticker.description` + + :type: :class:`str` + + .. attribute:: available + + The availability of a sticker being changed. + + See also :attr:`GuildSticker.available` + + :type: :class:`bool` + + .. attribute:: archived + + The thread is now archived. + + :type: :class:`bool` + + .. attribute:: locked + + The thread is being locked or unlocked. + + :type: :class:`bool` + + .. attribute:: auto_archive_duration + + The thread's auto archive duration being changed. + + See also :attr:`Thread.auto_archive_duration` + + :type: :class:`int` + + .. attribute:: default_auto_archive_duration + + The default auto archive duration for newly created threads being changed. + + :type: :class:`int` + +.. this is currently missing the following keys: reason and application_id + I'm not sure how to about porting these + +Webhook Support +------------------ + +discord.py offers support for creating, editing, and executing webhooks through the :class:`Webhook` class. + +Webhook +~~~~~~~~~ + +.. attributetable:: Webhook + +.. autoclass:: Webhook() + :members: + :inherited-members: + +WebhookMessage +~~~~~~~~~~~~~~~~ + +.. attributetable:: WebhookMessage + +.. autoclass:: WebhookMessage() + :members: + +SyncWebhook +~~~~~~~~~~~~ + +.. attributetable:: SyncWebhook + +.. autoclass:: SyncWebhook() + :members: + :inherited-members: + +SyncWebhookMessage +~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: SyncWebhookMessage + +.. autoclass:: SyncWebhookMessage() + :members: + +.. _discord_api_abcs: + +Abstract Base Classes +----------------------- + +An :term:`abstract base class` (also known as an ``abc``) is a class that models can inherit +to get their behaviour. **Abstract base classes should not be instantiated**. +They are mainly there for usage with :func:`isinstance` and :func:`issubclass`\. + +This library has a module related to abstract base classes, in which all the ABCs are subclasses of +:class:`typing.Protocol`. + +Snowflake +~~~~~~~~~~ + +.. attributetable:: discord.abc.Snowflake + +.. autoclass:: discord.abc.Snowflake() + :members: + +User +~~~~~ + +.. attributetable:: discord.abc.User + +.. autoclass:: discord.abc.User() + :members: + +PrivateChannel +~~~~~~~~~~~~~~~ + +.. attributetable:: discord.abc.PrivateChannel + +.. autoclass:: discord.abc.PrivateChannel() + :members: + +GuildChannel +~~~~~~~~~~~~~ + +.. attributetable:: discord.abc.GuildChannel + +.. autoclass:: discord.abc.GuildChannel() + :members: + +Messageable +~~~~~~~~~~~~ + +.. attributetable:: discord.abc.Messageable + +.. autoclass:: discord.abc.Messageable() + :members: + :exclude-members: history, typing + + .. automethod:: discord.abc.Messageable.history + :async-for: + + .. automethod:: discord.abc.Messageable.typing + :async-with: + +Connectable +~~~~~~~~~~~~ + +.. attributetable:: discord.abc.Connectable + +.. autoclass:: discord.abc.Connectable() + +.. _discord_api_models: + +Discord Models +--------------- + +Models are classes that are received from Discord and are not meant to be created by +the user of the library. + +.. danger:: + + The classes listed below are **not intended to be created by users** and are also + **read-only**. + + For example, this means that you should not make your own :class:`User` instances + nor should you modify the :class:`User` instance yourself. + + If you want to get one of these model classes instances they'd have to be through + the cache, and a common way of doing so is through the :func:`utils.find` function + or attributes of model classes that you receive from the events specified in the + :ref:`discord-api-events`. + +.. note:: + + Nearly all classes here have :ref:`py:slots` defined which means that it is + impossible to have dynamic attributes to the data classes. + + +ClientUser +~~~~~~~~~~~~ + +.. attributetable:: ClientUser + +.. autoclass:: ClientUser() + :members: + :inherited-members: + +User +~~~~~ + +.. attributetable:: User + +.. autoclass:: User() + :members: + :inherited-members: + :exclude-members: history, typing + + .. automethod:: history + :async-for: + + .. automethod:: typing + :async-with: + +Attachment +~~~~~~~~~~~ + +.. attributetable:: Attachment + +.. autoclass:: Attachment() + :members: + +Asset +~~~~~ + +.. attributetable:: Asset + +.. autoclass:: Asset() + :members: + :inherited-members: + +Message +~~~~~~~ + +.. attributetable:: Message + +.. autoclass:: Message() + :members: + +Component +~~~~~~~~~~ + +.. attributetable:: Component + +.. autoclass:: Component() + :members: + +ActionRow +~~~~~~~~~~ + +.. attributetable:: ActionRow + +.. autoclass:: ActionRow() + :members: + +Button +~~~~~~~ + +.. attributetable:: Button + +.. autoclass:: Button() + :members: + :inherited-members: + +SelectMenu +~~~~~~~~~~~ + +.. attributetable:: SelectMenu + +.. autoclass:: SelectMenu() + :members: + :inherited-members: + + +DeletedReferencedMessage +~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: DeletedReferencedMessage + +.. autoclass:: DeletedReferencedMessage() + :members: + + +Reaction +~~~~~~~~~ + +.. attributetable:: Reaction + +.. autoclass:: Reaction() + :members: + :exclude-members: users + + .. automethod:: users + :async-for: + +Guild +~~~~~~ + +.. attributetable:: Guild + +.. autoclass:: Guild() + :members: + :exclude-members: fetch_members, audit_logs + + .. automethod:: fetch_members + :async-for: + + .. automethod:: audit_logs + :async-for: + +.. class:: BanEntry + + A namedtuple which represents a ban returned from :meth:`~Guild.bans`. + + .. attribute:: reason + + The reason this user was banned. + + :type: Optional[:class:`str`] + .. attribute:: user + + The :class:`User` that was banned. + + :type: :class:`User` + + +Integration +~~~~~~~~~~~~ + +.. autoclass:: Integration() + :members: + +.. autoclass:: IntegrationAccount() + :members: + +.. autoclass:: BotIntegration() + :members: + +.. autoclass:: IntegrationApplication() + :members: + +.. autoclass:: StreamIntegration() + :members: + +Interaction +~~~~~~~~~~~~ + +.. attributetable:: Interaction + +.. autoclass:: Interaction() + :members: + +InteractionResponse +~~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: InteractionResponse + +.. autoclass:: InteractionResponse() + :members: + +InteractionMessage +~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: InteractionMessage + +.. autoclass:: InteractionMessage() + :members: + +Member +~~~~~~ + +.. attributetable:: Member + +.. autoclass:: Member() + :members: + :inherited-members: + :exclude-members: history, typing + + .. automethod:: history + :async-for: + + .. automethod:: typing + :async-with: + +Spotify +~~~~~~~~ + +.. attributetable:: Spotify + +.. autoclass:: Spotify() + :members: + +VoiceState +~~~~~~~~~~~ + +.. attributetable:: VoiceState + +.. autoclass:: VoiceState() + :members: + +Emoji +~~~~~ + +.. attributetable:: Emoji + +.. autoclass:: Emoji() + :members: + :inherited-members: + +PartialEmoji +~~~~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: PartialEmoji + +.. autoclass:: PartialEmoji() + :members: + :inherited-members: + +Role +~~~~~ + +.. attributetable:: Role + +.. autoclass:: Role() + :members: + +RoleTags +~~~~~~~~~~ + +.. attributetable:: RoleTags + +.. autoclass:: RoleTags() + :members: + +PartialMessageable +~~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: PartialMessageable + +.. autoclass:: PartialMessageable() + :members: + :inherited-members: + +TextChannel +~~~~~~~~~~~~ + +.. attributetable:: TextChannel + +.. autoclass:: TextChannel() + :members: + :inherited-members: + :exclude-members: history, typing + + .. automethod:: history + :async-for: + + .. automethod:: typing + :async-with: + +Thread +~~~~~~~~ + +.. attributetable:: Thread + +.. autoclass:: Thread() + :members: + :inherited-members: + :exclude-members: history, typing + + .. automethod:: history + :async-for: + + .. automethod:: typing + :async-with: + +ThreadMember +~~~~~~~~~~~~~ + +.. attributetable:: ThreadMember + +.. autoclass:: ThreadMember() + :members: + +StoreChannel +~~~~~~~~~~~~~ + +.. attributetable:: StoreChannel + +.. autoclass:: StoreChannel() + :members: + :inherited-members: + +VoiceChannel +~~~~~~~~~~~~~ + +.. attributetable:: VoiceChannel + +.. autoclass:: VoiceChannel() + :members: + :inherited-members: + +StageChannel +~~~~~~~~~~~~~ + +.. attributetable:: StageChannel + +.. autoclass:: StageChannel() + :members: + :inherited-members: + + +StageInstance +~~~~~~~~~~~~~~ + +.. attributetable:: StageInstance + +.. autoclass:: StageInstance() + :members: + +CategoryChannel +~~~~~~~~~~~~~~~~~ + +.. attributetable:: CategoryChannel + +.. autoclass:: CategoryChannel() + :members: + :inherited-members: + +DMChannel +~~~~~~~~~ + +.. attributetable:: DMChannel + +.. autoclass:: DMChannel() + :members: + :inherited-members: + :exclude-members: history, typing + + .. automethod:: history + :async-for: + + .. automethod:: typing + :async-with: + +GroupChannel +~~~~~~~~~~~~ + +.. attributetable:: GroupChannel + +.. autoclass:: GroupChannel() + :members: + :inherited-members: + :exclude-members: history, typing + + .. automethod:: history + :async-for: + + .. automethod:: typing + :async-with: + +PartialInviteGuild +~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: PartialInviteGuild + +.. autoclass:: PartialInviteGuild() + :members: + +PartialInviteChannel +~~~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: PartialInviteChannel + +.. autoclass:: PartialInviteChannel() + :members: + +Invite +~~~~~~~ + +.. attributetable:: Invite + +.. autoclass:: Invite() + :members: + +Template +~~~~~~~~~ + +.. attributetable:: Template + +.. autoclass:: Template() + :members: + +WidgetChannel +~~~~~~~~~~~~~~~ + +.. attributetable:: WidgetChannel + +.. autoclass:: WidgetChannel() + :members: + +WidgetMember +~~~~~~~~~~~~~ + +.. attributetable:: WidgetMember + +.. autoclass:: WidgetMember() + :members: + :inherited-members: + +Widget +~~~~~~~ + +.. attributetable:: Widget + +.. autoclass:: Widget() + :members: + +StickerPack +~~~~~~~~~~~~~ + +.. attributetable:: StickerPack + +.. autoclass:: StickerPack() + :members: + +StickerItem +~~~~~~~~~~~~~ + +.. attributetable:: StickerItem + +.. autoclass:: StickerItem() + :members: + +Sticker +~~~~~~~~~~~~~~~ + +.. attributetable:: Sticker + +.. autoclass:: Sticker() + :members: + +StandardSticker +~~~~~~~~~~~~~~~~ + +.. attributetable:: StandardSticker + +.. autoclass:: StandardSticker() + :members: + +GuildSticker +~~~~~~~~~~~~~ + +.. attributetable:: GuildSticker + +.. autoclass:: GuildSticker() + :members: + +RawTypingEvent +~~~~~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: RawTypingEvent + +.. autoclass:: RawTypingEvent() + :members: + +RawMessageDeleteEvent +~~~~~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: RawMessageDeleteEvent + +.. autoclass:: RawMessageDeleteEvent() + :members: + +RawBulkMessageDeleteEvent +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: RawBulkMessageDeleteEvent + +.. autoclass:: RawBulkMessageDeleteEvent() + :members: + +RawMessageUpdateEvent +~~~~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: RawMessageUpdateEvent + +.. autoclass:: RawMessageUpdateEvent() + :members: + +RawReactionActionEvent +~~~~~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: RawReactionActionEvent + +.. autoclass:: RawReactionActionEvent() + :members: + +RawReactionClearEvent +~~~~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: RawReactionClearEvent + +.. autoclass:: RawReactionClearEvent() + :members: + +RawReactionClearEmojiEvent +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: RawReactionClearEmojiEvent + +.. autoclass:: RawReactionClearEmojiEvent() + :members: + +RawIntegrationDeleteEvent +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: RawIntegrationDeleteEvent + +.. autoclass:: RawIntegrationDeleteEvent() + :members: + +PartialWebhookGuild +~~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: PartialWebhookGuild + +.. autoclass:: PartialWebhookGuild() + :members: + +PartialWebhookChannel +~~~~~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: PartialWebhookChannel + +.. autoclass:: PartialWebhookChannel() + :members: + +.. _discord_api_data: + +Data Classes +-------------- + +Some classes are just there to be data containers, this lists them. + +Unlike :ref:`models ` you are allowed to create +most of these yourself, even if they can also be used to hold attributes. + +Nearly all classes here have :ref:`py:slots` defined which means that it is +impossible to have dynamic attributes to the data classes. + +The only exception to this rule is :class:`Object`, which is made with +dynamic attributes in mind. + + +Object +~~~~~~~ + +.. attributetable:: Object + +.. autoclass:: Object + :members: + +Embed +~~~~~~ + +.. attributetable:: Embed + +.. autoclass:: Embed + :members: + +AllowedMentions +~~~~~~~~~~~~~~~~~ + +.. attributetable:: AllowedMentions + +.. autoclass:: AllowedMentions + :members: + +MessageReference +~~~~~~~~~~~~~~~~~ + +.. attributetable:: MessageReference + +.. autoclass:: MessageReference + :members: + +PartialMessage +~~~~~~~~~~~~~~~~~ + +.. attributetable:: PartialMessage + +.. autoclass:: PartialMessage + :members: + +SelectOption +~~~~~~~~~~~~~ + +.. attributetable:: SelectOption + +.. autoclass:: SelectOption + :members: + +Intents +~~~~~~~~~~ + +.. attributetable:: Intents + +.. autoclass:: Intents + :members: + +MemberCacheFlags +~~~~~~~~~~~~~~~~~~ + +.. attributetable:: MemberCacheFlags + +.. autoclass:: MemberCacheFlags + :members: + +ApplicationFlags +~~~~~~~~~~~~~~~~~ + +.. attributetable:: ApplicationFlags + +.. autoclass:: ApplicationFlags + :members: + +File +~~~~~ + +.. attributetable:: File + +.. autoclass:: File + :members: + +Colour +~~~~~~ + +.. attributetable:: Colour + +.. autoclass:: Colour + :members: + +BaseActivity +~~~~~~~~~~~~~~ + +.. attributetable:: BaseActivity + +.. autoclass:: BaseActivity + :members: + +Activity +~~~~~~~~~ + +.. attributetable:: Activity + +.. autoclass:: Activity + :members: + +Game +~~~~~ + +.. attributetable:: Game + +.. autoclass:: Game + :members: + +Streaming +~~~~~~~~~~~ + +.. attributetable:: Streaming + +.. autoclass:: Streaming + :members: + +CustomActivity +~~~~~~~~~~~~~~~ + +.. attributetable:: CustomActivity + +.. autoclass:: CustomActivity + :members: + +Permissions +~~~~~~~~~~~~ + +.. attributetable:: Permissions + +.. autoclass:: Permissions + :members: + +PermissionOverwrite +~~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: PermissionOverwrite + +.. autoclass:: PermissionOverwrite + :members: + +ShardInfo +~~~~~~~~~~~ + +.. attributetable:: ShardInfo + +.. autoclass:: ShardInfo() + :members: + +SystemChannelFlags +~~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: SystemChannelFlags + +.. autoclass:: SystemChannelFlags() + :members: + +MessageFlags +~~~~~~~~~~~~ + +.. attributetable:: MessageFlags + +.. autoclass:: MessageFlags() + :members: + +PublicUserFlags +~~~~~~~~~~~~~~~ + +.. attributetable:: PublicUserFlags + +.. autoclass:: PublicUserFlags() + :members: + +.. _discord_ui_kit: + +Bot UI Kit +------------- + +The library has helpers to help create component-based UIs. + +View +~~~~~~~ + +.. attributetable:: discord.ui.View + +.. autoclass:: discord.ui.View + :members: + +Item +~~~~~~~ + +.. attributetable:: discord.ui.Item + +.. autoclass:: discord.ui.Item + :members: + +Button +~~~~~~~ + +.. attributetable:: discord.ui.Button + +.. autoclass:: discord.ui.Button + :members: + :inherited-members: + +.. autofunction:: discord.ui.button + +Select +~~~~~~~ + +.. attributetable:: discord.ui.Select + +.. autoclass:: discord.ui.Select + :members: + :inherited-members: + +.. autofunction:: discord.ui.select + + +Exceptions +------------ + +The following exceptions are thrown by the library. + +.. autoexception:: DiscordException + +.. autoexception:: ClientException + +.. autoexception:: LoginFailure + +.. autoexception:: NoMoreItems + +.. autoexception:: HTTPException + :members: + +.. autoexception:: Forbidden + +.. autoexception:: NotFound + +.. autoexception:: DiscordServerError + +.. autoexception:: InvalidData + +.. autoexception:: InvalidArgument + +.. autoexception:: GatewayNotFound + +.. autoexception:: ConnectionClosed + +.. autoexception:: PrivilegedIntentsRequired + +.. autoexception:: InteractionResponded + +.. autoexception:: discord.opus.OpusError + +.. autoexception:: discord.opus.OpusNotLoaded + +Exception Hierarchy +~~~~~~~~~~~~~~~~~~~~~ + +.. exception_hierarchy:: + + - :exc:`Exception` + - :exc:`DiscordException` + - :exc:`ClientException` + - :exc:`InvalidData` + - :exc:`InvalidArgument` + - :exc:`LoginFailure` + - :exc:`ConnectionClosed` + - :exc:`PrivilegedIntentsRequired` + - :exc:`InteractionResponded` + - :exc:`NoMoreItems` + - :exc:`GatewayNotFound` + - :exc:`HTTPException` + - :exc:`Forbidden` + - :exc:`NotFound` + - :exc:`DiscordServerError` diff --git a/docs/Python/html/_sources/discord.rst.txt b/docs/Python/html/_sources/discord.rst.txt new file mode 100644 index 00000000..ac12417f --- /dev/null +++ b/docs/Python/html/_sources/discord.rst.txt @@ -0,0 +1,96 @@ +:orphan: + +.. _discord-intro: + +Creating a Bot Account +======================== + +In order to work with the library and the Discord API in general, we must first create a Discord Bot account. + +Creating a Bot account is a pretty straightforward process. + +1. Make sure you're logged on to the `Discord website `_. +2. Navigate to the `application page `_ +3. Click on the "New Application" button. + + .. image:: /images/discord_create_app_button.png + :alt: The new application button. + +4. Give the application a name and click "Create". + + .. image:: /images/discord_create_app_form.png + :alt: The new application form filled in. + +5. Create a Bot User by navigating to the "Bot" tab and clicking "Add Bot". + + - Click "Yes, do it!" to continue. + + .. image:: /images/discord_create_bot_user.png + :alt: The Add Bot button. +6. Make sure that **Public Bot** is ticked if you want others to invite your bot. + + - You should also make sure that **Require OAuth2 Code Grant** is unchecked unless you + are developing a service that needs it. If you're unsure, then **leave it unchecked**. + + .. image:: /images/discord_bot_user_options.png + :alt: How the Bot User options should look like for most people. + +7. Copy the token using the "Copy" button. + + - **This is not the Client Secret at the General Information page.** + + .. warning:: + + It should be worth noting that this token is essentially your bot's + password. You should **never** share this with someone else. In doing so, + someone can log in to your bot and do malicious things, such as leaving + servers, ban all members inside a server, or pinging everyone maliciously. + + The possibilities are endless, so **do not share this token.** + + If you accidentally leaked your token, click the "Regenerate" button as soon + as possible. This revokes your old token and re-generates a new one. + Now you need to use the new token to login. + +And that's it. You now have a bot account and you can login with that token. + +.. _discord_invite_bot: + +Inviting Your Bot +------------------- + +So you've made a Bot User but it's not actually in any server. + +If you want to invite your bot you must create an invite URL for it. + +1. Make sure you're logged on to the `Discord website `_. +2. Navigate to the `application page `_ +3. Click on your bot's page. +4. Go to the "OAuth2" tab. + + .. image:: /images/discord_oauth2.png + :alt: How the OAuth2 page should look like. + +5. Tick the "bot" checkbox under "scopes". + + .. image:: /images/discord_oauth2_scope.png + :alt: The scopes checkbox with "bot" ticked. + +6. Tick the permissions required for your bot to function under "Bot Permissions". + + - Please be aware of the consequences of requiring your bot to have the "Administrator" permission. + + - Bot owners must have 2FA enabled for certain actions and permissions when added in servers that have Server-Wide 2FA enabled. Check the `2FA support page `_ for more information. + + .. image:: /images/discord_oauth2_perms.png + :alt: The permission checkboxes with some permissions checked. + +7. Now the resulting URL can be used to add your bot to a server. Copy and paste the URL into your browser, choose a server to invite the bot to, and click "Authorize". + + +.. note:: + + The person adding the bot needs "Manage Server" permissions to do so. + +If you want to generate this URL dynamically at run-time inside your bot and using the +:class:`discord.Permissions` interface, you can use :func:`discord.utils.oauth_url`. diff --git a/docs/Python/html/_sources/ext/commands/api.rst.txt b/docs/Python/html/_sources/ext/commands/api.rst.txt new file mode 100644 index 00000000..f70d835c --- /dev/null +++ b/docs/Python/html/_sources/ext/commands/api.rst.txt @@ -0,0 +1,681 @@ +.. currentmodule:: discord + +API Reference +=============== + +The following section outlines the API of discord.py's command extension module. + +.. _ext_commands_api_bot: + +Bots +------ + +Bot +~~~~ + +.. attributetable:: discord.ext.commands.Bot + +.. autoclass:: discord.ext.commands.Bot + :members: + :inherited-members: + :exclude-members: after_invoke, before_invoke, check, check_once, command, event, group, listen + + .. automethod:: Bot.after_invoke() + :decorator: + + .. automethod:: Bot.before_invoke() + :decorator: + + .. automethod:: Bot.check() + :decorator: + + .. automethod:: Bot.check_once() + :decorator: + + .. automethod:: Bot.command(*args, **kwargs) + :decorator: + + .. automethod:: Bot.event() + :decorator: + + .. automethod:: Bot.group(*args, **kwargs) + :decorator: + + .. automethod:: Bot.listen(name=None) + :decorator: + +AutoShardedBot +~~~~~~~~~~~~~~~~ + +.. attributetable:: discord.ext.commands.AutoShardedBot + +.. autoclass:: discord.ext.commands.AutoShardedBot + :members: + +Prefix Helpers +---------------- + +.. autofunction:: discord.ext.commands.when_mentioned + +.. autofunction:: discord.ext.commands.when_mentioned_or + +.. _ext_commands_api_events: + +Event Reference +----------------- + +These events function similar to :ref:`the regular events `, except they +are custom to the command extension module. + +.. function:: discord.ext.commands.on_command_error(ctx, error) + + An error handler that is called when an error is raised + inside a command either through user input error, check + failure, or an error in your own code. + + A default one is provided (:meth:`.Bot.on_command_error`). + + :param ctx: The invocation context. + :type ctx: :class:`.Context` + :param error: The error that was raised. + :type error: :class:`.CommandError` derived + +.. function:: discord.ext.commands.on_command(ctx) + + An event that is called when a command is found and is about to be invoked. + + This event is called regardless of whether the command itself succeeds via + error or completes. + + :param ctx: The invocation context. + :type ctx: :class:`.Context` + +.. function:: discord.ext.commands.on_command_completion(ctx) + + An event that is called when a command has completed its invocation. + + This event is called only if the command succeeded, i.e. all checks have + passed and the user input it correctly. + + :param ctx: The invocation context. + :type ctx: :class:`.Context` + +.. _ext_commands_api_command: + +Commands +---------- + +Decorators +~~~~~~~~~~~~ + +.. autofunction:: discord.ext.commands.command + :decorator: + +.. autofunction:: discord.ext.commands.group + :decorator: + +Command +~~~~~~~~~ + +.. attributetable:: discord.ext.commands.Command + +.. autoclass:: discord.ext.commands.Command + :members: + :special-members: __call__ + :exclude-members: after_invoke, before_invoke, error + + .. automethod:: Command.after_invoke() + :decorator: + + .. automethod:: Command.before_invoke() + :decorator: + + .. automethod:: Command.error() + :decorator: + +Group +~~~~~~ + +.. attributetable:: discord.ext.commands.Group + +.. autoclass:: discord.ext.commands.Group + :members: + :inherited-members: + :exclude-members: after_invoke, before_invoke, command, error, group + + .. automethod:: Group.after_invoke() + :decorator: + + .. automethod:: Group.before_invoke() + :decorator: + + .. automethod:: Group.command(*args, **kwargs) + :decorator: + + .. automethod:: Group.error() + :decorator: + + .. automethod:: Group.group(*args, **kwargs) + :decorator: + +GroupMixin +~~~~~~~~~~~ + +.. attributetable:: discord.ext.commands.GroupMixin + +.. autoclass:: discord.ext.commands.GroupMixin + :members: + :exclude-members: command, group + + .. automethod:: GroupMixin.command(*args, **kwargs) + :decorator: + + .. automethod:: GroupMixin.group(*args, **kwargs) + :decorator: + +.. _ext_commands_api_cogs: + +Cogs +------ + +Cog +~~~~ + +.. attributetable:: discord.ext.commands.Cog + +.. autoclass:: discord.ext.commands.Cog + :members: + +CogMeta +~~~~~~~~ + +.. attributetable:: discord.ext.commands.CogMeta + +.. autoclass:: discord.ext.commands.CogMeta + :members: + +.. _ext_commands_help_command: + +Help Commands +--------------- + +HelpCommand +~~~~~~~~~~~~ + +.. attributetable:: discord.ext.commands.HelpCommand + +.. autoclass:: discord.ext.commands.HelpCommand + :members: + +DefaultHelpCommand +~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: discord.ext.commands.DefaultHelpCommand + +.. autoclass:: discord.ext.commands.DefaultHelpCommand + :members: + :exclude-members: send_bot_help, send_cog_help, send_group_help, send_command_help, prepare_help_command + +MinimalHelpCommand +~~~~~~~~~~~~~~~~~~~ + +.. attributetable:: discord.ext.commands.MinimalHelpCommand + +.. autoclass:: discord.ext.commands.MinimalHelpCommand + :members: + :exclude-members: send_bot_help, send_cog_help, send_group_help, send_command_help, prepare_help_command + +Paginator +~~~~~~~~~~ + +.. attributetable:: discord.ext.commands.Paginator + +.. autoclass:: discord.ext.commands.Paginator + :members: + +Enums +------ + +.. class:: BucketType + :module: discord.ext.commands + + Specifies a type of bucket for, e.g. a cooldown. + + .. attribute:: default + + The default bucket operates on a global basis. + .. attribute:: user + + The user bucket operates on a per-user basis. + .. attribute:: guild + + The guild bucket operates on a per-guild basis. + .. attribute:: channel + + The channel bucket operates on a per-channel basis. + .. attribute:: member + + The member bucket operates on a per-member basis. + .. attribute:: category + + The category bucket operates on a per-category basis. + .. attribute:: role + + The role bucket operates on a per-role basis. + + .. versionadded:: 1.3 + + +.. _ext_commands_api_checks: + +Checks +------- + +.. autofunction:: discord.ext.commands.check(predicate) + :decorator: + +.. autofunction:: discord.ext.commands.check_any(*checks) + :decorator: + +.. autofunction:: discord.ext.commands.has_role(item) + :decorator: + +.. autofunction:: discord.ext.commands.has_permissions(**perms) + :decorator: + +.. autofunction:: discord.ext.commands.has_guild_permissions(**perms) + :decorator: + +.. autofunction:: discord.ext.commands.has_any_role(*items) + :decorator: + +.. autofunction:: discord.ext.commands.bot_has_role(item) + :decorator: + +.. autofunction:: discord.ext.commands.bot_has_permissions(**perms) + :decorator: + +.. autofunction:: discord.ext.commands.bot_has_guild_permissions(**perms) + :decorator: + +.. autofunction:: discord.ext.commands.bot_has_any_role(*items) + :decorator: + +.. autofunction:: discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default) + :decorator: + +.. autofunction:: discord.ext.commands.dynamic_cooldown(cooldown, type=BucketType.default) + :decorator: + +.. autofunction:: discord.ext.commands.max_concurrency(number, per=discord.ext.commands.BucketType.default, *, wait=False) + :decorator: + +.. autofunction:: discord.ext.commands.before_invoke(coro) + :decorator: + +.. autofunction:: discord.ext.commands.after_invoke(coro) + :decorator: + +.. autofunction:: discord.ext.commands.guild_only(,) + :decorator: + +.. autofunction:: discord.ext.commands.dm_only(,) + :decorator: + +.. autofunction:: discord.ext.commands.is_owner(,) + :decorator: + +.. autofunction:: discord.ext.commands.is_nsfw(,) + :decorator: + +.. _ext_commands_api_context: + +Cooldown +--------- + +.. attributetable:: discord.ext.commands.Cooldown + +.. autoclass:: discord.ext.commands.Cooldown + :members: + +Context +-------- + +.. attributetable:: discord.ext.commands.Context + +.. autoclass:: discord.ext.commands.Context + :members: + :inherited-members: + :exclude-members: history, typing + + .. automethod:: discord.ext.commands.Context.history + :async-for: + + .. automethod:: discord.ext.commands.Context.typing + :async-with: + +.. _ext_commands_api_converters: + +Converters +------------ + +.. autoclass:: discord.ext.commands.Converter + :members: + +.. autoclass:: discord.ext.commands.ObjectConverter + :members: + +.. autoclass:: discord.ext.commands.MemberConverter + :members: + +.. autoclass:: discord.ext.commands.UserConverter + :members: + +.. autoclass:: discord.ext.commands.MessageConverter + :members: + +.. autoclass:: discord.ext.commands.PartialMessageConverter + :members: + +.. autoclass:: discord.ext.commands.GuildChannelConverter + :members: + +.. autoclass:: discord.ext.commands.TextChannelConverter + :members: + +.. autoclass:: discord.ext.commands.VoiceChannelConverter + :members: + +.. autoclass:: discord.ext.commands.StoreChannelConverter + :members: + +.. autoclass:: discord.ext.commands.StageChannelConverter + :members: + +.. autoclass:: discord.ext.commands.CategoryChannelConverter + :members: + +.. autoclass:: discord.ext.commands.InviteConverter + :members: + +.. autoclass:: discord.ext.commands.GuildConverter + :members: + +.. autoclass:: discord.ext.commands.RoleConverter + :members: + +.. autoclass:: discord.ext.commands.GameConverter + :members: + +.. autoclass:: discord.ext.commands.ColourConverter + :members: + +.. autoclass:: discord.ext.commands.EmojiConverter + :members: + +.. autoclass:: discord.ext.commands.PartialEmojiConverter + :members: + +.. autoclass:: discord.ext.commands.ThreadConverter + :members: + +.. autoclass:: discord.ext.commands.GuildStickerConverter + :members: + +.. autoclass:: discord.ext.commands.clean_content + :members: + +.. autoclass:: discord.ext.commands.Greedy() + +.. autofunction:: discord.ext.commands.run_converters + +Option +~~~~~~ + +.. autoclass:: discord.ext.commands.Option + :members: + +Flag Converter +~~~~~~~~~~~~~~~ + +.. autoclass:: discord.ext.commands.FlagConverter + :members: + +.. autoclass:: discord.ext.commands.Flag() + :members: + +.. autofunction:: discord.ext.commands.flag + +.. _ext_commands_api_errors: + +Exceptions +----------- + +.. autoexception:: discord.ext.commands.CommandError + :members: + +.. autoexception:: discord.ext.commands.ConversionError + :members: + +.. autoexception:: discord.ext.commands.MissingRequiredArgument + :members: + +.. autoexception:: discord.ext.commands.ArgumentParsingError + :members: + +.. autoexception:: discord.ext.commands.UnexpectedQuoteError + :members: + +.. autoexception:: discord.ext.commands.InvalidEndOfQuotedStringError + :members: + +.. autoexception:: discord.ext.commands.ExpectedClosingQuoteError + :members: + +.. autoexception:: discord.ext.commands.BadArgument + :members: + +.. autoexception:: discord.ext.commands.BadUnionArgument + :members: + +.. autoexception:: discord.ext.commands.BadLiteralArgument + :members: + +.. autoexception:: discord.ext.commands.PrivateMessageOnly + :members: + +.. autoexception:: discord.ext.commands.NoPrivateMessage + :members: + +.. autoexception:: discord.ext.commands.CheckFailure + :members: + +.. autoexception:: discord.ext.commands.CheckAnyFailure + :members: + +.. autoexception:: discord.ext.commands.CommandNotFound + :members: + +.. autoexception:: discord.ext.commands.DisabledCommand + :members: + +.. autoexception:: discord.ext.commands.CommandInvokeError + :members: + +.. autoexception:: discord.ext.commands.TooManyArguments + :members: + +.. autoexception:: discord.ext.commands.UserInputError + :members: + +.. autoexception:: discord.ext.commands.CommandOnCooldown + :members: + +.. autoexception:: discord.ext.commands.MaxConcurrencyReached + :members: + +.. autoexception:: discord.ext.commands.NotOwner + :members: + +.. autoexception:: discord.ext.commands.MessageNotFound + :members: + +.. autoexception:: discord.ext.commands.MemberNotFound + :members: + +.. autoexception:: discord.ext.commands.GuildNotFound + :members: + +.. autoexception:: discord.ext.commands.UserNotFound + :members: + +.. autoexception:: discord.ext.commands.ChannelNotFound + :members: + +.. autoexception:: discord.ext.commands.ChannelNotReadable + :members: + +.. autoexception:: discord.ext.commands.ThreadNotFound + :members: + +.. autoexception:: discord.ext.commands.BadColourArgument + :members: + +.. autoexception:: discord.ext.commands.RoleNotFound + :members: + +.. autoexception:: discord.ext.commands.BadInviteArgument + :members: + +.. autoexception:: discord.ext.commands.EmojiNotFound + :members: + +.. autoexception:: discord.ext.commands.PartialEmojiConversionFailure + :members: + +.. autoexception:: discord.ext.commands.GuildStickerNotFound + :members: + +.. autoexception:: discord.ext.commands.BadBoolArgument + :members: + +.. autoexception:: discord.ext.commands.MissingPermissions + :members: + +.. autoexception:: discord.ext.commands.BotMissingPermissions + :members: + +.. autoexception:: discord.ext.commands.MissingRole + :members: + +.. autoexception:: discord.ext.commands.BotMissingRole + :members: + +.. autoexception:: discord.ext.commands.MissingAnyRole + :members: + +.. autoexception:: discord.ext.commands.BotMissingAnyRole + :members: + +.. autoexception:: discord.ext.commands.NSFWChannelRequired + :members: + +.. autoexception:: discord.ext.commands.FlagError + :members: + +.. autoexception:: discord.ext.commands.BadFlagArgument + :members: + +.. autoexception:: discord.ext.commands.MissingFlagArgument + :members: + +.. autoexception:: discord.ext.commands.TooManyFlags + :members: + +.. autoexception:: discord.ext.commands.MissingRequiredFlag + :members: + +.. autoexception:: discord.ext.commands.ExtensionError + :members: + +.. autoexception:: discord.ext.commands.ExtensionAlreadyLoaded + :members: + +.. autoexception:: discord.ext.commands.ExtensionNotLoaded + :members: + +.. autoexception:: discord.ext.commands.NoEntryPointError + :members: + +.. autoexception:: discord.ext.commands.ExtensionFailed + :members: + +.. autoexception:: discord.ext.commands.ExtensionNotFound + :members: + +.. autoexception:: discord.ext.commands.CommandRegistrationError + :members: + + +Exception Hierarchy +~~~~~~~~~~~~~~~~~~~~~ + +.. exception_hierarchy:: + + - :exc:`~.DiscordException` + - :exc:`~.commands.CommandError` + - :exc:`~.commands.ConversionError` + - :exc:`~.commands.UserInputError` + - :exc:`~.commands.MissingRequiredArgument` + - :exc:`~.commands.TooManyArguments` + - :exc:`~.commands.BadArgument` + - :exc:`~.commands.MessageNotFound` + - :exc:`~.commands.MemberNotFound` + - :exc:`~.commands.GuildNotFound` + - :exc:`~.commands.UserNotFound` + - :exc:`~.commands.ChannelNotFound` + - :exc:`~.commands.ChannelNotReadable` + - :exc:`~.commands.BadColourArgument` + - :exc:`~.commands.RoleNotFound` + - :exc:`~.commands.BadInviteArgument` + - :exc:`~.commands.EmojiNotFound` + - :exc:`~.commands.GuildStickerNotFound` + - :exc:`~.commands.PartialEmojiConversionFailure` + - :exc:`~.commands.BadBoolArgument` + - :exc:`~.commands.ThreadNotFound` + - :exc:`~.commands.FlagError` + - :exc:`~.commands.BadFlagArgument` + - :exc:`~.commands.MissingFlagArgument` + - :exc:`~.commands.TooManyFlags` + - :exc:`~.commands.MissingRequiredFlag` + - :exc:`~.commands.BadUnionArgument` + - :exc:`~.commands.BadLiteralArgument` + - :exc:`~.commands.ArgumentParsingError` + - :exc:`~.commands.UnexpectedQuoteError` + - :exc:`~.commands.InvalidEndOfQuotedStringError` + - :exc:`~.commands.ExpectedClosingQuoteError` + - :exc:`~.commands.CommandNotFound` + - :exc:`~.commands.CheckFailure` + - :exc:`~.commands.CheckAnyFailure` + - :exc:`~.commands.PrivateMessageOnly` + - :exc:`~.commands.NoPrivateMessage` + - :exc:`~.commands.NotOwner` + - :exc:`~.commands.MissingPermissions` + - :exc:`~.commands.BotMissingPermissions` + - :exc:`~.commands.MissingRole` + - :exc:`~.commands.BotMissingRole` + - :exc:`~.commands.MissingAnyRole` + - :exc:`~.commands.BotMissingAnyRole` + - :exc:`~.commands.NSFWChannelRequired` + - :exc:`~.commands.DisabledCommand` + - :exc:`~.commands.CommandInvokeError` + - :exc:`~.commands.CommandOnCooldown` + - :exc:`~.commands.MaxConcurrencyReached` + - :exc:`~.commands.ExtensionError` + - :exc:`~.commands.ExtensionAlreadyLoaded` + - :exc:`~.commands.ExtensionNotLoaded` + - :exc:`~.commands.NoEntryPointError` + - :exc:`~.commands.ExtensionFailed` + - :exc:`~.commands.ExtensionNotFound` + - :exc:`~.ClientException` + - :exc:`~.commands.CommandRegistrationError` diff --git a/docs/Python/html/_sources/ext/commands/cogs.rst.txt b/docs/Python/html/_sources/ext/commands/cogs.rst.txt new file mode 100644 index 00000000..25bb1a0b --- /dev/null +++ b/docs/Python/html/_sources/ext/commands/cogs.rst.txt @@ -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 ` named ``hello`` as well as a listener to listen to an :ref:`Event `. + +.. 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(f'Welcome {member.mention}.') + + @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(f'Hello {member.name}~') + else: + await ctx.send(f'Hello {member.name}... This feels familiar.') + 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:`list` 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) + diff --git a/docs/Python/html/_sources/ext/commands/commands.rst.txt b/docs/Python/html/_sources/ext/commands/commands.rst.txt new file mode 100644 index 00000000..f29dc70b --- /dev/null +++ b/docs/Python/html/_sources/ext/commands/commands.rst.txt @@ -0,0 +1,962 @@ +.. currentmodule:: discord + +.. _ext_commands_commands: + +Commands +========== + +One of the most appealing aspects of the command extension is how easy it is to define commands and +how you can arbitrarily nest groups and commands to have a rich sub-command system. + +Commands are defined by attaching it to a regular Python function. The command is then invoked by the user using a similar +signature to the Python function. + +For example, in the given command definition: + +.. code-block:: python3 + + @bot.command() + async def foo(ctx, arg): + await ctx.send(arg) + +With the following prefix (``$``), it would be invoked by the user via: + +.. code-block:: none + + $foo abc + +A command must always have at least one parameter, ``ctx``, which is the :class:`.Context` as the first one. + +There are two ways of registering a command. The first one is by using :meth:`.Bot.command` decorator, +as seen in the example above. The second is using the :func:`~ext.commands.command` decorator followed by +:meth:`.Bot.add_command` on the instance. + +Essentially, these two are equivalent: :: + + from discord.ext import commands + + bot = commands.Bot(command_prefix='$') + + @bot.command() + async def test(ctx): + pass + + # or: + + @commands.command() + async def test(ctx): + pass + + bot.add_command(test) + +Since the :meth:`.Bot.command` decorator is shorter and easier to comprehend, it will be the one used throughout the +documentation here. + +Any parameter that is accepted by the :class:`.Command` constructor can be passed into the decorator. For example, to change +the name to something other than the function would be as simple as doing this: + +.. code-block:: python3 + + @bot.command(name='list') + async def _list(ctx, arg): + pass + + +Parameters +------------ + +Since we define commands by making Python functions, we also define the argument passing behaviour by the function +parameters. + +Certain parameter types do different things in the user side and most forms of parameter types are supported. + +Positional +++++++++++++ + +The most basic form of parameter passing is the positional parameter. This is where we pass a parameter as-is: + +.. code-block:: python3 + + @bot.command() + async def test(ctx, arg): + await ctx.send(arg) + + +On the bot using side, you can provide positional arguments by just passing a regular string: + +.. image:: /images/commands/positional1.png + +To make use of a word with spaces in between, you should quote it: + +.. image:: /images/commands/positional2.png + +As a note of warning, if you omit the quotes, you will only get the first word: + +.. image:: /images/commands/positional3.png + +Since positional arguments are just regular Python arguments, you can have as many as you want: + +.. code-block:: python3 + + @bot.command() + async def test(ctx, arg1, arg2): + await ctx.send(f'You passed {arg1} and {arg2}') + +Variable +++++++++++ + +Sometimes you want users to pass in an undetermined number of parameters. The library supports this +similar to how variable list parameters are done in Python: + +.. code-block:: python3 + + @bot.command() + async def test(ctx, *args): + arguments = ', '.join(args) + await ctx.send(f'{len(args)} arguments: {arguments}') + +This allows our user to accept either one or many arguments as they please. This works similar to positional arguments, +so multi-word parameters should be quoted. + +For example, on the bot side: + +.. image:: /images/commands/variable1.png + +If the user wants to input a multi-word argument, they have to quote it like earlier: + +.. image:: /images/commands/variable2.png + +Do note that similar to the Python function behaviour, a user can technically pass no arguments +at all: + +.. image:: /images/commands/variable3.png + +Since the ``args`` variable is a :class:`py:tuple`, +you can do anything you would usually do with one. + +.. admonition:: Slash Command Only + + This functionally is currently not supported by the slash command API, so is turned into + a single ``STRING`` parameter on discord's end which we do our own parsing on. + +Keyword-Only Arguments +++++++++++++++++++++++++ + +When you want to handle parsing of the argument yourself or do not feel like you want to wrap multi-word user input into +quotes, you can ask the library to give you the rest as a single argument. We do this by using a **keyword-only argument**, +seen below: + +.. code-block:: python3 + + @bot.command() + async def test(ctx, *, arg): + await ctx.send(arg) + +.. warning:: + + You can only have one keyword-only argument due to parsing ambiguities. + +On the bot side, we do not need to quote input with spaces: + +.. image:: /images/commands/keyword1.png + +Do keep in mind that wrapping it in quotes leaves it as-is: + +.. image:: /images/commands/keyword2.png + +By default, the keyword-only arguments are stripped of white space to make it easier to work with. This behaviour can be +toggled by the :attr:`.Command.rest_is_raw` argument in the decorator. + +.. _ext_commands_context: + +Invocation Context +------------------- + +As seen earlier, every command must take at least a single parameter, called the :class:`~ext.commands.Context`. + +This parameter gives you access to something called the "invocation context". Essentially all the information you need to +know how the command was executed. It contains a lot of useful information: + +- :attr:`.Context.guild` to fetch the :class:`Guild` of the command, if any. +- :attr:`.Context.message` to fetch the :class:`Message` of the command. +- :attr:`.Context.author` to fetch the :class:`Member` or :class:`User` that called the command. +- :meth:`.Context.send` to send a message to the channel the command was used in. + +The context implements the :class:`abc.Messageable` interface, so anything you can do on a :class:`abc.Messageable` you +can do on the :class:`~ext.commands.Context`. + +.. admonition:: Slash Command Only + + :attr:`.Context.message` will be fake if in a slash command, it is not + recommended to access if :attr:`.Context.interaction` is not None as most + methods will error due to the message not actually existing. + +Converters +------------ + +Adding bot arguments with function parameters is only the first step in defining your bot's command interface. To actually +make use of the arguments, we usually want to convert the data into a target type. We call these +:ref:`ext_commands_api_converters`. + +Converters come in a few flavours: + +- A regular callable object that takes an argument as a sole parameter and returns a different type. + + - These range from your own function, to something like :class:`bool` or :class:`int`. + +- A custom class that inherits from :class:`~ext.commands.Converter`. + +.. _ext_commands_basic_converters: + +Basic Converters +++++++++++++++++++ + +At its core, a basic converter is a callable that takes in an argument and turns it into something else. + +For example, if we wanted to add two numbers together, we could request that they are turned into integers +for us by specifying the converter: + +.. code-block:: python3 + + @bot.command() + async def add(ctx, a: int, b: int): + await ctx.send(a + b) + +We specify converters by using something called a **function annotation**. This is a Python 3 exclusive feature that was +introduced in :pep:`3107`. + +This works with any callable, such as a function that would convert a string to all upper-case: + +.. code-block:: python3 + + def to_upper(argument): + return argument.upper() + + @bot.command() + async def up(ctx, *, content: to_upper): + await ctx.send(content) + +bool +^^^^^^ + +Unlike the other basic converters, the :class:`bool` converter is treated slightly different. Instead of casting directly to the :class:`bool` type, which would result in any non-empty argument returning ``True``, it instead evaluates the argument as ``True`` or ``False`` based on its given content: + +.. code-block:: python3 + + if lowered in ('yes', 'y', 'true', 't', '1', 'enable', 'on'): + return True + elif lowered in ('no', 'n', 'false', 'f', '0', 'disable', 'off'): + return False + +.. _ext_commands_adv_converters: + +Advanced Converters ++++++++++++++++++++++ + +Sometimes a basic converter doesn't have enough information that we need. For example, sometimes we want to get some +information from the :class:`Message` that called the command or we want to do some asynchronous processing. + +For this, the library provides the :class:`~ext.commands.Converter` interface. This allows you to have access to the +:class:`.Context` and have the callable be asynchronous. Defining a custom converter using this interface requires +overriding a single method, :meth:`.Converter.convert`. + +An example converter: + +.. code-block:: python3 + + import random + + class Slapper(commands.Converter): + async def convert(self, ctx, argument): + to_slap = random.choice(ctx.guild.members) + return f'{ctx.author} slapped {to_slap} because *{argument}*' + + @bot.command() + async def slap(ctx, *, reason: Slapper): + await ctx.send(reason) + +The converter provided can either be constructed or not. Essentially these two are equivalent: + +.. code-block:: python3 + + @bot.command() + async def slap(ctx, *, reason: Slapper): + await ctx.send(reason) + + # is the same as... + + @bot.command() + async def slap(ctx, *, reason: Slapper()): + await ctx.send(reason) + +Having the possibility of the converter be constructed allows you to set up some state in the converter's ``__init__`` for +fine tuning the converter. An example of this is actually in the library, :class:`~ext.commands.clean_content`. + +.. code-block:: python3 + + @bot.command() + async def clean(ctx, *, content: commands.clean_content): + await ctx.send(content) + + # or for fine-tuning + + @bot.command() + async def clean(ctx, *, content: commands.clean_content(use_nicknames=False)): + await ctx.send(content) + + +If a converter fails to convert an argument to its designated target type, the :exc:`.BadArgument` exception must be +raised. + +Inline Advanced Converters ++++++++++++++++++++++++++++++ + +If we don't want to inherit from :class:`~ext.commands.Converter`, we can still provide a converter that has the +advanced functionalities of an advanced converter and save us from specifying two types. + +For example, a common idiom would be to have a class and a converter for that class: + +.. code-block:: python3 + + class JoinDistance: + def __init__(self, joined, created): + self.joined = joined + self.created = created + + @property + def delta(self): + return self.joined - self.created + + class JoinDistanceConverter(commands.MemberConverter): + async def convert(self, ctx, argument): + member = await super().convert(ctx, argument) + return JoinDistance(member.joined_at, member.created_at) + + @bot.command() + async def delta(ctx, *, member: JoinDistanceConverter): + is_new = member.delta.days < 100 + if is_new: + await ctx.send("Hey you're pretty new!") + else: + await ctx.send("Hm you're not so new.") + +This can get tedious, so an inline advanced converter is possible through a :func:`classmethod` inside the type: + +.. code-block:: python3 + + class JoinDistance: + def __init__(self, joined, created): + self.joined = joined + self.created = created + + @classmethod + async def convert(cls, ctx, argument): + member = await commands.MemberConverter().convert(ctx, argument) + return cls(member.joined_at, member.created_at) + + @property + def delta(self): + return self.joined - self.created + + @bot.command() + async def delta(ctx, *, member: JoinDistance): + is_new = member.delta.days < 100 + if is_new: + await ctx.send("Hey you're pretty new!") + else: + await ctx.send("Hm you're not so new.") + +Discord Converters +++++++++++++++++++++ + +Working with :ref:`discord_api_models` is a fairly common thing when defining commands, as a result the library makes +working with them easy. + +For example, to receive a :class:`Member` you can just pass it as a converter: + +.. code-block:: python3 + + @bot.command() + async def joined(ctx, *, member: discord.Member): + await ctx.send(f'{member} joined on {member.joined_at}') + +When this command is executed, it attempts to convert the string given into a :class:`Member` and then passes it as a +parameter for the function. This works by checking if the string is a mention, an ID, a nickname, a username + discriminator, +or just a regular username. The default set of converters have been written to be as easy to use as possible. + +A lot of discord models work out of the gate as a parameter: + +- :class:`Object` (since v2.0) +- :class:`Member` +- :class:`User` +- :class:`Message` (since v1.1) +- :class:`PartialMessage` (since v1.7) +- :class:`abc.GuildChannel` (since 2.0) +- :class:`TextChannel` +- :class:`VoiceChannel` +- :class:`StageChannel` (since v1.7) +- :class:`StoreChannel` (since v1.7) +- :class:`CategoryChannel` +- :class:`Invite` +- :class:`Guild` (since v1.7) +- :class:`Role` +- :class:`Game` +- :class:`Colour` +- :class:`Emoji` +- :class:`PartialEmoji` +- :class:`Thread` (since v2.0) + +Having any of these set as the converter will intelligently convert the argument to the appropriate target type you +specify. + +Under the hood, these are implemented by the :ref:`ext_commands_adv_converters` interface. A table of the equivalent +converter is given below: + ++--------------------------+-------------------------------------------------+-----------------------------+ +| Discord Class | Converter | Supported By Slash Commands | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`Object` | :class:`~ext.commands.ObjectConverter` | Not currently | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`Member` | :class:`~ext.commands.MemberConverter` | Yes, as type 6 (USER) | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`User` | :class:`~ext.commands.UserConverter` | Yes, as type 6 (USER) | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`Message` | :class:`~ext.commands.MessageConverter` | Not currently | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`PartialMessage` | :class:`~ext.commands.PartialMessageConverter` | Not currently | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`.GuildChannel` | :class:`~ext.commands.GuildChannelConverter` | Yes, as type 7 (CHANNEL) | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`TextChannel` | :class:`~ext.commands.TextChannelConverter` | Yes, as type 7 (CHANNEL) | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`VoiceChannel` | :class:`~ext.commands.VoiceChannelConverter` | Yes, as type 7 (CHANNEL) | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`StageChannel` | :class:`~ext.commands.StageChannelConverter` | Yes, as type 7 (CHANNEL) | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`StoreChannel` | :class:`~ext.commands.StoreChannelConverter` | Yes, as type 7 (CHANNEL) | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`CategoryChannel` | :class:`~ext.commands.CategoryChannelConverter` | Yes, as type 7 (CHANNEL) | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`Thread` | :class:`~ext.commands.ThreadConverter` | Yes, as type 7 (CHANNEL) | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`Invite` | :class:`~ext.commands.InviteConverter` | Not currently | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`Guild` | :class:`~ext.commands.GuildConverter` | Not currently | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`Role` | :class:`~ext.commands.RoleConverter` | Yes, as type 8 (ROLE) | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`Game` | :class:`~ext.commands.GameConverter` | Not currently | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`Colour` | :class:`~ext.commands.ColourConverter` | Not currently | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`Emoji` | :class:`~ext.commands.EmojiConverter` | Not currently | ++--------------------------+-------------------------------------------------+-----------------------------+ +| :class:`PartialEmoji` | :class:`~ext.commands.PartialEmojiConverter` | Not currently | ++--------------------------+-------------------------------------------------+-----------------------------+ + +.. admonition:: Slash Command Only + + If a slash command is not marked on the table above as supported, it will be sent as type 3 (STRING) + and parsed by normal content parsing, see + `the discord documentation `_ + for all supported types by the API. + + +By providing the converter it allows us to use them as building blocks for another converter: + +.. code-block:: python3 + + class MemberRoles(commands.MemberConverter): + async def convert(self, ctx, argument): + member = await super().convert(ctx, argument) + return [role.name for role in member.roles[1:]] # Remove everyone role! + + @bot.command() + async def roles(ctx, *, member: MemberRoles): + """Tells you a member's roles.""" + await ctx.send('I see the following roles: ' + ', '.join(member)) + +.. _ext_commands_special_converters: + +Special Converters +++++++++++++++++++++ + +The command extension also has support for certain converters to allow for more advanced and intricate use cases that go +beyond the generic linear parsing. These converters allow you to introduce some more relaxed and dynamic grammar to your +commands in an easy to use manner. + +typing.Union +^^^^^^^^^^^^^^ + +A :data:`typing.Union` is a special type hint that allows for the command to take in any of the specific types instead of +a singular type. For example, given the following: + +.. code-block:: python3 + + import typing + + @bot.command() + async def union(ctx, what: typing.Union[discord.TextChannel, discord.Member]): + await ctx.send(what) + + +The ``what`` parameter would either take a :class:`discord.TextChannel` converter or a :class:`discord.Member` converter. +The way this works is through a left-to-right order. It first attempts to convert the input to a +:class:`discord.TextChannel`, and if it fails it tries to convert it to a :class:`discord.Member`. If all converters fail, +then a special error is raised, :exc:`~ext.commands.BadUnionArgument`. + +Note that any valid converter discussed above can be passed in to the argument list of a :data:`typing.Union`. + +.. admonition:: Slash Command Only + + These are not currently supported by the Discord API and will be sent as type 3 (STRING) + +typing.Optional +^^^^^^^^^^^^^^^^^ + +A :data:`typing.Optional` is a special type hint that allows for "back-referencing" behaviour. If the converter fails to +parse into the specified type, the parser will skip the parameter and then either ``None`` or the specified default will be +passed into the parameter instead. The parser will then continue on to the next parameters and converters, if any. + +Consider the following example: + +.. code-block:: python3 + + import typing + + @bot.command() + async def bottles(ctx, amount: typing.Optional[int] = 99, *, liquid="beer"): + await ctx.send(f'{amount} bottles of {liquid} on the wall!') + + +.. image:: /images/commands/optional1.png + +In this example, since the argument could not be converted into an ``int``, the default of ``99`` is passed and the parser +resumes handling, which in this case would be to pass it into the ``liquid`` parameter. + +.. note:: + + This converter only works in regular positional parameters, not variable parameters or keyword-only parameters. + +typing.Literal +^^^^^^^^^^^^^^^^ + +A :data:`typing.Literal` is a special type hint that requires the passed parameter to be equal to one of the listed values +after being converted to the same type. For example, given the following: + +.. code-block:: python3 + + from typing import Literal + + @bot.command() + async def shop(ctx, buy_sell: Literal['buy', 'sell'], amount: Literal[1, 2], *, item: str): + await ctx.send(f'{buy_sell.capitalize()}ing {amount} {item}(s)!') + + +The ``buy_sell`` parameter must be either the literal string ``"buy"`` or ``"sell"`` and ``amount`` must convert to the +``int`` ``1`` or ``2``. If ``buy_sell`` or ``amount`` don't match any value, then a special error is raised, +:exc:`~.ext.commands.BadLiteralArgument`. Any literal values can be mixed and matched within the same :data:`typing.Literal` converter. + +Note that ``typing.Literal[True]`` and ``typing.Literal[False]`` still follow the :class:`bool` converter rules. + +Greedy +^^^^^^^^ + +The :class:`~ext.commands.Greedy` converter is a generalisation of the :data:`typing.Optional` converter, except applied +to a list of arguments. In simple terms, this means that it tries to convert as much as it can until it can't convert +any further. + +Consider the following example: + +.. code-block:: python3 + + @bot.command() + async def slap(ctx, members: commands.Greedy[discord.Member], *, reason='no reason'): + slapped = ", ".join(x.name for x in members) + await ctx.send(f'{slapped} just got slapped for {reason}') + +When invoked, it allows for any number of members to be passed in: + +.. image:: /images/commands/greedy1.png + +The type passed when using this converter depends on the parameter type that it is being attached to: + +- Positional parameter types will receive either the default parameter or a :class:`list` of the converted values. +- Variable parameter types will be a :class:`tuple` as usual. +- Keyword-only parameter types will be the same as if :class:`~ext.commands.Greedy` was not passed at all. + +:class:`~ext.commands.Greedy` parameters can also be made optional by specifying an optional value. + +When mixed with the :data:`typing.Optional` converter you can provide simple and expressive command invocation syntaxes: + +.. code-block:: python3 + + import typing + + @bot.command() + async def ban(ctx, members: commands.Greedy[discord.Member], + delete_days: typing.Optional[int] = 0, *, + reason: str): + """Mass bans members with an optional delete_days parameter""" + for member in members: + await member.ban(delete_message_days=delete_days, reason=reason) + + +This command can be invoked any of the following ways: + +.. code-block:: none + + $ban @Member @Member2 spam bot + $ban @Member @Member2 7 spam bot + $ban @Member spam + +.. warning:: + + The usage of :class:`~ext.commands.Greedy` and :data:`typing.Optional` are powerful and useful, however as a + price, they open you up to some parsing ambiguities that might surprise some people. + + For example, a signature expecting a :data:`typing.Optional` of a :class:`discord.Member` followed by a + :class:`int` could catch a member named after a number due to the different ways a + :class:`~ext.commands.MemberConverter` decides to fetch members. You should take care to not introduce + unintended parsing ambiguities in your code. One technique would be to clamp down the expected syntaxes + allowed through custom converters or reordering the parameters to minimise clashes. + + To help aid with some parsing ambiguities, :class:`str`, ``None``, :data:`typing.Optional` and + :class:`~ext.commands.Greedy` are forbidden as parameters for the :class:`~ext.commands.Greedy` converter. + +.. _ext_commands_flag_converter: + +FlagConverter +++++++++++++++ + +.. versionadded:: 2.0 + +A :class:`~ext.commands.FlagConverter` allows the user to specify user-friendly "flags" using :pep:`526` type annotations +or a syntax more reminiscent of the :mod:`py:dataclasses` module. + +For example, the following code: + +.. code-block:: python3 + + from discord.ext import commands + import discord + + class BanFlags(commands.FlagConverter): + member: discord.Member + reason: str + days: int = 1 + + @commands.command() + async def ban(ctx, *, flags: BanFlags): + plural = f'{flags.days} days' if flags.days != 1 else f'{flags.days} day' + await ctx.send(f'Banned {flags.member} for {flags.reason!r} (deleted {plural} worth of messages)') + +Allows the user to invoke the command using a simple flag-like syntax: + +.. image:: /images/commands/flags1.png + +Flags use a syntax that allows the user to not require quotes when passing in values to the flag. The goal of the +flag syntax is to be as user-friendly as possible. This makes flags a good choice for complicated commands that can have +multiple knobs to turn or simulating keyword-only parameters in your external command interface. **It is recommended to use +keyword-only parameters with the flag converter**. This ensures proper parsing and behaviour with quoting. + +Internally, the :class:`~ext.commands.FlagConverter` class examines the class to find flags. A flag can either be a +class variable with a type annotation or a class variable that's been assigned the result of the :func:`~ext.commands.flag` +function. These flags are then used to define the interface that your users will use. The annotations correspond to +the converters that the flag arguments must adhere to. + +For most use cases, no extra work is required to define flags. However, if customisation is needed to control the flag name +or the default value then the :func:`~ext.commands.flag` function can come in handy: + +.. code-block:: python3 + + from typing import List + + class BanFlags(commands.FlagConverter): + members: List[discord.Member] = commands.flag(name='member', default=lambda ctx: []) + +This tells the parser that the ``members`` attribute is mapped to a flag named ``member`` and that +the default value is an empty list. For greater customisability, the default can either be a value or a callable +that takes the :class:`~ext.commands.Context` as a sole parameter. This callable can either be a function or a coroutine. + +In order to customise the flag syntax we also have a few options that can be passed to the class parameter list: + +.. code-block:: python3 + + # --hello world syntax + class PosixLikeFlags(commands.FlagConverter, delimiter=' ', prefix='--'): + hello: str + + + # /make food + class WindowsLikeFlags(commands.FlagConverter, prefix='/', delimiter=''): + make: str + + # TOPIC: not allowed nsfw: yes Slowmode: 100 + class Settings(commands.FlagConverter, case_insensitive=True): + topic: Optional[str] + nsfw: Optional[bool] + slowmode: Optional[int] + +.. note:: + + Despite the similarities in these examples to command like arguments, the syntax and parser is not + a command line parser. The syntax is mainly inspired by Discord's search bar input and as a result + all flags need a corresponding value. + +.. admonition:: Slash Command Only + + As these are built very similar to slash command options, they are converted into options and parsed + back into flags when the slash command is executed. + +The flag converter is similar to regular commands and allows you to use most types of converters +(with the exception of :class:`~ext.commands.Greedy`) as the type annotation. Some extra support is added for specific +annotations as described below. + +typing.List +^^^^^^^^^^^^^ + +If a list is given as a flag annotation it tells the parser that the argument can be passed multiple times. + +For example, augmenting the example above: + +.. code-block:: python3 + + from discord.ext import commands + from typing import List + import discord + + class BanFlags(commands.FlagConverter): + members: List[discord.Member] = commands.flag(name='member') + reason: str + days: int = 1 + + @commands.command() + async def ban(ctx, *, flags: BanFlags): + for member in flags.members: + await member.ban(reason=flags.reason, delete_message_days=flags.days) + + members = ', '.join(str(member) for member in flags.members) + plural = f'{flags.days} days' if flags.days != 1 else f'{flags.days} day' + await ctx.send(f'Banned {members} for {flags.reason!r} (deleted {plural} worth of messages)') + +This is called by repeatedly specifying the flag: + +.. image:: /images/commands/flags2.png + +typing.Tuple +^^^^^^^^^^^^^ + +Since the above syntax can be a bit repetitive when specifying a flag many times, the :class:`py:tuple` type annotation +allows for "greedy-like" semantics using a variadic tuple: + +.. code-block:: python3 + + from discord.ext import commands + from typing import Tuple + import discord + + class BanFlags(commands.FlagConverter): + members: Tuple[discord.Member, ...] + reason: str + days: int = 1 + +This allows the previous ``ban`` command to be called like this: + +.. image:: /images/commands/flags3.png + +The :class:`py:tuple` annotation also allows for parsing of pairs. For example, given the following code: + +.. code-block:: python3 + + # point: 10 11 point: 12 13 + class Coordinates(commands.FlagConverter): + point: Tuple[int, int] + + +.. warning:: + + Due to potential parsing ambiguities, the parser expects tuple arguments to be quoted + if they require spaces. So if one of the inner types is :class:`str` and the argument requires spaces + then quotes should be used to disambiguate it from the other element of the tuple. + +typing.Dict +^^^^^^^^^^^^^ + +A :class:`dict` annotation is functionally equivalent to ``List[Tuple[K, V]]`` except with the return type +given as a :class:`dict` rather than a :class:`list`. + + +.. _ext_commands_error_handler: + +Error Handling +---------------- + +When our commands fail to parse we will, by default, receive a noisy error in ``stderr`` of our console that tells us +that an error has happened and has been silently ignored. + +In order to handle our errors, we must use something called an error handler. There is a global error handler, called +:func:`.on_command_error` which works like any other event in the :ref:`discord-api-events`. This global error handler is +called for every error reached. + +Most of the time however, we want to handle an error local to the command itself. Luckily, commands come with local error +handlers that allow us to do just that. First we decorate an error handler function with :meth:`.Command.error`: + +.. code-block:: python3 + + @bot.command() + async def info(ctx, *, member: discord.Member): + """Tells you some info about the member.""" + msg = f'{member} joined on {member.joined_at} and has {len(member.roles)} roles.' + await ctx.send(msg) + + @info.error + async def info_error(ctx, error): + if isinstance(error, commands.BadArgument): + await ctx.send('I could not find that member...') + +The first parameter of the error handler is the :class:`.Context` while the second one is an exception that is derived from +:exc:`~ext.commands.CommandError`. A list of errors is found in the :ref:`ext_commands_api_errors` page of the documentation. + +Checks +------- + +There are cases when we don't want a user to use our commands. They don't have permissions to do so or maybe we blocked +them from using our bot earlier. The commands extension comes with full support for these things in a concept called a +:ref:`ext_commands_api_checks`. + +A check is a basic predicate that can take in a :class:`.Context` as its sole parameter. Within it, you have the following +options: + +- Return ``True`` to signal that the person can run the command. +- Return ``False`` to signal that the person cannot run the command. +- Raise a :exc:`~ext.commands.CommandError` derived exception to signal the person cannot run the command. + + - This allows you to have custom error messages for you to handle in the + :ref:`error handlers `. + +To register a check for a command, we would have two ways of doing so. The first is using the :meth:`~ext.commands.check` +decorator. For example: + +.. code-block:: python3 + + async def is_owner(ctx): + return ctx.author.id == 316026178463072268 + + @bot.command(name='eval') + @commands.check(is_owner) + async def _eval(ctx, *, code): + """A bad example of an eval command""" + await ctx.send(eval(code)) + +This would only evaluate the command if the function ``is_owner`` returns ``True``. Sometimes we re-use a check often and +want to split it into its own decorator. To do that we can just add another level of depth: + +.. code-block:: python3 + + def is_owner(): + async def predicate(ctx): + return ctx.author.id == 316026178463072268 + return commands.check(predicate) + + @bot.command(name='eval') + @is_owner() + async def _eval(ctx, *, code): + """A bad example of an eval command""" + await ctx.send(eval(code)) + + +Since an owner check is so common, the library provides it for you (:func:`~ext.commands.is_owner`): + +.. code-block:: python3 + + @bot.command(name='eval') + @commands.is_owner() + async def _eval(ctx, *, code): + """A bad example of an eval command""" + await ctx.send(eval(code)) + +When multiple checks are specified, **all** of them must be ``True``: + +.. code-block:: python3 + + def is_in_guild(guild_id): + async def predicate(ctx): + return ctx.guild and ctx.guild.id == guild_id + return commands.check(predicate) + + @bot.command() + @commands.is_owner() + @is_in_guild(41771983423143937) + async def secretguilddata(ctx): + """super secret stuff""" + await ctx.send('secret stuff') + +If any of those checks fail in the example above, then the command will not be run. + +When an error happens, the error is propagated to the :ref:`error handlers `. If you do not +raise a custom :exc:`~ext.commands.CommandError` derived exception, then it will get wrapped up into a +:exc:`~ext.commands.CheckFailure` exception as so: + +.. code-block:: python3 + + @bot.command() + @commands.is_owner() + @is_in_guild(41771983423143937) + async def secretguilddata(ctx): + """super secret stuff""" + await ctx.send('secret stuff') + + @secretguilddata.error + async def secretguilddata_error(ctx, error): + if isinstance(error, commands.CheckFailure): + await ctx.send('nothing to see here comrade.') + +If you want a more robust error system, you can derive from the exception and raise it instead of returning ``False``: + +.. code-block:: python3 + + class NoPrivateMessages(commands.CheckFailure): + pass + + def guild_only(): + async def predicate(ctx): + if ctx.guild is None: + raise NoPrivateMessages('Hey no DMs!') + return True + return commands.check(predicate) + + @guild_only() + async def test(ctx): + await ctx.send('Hey this is not a DM! Nice.') + + @test.error + async def test_error(ctx, error): + if isinstance(error, NoPrivateMessages): + await ctx.send(error) + +.. note:: + + Since having a ``guild_only`` decorator is pretty common, it comes built-in via :func:`~ext.commands.guild_only`. + +Global Checks +++++++++++++++ + +Sometimes we want to apply a check to **every** command, not just certain commands. The library supports this as well +using the global check concept. + +Global checks work similarly to regular checks except they are registered with the :meth:`.Bot.check` decorator. + +For example, to block all DMs we could do the following: + +.. code-block:: python3 + + @bot.check + async def globally_block_dms(ctx): + return ctx.guild is not None + +.. warning:: + + Be careful on how you write your global checks, as it could also lock you out of your own bot. + +.. need a note on global check once here I think diff --git a/docs/Python/html/_sources/ext/commands/extensions.rst.txt b/docs/Python/html/_sources/ext/commands/extensions.rst.txt new file mode 100644 index 00000000..20aa6e12 --- /dev/null +++ b/docs/Python/html/_sources/ext/commands/extensions.rst.txt @@ -0,0 +1,64 @@ +.. 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(f'Hello {ctx.author.display_name}.') + + 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:`.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 +----------- + +When you make a change to the extension and want to reload the references, the library comes with a function to do this for you, :meth:`.Bot.reload_extension`. + +.. code-block:: python3 + + >>> bot.reload_extension('hello') + +Once the extension reloads, any changes that we did will be applied. This is useful if we want to add or remove functionality without restarting our bot. If an error occurred during the reloading process, the bot will pretend as if the reload never happened. + +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!') diff --git a/docs/Python/html/_sources/ext/commands/index.rst.txt b/docs/Python/html/_sources/ext/commands/index.rst.txt new file mode 100644 index 00000000..9fd5e63c --- /dev/null +++ b/docs/Python/html/_sources/ext/commands/index.rst.txt @@ -0,0 +1,19 @@ +.. _discord_ext_commands: + +``discord.ext.commands`` -- Bot commands framework +==================================================== + +``discord.py`` offers a lower level aspect on interacting with Discord. Often times, the library is used for the creation of +bots. However this task can be daunting and confusing to get correctly the first time. Many times there comes a repetition in +creating a bot command framework that is extensible, flexible, and powerful. For this reason, ``discord.py`` comes with an +extension library that handles this for you. + + +.. toctree:: + :maxdepth: 2 + + commands + cogs + extensions + slash-commands + api diff --git a/docs/Python/html/_sources/ext/commands/slash-commands.rst.txt b/docs/Python/html/_sources/ext/commands/slash-commands.rst.txt new file mode 100644 index 00000000..db0b89b6 --- /dev/null +++ b/docs/Python/html/_sources/ext/commands/slash-commands.rst.txt @@ -0,0 +1,23 @@ +.. currentmodule:: discord + +.. _ext_commands_slash_commands: + +Slash Commands +============== + +Slash Commands are currently supported in enhanced-discord.py using a system on top of ext.commands. + +This system is very simple to use, and can be enabled via :attr:`.Bot.slash_commands` globally, +or only for specific commands via :attr:`.Command.slash_command`. + +There is also the parameter ``slash_command_guilds`` which can be passed to either :class:`.Bot` or the command +decorator in order to only upload the commands as guild commands to these specific guild IDs, however this +should only be used for testing or small (<10 guilds) bots. + +If you want to add option descriptions to your commands, you should use :class:`.Option` + +For troubleshooting, see the :ref:`FAQ ` + +.. admonition:: Slash Command Only + + For parts of the docs specific to slash commands, look for this box! diff --git a/docs/Python/html/_sources/ext/tasks/index.rst.txt b/docs/Python/html/_sources/ext/tasks/index.rst.txt new file mode 100644 index 00000000..8f90a87d --- /dev/null +++ b/docs/Python/html/_sources/ext/tasks/index.rst.txt @@ -0,0 +1,154 @@ +.. _discord_ext_tasks: + +``discord.ext.tasks`` -- asyncio.Task helpers +==================================================== + +.. versionadded:: 1.1.0 + +One of the most common operations when making a bot is having a loop run in the background at a specified interval. This pattern is very common but has a lot of things you need to look out for: + +- How do I handle :exc:`asyncio.CancelledError`? +- What do I do if the internet goes out? +- What is the maximum number of seconds I can sleep anyway? + +The goal of this discord.py extension is to abstract all these worries away from you. + +Recipes +--------- + +A simple background task in a :class:`~discord.ext.commands.Cog`: + +.. code-block:: python3 + + from discord.ext import tasks, commands + + class MyCog(commands.Cog): + def __init__(self): + self.index = 0 + self.printer.start() + + def cog_unload(self): + self.printer.cancel() + + @tasks.loop(seconds=5.0) + async def printer(self): + print(self.index) + self.index += 1 + +Adding an exception to handle during reconnect: + +.. code-block:: python3 + + import asyncpg + from discord.ext import tasks, commands + + class MyCog(commands.Cog): + def __init__(self, bot): + self.bot = bot + self.data = [] + self.batch_update.add_exception_type(asyncpg.PostgresConnectionError) + self.batch_update.start() + + def cog_unload(self): + self.batch_update.cancel() + + @tasks.loop(minutes=5.0) + async def batch_update(self): + async with self.bot.pool.acquire() as con: + # batch update here... + pass + +Looping a certain amount of times before exiting: + +.. code-block:: python3 + + from discord.ext import tasks + + @tasks.loop(seconds=5.0, count=5) + async def slow_count(): + print(slow_count.current_loop) + + @slow_count.after_loop + async def after_slow_count(): + print('done!') + + slow_count.start() + +Waiting until the bot is ready before the loop starts: + +.. code-block:: python3 + + from discord.ext import tasks, commands + + class MyCog(commands.Cog): + def __init__(self, bot): + self.index = 0 + self.bot = bot + self.printer.start() + + def cog_unload(self): + self.printer.cancel() + + @tasks.loop(seconds=5.0) + async def printer(self): + print(self.index) + self.index += 1 + + @printer.before_loop + async def before_printer(self): + print('waiting...') + await self.bot.wait_until_ready() + +Doing something during cancellation: + +.. code-block:: python3 + + from discord.ext import tasks, commands + import asyncio + + class MyCog(commands.Cog): + def __init__(self, bot): + self.bot= bot + self._batch = [] + self.lock = asyncio.Lock() + self.bulker.start() + + async def do_bulk(self): + # bulk insert data here + ... + + @tasks.loop(seconds=10.0) + async def bulker(self): + async with self.lock: + await self.do_bulk() + + @bulker.after_loop + async def on_bulker_cancel(self): + if self.bulker.is_being_cancelled() and len(self._batch) != 0: + # if we're cancelled and we have some data left... + # let's insert it to our database + await self.do_bulk() + + +.. _ext_tasks_api: + +API Reference +--------------- + +.. attributetable:: discord.ext.tasks.Loop + +.. autoclass:: discord.ext.tasks.Loop() + :members: + :special-members: __call__ + :exclude-members: after_loop, before_loop, error + + .. automethod:: Loop.after_loop() + :decorator: + + .. automethod:: Loop.before_loop() + :decorator: + + .. automethod:: Loop.error() + :decorator: + +.. autofunction:: discord.ext.tasks.loop diff --git a/docs/Python/html/_sources/faq.rst.txt b/docs/Python/html/_sources/faq.rst.txt new file mode 100644 index 00000000..556bb34f --- /dev/null +++ b/docs/Python/html/_sources/faq.rst.txt @@ -0,0 +1,443 @@ +:orphan: + +.. currentmodule:: discord +.. _faq: + +Frequently Asked Questions +=========================== + +This is a list of Frequently Asked Questions regarding using ``discord.py`` and its extension modules. Feel free to suggest a +new question or submit one via pull requests. + +.. contents:: Questions + :local: + +Coroutines +------------ + +Questions regarding coroutines and asyncio belong here. + +What is a coroutine? +~~~~~~~~~~~~~~~~~~~~~~ + +A |coroutine_link|_ is a function that must be invoked with ``await`` or ``yield from``. When Python encounters an ``await`` it stops +the function's execution at that point and works on other things until it comes back to that point and finishes off its work. +This allows for your program to be doing multiple things at the same time without using threads or complicated +multiprocessing. + +**If you forget to await a coroutine then the coroutine will not run. Never forget to await a coroutine.** + +Where can I use ``await``\? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can only use ``await`` inside ``async def`` functions and nowhere else. + +What does "blocking" mean? +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In asynchronous programming a blocking call is essentially all the parts of the function that are not ``await``. Do not +despair however, because not all forms of blocking are bad! Using blocking calls is inevitable, but you must work to make +sure that you don't excessively block functions. Remember, if you block for too long then your bot will freeze since it has +not stopped the function's execution at that point to do other things. + +If logging is enabled, this library will attempt to warn you that blocking is occurring with the message: +``Heartbeat blocked for more than N seconds.`` +See :ref:`logging_setup` for details on enabling logging. + +A common source of blocking for too long is something like :func:`time.sleep`. Don't do that. Use :func:`asyncio.sleep` +instead. Similar to this example: :: + + # bad + time.sleep(10) + + # good + await asyncio.sleep(10) + +Another common source of blocking for too long is using HTTP requests with the famous module :doc:`req:index`. +While :doc:`req:index` is an amazing module for non-asynchronous programming, it is not a good choice for +:mod:`asyncio` because certain requests can block the event loop too long. Instead, use the :doc:`aiohttp ` library which +is installed on the side with this library. + +Consider the following example: :: + + # bad + r = requests.get('http://aws.random.cat/meow') + if r.status_code == 200: + js = r.json() + await channel.send(js['file']) + + # good + async with aiohttp.ClientSession() as session: + async with session.get('http://aws.random.cat/meow') as r: + if r.status == 200: + js = await r.json() + await channel.send(js['file']) + +General +--------- + +General questions regarding library usage belong here. + +Where can I find usage examples? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Example code can be found in the `examples folder `_ +in the repository. + +How do I set the "Playing" status? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``activity`` keyword argument may be passed in the :class:`Client` constructor or :meth:`Client.change_presence`, given an :class:`Activity` object. + +The constructor may be used for static activities, while :meth:`Client.change_presence` may be used to update the activity at runtime. + +.. warning:: + + It is highly discouraged to use :meth:`Client.change_presence` or API calls in :func:`on_ready` as this event may be called many times while running, not just once. + + There is a high chance of disconnecting if presences are changed right after connecting. + +The status type (playing, listening, streaming, watching) can be set using the :class:`ActivityType` enum. +For memory optimisation purposes, some activities are offered in slimmed-down versions: + +- :class:`Game` +- :class:`Streaming` + +Putting both of these pieces of info together, you get the following: :: + + client = discord.Client(activity=discord.Game(name='my game')) + + # or, for watching: + activity = discord.Activity(name='my activity', type=discord.ActivityType.watching) + client = discord.Client(activity=activity) + +How do I send a message to a specific channel? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You must fetch the channel directly and then call the appropriate method. Example: :: + + channel = client.get_channel(12324234183172) + await channel.send('hello') + +How do I send a DM? +~~~~~~~~~~~~~~~~~~~ + +Get the :class:`User` or :class:`Member` object and call :meth:`abc.Messageable.send`. For example: :: + + user = client.get_user(381870129706958858) + await user.send('👀') + +If you are responding to an event, such as :func:`on_message`, you already have the :class:`User` object via :attr:`Message.author`: :: + + await message.author.send('👋') + +How do I get the ID of a sent message? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +:meth:`abc.Messageable.send` returns the :class:`Message` that was sent. +The ID of a message can be accessed via :attr:`Message.id`: :: + + message = await channel.send('hmm…') + message_id = message.id + +How do I upload an image? +~~~~~~~~~~~~~~~~~~~~~~~~~ + +To upload something to Discord you have to use the :class:`File` object. + +A :class:`File` accepts two parameters, the file-like object (or file path) and the filename +to pass to Discord when uploading. + +If you want to upload an image it's as simple as: :: + + await channel.send(file=discord.File('my_file.png')) + +If you have a file-like object you can do as follows: :: + + with open('my_file.png', 'rb') as fp: + await channel.send(file=discord.File(fp, 'new_filename.png')) + +To upload multiple files, you can use the ``files`` keyword argument instead of ``file``\: :: + + my_files = [ + discord.File('result.zip'), + discord.File('teaser_graph.png'), + ] + await channel.send(files=my_files) + +If you want to upload something from a URL, you will have to use an HTTP request using :doc:`aiohttp ` +and then pass an :class:`io.BytesIO` instance to :class:`File` like so: + +.. code-block:: python3 + + import io + import aiohttp + + async with aiohttp.ClientSession() as session: + async with session.get(my_url) as resp: + if resp.status != 200: + return await channel.send('Could not download file...') + data = io.BytesIO(await resp.read()) + await channel.send(file=discord.File(data, 'cool_image.png')) + + +How can I add a reaction to a message? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You use the :meth:`Message.add_reaction` method. + +If you want to use unicode emoji, you must pass a valid unicode code point in a string. In your code, you can write this in a few different ways: + +- ``'👍'`` +- ``'\U0001F44D'`` +- ``'\N{THUMBS UP SIGN}'`` + +Quick example: :: + + emoji = '\N{THUMBS UP SIGN}' + # or '\U0001f44d' or '👍' + await message.add_reaction(emoji) + +In case you want to use emoji that come from a message, you already get their code points in the content without needing +to do anything special. You **cannot** send ``':thumbsup:'`` style shorthands. + +For custom emoji, you should pass an instance of :class:`Emoji`. You can also pass a ``'<:name:id>'`` string, but if you +can use said emoji, you should be able to use :meth:`Client.get_emoji` to get an emoji via ID or use :func:`utils.find`/ +:func:`utils.get` on :attr:`Client.emojis` or :attr:`Guild.emojis` collections. + +The name and ID of a custom emoji can be found with the client by prefixing ``:custom_emoji:`` with a backslash. +For example, sending the message ``\:python3:`` with the client will result in ``<:python3:232720527448342530>``. + +Quick example: :: + + + # if you have the ID already + emoji = client.get_emoji(310177266011340803) + await message.add_reaction(emoji) + + # no ID, do a lookup + emoji = discord.utils.get(guild.emojis, name='LUL') + if emoji: + await message.add_reaction(emoji) + + # if you have the name and ID of a custom emoji: + emoji = '<:python3:232720527448342530>' + await message.add_reaction(emoji) + +How do I pass a coroutine to the player's "after" function? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The library's music player launches on a separate thread, ergo it does not execute inside a coroutine. +This does not mean that it is not possible to call a coroutine in the ``after`` parameter. To do so you must pass a callable +that wraps up a couple of aspects. + +The first gotcha that you must be aware of is that calling a coroutine is not a thread-safe operation. Since we are +technically in another thread, we must take caution in calling thread-safe operations so things do not bug out. Luckily for +us, :mod:`asyncio` comes with a :func:`asyncio.run_coroutine_threadsafe` function that allows us to call +a coroutine from another thread. + +However, this function returns a :class:`~concurrent.futures.Future` and to actually call it we have to fetch its result. Putting all of +this together we can do the following: :: + + def my_after(error): + coro = some_channel.send('Song is done!') + fut = asyncio.run_coroutine_threadsafe(coro, client.loop) + try: + fut.result() + except: + # an error happened sending the message + pass + + voice.play(discord.FFmpegPCMAudio(url), after=my_after) + +How do I run something in the background? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +`Check the background_task.py example. `_ + +How do I get a specific model? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +There are multiple ways of doing this. If you have a specific model's ID then you can use +one of the following functions: + +- :meth:`Client.get_channel` +- :meth:`Client.get_guild` +- :meth:`Client.get_user` +- :meth:`Client.get_emoji` +- :meth:`Guild.get_member` +- :meth:`Guild.get_channel` +- :meth:`Guild.get_role` + +The following use an HTTP request: + +- :meth:`abc.Messageable.fetch_message` +- :meth:`Client.fetch_user` +- :meth:`Client.fetch_guilds` +- :meth:`Client.fetch_guild` +- :meth:`Guild.fetch_emoji` +- :meth:`Guild.fetch_emojis` +- :meth:`Guild.fetch_member` + + +If the functions above do not help you, then use of :func:`utils.find` or :func:`utils.get` would serve some use in finding +specific models. + +Quick example: :: + + # find a guild by name + guild = discord.utils.get(client.guilds, name='My Server') + + # make sure to check if it's found + if guild is not None: + # find a channel by name + channel = discord.utils.get(guild.text_channels, name='cool-channel') + +How do I make a web request? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To make a request, you should use a non-blocking library. +This library already uses and requires a 3rd party library for making requests, :doc:`aiohttp `. + +Quick example: :: + + async with aiohttp.ClientSession() as session: + async with session.get('http://aws.random.cat/meow') as r: + if r.status == 200: + js = await r.json() + +See `aiohttp's full documentation `_ for more information. + +How do I use a local image file for an embed image? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Discord special-cases uploading an image attachment and using it within an embed so that it will not +display separately, but instead in the embed's thumbnail, image, footer or author icon. + +To do so, upload the image normally with :meth:`abc.Messageable.send`, +and set the embed's image URL to ``attachment://image.png``, +where ``image.png`` is the filename of the image you will send. + + +Quick example: :: + + file = discord.File("path/to/my/image.png", filename="image.png") + embed = discord.Embed() + embed.set_image(url="attachment://image.png") + await channel.send(file=file, embed=embed) + +.. note :: + + Due to a Discord limitation, filenames may not include underscores. + +Is there an event for audit log entries being created? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Since Discord does not dispatch this information in the gateway, the library cannot provide this information. +This is currently a Discord limitation. + +Commands Extension +------------------- + +Questions regarding ``discord.ext.commands`` belong here. + +Why does ``on_message`` make my commands stop working? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Overriding the default provided ``on_message`` forbids any extra commands from running. To fix this, add a +``bot.process_commands(message)`` line at the end of your ``on_message``. For example: :: + + @bot.event + async def on_message(message): + # do some extra stuff here + + await bot.process_commands(message) + +Alternatively, you can place your ``on_message`` logic into a **listener**. In this setup, you should not +manually call ``bot.process_commands()``. This also allows you to do multiple things asynchronously in response +to a message. Example:: + + @bot.listen('on_message') + async def whatever_you_want_to_call_it(message): + # do stuff here + # do not process commands here + +Why do my arguments require quotes? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In a simple command defined as: :: + + @bot.command() + async def echo(ctx, message: str): + await ctx.send(message) + +Calling it via ``?echo a b c`` will only fetch the first argument and disregard the rest. To fix this you should either call +it via ``?echo "a b c"`` or change the signature to have "consume rest" behaviour. Example: :: + + @bot.command() + async def echo(ctx, *, message: str): + await ctx.send(message) + +This will allow you to use ``?echo a b c`` without needing the quotes. + +How do I get the original ``message``\? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The :class:`~ext.commands.Context` contains an attribute, :attr:`~.Context.message` to get the original +message. + +Example: :: + + @bot.command() + async def length(ctx): + await ctx.send(f'Your message is {len(ctx.message.content)} characters long.') + +How do I make a subcommand? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Use the :func:`~ext.commands.group` decorator. This will transform the callback into a :class:`~ext.commands.Group` which will allow you to add commands into +the group operating as "subcommands". These groups can be arbitrarily nested as well. + +Example: :: + + @bot.group() + async def git(ctx): + if ctx.invoked_subcommand is None: + await ctx.send('Invalid git command passed...') + + @git.command() + async def push(ctx, remote: str, branch: str): + await ctx.send(f'Pushing to {remote} {branch}') + +This could then be used as ``?git push origin master``. + +How do I make slash commands? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +See :doc:`/ext/commands/slash-commands` + +My slash commands aren't showing up! +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _ext_commands_slash_command_troubleshooting: + +You need to invite your bot with the ``application.commands`` scope on each guild and +you need the :attr:`Permissions.use_slash_commands` permission in order to see slash commands. + +.. image:: /images/discord_oauth2_slash_scope.png + :alt: The scopes checkbox with "bot" and "applications.commands" ticked. + +Global slash commands (created by not specifying :attr:`~ext.commands.Bot.slash_command_guilds`) will also take up an +hour to refresh on discord's end, so it is recommended to set :attr:`~ext.commands.Bot.slash_command_guilds` for development. + +If none of this works, make sure you are actually running enhanced-discord.py by doing ``print(bot.slash_commands)`` + +My bot won't start after enabling slash commands! +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This means some of your command metadata is invalid for slash commands. +Make sure your command names and option names are lowercase, and they have to match the regex ``^[\w-]{1,32}$`` + +If you cannot figure out the problem, you should disable slash commands globally (:attr:`~ext.commands.Bot.slash_commands`\=False) +then go through commands, enabling them specifically with :attr:`~.commands.Command.slash_command`\=True until it +errors, then you can debug the problem with that command specifically. diff --git a/docs/Python/html/_sources/index.rst.txt b/docs/Python/html/_sources/index.rst.txt new file mode 100644 index 00000000..e1af5163 --- /dev/null +++ b/docs/Python/html/_sources/index.rst.txt @@ -0,0 +1,76 @@ +.. discord.py documentation master file, created by + sphinx-quickstart on Fri Aug 21 05:43:30 2015. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to discord.py +=========================== + +.. image:: /images/snake.svg +.. image:: /images/snake_dark.svg + +discord.py is a modern, easy to use, feature-rich, and async ready API wrapper +for Discord. + +**Features:** + +- Modern Pythonic API using ``async``\/``await`` syntax +- Sane rate limit handling that prevents 429s +- Command extension to aid with bot creation +- Easy to use with an object oriented design +- Optimised for both speed and memory + +Getting started +----------------- + +Is this your first time using the library? This is the place to get started! + +- **First steps:** :doc:`intro` | :doc:`quickstart` | :doc:`logging` +- **Working with Discord:** :doc:`discord` | :doc:`intents` +- **Examples:** Many examples are available in the :resource:`repository `. + +Getting help +-------------- + +If you're having trouble with something, these resources might help. + +- Try the :doc:`faq` first, it's got answers to all common questions. +- Ask us and hang out with us in our :resource:`Discord ` server. +- If you're looking for something specific, try the :ref:`index ` or :ref:`searching `. +- Report bugs in the :resource:`issue tracker `. +- Ask in our :resource:`GitHub discussions page `. + +Extensions +------------ + +These extensions help you during development when it comes to common tasks. + +.. toctree:: + :maxdepth: 1 + + ext/commands/index.rst + ext/tasks/index.rst + +Manuals +--------- + +These pages go into great detail about everything the API can do. + +.. toctree:: + :maxdepth: 1 + + api + discord.ext.commands API Reference + discord.ext.tasks API Reference + +Meta +------ + +If you're looking for something related to the project itself, it's here. + +.. toctree:: + :maxdepth: 1 + + whats_new + version_guarantees + migrating diff --git a/docs/Python/html/_sources/intents.rst.txt b/docs/Python/html/_sources/intents.rst.txt new file mode 100644 index 00000000..a9708aaf --- /dev/null +++ b/docs/Python/html/_sources/intents.rst.txt @@ -0,0 +1,192 @@ +:orphan: + +.. currentmodule:: discord +.. versionadded:: 1.5 +.. _intents_primer: + +A Primer to Gateway Intents +============================= + +In version 1.5 comes the introduction of :class:`Intents`. This is a radical change in how bots are written. An intent basically allows a bot to subscribe to specific buckets of events. The events that correspond to each intent is documented in the individual attribute of the :class:`Intents` documentation. + +These intents are passed to the constructor of :class:`Client` or its subclasses (:class:`AutoShardedClient`, :class:`~.AutoShardedBot`, :class:`~.Bot`) with the ``intents`` argument. + +If intents are not passed, then the library defaults to every intent being enabled except the privileged intents, currently :attr:`Intents.members` and :attr:`Intents.presences`. + +What intents are needed? +-------------------------- + +The intents that are necessary for your bot can only be dictated by yourself. Each attribute in the :class:`Intents` class documents what :ref:`events ` it corresponds to and what kind of cache it enables. + +For example, if you want a bot that functions without spammy events like presences or typing then we could do the following: + +.. code-block:: python3 + :emphasize-lines: 7,9,10 + + import discord + intents = discord.Intents.default() + intents.typing = False + intents.presences = False + + # Somewhere else: + # client = discord.Client(intents=intents) + # or + # from discord.ext import commands + # bot = commands.Bot(command_prefix='!', intents=intents) + +Note that this doesn't enable :attr:`Intents.members` since it's a privileged intent. + +Another example showing a bot that only deals with messages and guild information: + +.. code-block:: python3 + :emphasize-lines: 7,9,10 + + import discord + intents = discord.Intents(messages=True, guilds=True) + # If you also want reaction events enable the following: + # intents.reactions = True + + # Somewhere else: + # client = discord.Client(intents=intents) + # or + # from discord.ext import commands + # bot = commands.Bot(command_prefix='!', intents=intents) + +.. _privileged_intents: + +Privileged Intents +--------------------- + +With the API change requiring bot authors to specify intents, some intents were restricted further and require more manual steps. These intents are called **privileged intents**. + +A privileged intent is one that requires you to go to the developer portal and manually enable it. To enable privileged intents do the following: + +1. Make sure you're logged on to the `Discord website `_. +2. Navigate to the `application page `_. +3. Click on the bot you want to enable privileged intents for. +4. Navigate to the bot tab on the left side of the screen. + + .. image:: /images/discord_bot_tab.png + :alt: The bot tab in the application page. + +5. Scroll down to the "Privileged Gateway Intents" section and enable the ones you want. + + .. image:: /images/discord_privileged_intents.png + :alt: The privileged gateway intents selector. + +.. warning:: + + Enabling privileged intents when your bot is in over 100 guilds requires going through `bot verification `_. If your bot is already verified and you would like to enable a privileged intent you must go through `Discord support `_ and talk to them about it. + +.. note:: + + Even if you enable intents through the developer portal, you still have to enable the intents + through code as well. + +Do I need privileged intents? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This is a quick checklist to see if you need specific privileged intents. + +.. _need_presence_intent: + +Presence Intent ++++++++++++++++++ + +- Whether you use :attr:`Member.status` at all to track member statuses. +- Whether you use :attr:`Member.activity` or :attr:`Member.activities` to check member's activities. + +.. _need_members_intent: + +Member Intent ++++++++++++++++ + +- Whether you track member joins or member leaves, corresponds to :func:`on_member_join` and :func:`on_member_remove` events. +- Whether you want to track member updates such as nickname or role changes. +- Whether you want to track user updates such as usernames, avatars, discriminators, etc. +- Whether you want to request the guild member list through :meth:`Guild.chunk` or :meth:`Guild.fetch_members`. +- Whether you want high accuracy member cache under :attr:`Guild.members`. + +.. _intents_member_cache: + +Member Cache +------------- + +Along with intents, Discord now further restricts the ability to cache members and expects bot authors to cache as little as is necessary. However, to properly maintain a cache the :attr:`Intents.members` intent is required in order to track the members who left and properly evict them. + +To aid with member cache where we don't need members to be cached, the library now has a :class:`MemberCacheFlags` flag to control the member cache. The documentation page for the class goes over the specific policies that are possible. + +It should be noted that certain things do not need a member cache since Discord will provide full member information if possible. For example: + +- :func:`on_message` will have :attr:`Message.author` be a member even if cache is disabled. +- :func:`on_voice_state_update` will have the ``member`` parameter be a member even if cache is disabled. +- :func:`on_reaction_add` will have the ``user`` parameter be a member when in a guild even if cache is disabled. +- :func:`on_raw_reaction_add` will have :attr:`RawReactionActionEvent.member` be a member when in a guild even if cache is disabled. +- The reaction add events do not contain additional information when in direct messages. This is a Discord limitation. +- The reaction removal events do not have member information. This is a Discord limitation. + +Other events that take a :class:`Member` will require the use of the member cache. If absolute accuracy over the member cache is desirable, then it is advisable to have the :attr:`Intents.members` intent enabled. + +.. _retrieving_members: + +Retrieving Members +-------------------- + +If the cache is disabled or you disable chunking guilds at startup, we might still need a way to load members. The library offers a few ways to do this: + +- :meth:`Guild.query_members` + - Used to query members by a prefix matching nickname or username. + - This can also be used to query members by their user ID. + - This uses the gateway and not the HTTP. +- :meth:`Guild.chunk` + - This can be used to fetch the entire member list through the gateway. +- :meth:`Guild.fetch_member` + - Used to fetch a member by ID through the HTTP API. +- :meth:`Guild.fetch_members` + - used to fetch a large number of members through the HTTP API. + +It should be noted that the gateway has a strict rate limit of 120 requests per 60 seconds. + +Troubleshooting +------------------ + +Some common issues relating to the mandatory intent change. + +Where'd my members go? +~~~~~~~~~~~~~~~~~~~~~~~~ + +Due to an :ref:`API change ` Discord is now forcing developers who want member caching to explicitly opt-in to it. This is a Discord mandated change and there is no way to bypass it. In order to get members back you have to explicitly enable the :ref:`members privileged intent ` and change the :attr:`Intents.members` attribute to true. + +For example: + +.. code-block:: python3 + :emphasize-lines: 3,6,8,9 + + import discord + intents = discord.Intents.default() + intents.members = True + + # Somewhere else: + # client = discord.Client(intents=intents) + # or + # from discord.ext import commands + # bot = commands.Bot(command_prefix='!', intents=intents) + +Why does ``on_ready`` take so long to fire? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +As part of the API change regarding intents, Discord also changed how members are loaded in the beginning. Originally the library could request 75 guilds at once and only request members from guilds that have the :attr:`Guild.large` attribute set to ``True``. With the new intent changes, Discord mandates that we can only send 1 guild per request. This causes a 75x slowdown which is further compounded by the fact that *all* guilds, not just large guilds are being requested. + +There are a few solutions to fix this. + +The first solution is to request the privileged presences intent along with the privileged members intent and enable both of them. This allows the initial member list to contain online members just like the old gateway. Note that we're still limited to 1 guild per request but the number of guilds we request is significantly reduced. + +The second solution is to disable member chunking by setting ``chunk_guilds_at_startup`` to ``False`` when constructing a client. Then, when chunking for a guild is necessary you can use the various techniques to :ref:`retrieve members `. + +To illustrate the slowdown caused by the API change, take a bot who is in 840 guilds and 95 of these guilds are "large" (over 250 members). + +Under the original system this would result in 2 requests to fetch the member list (75 guilds, 20 guilds) roughly taking 60 seconds. With :attr:`Intents.members` but not :attr:`Intents.presences` this requires 840 requests, with a rate limit of 120 requests per 60 seconds means that due to waiting for the rate limit it totals to around 7 minutes of waiting for the rate limit to fetch all the members. With both :attr:`Intents.members` and :attr:`Intents.presences` we mostly get the old behaviour so we're only required to request for the 95 guilds that are large, this is slightly less than our rate limit so it's close to the original timing to fetch the member list. + +Unfortunately due to this change being required from Discord there is nothing that the library can do to mitigate this. + +If you truly dislike the direction Discord is going with their API, you can contact them via `support `_. diff --git a/docs/Python/html/_sources/intro.rst.txt b/docs/Python/html/_sources/intro.rst.txt new file mode 100644 index 00000000..12a73c70 --- /dev/null +++ b/docs/Python/html/_sources/intro.rst.txt @@ -0,0 +1,113 @@ +:orphan: + +.. currentmodule:: discord + +.. _intro: + +Introduction +============== + +This is the documentation for discord.py, a library for Python to aid +in creating applications that utilise the Discord API. + +Prerequisites +--------------- + +discord.py works with Python 3.8 or higher. Support for earlier versions of Python +is not provided. Python 2.7 or lower is not supported. Python 3.7 or lower is not supported. + + +.. _installing: + +Installing +----------- + +You can get the library directly from PyPI: :: + + python3 -m pip install -U discord.py + +If you are using Windows, then the following should be used instead: :: + + py -3 -m pip install -U discord.py + + +To get voice support, you should use ``discord.py[voice]`` instead of ``discord.py``, e.g. :: + + python3 -m pip install -U discord.py[voice] + +On Linux environments, installing voice requires getting the following dependencies: + +- `libffi `_ +- `libnacl `_ +- `python3-dev `_ + +For a Debian-based system, the following command will get these dependencies: + +.. code-block:: shell + + $ apt install libffi-dev libnacl-dev python3-dev + +Remember to check your permissions! + +Virtual Environments +~~~~~~~~~~~~~~~~~~~~~ + +Sometimes you want to keep libraries from polluting system installs or use a different version of +libraries than the ones installed on the system. You might also not have permissions to install libraries system-wide. +For this purpose, the standard library as of Python 3.3 comes with a concept called "Virtual Environment"s to +help maintain these separate versions. + +A more in-depth tutorial is found on :doc:`py:tutorial/venv`. + +However, for the quick and dirty: + +1. Go to your project's working directory: + + .. code-block:: shell + + $ cd your-bot-source + $ python3 -m venv bot-env + +2. Activate the virtual environment: + + .. code-block:: shell + + $ source bot-env/bin/activate + + On Windows you activate it with: + + .. code-block:: shell + + $ bot-env\Scripts\activate.bat + +3. Use pip like usual: + + .. code-block:: shell + + $ pip install -U discord.py + +Congratulations. You now have a virtual environment all set up. + +Basic Concepts +--------------- + +discord.py revolves around the concept of :ref:`events `. +An event is something you listen to and then respond to. For example, when a message +happens, you will receive an event about it that you can respond to. + +A quick example to showcase how events work: + +.. code-block:: python3 + + import discord + + class MyClient(discord.Client): + async def on_ready(self): + print(f'Logged on as {self.user}!') + + async def on_message(self, message): + print(f'Message from {messsage.author}: {message.content}') + + client = MyClient() + client.run('my token goes here') + diff --git a/docs/Python/html/_sources/logging.rst.txt b/docs/Python/html/_sources/logging.rst.txt new file mode 100644 index 00000000..535a373f --- /dev/null +++ b/docs/Python/html/_sources/logging.rst.txt @@ -0,0 +1,46 @@ +:orphan: + +.. versionadded:: 0.6.0 +.. _logging_setup: + +Setting Up Logging +=================== + +*discord.py* logs errors and debug information via the :mod:`logging` python +module. It is strongly recommended that the logging module is +configured, as no errors or warnings will be output if it is not set up. +Configuration of the ``logging`` module can be as simple as:: + + import logging + + logging.basicConfig(level=logging.INFO) + +Placed at the start of the application. This will output the logs from +discord as well as other libraries that use the ``logging`` module +directly to the console. + +The optional ``level`` argument specifies what level of events to log +out and can be any of ``CRITICAL``, ``ERROR``, ``WARNING``, ``INFO``, and +``DEBUG`` and if not specified defaults to ``WARNING``. + +More advanced setups are possible with the :mod:`logging` module. For +example to write the logs to a file called ``discord.log`` instead of +outputting them to the console the following snippet can be used:: + + import discord + import logging + + logger = logging.getLogger('discord') + logger.setLevel(logging.DEBUG) + handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w') + handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) + logger.addHandler(handler) + +This is recommended, especially at verbose levels such as ``INFO`` +and ``DEBUG``, as there are a lot of events logged and it would clog the +stdout of your program. + + + +For more information, check the documentation and tutorial of the +:mod:`logging` module. diff --git a/docs/Python/html/_sources/migrating.rst.txt b/docs/Python/html/_sources/migrating.rst.txt new file mode 100644 index 00000000..baf97160 --- /dev/null +++ b/docs/Python/html/_sources/migrating.rst.txt @@ -0,0 +1,1172 @@ +.. currentmodule:: discord + +.. _migrating_1_0: + +Migrating to v1.0 +====================== + +v1.0 is one of the biggest breaking changes in the library due to a complete +redesign. + +The amount of changes are so massive and long that for all intents and purposes, it is a completely +new library. + +Part of the redesign involves making things more easy to use and natural. Things are done on the +:ref:`models ` instead of requiring a :class:`Client` instance to do any work. + +Python Version Change +----------------------- + +In order to make development easier and also to allow for our dependencies to upgrade to allow usage of 3.7 or higher, +the library had to remove support for Python versions lower than 3.5.3, which essentially means that **support for Python 3.4 +is dropped**. + +Major Model Changes +--------------------- + +Below are major model changes that have happened in v1.0 + +Snowflakes are int +~~~~~~~~~~~~~~~~~~~~ + +Before v1.0, all snowflakes (the ``id`` attribute) were strings. This has been changed to :class:`int`. + +Quick example: :: + + # before + ch = client.get_channel('84319995256905728') + if message.author.id == '80528701850124288': + ... + + # after + ch = client.get_channel(84319995256905728) + if message.author.id == 80528701850124288: + ... + +This change allows for fewer errors when using the Copy ID feature in the official client since you no longer have +to wrap it in quotes and allows for optimisation opportunities by allowing ETF to be used instead of JSON internally. + +Server is now Guild +~~~~~~~~~~~~~~~~~~~~~ + +The official API documentation calls the "Server" concept a "Guild" instead. In order to be more consistent with the +API documentation when necessary, the model has been renamed to :class:`Guild` and all instances referring to it has +been changed as well. + +A list of changes is as follows: + ++-------------------------------+----------------------------------+ +| Before | After | ++-------------------------------+----------------------------------+ +| ``Message.server`` | :attr:`Message.guild` | ++-------------------------------+----------------------------------+ +| ``Channel.server`` | :attr:`.GuildChannel.guild` | ++-------------------------------+----------------------------------+ +| ``Client.servers`` | :attr:`Client.guilds` | ++-------------------------------+----------------------------------+ +| ``Client.get_server`` | :meth:`Client.get_guild` | ++-------------------------------+----------------------------------+ +| ``Emoji.server`` | :attr:`Emoji.guild` | ++-------------------------------+----------------------------------+ +| ``Role.server`` | :attr:`Role.guild` | ++-------------------------------+----------------------------------+ +| ``Invite.server`` | :attr:`Invite.guild` | ++-------------------------------+----------------------------------+ +| ``Member.server`` | :attr:`Member.guild` | ++-------------------------------+----------------------------------+ +| ``Permissions.manage_server`` | :attr:`Permissions.manage_guild` | ++-------------------------------+----------------------------------+ +| ``VoiceClient.server`` | :attr:`VoiceClient.guild` | ++-------------------------------+----------------------------------+ +| ``Client.create_server`` | :meth:`Client.create_guild` | ++-------------------------------+----------------------------------+ + +.. _migrating_1_0_model_state: + +Models are Stateful +~~~~~~~~~~~~~~~~~~~~~ + +As mentioned earlier, a lot of functionality was moved out of :class:`Client` and +put into their respective :ref:`model `. + +A list of these changes is enumerated below. + ++---------------------------------------+------------------------------------------------------------------------------+ +| Before | After | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.add_reaction`` | :meth:`Message.add_reaction` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.add_roles`` | :meth:`Member.add_roles` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.ban`` | :meth:`Member.ban` or :meth:`Guild.ban` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.change_nickname`` | :meth:`Member.edit` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.clear_reactions`` | :meth:`Message.clear_reactions` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.create_channel`` | :meth:`Guild.create_text_channel` and :meth:`Guild.create_voice_channel` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.create_custom_emoji`` | :meth:`Guild.create_custom_emoji` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.create_invite`` | :meth:`abc.GuildChannel.create_invite` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.create_role`` | :meth:`Guild.create_role` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.delete_channel`` | :meth:`abc.GuildChannel.delete` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.delete_channel_permissions`` | :meth:`abc.GuildChannel.set_permissions` with ``overwrite`` set to ``None`` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.delete_custom_emoji`` | :meth:`Emoji.delete` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.delete_invite`` | :meth:`Invite.delete` or :meth:`Client.delete_invite` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.delete_message`` | :meth:`Message.delete` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.delete_messages`` | :meth:`TextChannel.delete_messages` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.delete_role`` | :meth:`Role.delete` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.delete_server`` | :meth:`Guild.delete` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.edit_channel`` | :meth:`TextChannel.edit` or :meth:`VoiceChannel.edit` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.edit_channel_permissions`` | :meth:`abc.GuildChannel.set_permissions` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.edit_custom_emoji`` | :meth:`Emoji.edit` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.edit_message`` | :meth:`Message.edit` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.edit_profile`` | :meth:`ClientUser.edit` (you get this from :attr:`Client.user`) | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.edit_role`` | :meth:`Role.edit` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.edit_server`` | :meth:`Guild.edit` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.estimate_pruned_members`` | :meth:`Guild.estimate_pruned_members` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.get_all_emojis`` | :attr:`Client.emojis` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.get_bans`` | :meth:`Guild.bans` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.get_invite`` | :meth:`Client.fetch_invite` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.get_message`` | :meth:`abc.Messageable.fetch_message` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.get_reaction_users`` | :meth:`Reaction.users` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.get_user_info`` | :meth:`Client.fetch_user` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.invites_from`` | :meth:`abc.GuildChannel.invites` or :meth:`Guild.invites` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.join_voice_channel`` | :meth:`VoiceChannel.connect` (see :ref:`migrating_1_0_voice`) | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.kick`` | :meth:`Guild.kick` or :meth:`Member.kick` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.leave_server`` | :meth:`Guild.leave` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.logs_from`` | :meth:`abc.Messageable.history` (see :ref:`migrating_1_0_async_iter`) | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.move_channel`` | :meth:`TextChannel.edit` or :meth:`VoiceChannel.edit` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.move_member`` | :meth:`Member.edit` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.move_role`` | :meth:`Role.edit` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.pin_message`` | :meth:`Message.pin` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.pins_from`` | :meth:`abc.Messageable.pins` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.prune_members`` | :meth:`Guild.prune_members` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.purge_from`` | :meth:`TextChannel.purge` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.remove_reaction`` | :meth:`Message.remove_reaction` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.remove_roles`` | :meth:`Member.remove_roles` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.replace_roles`` | :meth:`Member.edit` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.send_file`` | :meth:`abc.Messageable.send` (see :ref:`migrating_1_0_sending_messages`) | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.send_message`` | :meth:`abc.Messageable.send` (see :ref:`migrating_1_0_sending_messages`) | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.send_typing`` | :meth:`abc.Messageable.trigger_typing` (use :meth:`abc.Messageable.typing`) | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.server_voice_state`` | :meth:`Member.edit` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.start_private_message`` | :meth:`User.create_dm` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.unban`` | :meth:`Guild.unban` or :meth:`Member.unban` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.unpin_message`` | :meth:`Message.unpin` | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.wait_for_message`` | :meth:`Client.wait_for` (see :ref:`migrating_1_0_wait_for`) | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.wait_for_reaction`` | :meth:`Client.wait_for` (see :ref:`migrating_1_0_wait_for`) | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.wait_until_login`` | Removed | ++---------------------------------------+------------------------------------------------------------------------------+ +| ``Client.wait_until_ready`` | No change | ++---------------------------------------+------------------------------------------------------------------------------+ + +Property Changes +~~~~~~~~~~~~~~~~~~ + +In order to be a bit more consistent, certain things that were properties were changed to methods instead. + +The following are now methods instead of properties (requires parentheses): + +- :meth:`Role.is_default` +- :meth:`Client.is_ready` +- :meth:`Client.is_closed` + +Dict Value Change +~~~~~~~~~~~~~~~~~~~~~ + +Prior to v1.0 some aggregating properties that retrieved models would return "dict view" objects. + +As a consequence, when the dict would change size while you would iterate over it, a RuntimeError would +be raised and crash the task. To alleviate this, the "dict view" objects were changed into lists. + +The following views were changed to a list: + +- :attr:`Client.guilds` +- :attr:`Client.users` (new in v1.0) +- :attr:`Client.emojis` (new in v1.0) +- :attr:`Guild.channels` +- :attr:`Guild.text_channels` (new in v1.0) +- :attr:`Guild.voice_channels` (new in v1.0) +- :attr:`Guild.emojis` +- :attr:`Guild.members` + +Voice State Changes +~~~~~~~~~~~~~~~~~~~~~ + +Earlier, in v0.11.0 a :class:`VoiceState` class was added to refer to voice states along with a +:attr:`Member.voice` attribute to refer to it. + +However, it was transparent to the user. In an effort to make the library save more memory, the +voice state change is now more visible. + +The only way to access voice attributes is via the :attr:`Member.voice` attribute. Note that if +the member does not have a voice state this attribute can be ``None``. + +Quick example: :: + + # 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, :class:`User` and :class:`Member` are no longer inherited. Instead, they are "flattened" +by having equivalent properties that map out to the functional underlying :class:`User`. Thus, there is no functional +change in how they are used. However this breaks :func:`isinstance` checks and thus is something to keep in mind. + +These memory savings were accomplished by having a global :class:`User` cache, and as a positive consequence you +can now easily fetch a :class:`User` by their ID by using the new :meth:`Client.get_user`. You can also get a list +of all :class:`User` your client can see with :attr:`Client.users`. + +.. _migrating_1_0_channel_split: + +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: + +- :class:`TextChannel` for guild text channels. +- :class:`VoiceChannel` for guild voice channels. +- :class:`DMChannel` for DM channels with members. +- :class:`GroupChannel` for Group DM channels with members. + +With this split came the removal of the ``is_private`` attribute. You should now use :func:`isinstance`. + +The types are split into two different :ref:`discord_api_abcs`: + +- :class:`abc.GuildChannel` for guild channels. +- :class:`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 :ref:`migrating_1_0_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** + +- :meth:`Client.login` no longer accepts email and password logins. + + - Use a token and ``bot=False``. + +- ``Client.get_all_emojis`` + + - Use :attr:`Client.emojis` instead. + +- ``Client.messages`` + + - Use read-only :attr:`Client.cached_messages` instead. + +- ``Client.wait_for_message`` and ``Client.wait_for_reaction`` are gone. + + - Use :meth:`Client.wait_for` instead. + +- ``Channel.voice_members`` + + - Use :attr:`VoiceChannel.members` instead. + +- ``Channel.is_private`` + + - Use ``isinstance`` instead with one of the :ref:`discord_api_abcs` 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`` and ``Channel.is_default`` + + - The concept of a default channel was removed from Discord. + See `#329 `_. + +- ``Message.edited_timestamp`` + + - Use :attr:`Message.edited_at` instead. + +- ``Message.timestamp`` + + - Use :attr:`Message.created_at` instead. + +- ``Colour.to_tuple()`` + + - Use :meth:`Colour.to_rgb` instead. + +- ``Permissions.view_audit_logs`` + + - Use :attr:`Permissions.view_audit_log` instead. + +- ``Member.game`` + + - Use :attr:`Member.activities` instead. + +- ``Guild.role_hierarchy`` / ``Server.role_hierarchy`` + + - Use :attr:`Guild.roles` instead. Note that while sorted, it is in the opposite order + of what the old ``Guild.role_hierarchy`` used to be. + +**Changed** + +- :attr:`Member.avatar_url` and :attr:`User.avatar_url` now return the default avatar if a custom one is not set. +- :attr:`Message.embeds` is now a list of :class:`Embed` instead of :class:`dict` objects. +- :attr:`Message.attachments` is now a list of :class:`Attachment` instead of :class:`dict` object. +- :attr:`Guild.roles` is now sorted through hierarchy. The first element is always the ``@everyone`` role. + +**Added** + +- :class:`Attachment` to represent a discord attachment. +- :class:`CategoryChannel` to represent a channel category. +- :attr:`VoiceChannel.members` for fetching members connected to a voice channel. +- :attr:`TextChannel.members` for fetching members that can see the channel. +- :attr:`Role.members` for fetching members that have the role. +- :attr:`Guild.text_channels` for fetching text channels only. +- :attr:`Guild.voice_channels` for fetching voice channels only. +- :attr:`Guild.categories` for fetching channel categories only. +- :attr:`TextChannel.category` and :attr:`VoiceChannel.category` to get the category a channel belongs to. +- :meth:`Guild.by_category` to get channels grouped by their category. +- :attr:`Guild.chunked` to check member chunking status. +- :attr:`Guild.explicit_content_filter` to fetch the content filter. +- :attr:`Guild.shard_id` to get a guild's Shard ID if you're sharding. +- :attr:`Client.users` to get all visible :class:`User` instances. +- :meth:`Client.get_user` to get a :class:`User` by ID. +- :meth:`User.avatar_url_as` to get an avatar in a specific size or format. +- :meth:`Guild.vanity_invite` to fetch the guild's vanity invite. +- :meth:`Guild.audit_logs` to fetch the guild's audit logs. +- :attr:`Message.webhook_id` to fetch the message's webhook ID. +- :attr:`Message.activity` and :attr:`Message.application` for Rich Presence related information. +- :meth:`TextChannel.is_nsfw` to check if a text channel is NSFW. +- :meth:`Colour.from_rgb` to construct a :class:`Colour` from RGB tuple. +- :meth:`Guild.get_role` to get a role by its ID. + +.. _migrating_1_0_sending_messages: + +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, :meth:`~abc.Messageable.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 :class:`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) + +.. _migrating_1_0_async_iter: + +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 +:class:`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 :class:`AsyncIterator` is that it allows you to chain functions together such as +:meth:`AsyncIterator.map` or :meth:`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 :meth:`AsyncIterator.map` or :meth:`AsyncIterator.filter` can be either coroutines or regular +functions. + +You can also get single elements a la :func:`discord.utils.find` or :func:`discord.utils.get` via +:meth:`AsyncIterator.get` or :meth:`AsyncIterator.find`: :: + + my_last_message = await channel.history().get(author=client.user) + +The following return :class:`AsyncIterator`: + +- :meth:`abc.Messageable.history` +- :meth:`Guild.audit_logs` +- :meth:`Reaction.users` + +.. _migrating_1_0_event_changes: + +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: + +- :func:`on_guild_join` +- :func:`on_guild_remove` +- :func:`on_guild_update` +- :func:`on_guild_role_create` +- :func:`on_guild_role_delete` +- :func:`on_guild_role_update` +- :func:`on_guild_emojis_update` +- :func:`on_guild_available` +- :func:`on_guild_unavailable` + + +The :func:`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 :class:`Member` objects, the new event takes one :class:`Member` object and two :class:`VoiceState` objects. + +The :func:`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 :class:`Guild` that the emojis were updated from. + +The :func:`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 :class:`User` or :class:`Member`. To help in the cases that have +:class:`User`, the :class:`Guild` is provided as the first parameter. + +The ``on_channel_`` events have received a type level split (see :ref:`migrating_1_0_channel_split`). + +Before: + +- ``on_channel_delete`` +- ``on_channel_create`` +- ``on_channel_update`` + +After: + +- :func:`on_guild_channel_delete` +- :func:`on_guild_channel_create` +- :func:`on_guild_channel_update` +- :func:`on_private_channel_delete` +- :func:`on_private_channel_create` +- :func:`on_private_channel_update` + +The ``on_guild_channel_`` events correspond to :class:`abc.GuildChannel` being updated (i.e. :class:`TextChannel` +and :class:`VoiceChannel`) and the ``on_private_channel_`` events correspond to :class:`abc.PrivateChannel` being +updated (i.e. :class:`DMChannel` and :class:`GroupChannel`). + +.. _migrating_1_0_voice: + +Voice Changes +--------------- + +Voice sending has gone through a complete redesign. + +In particular: + +- Connection is done through :meth:`VoiceChannel.connect` instead of ``Client.join_voice_channel``. +- You no longer create players and operate on them (you no longer store them). +- You instead request :class:`VoiceClient` to play an :class:`AudioSource` via :meth:`VoiceClient.play`. +- There are different built-in :class:`AudioSource`\s. + + - :class:`FFmpegPCMAudio` is the equivalent of ``create_ffmpeg_player`` + +- create_ffmpeg_player/create_stream_player/create_ytdl_player have all been removed. + + - The goal is to create :class:`AudioSource` instead. + +- Using :meth:`VoiceClient.play` will not return an ``AudioPlayer``. + + - Instead, it's "flattened" like :class:`User` -> :class:`Member` is. + +- 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 :class:`AudioSource` design, you can now change the source that the :class:`VoiceClient` is +playing at runtime via :attr:`VoiceClient.source`. + +For example, you can add a :class:`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. + + +.. _migrating_1_0_wait_for: + +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 :meth:`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, :meth:`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 :exc:`asyncio.TimeoutError` +when reached instead of setting the return to ``None``. For example: + +.. code-block:: python3 + + 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 :doc:`aiohttp ` v2.0 or higher. + +Since this is a backwards incompatible change, it is recommended that you see the +`changes `_ +and the :doc:`aio:migration_to_2xx` pages for details on the breaking changes in +:doc:`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. + +Sharding +---------- + +The library has received significant changes on how it handles sharding and now has sharding as a first-class citizen. + +If using a Bot account and you want to shard your bot in a single process then you can use the :class:`AutoShardedClient`. + +This class allows you to use sharding without having to launch multiple processes or deal with complicated IPC. + +It should be noted that **the sharded client does not support user accounts**. This is due to the changes in connection +logic and state handling. + +Usage is as simple as doing: :: + + client = discord.AutoShardedClient() + +instead of using :class:`Client`. + +This will launch as many shards as your bot needs using the ``/gateway/bot`` endpoint, which allocates about 1000 guilds +per shard. + +If you want more control over the sharding you can specify ``shard_count`` and ``shard_ids``. :: + + # launch 10 shards regardless + client = discord.AutoShardedClient(shard_count=10) + + # launch specific shard IDs in this process + client = discord.AutoShardedClient(shard_count=10, shard_ids=(1, 2, 5, 6)) + +For users of the command extension, there is also :class:`~ext.commands.AutoShardedBot` which behaves similarly. + +Connection Improvements +------------------------- + +In v1.0, the auto reconnection logic has been powered up significantly. + +:meth:`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. + +:meth:`Client.run` and :meth:`Client.start` gains this keyword argument as well, but for most cases you will not +need to specify it unless turning it off. + +.. _migrating_1_0_commands: + +Command Extension Changes +-------------------------- + +Due to the :ref:`migrating_1_0_model_state` changes, some of the design of the extension module had to +undergo some design changes as well. + +Context Changes +~~~~~~~~~~~~~~~~~ + +In v1.0, the :class:`.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, :class:`.Context` is always passed. Ergo: + +.. code-block:: python3 + + # 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 :class:`~ext.commands.Context` now meets the requirements of :class:`abc.Messageable`. This +makes it have similar functionality to :class:`TextChannel` or :class:`DMChannel`. Using :meth:`~.Context.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 :class:`abc.Messageable` interface. See +:ref:`migrating_1_0_removed_helpers` for more information. + +Since the :class:`~ext.commands.Context` is now passed by default, several shortcuts have been added: + +**New Shortcuts** + +- :attr:`ctx.author ` is a shortcut for ``ctx.message.author``. +- :attr:`ctx.guild ` is a shortcut for ``ctx.message.guild``. +- :attr:`ctx.channel ` is a shortcut for ``ctx.message.channel``. +- :attr:`ctx.me ` is a shortcut for ``ctx.message.guild.me`` or ``ctx.bot.user``. +- :attr:`ctx.voice_client ` is a shortcut for ``ctx.message.guild.voice_client``. + +**New Functionality** + +- :meth:`.Context.reinvoke` to invoke a command again. + + - This is useful for bypassing cooldowns. +- :attr:`.Context.valid` to check if a context can be invoked with :meth:`.Bot.invoke`. +- :meth:`.Context.send_help` to show the help command for an entity using the new :class:`~.ext.commands.HelpCommand` 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 :class:`~ext.commands.Context` and use it instead of the default +provided one. + +For example, if you want to add some functionality to the context: + +.. code-block:: python3 + + class MyContext(commands.Context): + @property + def secret(self): + return 'my secret here' + +Then you can use :meth:`~ext.commands.Bot.get_context` inside :func:`on_message` with combination with +:meth:`~ext.commands.Bot.invoke` to use your custom context: + +.. code-block:: python3 + + 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: + +.. code-block:: python3 + + @bot.command() + async def secret(ctx): + await ctx.send(ctx.secret) + +.. _migrating_1_0_removed_helpers: + +Removed Helpers ++++++++++++++++++ + +With the new :class:`.Context` changes, a lot of message sending helpers have been removed. + +For a full list of changes, see below: + ++-----------------+------------------------------------------------------------+ +| Before | After | ++-----------------+------------------------------------------------------------+ +| ``Bot.say`` | :meth:`.Context.send` | ++-----------------+------------------------------------------------------------+ +| ``Bot.upload`` | :meth:`.Context.send` | ++-----------------+------------------------------------------------------------+ +| ``Bot.whisper`` | ``ctx.author.send`` | ++-----------------+------------------------------------------------------------+ +| ``Bot.type`` | :meth:`.Context.typing` or :meth:`.Context.trigger_typing` | ++-----------------+------------------------------------------------------------+ +| ``Bot.reply`` | 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 :func:`~ext.commands.guild_only` built-in +check. + +The ``commands`` attribute of :class:`~ext.commands.Bot` and :class:`~ext.commands.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: + +1. :attr:`~ext.commands.Command.signature` to get the signature of the command. +2. :attr:`~.Command.usage`, an attribute to override the default signature. +3. :attr:`~.Command.root_parent` to get the root parent group of a subcommand. + +For :class:`~ext.commands.Group` and :class:`~ext.commands.Bot` the following changed: + +- Changed :attr:`~.GroupMixin.commands` to be a :class:`set` without aliases. + + - Use :attr:`~.GroupMixin.all_commands` to get the old :class:`dict` with all commands. + +Check Changes +~~~~~~~~~~~~~~~ + +Prior to v1.0, :func:`~ext.commands.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. + +- :func:`~ext.commands.guild_only` replaces the old ``no_pm=True`` functionality. +- :func:`~ext.commands.is_owner` uses the :meth:`Client.application_info` endpoint by default to fetch owner ID. + + - This is actually powered by a different function, :meth:`~ext.commands.Bot.is_owner`. + - You can set the owner ID yourself by setting :attr:`.Bot.owner_id`. + +- :func:`~ext.commands.is_nsfw` checks if the channel the command is in is a NSFW channel. + + - This is powered by the new :meth:`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 :func:`.on_command` and :func:`.on_command_completion` +have been removed. The :class:`~ext.commands.Command` instance was not kept up-to date so it was incorrect. In order to get +the up to date :class:`~ext.commands.Command` instance, use the :attr:`.Context.command` +attribute. + +The error handlers, either :meth:`.Command.error` or :func:`.on_command_error`, +have been re-ordered to use the :class:`~ext.commands.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 :class:`~.commands.HelpCommand` class. This class now stores all the command handling and processing of the help command. + +The help command is now stored in the :attr:`.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. + +- :meth:`.HelpCommand.send_bot_help` + - Called when the user requested for help with the entire bot. +- :meth:`.HelpCommand.send_cog_help` + - Called when the user requested for help with a specific cog. +- :meth:`.HelpCommand.send_group_help` + - Called when the user requested for help with a :class:`~.commands.Group` +- :meth:`.HelpCommand.send_command_help` + - Called when the user requested for help with a :class:`~.commands.Command` +- :meth:`.HelpCommand.get_destination` + - Called to know where to send the help messages. Useful for deciding whether to DM or not. +- :meth:`.HelpCommand.command_not_found` + - A function (or coroutine) that returns a presentable no command found string. +- :meth:`.HelpCommand.subcommand_not_found` + - A function (or coroutine) that returns a string when a subcommand is not found. +- :meth:`.HelpCommand.send_error_message` + - A coroutine that gets passed the result of :meth:`.HelpCommand.command_not_found` and :meth:`.HelpCommand.subcommand_not_found`. + - By default it just sends the message. But you can, for example, override it to put it in an embed. +- :meth:`.HelpCommand.on_help_command_error` + - The :ref:`error handler ` for the help command if you want to add one. +- :meth:`.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 :class:`~.commands.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 :class:`~.commands.HelpCommand` implementation that doesn't take as much space, :class:`~.commands.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 :attr:`.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 :class:`~.commands.HelpCommand` in a cog, the following snippet can be used. + +.. code-block:: python3 + + 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 :ref:`documentation `. + +Cog Changes +~~~~~~~~~~~~~ + +Cogs have completely been revamped. They are documented in :ref:`ext_commands_cogs` as well. + +Cogs are now required to have a base class, :class:`~.commands.Cog` for future proofing purposes. This comes with special methods to customise some behaviour. + +* :meth:`.Cog.cog_unload` + - This is called when a cog needs to do some cleanup, such as cancelling a task. +* :meth:`.Cog.bot_check_once` + - This registers a :meth:`.Bot.check_once` check. +* :meth:`.Cog.bot_check` + - This registers a regular :meth:`.Bot.check` check. +* :meth:`.Cog.cog_check` + - This registers a check that applies to every command in the cog. +* :meth:`.Cog.cog_command_error` + - This is a special error handler that is called whenever an error happens inside the cog. +* :meth:`.Cog.cog_before_invoke` and :meth:`.Cog.cog_after_invoke` + - A special method that registers a cog before and after invoke hook. More information can be found in :ref:`migrating_1_0_before_after_hook`. + +Those that were using listeners, such as ``on_message`` inside a cog will now have to explicitly mark them as such using the :meth:`.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, :class:`.commands.CogMeta`. + +An example cog with every special method registered and a custom name is as follows: + +.. code-block:: python3 + + 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 + + +.. _migrating_1_0_before_after_hook: + +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, :class:`~ext.commands.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 :meth:`.Cog.cog_before_invoke` and :meth:`.Cog.cog_after_invoke`, e.g.: + +.. code-block:: python3 + + 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 +:attr:`.Context.command_failed`. + +The invocation order is as follows: + +1. Command local before invocation hook +2. Cog local before invocation hook +3. Global before invocation hook +4. The actual command +5. Command local after invocation hook +6. Cog local after invocation hook +7. 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 :class:`~ext.commands.Converter` system to +allow plugging in the :class:`~ext.commands.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 :class:`~ext.commands.Converter` derived +classes to be passed. For consistency, the :meth:`~ext.commands.Converter.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: + +- :class:`~ext.commands.clean_content` this is akin to :attr:`Message.clean_content` which scrubs mentions. +- :class:`~ext.commands.UserConverter` will now appropriately convert :class:`User` only. +- ``ChannelConverter`` is now split into two different converters. + + - :class:`~ext.commands.TextChannelConverter` for :class:`TextChannel`. + - :class:`~ext.commands.VoiceChannelConverter` for :class:`VoiceChannel`. diff --git a/docs/Python/html/_sources/migrating_to_async.rst.txt b/docs/Python/html/_sources/migrating_to_async.rst.txt new file mode 100644 index 00000000..a705f723 --- /dev/null +++ b/docs/Python/html/_sources/migrating_to_async.rst.txt @@ -0,0 +1,322 @@ +:orphan: + +.. currentmodule:: discord + +.. _migrating-to-async: + +Migrating to v0.10.0 +====================== + +v0.10.0 is one of the biggest breaking changes in the library due to massive +fundamental changes in how the library operates. + +The biggest major change is that the library has dropped support to all versions prior to +Python 3.4.2. This was made to support :mod:`asyncio`, in which more detail can be seen +:issue:`in the corresponding issue <50>`. To reiterate this, the implication is that +**python version 2.7 and 3.3 are no longer supported**. + +Below are all the other major changes from v0.9.0 to v0.10.0. + +Event Registration +-------------------- + +All events before were registered using :meth:`Client.event`. While this is still +possible, the events must be decorated with ``@asyncio.coroutine``. + +Before: + +.. code-block:: python3 + + @client.event + def on_message(message): + pass + +After: + +.. code-block:: python3 + + @client.event + @asyncio.coroutine + def on_message(message): + pass + +Or in Python 3.5+: + +.. code-block:: python3 + + @client.event + async def on_message(message): + pass + +Because there is a lot of typing, a utility decorator (:meth:`Client.async_event`) is provided +for easier registration. For example: + +.. code-block:: python3 + + @client.async_event + def on_message(message): + pass + + +Be aware however, that this is still a coroutine and your other functions that are coroutines must +be decorated with ``@asyncio.coroutine`` or be ``async def``. + +Event Changes +-------------- + +Some events in v0.9.0 were considered pretty useless due to having no separate states. The main +events that were changed were the ``_update`` events since previously they had no context on what +was changed. + +Before: + +.. code-block:: python3 + + def on_channel_update(channel): pass + def on_member_update(member): pass + def on_status(member): pass + def on_server_role_update(role): pass + def on_voice_state_update(member): pass + def on_socket_raw_send(payload, is_binary): pass + + +After: + +.. code-block:: python3 + + def on_channel_update(before, after): pass + def on_member_update(before, after): pass + def on_server_role_update(before, after): pass + def on_voice_state_update(before, after): pass + def on_socket_raw_send(payload): pass + +Note that ``on_status`` was removed. If you want its functionality, use :func:`on_member_update`. +See :ref:`discord-api-events` for more information. Other removed events include ``on_socket_closed``, ``on_socket_receive``, and ``on_socket_opened``. + + +Coroutines +----------- + +The biggest change that the library went through is that almost every function in :class:`Client` +was changed to be a `coroutine `_. Functions +that are marked as a coroutine in the documentation must be awaited from or yielded from in order +for the computation to be done. For example... + +Before: + +.. code-block:: python3 + + client.send_message(message.channel, 'Hello') + +After: + +.. code-block:: python3 + + yield from client.send_message(message.channel, 'Hello') + + # or in python 3.5+ + await client.send_message(message.channel, 'Hello') + +In order for you to ``yield from`` or ``await`` a coroutine then your function must be decorated +with ``@asyncio.coroutine`` or ``async def``. + +Iterables +---------- + +For performance reasons, many of the internal data structures were changed into a dictionary to support faster +lookup. As a consequence, this meant that some lists that were exposed via the API have changed into iterables +and not sequences. In short, this means that certain attributes now only support iteration and not any of the +sequence functions. + +The affected attributes are as follows: + +- :attr:`Client.servers` +- :attr:`Client.private_channels` +- :attr:`Server.channels` +- :attr:`Server.members` + +Some examples of previously valid behaviour that is now invalid + +.. code-block:: python3 + + if client.servers[0].name == "test": + # do something + +Since they are no longer :obj:`list`\s, they no longer support indexing or any operation other than iterating. +In order to get the old behaviour you should explicitly cast it to a list. + +.. code-block:: python3 + + servers = list(client.servers) + # work with servers + +.. warning:: + + Due to internal changes of the structure, the order you receive the data in + is not in a guaranteed order. + +Enumerations +------------ + +Due to dropping support for versions lower than Python 3.4.2, the library can now use +:doc:`py:library/enum` in places where it makes sense. + +The common places where this was changed was in the server region, member status, and channel type. + +Before: + +.. code-block:: python3 + + server.region == 'us-west' + member.status == 'online' + channel.type == 'text' + +After: + +.. code-block:: python3 + + server.region == discord.ServerRegion.us_west + member.status = discord.Status.online + channel.type == discord.ChannelType.text + +The main reason for this change was to reduce the use of finicky strings in the API as this +could give users a false sense of power. More information can be found in the :ref:`discord-api-enums` page. + +Properties +----------- + +A lot of function calls that returned constant values were changed into Python properties for ease of use +in format strings. + +The following functions were changed into properties: + ++----------------------------------------+--------------------------------------+ +| Before | After | ++----------------------------------------+--------------------------------------+ +| ``User.avatar_url()`` | :attr:`User.avatar_url` | ++----------------------------------------+--------------------------------------+ +| ``User.mention()`` | :attr:`User.mention` | ++----------------------------------------+--------------------------------------+ +| ``Channel.mention()`` | :attr:`Channel.mention` | ++----------------------------------------+--------------------------------------+ +| ``Channel.is_default_channel()`` | :attr:`Channel.is_default` | ++----------------------------------------+--------------------------------------+ +| ``Role.is_everyone()`` | :attr:`Role.is_everyone` | ++----------------------------------------+--------------------------------------+ +| ``Server.get_default_role()`` | :attr:`Server.default_role` | ++----------------------------------------+--------------------------------------+ +| ``Server.icon_url()`` | :attr:`Server.icon_url` | ++----------------------------------------+--------------------------------------+ +| ``Server.get_default_channel()`` | :attr:`Server.default_channel` | ++----------------------------------------+--------------------------------------+ +| ``Message.get_raw_mentions()`` | :attr:`Message.raw_mentions` | ++----------------------------------------+--------------------------------------+ +| ``Message.get_raw_channel_mentions()`` | :attr:`Message.raw_channel_mentions` | ++----------------------------------------+--------------------------------------+ + +Member Management +------------------- + +Functions that involved banning and kicking were changed. + ++--------------------------------+--------------------------+ +| Before | After | ++--------------------------------+--------------------------+ +| ``Client.ban(server, user)`` | ``Client.ban(member)`` | ++--------------------------------+--------------------------+ +| ``Client.kick(server, user)`` | ``Client.kick(member)`` | ++--------------------------------+--------------------------+ + +.. migrating-renames: + +Renamed Functions +------------------- + +Functions have been renamed. + ++------------------------------------+-------------------------------------------+ +| Before | After | ++------------------------------------+-------------------------------------------+ +| ``Client.set_channel_permissions`` | :meth:`Client.edit_channel_permissions` | ++------------------------------------+-------------------------------------------+ + +All the :class:`Permissions` related attributes have been renamed and the `can_` prefix has been +dropped. So for example, ``can_manage_messages`` has become ``manage_messages``. + +Forced Keyword Arguments +------------------------- + +Since 3.0+ of Python, we can now force questions to take in forced keyword arguments. A keyword argument is when you +explicitly specify the name of the variable and assign to it, for example: ``foo(name='test')``. Due to this support, +some functions in the library were changed to force things to take said keyword arguments. This is to reduce errors of +knowing the argument order and the issues that could arise from them. + +The following parameters are now exclusively keyword arguments: + +- :meth:`Client.send_message` + - ``tts`` +- :meth:`Client.logs_from` + - ``before`` + - ``after`` +- :meth:`Client.edit_channel_permissions` + - ``allow`` + - ``deny`` + +In the documentation you can tell if a function parameter is a forced keyword argument if it is after ``\*,`` +in the function signature. + +.. _migrating-running: + +Running the Client +-------------------- + +In earlier versions of discord.py, ``client.run()`` was a blocking call to the main thread +that called it. In v0.10.0 it is still a blocking call but it handles the event loop for you. +However, in order to do that you must pass in your credentials to :meth:`Client.run`. + +Basically, before: + +.. code-block:: python3 + + client.login('token') + client.run() + +After: + +.. code-block:: python3 + + client.run('token') + +.. warning:: + + Like in the older ``Client.run`` function, the newer one must be the one of + the last functions to call. This is because the function is **blocking**. Registering + events or doing anything after :meth:`Client.run` will not execute until the function + returns. + +This is a utility function that abstracts the event loop for you. There's no need for +the run call to be blocking and out of your control. Indeed, if you want control of the +event loop then doing so is quite straightforward: + +.. code-block:: python3 + + import discord + import asyncio + + client = discord.Client() + + @asyncio.coroutine + def main_task(): + yield from client.login('token') + yield from client.connect() + + loop = asyncio.get_event_loop() + try: + loop.run_until_complete(main_task()) + except: + loop.run_until_complete(client.logout()) + finally: + loop.close() + + + diff --git a/docs/Python/html/_sources/quickstart.rst.txt b/docs/Python/html/_sources/quickstart.rst.txt new file mode 100644 index 00000000..8b3daeb2 --- /dev/null +++ b/docs/Python/html/_sources/quickstart.rst.txt @@ -0,0 +1,79 @@ +:orphan: + +.. _quickstart: + +.. currentmodule:: discord + +Quickstart +============ + +This page gives a brief introduction to the library. It assumes you have the library installed, +if you don't check the :ref:`installing` portion. + +A Minimal Bot +--------------- + +Let's make a bot that responds to a specific message and walk you through it. + +It looks something like this: + +.. code-block:: python3 + + import discord + + client = discord.Client() + + @client.event + async def on_ready(): + print(f'We have logged in as {client.user}') + + @client.event + async def on_message(message): + if message.author == client.user: + return + + if message.content.startswith('$hello'): + await message.channel.send('Hello!') + + client.run('your token here') + +Let's name this file ``example_bot.py``. Make sure not to name it ``discord.py`` as that'll conflict +with the library. + +There's a lot going on here, so let's walk you through it step by step. + +1. The first line just imports the library, if this raises a `ModuleNotFoundError` or `ImportError` + then head on over to :ref:`installing` section to properly install. +2. Next, we create an instance of a :class:`Client`. This client is our connection to Discord. +3. We then use the :meth:`Client.event` decorator to register an event. This library has many events. + Since this library is asynchronous, we do things in a "callback" style manner. + + A callback is essentially a function that is called when something happens. In our case, + the :func:`on_ready` event is called when the bot has finished logging in and setting things + up and the :func:`on_message` event is called when the bot has received a message. +4. Since the :func:`on_message` event triggers for *every* message received, we have to make + sure that we ignore messages from ourselves. We do this by checking if the :attr:`Message.author` + is the same as the :attr:`Client.user`. +5. Afterwards, we check if the :class:`Message.content` starts with ``'$hello'``. If it does, + then we send a message in the channel it was used in with ``'Hello!'``. This is a basic way of + handling commands, which can be later automated with the :doc:`./ext/commands/index` framework. +6. Finally, we run the bot with our login token. If you need help getting your token or creating a bot, + look in the :ref:`discord-intro` section. + + +Now that we've made a bot, we have to *run* the bot. Luckily, this is simple since this is just a +Python script, we can run it directly. + +On Windows: + +.. code-block:: shell + + $ py -3 example_bot.py + +On other systems: + +.. code-block:: shell + + $ python3 example_bot.py + +Now you can try playing around with your basic bot. diff --git a/docs/Python/html/_sources/version_guarantees.rst.txt b/docs/Python/html/_sources/version_guarantees.rst.txt new file mode 100644 index 00000000..7909bd6b --- /dev/null +++ b/docs/Python/html/_sources/version_guarantees.rst.txt @@ -0,0 +1,30 @@ +.. _version_guarantees: + +Version Guarantees +===================== + +The library follows a `semantic versioning principle `_ which means that the major version is updated every time there is an incompatible API change. However due to the lack of guarantees on the Discord side when it comes to breaking changes along with the fairly dynamic nature of Python it can be hard to discern what can be considered a breaking change and what isn't. + +The first thing to keep in mind is that breaking changes only apply to **publicly documented functions and classes**. If it's not listed in the documentation here then it is not part of the public API and is thus bound to change. This includes attributes that start with an underscore or functions without an underscore that are not documented. + +.. note:: + + The examples below are non-exhaustive. + +Examples of Breaking Changes +------------------------------ + +- Changing the default parameter value to something else. +- Renaming a function without an alias to an old function. +- Adding or removing parameters to an event. + +Examples of Non-Breaking Changes +---------------------------------- + +- Adding or removing private underscored attributes. +- Adding an element into the ``__slots__`` of a data class. +- Changing the behaviour of a function to fix a bug. +- Changes in the documentation. +- Modifying the internal HTTP handling. +- Upgrading the dependencies to a new version, major or otherwise. + diff --git a/docs/Python/html/_sources/whats_new.rst.txt b/docs/Python/html/_sources/whats_new.rst.txt new file mode 100644 index 00000000..bc283d22 --- /dev/null +++ b/docs/Python/html/_sources/whats_new.rst.txt @@ -0,0 +1,1315 @@ +.. currentmodule:: discord + +.. |commands| replace:: [:ref:`ext.commands `] +.. |tasks| replace:: [:ref:`ext.tasks `] + +.. _whats_new: + +Changelog +============ + +This page keeps a detailed human friendly rendering of what's new and changed +in specific versions. + +.. _vp2p0p0: + +v2.0.0 +-------- + +This version was partly developed by Danny, and partly by the enhanced-discord.py contributors. +The library has been updated with breaking changes, and as such the major version was changed. + + +- Performance of the library has improved significantly (all times with 1 process and 1 AutoShardedBot): + - 735 guilds boot up time (with chunking): 57s/1.7 GiB RAM -> 42s/1.4 GiB RAM + - 27k guilds boot up time (with chunking): 477s/8 GiB RAM -> 303s/7.2 GiB RAM + - 48k guilds boot up time (without chunking): 109s -> 67s + - 106k guilds boot up time (without chunking): 3300s -> 3090s +- The entire public API of the library is now completely type hinted. + - There may still be bugs however. + - For best type hinting experience consider using Pyright. +- Almost all edit methods now return their updated counterpart rather than doing an in-place edit. +- Japanese docs were removed, as we are no longer able to keep them in sync. + + +Breaking Changes +~~~~~~~~~~~~~~~~~ + +- :meth:`Asset.replace` now only accepts keyword arguments +- ``Asset.with_`` functions now only accept positional only arguments +- :meth:`TextChannel.get_partial_message` is now pos-only +- :meth:`TextChannel.get_thread` is now pos-only +- ``permissions_for`` is now pos-only +- :attr:`GroupChannel.owner` is now Optional +- ``edit`` methods now only accept None if it actually means something (e.g. clearing it) +- ``timeout`` parameter for ``ui.View.__init__`` is now keyword only +- When an interaction has already been responded and another one is sent, :exc:`InteractionResponded` is now raised. + - Discord's API only allows a single :attr:`interaction.response`. +- Separate :func:`on_member_update` and :func:`on_presence_update` + - The new event :func:`on_presence_update` is now called when status/activity is changed. + - :func:`on_member_update` will now no longer have status/activity changes. +- afk parameter in :meth:`Client.change_presence` is removed +- The undocumented private :func:`on_socket_response` event got removed. + - Consider using the newer documented :func:`on_socket_event_type` event instead. +- Using :func:`on_socket_raw_receive` and :func:`on_socket_raw_send` are now opt-in via :attr:`enable_debug_events` toggle. +- :func:`on_socket_raw_receive` is now only dispatched after decompressing the payload. +- Persistent View dispatch mechanism now uses the ``message_id`` key if provided. +- :meth:`Message.start_thread` was renamed to :meth:`Message.create_thread` +- :meth:`TextChannel.start_thread` was renamed to :meth:`TextChannel.create_thread` +- All ``get_`` lookup functions now use positional-only parameters for the id parameter. +- Remove :meth:`TextChannel.active_threads` due to the endpoint being deprecated and slated for removal. + - Use :meth:`Guild.active_threads` instead. +- :attr:`User.avatar` now returns None if the user did not upload an avatar. + - Use :attr:`User.display_avatar` to get the avatar and fallback to the default avatar to go back to the old behaviour. + +New Features +~~~~~~~~~~~~~~ + +- Channel types are now typed +- Member is now typed +- Client is now typed +- Permissions are now typed +- Core library errors are now typed +- Add various examples showing how to use views. There are more to come. +- :attr:`GroupChannel.owner_id` now gets the owner ID +- ``edit`` methods now don't rely on previous state +- :meth:`View.from_message` converts a Message.components to a View +- :attr:`Thread.type` to get the thread channel type +- :attr:`ButtonStyle.url` alias for :attr:`ButtonStyle.link` +- Add default style for :class:`ui.Button` constructor + - This makes it so creating a URL button is as simple as ``ui.Button(url='...', label='...')`` +- :attr:`Thread.mention` to get the mention string for a thread +- :meth:`Thread.is_nsfw` to check whether the parent channel of the thread is NSFW +- Add support for fetching the original interaction response message. + - :meth:`Interaction.original_message` will retrieve it and returns an InteractionMessage + - :meth:`InteractionMessage.edit` or :meth:`Interaction.edit_original_message` will edit it + - :meth:`InteractionMessage.delete` or :meth:`Interaction.delete_original_message` will delete it +- :attr:`MessageFlags.ephemeral` to get whether a message is ephemeral +- :meth:`Client.fetch_channel` now fetches threads as well +- :class:`SelectOption` now has a __str__ that matches the client representation. + - This might change in the future to remove the description from it. +- Add a converter for :class:`discord.Thread` +- Allow ``clean_content`` converter to work stand-alone +- Add :meth:`User.banner` to get a user's banner and :meth:`User.accent_colour` to get the set banner colour. + - Due to an API limitation this requires using :meth:`Client.fetch_user`. +- Add ``reason`` keyword argument to more methods +- Add audit log events for threads +- Allow public threads to be created without a starter message +- Add :meth:`Guild.get_channel_or_thread` helper method +- Add full support for the new sticker API +- Add :func:`on_socket_event_type` event to get the event type of an event +- Add :attr:`TextChannel.default_auto_archive_duration` +- Add :class:`PartialMessageable` type to allow for sending messages to a channel using only its ``channel_id``. + - This is constructed with :meth:`Client.get_partial_messageable`. +- Add :meth:`Guild.active_threads` to get all of a guild's active threads. +- Add :attr:`Thread.members` to get all cached :class:`ThreadMember` instances of a thread. +- Add :meth:`Thread.fetch_members` to fetch all :class:`ThreadMember` instances of a thread. + - These two require :attr:`Intents.members` to be useful. +- Add support for guild avatars for members under :attr:`Member.guild_avatar` +- Add :attr:`User.display_avatar` and :attr:`Member.display_avatar` to get the user's displayed avatar. +- Add :attr:`Colour.brand_green` and :attr:`Colour.brand_red` +- |commands| :attr:`CommandOnCooldown.type` to get back the type of the cooldown since it was removed from :class:`Cooldown` +- Add :attr:`Guild.bots` and :attr:`Guild.humans` + + +Bug Fixes +~~~~~~~~~~~ + +- :class:`Channel` converters now work in DMs again +- Fix :attr:`Interaction.channel` being None in threads +- Change timeouts in :class:`ui.View` to work as documented +- :attr:`Message.__repr__` now shows the proper type, e.g. :class:`WebhookMessage` and :class:`InteractionMessage` +- Change :class:`Cooldown` handling to not reset token window when the number of tokens reaches 0 +- Fix audit log permission construction breaking due to unexpected type errors. +- Fix :func:`on_thread_join` not dispatching when a thread is unarchived +- Fix :attr:`Message.guild` being None when a thread is unarchived due to a new message +- :class:`MessageConverter` now works with threads +- Retry requests when a 504 is hit +- Fix :attr:`Thread.slowmode_delay` not updating on edit +- Fix ``permissions_for`` for roles +- Update :attr:`Message.system_content` for newer message types +- Fix :class:`PartialMessage` not working with threads +- Fix crash with stage instances not having the documented ``discoverable_enabled`` key +- Fix some built-in checks not working with threads +- Fix :class:`SyncWebhook` not working in a multi-threaded context +- Fix :func:`on_thread_member_remove` not dispatching properly +- Fix :func:`on_typing` not dispatching for threads +- Update :attr:`Message.is_system` to work with newer message types +- Fix some enums like :class:`VerificationLevel` not being comparable. +- Fix ``io.BytesIO`` sources not working with ffmpeg players +- Fix :meth:`Client.fetch_channel` and :meth:`Guild.fetch_channel` not returning threads + +.. _vp1p7p3: + +v1.7.3 +-------- + +Bug Fixes +~~~~~~~~~~ + +- Fix a crash involving guild uploaded stickers +- Fix :meth:`DMChannel.permissions_for` not having :attr:`Permissions.read_messages` set. + +.. _vp1p7p2: + +v1.7.2 +------- + +Bug Fixes +~~~~~~~~~~~ + +- Fix ``fail_if_not_exists`` causing certain message references to not be usable within :meth:`abc.Messageable.send` and :meth:`Message.reply` (:issue:`6726`) +- Fix :meth:`Guild.chunk` hanging when the user left the guild. (:issue:`6730`) +- Fix loop sleeping after final iteration rather than before (:issue:`6744`) + +.. _vp1p7p1: + +v1.7.1 +------- + +Bug Fixes +~~~~~~~~~~~ + +- |commands| Fix :meth:`Cog.has_error_handler ` not working as intended. + +.. _vp1p7p0: + +v1.7.0 +-------- + +This version is mainly for improvements and bug fixes. This is more than likely the last major version in the 1.x series. +Work after this will be spent on v2.0. As a result, **this is the last version to support Python 3.5**. +Likewise, **this is the last version to support user bots**. + +Development of v2.0 will have breaking changes and support for newer API features. + +New Features +~~~~~~~~~~~~~~ + +- Add support for stage channels via :class:`StageChannel` (:issue:`6602`, :issue:`6608`) +- Add support for :attr:`MessageReference.fail_if_not_exists` (:issue:`6484`) + - By default, if the message you're replying to doesn't exist then the API errors out. + This attribute tells the Discord API that it's okay for that message to be missing. + +- Add support for Discord's new permission serialisation scheme. +- Add an easier way to move channels using :meth:`abc.GuildChannel.move` +- Add :attr:`Permissions.use_slash_commands` +- Add :attr:`Permissions.request_to_speak` +- Add support for voice regions in voice channels via :attr:`VoiceChannel.rtc_region` (:issue:`6606`) +- Add support for :meth:`PartialEmoji.url_as` (:issue:`6341`) +- Add :attr:`MessageReference.jump_url` (:issue:`6318`) +- Add :attr:`File.spoiler` (:issue:`6317`) +- Add support for passing ``roles`` to :meth:`Guild.estimate_pruned_members` (:issue:`6538`) +- Allow callable class factories to be used in :meth:`abc.Connectable.play` (:issue:`6478`) +- Add a way to get mutual guilds from the client's cache via :attr:`User.mutual_guilds` (:issue:`2539`, :issue:`6444`) +- :meth:`PartialMessage.edit` now returns a full :class:`Message` upon success (:issue:`6309`) +- Add :attr:`RawMessageUpdateEvent.guild_id` (:issue:`6489`) +- :class:`AuditLogEntry` is now hashable (:issue:`6495`) +- :class:`Attachment` is now hashable +- Add :attr:`Attachment.content_type` attribute (:issue:`6618`) +- Add support for casting :class:`Attachment` to :class:`str` to get the URL. +- Add ``seed`` parameter for :class:`Colour.random` (:issue:`6562`) + - This only seeds it for one call. If seeding for multiple calls is desirable, use :func:`random.seed`. + +- Add a :func:`utils.remove_markdown` helper function (:issue:`6573`) +- Add support for passing scopes to :func:`utils.oauth_url` (:issue:`6568`) +- |commands| Add support for ``rgb`` CSS function as a parameter to :class:`ColourConverter ` (:issue:`6374`) +- |commands| Add support for converting :class:`StoreChannel` via :class:`StoreChannelConverter ` (:issue:`6603`) +- |commands| Add support for stripping whitespace after the prefix is encountered using the ``strip_after_prefix`` :class:`~ext.commands.Bot` constructor parameter. +- |commands| Add :attr:`Context.invoked_parents ` to get the aliases a command's parent was invoked with (:issue:`1874`, :issue:`6462`) +- |commands| Add a converter for :class:`PartialMessage` under :class:`ext.commands.PartialMessageConverter` (:issue:`6308`) +- |commands| Add a converter for :class:`Guild` under :class:`ext.commands.GuildConverter` (:issue:`6016`, :issue:`6365`) +- |commands| Add :meth:`Command.has_error_handler ` + - This is also adds :meth:`Cog.has_error_handler ` +- |commands| Allow callable types to act as a bucket key for cooldowns (:issue:`6563`) +- |commands| Add ``linesep`` keyword argument to :class:`Paginator ` (:issue:`5975`) +- |commands| Allow ``None`` to be passed to :attr:`HelpCommand.verify_checks ` to only verify in a guild context (:issue:`2008`, :issue:`6446`) +- |commands| Allow relative paths when loading extensions via a ``package`` keyword argument (:issue:`2465`, :issue:`6445`) + +Bug Fixes +~~~~~~~~~~ + +- Fix mentions not working if ``mention_author`` is passed in :meth:`abc.Messageable.send` without :attr:`Client.allowed_mentions` set (:issue:`6192`, :issue:`6458`) +- Fix user created instances of :class:`CustomActivity` triggering an error (:issue:`4049`) + - Note that currently, bot users still cannot set a custom activity due to a Discord limitation. +- Fix :exc:`ZeroDivisionError` being raised from :attr:`VoiceClient.average_latency` (:issue:`6430`, :issue:`6436`) +- Fix :attr:`User.public_flags` not updating upon edit (:issue:`6315`) +- Fix :attr:`Message.call` sometimes causing attribute errors (:issue:`6390`) +- Fix issue resending a file during request retries on newer versions of ``aiohttp`` (:issue:`6531`) +- Raise an error when ``user_ids`` is empty in :meth:`Guild.query_members` +- Fix ``__str__`` magic method raising when a :class:`Guild` is unavailable. +- Fix potential :exc:`AttributeError` when accessing :attr:`VoiceChannel.members` (:issue:`6602`) +- :class:`Embed` constructor parameters now implicitly convert to :class:`str` (:issue:`6574`) +- Ensure ``discord`` package is only run if executed as a script (:issue:`6483`) +- |commands| Fix irrelevant commands potentially being unloaded during cog unload due to failure. +- |commands| Fix attribute errors when setting a cog to :class:`~.ext.commands.HelpCommand` (:issue:`5154`) +- |commands| Fix :attr:`Context.invoked_with ` being improperly reassigned during a :meth:`~ext.commands.Context.reinvoke` (:issue:`6451`, :issue:`6462`) +- |commands| Remove duplicates from :meth:`HelpCommand.get_bot_mapping ` (:issue:`6316`) +- |commands| Properly handle positional-only parameters in bot command signatures (:issue:`6431`) +- |commands| Group signatures now properly show up in :attr:`Command.signature ` (:issue:`6529`, :issue:`6530`) + +Miscellaneous +~~~~~~~~~~~~~~ + +- User endpoints and all userbot related functionality has been deprecated and will be removed in the next major version of the library. +- :class:`Permission` class methods were updated to match the UI of the Discord client (:issue:`6476`) +- ``_`` and ``-`` characters are now stripped when making a new cog using the ``discord`` package (:issue:`6313`) + +.. _vp1p6p0: + +v1.6.0 +-------- + +This version comes with support for replies and stickers. + +New Features +~~~~~~~~~~~~~~ + +- An entirely redesigned documentation. This was the cumulation of multiple months of effort. + - There's now a dark theme, feel free to navigate to the cog on the screen to change your setting, though this should be automatic. +- Add support for :meth:`AppInfo.icon_url_as` and :meth:`AppInfo.cover_image_url_as` (:issue:`5888`) +- Add :meth:`Colour.random` to get a random colour (:issue:`6067`) +- Add support for stickers via :class:`Sticker` (:issue:`5946`) +- Add support for replying via :meth:`Message.reply` (:issue:`6061`) + - This also comes with the :attr:`AllowedMentions.replied_user` setting. + - :meth:`abc.Messageable.send` can now accept a :class:`MessageReference`. + - :class:`MessageReference` can now be constructed by users. + - :meth:`Message.to_reference` can now convert a message to a :class:`MessageReference`. +- Add support for getting the replied to resolved message through :attr:`MessageReference.resolved`. +- Add support for role tags. + - :attr:`Guild.premium_subscriber_role` to get the "Nitro Booster" role (if available). + - :attr:`Guild.self_role` to get the bot's own role (if available). + - :attr:`Role.tags` to get the role's tags. + - :meth:`Role.is_premium_subscriber` to check if a role is the "Nitro Booster" role. + - :meth:`Role.is_bot_managed` to check if a role is a bot role (i.e. the automatically created role for bots). + - :meth:`Role.is_integration` to check if a role is role created by an integration. +- Add :meth:`Client.is_ws_ratelimited` to check if the websocket is rate limited. + - :meth:`ShardInfo.is_ws_ratelimited` is the equivalent for checking a specific shard. +- Add support for chunking an :class:`AsyncIterator` through :meth:`AsyncIterator.chunk` (:issue:`6100`, :issue:`6082`) +- Add :attr:`PartialEmoji.created_at` (:issue:`6128`) +- Add support for editing and deleting webhook sent messages (:issue:`6058`) + - This adds :class:`WebhookMessage` as well to power this behaviour. +- Add :class:`PartialMessage` to allow working with a message via channel objects and just a message_id (:issue:`5905`) + - This is useful if you don't want to incur an extra API call to fetch the message. +- Add :meth:`Emoji.url_as` (:issue:`6162`) +- Add support for :attr:`Member.pending` for the membership gating feature. +- Allow ``colour`` parameter to take ``int`` in :meth:`Guild.create_role` (:issue:`6195`) +- Add support for ``presences`` in :meth:`Guild.query_members` (:issue:`2354`) +- |commands| Add support for ``description`` keyword argument in :class:`commands.Cog ` (:issue:`6028`) +- |tasks| Add support for calling the wrapped coroutine as a function via ``__call__``. + + +Bug Fixes +~~~~~~~~~~~ + +- Raise :exc:`DiscordServerError` when reaching 503s repeatedly (:issue:`6044`) +- Fix :exc:`AttributeError` when :meth:`Client.fetch_template` is called (:issue:`5986`) +- Fix errors when playing audio and moving to another channel (:issue:`5953`) +- Fix :exc:`AttributeError` when voice channels disconnect too fast (:issue:`6039`) +- Fix stale :class:`User` references when the members intent is off. +- Fix :func:`on_user_update` not dispatching in certain cases when a member is not cached but the user somehow is. +- Fix :attr:`Message.author` being overwritten in certain cases during message update. + - This would previously make it so :attr:`Message.author` is a :class:`User`. +- Fix :exc:`UnboundLocalError` for editing ``public_updates_channel`` in :meth:`Guild.edit` (:issue:`6093`) +- Fix uninitialised :attr:`CustomActivity.created_at` (:issue:`6095`) +- |commands| Errors during cog unload no longer stops module cleanup (:issue:`6113`) +- |commands| Properly cleanup lingering commands when a conflicting alias is found when adding commands (:issue:`6217`) + +Miscellaneous +~~~~~~~~~~~~~~~ + +- ``ffmpeg`` spawned processes no longer open a window in Windows (:issue:`6038`) +- Update dependencies to allow the library to work on Python 3.9+ without requiring build tools. (:issue:`5984`, :issue:`5970`) +- Fix docstring issue leading to a SyntaxError in 3.9 (:issue:`6153`) +- Update Windows opus binaries from 1.2.1 to 1.3.1 (:issue:`6161`) +- Allow :meth:`Guild.create_role` to accept :class:`int` as the ``colour`` parameter (:issue:`6195`) +- |commands| :class:`MessageConverter ` regex got updated to support ``www.`` prefixes (:issue:`6002`) +- |commands| :class:`UserConverter ` now fetches the API if an ID is passed and the user is not cached. +- |commands| :func:`max_concurrency ` is now called before cooldowns (:issue:`6172`) + +.. _vp1p5p1: + +v1.5.1 +------- + +Bug Fixes +~~~~~~~~~~~ + +- Fix :func:`utils.escape_markdown` not escaping quotes properly (:issue:`5897`) +- Fix :class:`Message` not being hashable (:issue:`5901`, :issue:`5866`) +- Fix moving channels to the end of the channel list (:issue:`5923`) +- Fix seemingly strange behaviour in ``__eq__`` for :class:`PermissionOverwrite` (:issue:`5929`) +- Fix aliases showing up in ``__iter__`` for :class:`Intents` (:issue:`5945`) +- Fix the bot disconnecting from voice when moving them to another channel (:issue:`5904`) +- Fix attribute errors when chunking times out sometimes during delayed on_ready dispatching. +- Ensure that the bot's own member is not evicted from the cache (:issue:`5949`) + +Miscellaneous +~~~~~~~~~~~~~~ + +- Members are now loaded during ``GUILD_MEMBER_UPDATE`` events if :attr:`MemberCacheFlags.joined` is set. (:issue:`5930`) +- |commands| :class:`MemberConverter ` now properly lazily fetches members if not available from cache. + - This is the same as having ``discord.Member`` as the type-hint. +- :meth:`Guild.chunk` now allows concurrent calls without spamming the gateway with requests. + +.. _vp1p5p0: + +v1.5.0 +-------- + +This version came with forced breaking changes that Discord is requiring all bots to go through on October 7th. It is highly recommended to read the documentation on intents, :ref:`intents_primer`. + +API Changes +~~~~~~~~~~~~~ + +- Members and presences will no longer be retrieved due to an API change. See :ref:`privileged_intents` for more info. +- As a consequence, fetching offline members is disabled if the members intent is not enabled. + +New Features +~~~~~~~~~~~~~~ + +- Support for gateway intents, passed via ``intents`` in :class:`Client` using :class:`Intents`. +- Add :attr:`VoiceRegion.south_korea` (:issue:`5233`) +- Add support for ``__eq__`` for :class:`Message` (:issue:`5789`) +- Add :meth:`Colour.dark_theme` factory method (:issue:`1584`) +- Add :meth:`AllowedMentions.none` and :meth:`AllowedMentions.all` (:issue:`5785`) +- Add more concrete exceptions for 500 class errors under :class:`DiscordServerError` (:issue:`5797`) +- Implement :class:`VoiceProtocol` to better intersect the voice flow. +- Add :meth:`Guild.chunk` to fully chunk a guild. +- Add :class:`MemberCacheFlags` to better control member cache. See :ref:`intents_member_cache` for more info. +- Add support for :attr:`ActivityType.competing` (:issue:`5823`) + - This seems currently unused API wise. + +- Add support for message references, :attr:`Message.reference` (:issue:`5754`, :issue:`5832`) +- Add alias for :class:`ColourConverter` under ``ColorConverter`` (:issue:`5773`) +- Add alias for :attr:`PublicUserFlags.verified_bot_developer` under :attr:`PublicUserFlags.early_verified_bot_developer` (:issue:`5849`) +- |commands| Add support for ``require_var_positional`` for :class:`Command` (:issue:`5793`) + +Bug Fixes +~~~~~~~~~~ + +- Fix issue with :meth:`Guild.by_category` not showing certain channels. +- Fix :attr:`abc.GuildChannel.permissions_synced` always being ``False`` (:issue:`5772`) +- Fix handling of cloudflare bans on webhook related requests (:issue:`5221`) +- Fix cases where a keep-alive thread would ack despite already dying (:issue:`5800`) +- Fix cases where a :class:`Member` reference would be stale when cache is disabled in message events (:issue:`5819`) +- Fix ``allowed_mentions`` not being sent when sending a single file (:issue:`5835`) +- Fix ``overwrites`` being ignored in :meth:`abc.GuildChannel.edit` if ``{}`` is passed (:issue:`5756`, :issue:`5757`) +- |commands| Fix exceptions being raised improperly in command invoke hooks (:issue:`5799`) +- |commands| Fix commands not being properly ejected during errors in a cog injection (:issue:`5804`) +- |commands| Fix cooldown timing ignoring edited timestamps. +- |tasks| Fix tasks extending the next iteration on handled exceptions (:issue:`5762`, :issue:`5763`) + +Miscellaneous +~~~~~~~~~~~~~~~ + +- Webhook requests are now logged (:issue:`5798`) +- Remove caching layer from :attr:`AutoShardedClient.shards`. This was causing issues if queried before launching shards. +- Gateway rate limits are now handled. +- Warnings logged due to missed caches are now changed to DEBUG log level. +- Some strings are now explicitly interned to reduce memory usage. +- Usage of namedtuples has been reduced to avoid potential breaking changes in the future (:issue:`5834`) +- |commands| All :class:`BadArgument` exceptions from the built-in converters now raise concrete exceptions to better tell them apart (:issue:`5748`) +- |tasks| Lazily fetch the event loop to prevent surprises when changing event loop policy (:issue:`5808`) + +.. _vp1p4p2: + +v1.4.2 +-------- + +This is a maintenance release with backports from :ref:`vp1p5p0`. + +Bug Fixes +~~~~~~~~~~~ + +- Fix issue with :meth:`Guild.by_category` not showing certain channels. +- Fix :attr:`abc.GuildChannel.permissions_synced` always being ``False`` (:issue:`5772`) +- Fix handling of cloudflare bans on webhook related requests (:issue:`5221`) +- Fix cases where a keep-alive thread would ack despite already dying (:issue:`5800`) +- Fix cases where a :class:`Member` reference would be stale when cache is disabled in message events (:issue:`5819`) +- Fix ``allowed_mentions`` not being sent when sending a single file (:issue:`5835`) +- Fix ``overwrites`` being ignored in :meth:`abc.GuildChannel.edit` if ``{}`` is passed (:issue:`5756`, :issue:`5757`) +- |commands| Fix exceptions being raised improperly in command invoke hooks (:issue:`5799`) +- |commands| Fix commands not being properly ejected during errors in a cog injection (:issue:`5804`) +- |commands| Fix cooldown timing ignoring edited timestamps. +- |tasks| Fix tasks extending the next iteration on handled exceptions (:issue:`5762`, :issue:`5763`) + +Miscellaneous +~~~~~~~~~~~~~~~ + +- Remove caching layer from :attr:`AutoShardedClient.shards`. This was causing issues if queried before launching shards. +- |tasks| Lazily fetch the event loop to prevent surprises when changing event loop policy (:issue:`5808`) + +.. _vp1p4p1: + +v1.4.1 +-------- + +Bug Fixes +~~~~~~~~~~~ + +- Properly terminate the connection when :meth:`Client.close` is called (:issue:`5207`) +- Fix error being raised when clearing embed author or image when it was already cleared (:issue:`5210`, :issue:`5212`) +- Fix ``__path__`` to allow editable extensions (:issue:`5213`) + +.. _vp1p4p0: + +v1.4.0 +-------- + +Another version with a long development time. Features like Intents are slated to be released in a v1.5 release. Thank you for your patience! + +New Features +~~~~~~~~~~~~~~ + +- Add support for :class:`AllowedMentions` to have more control over what gets mentioned. + - This can be set globally through :attr:`Client.allowed_mentions` + - This can also be set on a per message basis via :meth:`abc.Messageable.send` + +- :class:`AutoShardedClient` has been completely redesigned from the ground up to better suit multi-process clusters (:issue:`2654`) + - Add :class:`ShardInfo` which allows fetching specific information about a shard. + - The :class:`ShardInfo` allows for reconnecting and disconnecting of a specific shard as well. + - Add :meth:`AutoShardedClient.get_shard` and :attr:`AutoShardedClient.shards` to get information about shards. + - Rework the entire connection flow to better facilitate the ``IDENTIFY`` rate limits. + - Add a hook :meth:`Client.before_identify_hook` to have better control over what happens before an ``IDENTIFY`` is done. + - Add more shard related events such as :func:`on_shard_connect`, :func:`on_shard_disconnect` and :func:`on_shard_resumed`. + +- Add support for guild templates (:issue:`2652`) + - This adds :class:`Template` to read a template's information. + - :meth:`Client.fetch_template` can be used to fetch a template's information from the API. + - :meth:`Client.create_guild` can now take an optional template to base the creation from. + - Note that fetching a guild's template is currently restricted for bot accounts. + +- Add support for guild integrations (:issue:`2051`, :issue:`1083`) + - :class:`Integration` is used to read integration information. + - :class:`IntegrationAccount` is used to read integration account information. + - :meth:`Guild.integrations` will fetch all integrations in a guild. + - :meth:`Guild.create_integration` will create an integration. + - :meth:`Integration.edit` will edit an existing integration. + - :meth:`Integration.delete` will delete an integration. + - :meth:`Integration.sync` will sync an integration. + - There is currently no support in the audit log for this. + +- Add an alias for :attr:`VerificationLevel.extreme` under :attr:`VerificationLevel.very_high` (:issue:`2650`) +- Add various grey to gray aliases for :class:`Colour` (:issue:`5130`) +- Added :attr:`VoiceClient.latency` and :attr:`VoiceClient.average_latency` (:issue:`2535`) +- Add ``use_cached`` and ``spoiler`` parameters to :meth:`Attachment.to_file` (:issue:`2577`, :issue:`4095`) +- Add ``position`` parameter support to :meth:`Guild.create_category` (:issue:`2623`) +- Allow passing ``int`` for the colour in :meth:`Role.edit` (:issue:`4057`) +- Add :meth:`Embed.remove_author` to clear author information from an embed (:issue:`4068`) +- Add the ability to clear images and thumbnails in embeds using :attr:`Embed.Empty` (:issue:`4053`) +- Add :attr:`Guild.max_video_channel_users` (:issue:`4120`) +- Add :attr:`Guild.public_updates_channel` (:issue:`4120`) +- Add ``guild_ready_timeout`` parameter to :class:`Client` and subclasses to control timeouts when the ``GUILD_CREATE`` stream takes too long (:issue:`4112`) +- Add support for public user flags via :attr:`User.public_flags` and :class:`PublicUserFlags` (:issue:`3999`) +- Allow changing of channel types via :meth:`TextChannel.edit` to and from a news channel (:issue:`4121`) +- Add :meth:`Guild.edit_role_positions` to bulk edit role positions in a single API call (:issue:`2501`, :issue:`2143`) +- Add :meth:`Guild.change_voice_state` to change your voice state in a guild (:issue:`5088`) +- Add :meth:`PartialInviteGuild.is_icon_animated` for checking if the invite guild has animated icon (:issue:`4180`, :issue:`4181`) +- Add :meth:`PartialInviteGuild.icon_url_as` now supports ``static_format`` for consistency (:issue:`4180`, :issue:`4181`) +- Add support for ``user_ids`` in :meth:`Guild.query_members` +- Add support for pruning members by roles in :meth:`Guild.prune_members` (:issue:`4043`) +- |commands| Implement :func:`~ext.commands.before_invoke` and :func:`~ext.commands.after_invoke` decorators (:issue:`1986`, :issue:`2502`) +- |commands| Add a way to retrieve ``retry_after`` from a cooldown in a command via :meth:`Command.get_cooldown_retry_after <.ext.commands.Command.get_cooldown_retry_after>` (:issue:`5195`) +- |commands| Add a way to dynamically add and remove checks from a :class:`HelpCommand <.ext.commands.HelpCommand>` (:issue:`5197`) +- |tasks| Add :meth:`Loop.is_running <.ext.tasks.Loop.is_running>` method to the task objects (:issue:`2540`) +- |tasks| Allow usage of custom error handlers similar to the command extensions to tasks using :meth:`Loop.error <.ext.tasks.Loop.error>` decorator (:issue:`2621`) + + +Bug Fixes +~~~~~~~~~~~~ + +- Fix issue with :attr:`PartialEmoji.url` reads leading to a failure (:issue:`4015`, :issue:`4016`) +- Allow :meth:`abc.Messageable.history` to take a limit of ``1`` even if ``around`` is passed (:issue:`4019`) +- Fix :attr:`Guild.member_count` not updating in certain cases when a member has left the guild (:issue:`4021`) +- Fix the type of :attr:`Object.id` not being validated. For backwards compatibility ``str`` is still allowed but is converted to ``int`` (:issue:`4002`) +- Fix :meth:`Guild.edit` not allowing editing of notification settings (:issue:`4074`, :issue:`4047`) +- Fix crash when the guild widget contains channels that aren't in the payload (:issue:`4114`, :issue:`4115`) +- Close ffmpeg stdin handling from spawned processes with :class:`FFmpegOpusAudio` and :class:`FFmpegPCMAudio` (:issue:`4036`) +- Fix :func:`utils.escape_markdown` not escaping masked links (:issue:`4206`, :issue:`4207`) +- Fix reconnect loop due to failed handshake on region change (:issue:`4210`, :issue:`3996`) +- Fix :meth:`Guild.by_category` not returning empty categories (:issue:`4186`) +- Fix certain JPEG images not being identified as JPEG (:issue:`5143`) +- Fix a crash when an incomplete guild object is used when fetching reaction information (:issue:`5181`) +- Fix a timeout issue when fetching members using :meth:`Guild.query_members` +- Fix an issue with domain resolution in voice (:issue:`5188`, :issue:`5191`) +- Fix an issue where :attr:`PartialEmoji.id` could be a string (:issue:`4153`, :issue:`4152`) +- Fix regression where :attr:`Member.activities` would not clear. +- |commands| A :exc:`TypeError` is now raised when :obj:`typing.Optional` is used within :data:`commands.Greedy <.ext.commands.Greedy>` (:issue:`2253`, :issue:`5068`) +- |commands| :meth:`Bot.walk_commands <.ext.commands.Bot.walk_commands>` no longer yields duplicate commands due to aliases (:issue:`2591`) +- |commands| Fix regex characters not being escaped in :attr:`HelpCommand.clean_prefix <.ext.commands.HelpCommand.clean_prefix>` (:issue:`4058`, :issue:`4071`) +- |commands| Fix :meth:`Bot.get_command <.ext.commands.Bot.get_command>` from raising errors when a name only has whitespace (:issue:`5124`) +- |commands| Fix issue with :attr:`Context.subcommand_passed <.ext.commands.Context.subcommand_passed>` not functioning as expected (:issue:`5198`) +- |tasks| Task objects are no longer stored globally so two class instances can now start two separate tasks (:issue:`2294`) +- |tasks| Allow cancelling the loop within :meth:`before_loop <.ext.tasks.Loop.before_loop>` (:issue:`4082`) + + +Miscellaneous +~~~~~~~~~~~~~~~ + +- The :attr:`Member.roles` cache introduced in v1.3 was reverted due to issues caused (:issue:`4087`, :issue:`4157`) +- :class:`Webhook` objects are now comparable and hashable (:issue:`4182`) +- Some more API requests got a ``reason`` parameter for audit logs (:issue:`5086`) + - :meth:`TextChannel.follow` + - :meth:`Message.pin` and :meth:`Message.unpin` + - :meth:`Webhook.delete` and :meth:`Webhook.edit` + +- For performance reasons ``websockets`` has been dropped in favour of ``aiohttp.ws``. +- The blocking logging message now shows the stack trace of where the main thread was blocking +- The domain name was changed from ``discordapp.com`` to ``discord.com`` to prepare for the required domain migration +- Reduce memory usage when reconnecting due to stale references being held by the message cache (:issue:`5133`) +- Optimize :meth:`abc.GuildChannel.permissions_for` by not creating as many temporary objects (20-32% savings). +- |commands| Raise :exc:`~ext.commands.CommandRegistrationError` instead of :exc:`ClientException` when a duplicate error is registered (:issue:`4217`) +- |tasks| No longer handle :exc:`HTTPException` by default in the task reconnect loop (:issue:`5193`) + +.. _vp1p3p4: + +v1.3.4 +-------- + +Bug Fixes +~~~~~~~~~~~ + +- Fix an issue with channel overwrites causing multiple issues including crashes (:issue:`5109`) + +.. _vp1p3p3: + +v1.3.3 +-------- + +Bug Fixes +~~~~~~~~~~~~ + +- Change default WS close to 4000 instead of 1000. + - The previous close code caused sessions to be invalidated at a higher frequency than desired. + +- Fix ``None`` appearing in ``Member.activities``. (:issue:`2619`) + +.. _vp1p3p2: + +v1.3.2 +--------- + +Another minor bug fix release. + +Bug Fixes +~~~~~~~~~~~ + +- Higher the wait time during the ``GUILD_CREATE`` stream before ``on_ready`` is fired for :class:`AutoShardedClient`. +- :func:`on_voice_state_update` now uses the inner ``member`` payload which should make it more reliable. +- Fix various Cloudflare handling errors (:issue:`2572`, :issue:`2544`) +- Fix crashes if :attr:`Message.guild` is :class:`Object` instead of :class:`Guild`. +- Fix :meth:`Webhook.send` returning an empty string instead of ``None`` when ``wait=False``. +- Fix invalid format specifier in webhook state (:issue:`2570`) +- |commands| Passing invalid permissions to permission related checks now raises ``TypeError``. + +.. _vp1p3p1: + +v1.3.1 +-------- + +Minor bug fix release. + +Bug Fixes +~~~~~~~~~~~ + +- Fix fetching invites in guilds that the user is not in. +- Fix the channel returned from :meth:`Client.fetch_channel` raising when sending messages. (:issue:`2531`) + +Miscellaneous +~~~~~~~~~~~~~~ + +- Fix compatibility warnings when using the Python 3.9 alpha. +- Change the unknown event logging from WARNING to DEBUG to reduce noise. + +.. _vp1p3p0: + +v1.3.0 +-------- + +This version comes with a lot of bug fixes and new features. It's been in development for a lot longer than was anticipated! + +New Features +~~~~~~~~~~~~~~ + +- Add :meth:`Guild.fetch_members` to fetch members from the HTTP API. (:issue:`2204`) +- Add :meth:`Guild.fetch_roles` to fetch roles from the HTTP API. (:issue:`2208`) +- Add support for teams via :class:`Team` when fetching with :meth:`Client.application_info`. (:issue:`2239`) +- Add support for suppressing embeds via :meth:`Message.edit` +- Add support for guild subscriptions. See the :class:`Client` documentation for more details. +- Add :attr:`VoiceChannel.voice_states` to get voice states without relying on member cache. +- Add :meth:`Guild.query_members` to request members from the gateway. +- Add :class:`FFmpegOpusAudio` and other voice improvements. (:issue:`2258`) +- Add :attr:`RawMessageUpdateEvent.channel_id` for retrieving channel IDs during raw message updates. (:issue:`2301`) +- Add :attr:`RawReactionActionEvent.event_type` to disambiguate between reaction addition and removal in reaction events. +- Add :attr:`abc.GuildChannel.permissions_synced` to query whether permissions are synced with the category. (:issue:`2300`, :issue:`2324`) +- Add :attr:`MessageType.channel_follow_add` message type for announcement channels being followed. (:issue:`2314`) +- Add :meth:`Message.is_system` to allow for quickly filtering through system messages. +- Add :attr:`VoiceState.self_stream` to indicate whether someone is streaming via Go Live. (:issue:`2343`) +- Add :meth:`Emoji.is_usable` to check if the client user can use an emoji. (:issue:`2349`) +- Add :attr:`VoiceRegion.europe` and :attr:`VoiceRegion.dubai`. (:issue:`2358`, :issue:`2490`) +- Add :meth:`TextChannel.follow` to follow a news channel. (:issue:`2367`) +- Add :attr:`Permissions.view_guild_insights` permission. (:issue:`2415`) +- Add support for new audit log types. See :ref:`discord-api-audit-logs` for more information. (:issue:`2427`) + - Note that integration support is not finalized. + +- Add :attr:`Webhook.type` to query the type of webhook (:class:`WebhookType`). (:issue:`2441`) +- Allow bulk editing of channel overwrites through :meth:`abc.GuildChannel.edit`. (:issue:`2198`) +- Add :class:`Activity.created_at` to see when an activity was started. (:issue:`2446`) +- Add support for ``xsalsa20_poly1305_lite`` encryption mode for voice. (:issue:`2463`) +- Add :attr:`RawReactionActionEvent.member` to get the member who did the reaction. (:issue:`2443`) +- Add support for new YouTube streaming via :attr:`Streaming.platform` and :attr:`Streaming.game`. (:issue:`2445`) +- Add :attr:`Guild.discovery_splash_url` to get the discovery splash image asset. (:issue:`2482`) +- Add :attr:`Guild.rules_channel` to get the rules channel of public guilds. (:issue:`2482`) + - It should be noted that this feature is restricted to those who are either in Server Discovery or planning to be there. + +- Add support for message flags via :attr:`Message.flags` and :class:`MessageFlags`. (:issue:`2433`) +- Add :attr:`User.system` and :attr:`Profile.system` to know whether a user is an official Discord Trust and Safety account. +- Add :attr:`Profile.team_user` to check whether a user is a member of a team. +- Add :meth:`Attachment.to_file` to easily convert attachments to :class:`File` for sending. +- Add certain aliases to :class:`Permissions` to match the UI better. (:issue:`2496`) + - :attr:`Permissions.manage_permissions` + - :attr:`Permissions.view_channel` + - :attr:`Permissions.use_external_emojis` + +- Add support for passing keyword arguments when creating :class:`Permissions`. +- Add support for custom activities via :class:`CustomActivity`. (:issue:`2400`) + - Note that as of now, bots cannot send custom activities yet. + +- Add support for :func:`on_invite_create` and :func:`on_invite_delete` events. +- Add support for clearing a specific reaction emoji from a message. + - :meth:`Message.clear_reaction` and :meth:`Reaction.clear` methods. + - :func:`on_raw_reaction_clear_emoji` and :func:`on_reaction_clear_emoji` events. + +- Add :func:`utils.sleep_until` helper to sleep until a specific datetime. (:issue:`2517`, :issue:`2519`) +- |commands| Add support for teams and :attr:`Bot.owner_ids <.ext.commands.Bot.owner_ids>` to have multiple bot owners. (:issue:`2239`) +- |commands| Add new :attr:`BucketType.role <.ext.commands.BucketType.role>` bucket type. (:issue:`2201`) +- |commands| Expose :attr:`Command.cog <.ext.commands.Command.cog>` property publicly. (:issue:`2360`) +- |commands| Add non-decorator interface for adding checks to commands via :meth:`Command.add_check <.ext.commands.Command.add_check>` and :meth:`Command.remove_check <.ext.commands.Command.remove_check>`. (:issue:`2411`) +- |commands| Add :func:`has_guild_permissions <.ext.commands.has_guild_permissions>` check. (:issue:`2460`) +- |commands| Add :func:`bot_has_guild_permissions <.ext.commands.bot_has_guild_permissions>` check. (:issue:`2460`) +- |commands| Add ``predicate`` attribute to checks decorated with :func:`~.ext.commands.check`. +- |commands| Add :func:`~.ext.commands.check_any` check to logical OR multiple checks. +- |commands| Add :func:`~.ext.commands.max_concurrency` to allow only a certain amount of users to use a command concurrently before waiting or erroring. +- |commands| Add support for calling a :class:`~.ext.commands.Command` as a regular function. +- |tasks| :meth:`Loop.add_exception_type <.ext.tasks.Loop.add_exception_type>` now allows multiple exceptions to be set. (:issue:`2333`) +- |tasks| Add :attr:`Loop.next_iteration <.ext.tasks.Loop.next_iteration>` property. (:issue:`2305`) + +Bug Fixes +~~~~~~~~~~ + +- Fix issue with permission resolution sometimes failing for guilds with no owner. +- Tokens are now stripped upon use. (:issue:`2135`) +- Passing in a ``name`` is no longer required for :meth:`Emoji.edit`. (:issue:`2368`) +- Fix issue with webhooks not re-raising after retries have run out. (:issue:`2272`, :issue:`2380`) +- Fix mismatch in URL handling in :func:`utils.escape_markdown`. (:issue:`2420`) +- Fix issue with ports being read in little endian when they should be big endian in voice connections. (:issue:`2470`) +- Fix :meth:`Member.mentioned_in` not taking into consideration the message's guild. +- Fix bug with moving channels when there are gaps in positions due to channel deletion and creation. +- Fix :func:`on_shard_ready` not triggering when ``fetch_offline_members`` is disabled. (:issue:`2504`) +- Fix issue with large sharded bots taking too long to actually dispatch :func:`on_ready`. +- Fix issue with fetching group DM based invites in :meth:`Client.fetch_invite`. +- Fix out of order files being sent in webhooks when there are 10 files. +- |commands| Extensions that fail internally due to ImportError will no longer raise :exc:`~.ext.commands.ExtensionNotFound`. (:issue:`2244`, :issue:`2275`, :issue:`2291`) +- |commands| Updating the :attr:`Paginator.suffix <.ext.commands.Paginator.suffix>` will not cause out of date calculations. (:issue:`2251`) +- |commands| Allow converters from custom extension packages. (:issue:`2369`, :issue:`2374`) +- |commands| Fix issue with paginator prefix being ``None`` causing empty pages. (:issue:`2471`) +- |commands| :class:`~.commands.Greedy` now ignores parsing errors rather than propagating them. +- |commands| :meth:`Command.can_run <.ext.commands.Command.can_run>` now checks whether a command is disabled. +- |commands| :attr:`HelpCommand.clean_prefix <.ext.commands.HelpCommand.clean_prefix>` now takes into consideration nickname mentions. (:issue:`2489`) +- |commands| :meth:`Context.send_help <.ext.commands.Context.send_help>` now properly propagates to the :meth:`HelpCommand.on_help_command_error <.ext.commands.HelpCommand.on_help_command_error>` handler. + +Miscellaneous +~~~~~~~~~~~~~~~ + +- The library now fully supports Python 3.8 without warnings. +- Bump the dependency of ``websockets`` to 8.0 for those who can use it. (:issue:`2453`) +- Due to Discord providing :class:`Member` data in mentions, users will now be upgraded to :class:`Member` more often if mentioned. +- :func:`utils.escape_markdown` now properly escapes new quote markdown. +- The message cache can now be disabled by passing ``None`` to ``max_messages`` in :class:`Client`. +- The default message cache size has changed from 5000 to 1000 to accommodate small bots. +- Lower memory usage by only creating certain objects as needed in :class:`Role`. +- There is now a sleep of 5 seconds before re-IDENTIFYing during a reconnect to prevent long loops of session invalidation. +- The rate limiting code now uses millisecond precision to have more granular rate limit handling. + - Along with that, the rate limiting code now uses Discord's response to wait. If you need to use the system clock again for whatever reason, consider passing ``assume_synced_clock`` in :class:`Client`. + +- The performance of :attr:`Guild.default_role` has been improved from O(N) to O(1). (:issue:`2375`) +- The performance of :attr:`Member.roles` has improved due to usage of caching to avoid surprising performance traps. +- The GC is manually triggered during things that cause large deallocations (such as guild removal) to prevent memory fragmentation. +- There have been many changes to the documentation for fixes both for usability, correctness, and to fix some linter errors. Thanks to everyone who contributed to those. +- The loading of the opus module has been delayed which would make the result of :func:`opus.is_loaded` somewhat surprising. +- |commands| Usernames prefixed with @ inside DMs will properly convert using the :class:`User` converter. (:issue:`2498`) +- |tasks| The task sleeping time will now take into consideration the amount of time the task body has taken before sleeping. (:issue:`2516`) + +.. _vp1p2p5: + +v1.2.5 +-------- + +Bug Fixes +~~~~~~~~~~~ + +- Fix a bug that caused crashes due to missing ``animated`` field in Emoji structures in reactions. + +.. _vp1p2p4: + +v1.2.4 +-------- + +Bug Fixes +~~~~~~~~~~~ + +- Fix a regression when :attr:`Message.channel` would be ``None``. +- Fix a regression where :attr:`Message.edited_at` would not update during edits. +- Fix a crash that would trigger during message updates (:issue:`2265`, :issue:`2287`). +- Fix a bug when :meth:`VoiceChannel.connect` would not return (:issue:`2274`, :issue:`2372`, :issue:`2373`, :issue:`2377`). +- Fix a crash relating to token-less webhooks (:issue:`2364`). +- Fix issue where :attr:`Guild.premium_subscription_count` would be ``None`` due to a Discord bug. (:issue:`2331`, :issue:`2376`). + +.. _vp1p2p3: + +v1.2.3 +-------- + +Bug Fixes +~~~~~~~~~~~ + +- Fix an AttributeError when accessing :attr:`Member.premium_since` in :func:`on_member_update`. (:issue:`2213`) +- Handle :exc:`asyncio.CancelledError` in :meth:`abc.Messageable.typing` context manager. (:issue:`2218`) +- Raise the max encoder bitrate to 512kbps to account for nitro boosting. (:issue:`2232`) +- Properly propagate exceptions in :meth:`Client.run`. (:issue:`2237`) +- |commands| Ensure cooldowns are properly copied when used in cog level ``command_attrs``. + +.. _vp1p2p2: + +v1.2.2 +-------- + +Bug Fixes +~~~~~~~~~~~ + +- Audit log related attribute access have been fixed to not error out when they shouldn't have. + +.. _vp1p2p1: + +v1.2.1 +-------- + +Bug Fixes +~~~~~~~~~~~ + +- :attr:`User.avatar_url` and related attributes no longer raise an error. +- More compatibility shims with the ``enum.Enum`` code. + +.. _vp1p2p0: + +v1.2.0 +-------- + +This update mainly brings performance improvements and various nitro boosting attributes (referred to in the API as "premium guilds"). + +New Features +~~~~~~~~~~~~~~ + +- Add :attr:`Guild.premium_tier` to query the guild's current nitro boost level. +- Add :attr:`Guild.emoji_limit`, :attr:`Guild.bitrate_limit`, :attr:`Guild.filesize_limit` to query the new limits of a guild when taking into consideration boosting. +- Add :attr:`Guild.premium_subscription_count` to query how many members are boosting a guild. +- Add :attr:`Member.premium_since` to query since when a member has boosted a guild. +- Add :attr:`Guild.premium_subscribers` to query all the members currently boosting the guild. +- Add :attr:`Guild.system_channel_flags` to query the settings for a guild's :attr:`Guild.system_channel`. + - This includes a new type named :class:`SystemChannelFlags` +- Add :attr:`Emoji.available` to query if an emoji can be used (within the guild or otherwise). +- Add support for animated icons in :meth:`Guild.icon_url_as` and :attr:`Guild.icon_url`. +- Add :meth:`Guild.is_icon_animated`. +- Add support for the various new :class:`MessageType` involving nitro boosting. +- Add :attr:`VoiceRegion.india`. (:issue:`2145`) +- Add :meth:`Embed.insert_field_at`. (:issue:`2178`) +- Add a ``type`` attribute for all channels to their appropriate :class:`ChannelType`. (:issue:`2185`) +- Add :meth:`Client.fetch_channel` to fetch a channel by ID via HTTP. (:issue:`2169`) +- Add :meth:`Guild.fetch_channels` to fetch all channels via HTTP. (:issue:`2169`) +- |tasks| Add :meth:`Loop.stop <.ext.tasks.Loop.stop>` to gracefully stop a task rather than cancelling. +- |tasks| Add :meth:`Loop.failed <.ext.tasks.Loop.failed>` to query if a task had failed somehow. +- |tasks| Add :meth:`Loop.change_interval <.ext.tasks.Loop.change_interval>` to change the sleep interval at runtime (:issue:`2158`, :issue:`2162`) + +Bug Fixes +~~~~~~~~~~~ + +- Fix internal error when using :meth:`Guild.prune_members`. +- |commands| Fix :attr:`.Command.invoked_subcommand` being invalid in many cases. +- |tasks| Reset iteration count when the loop terminates and is restarted. +- |tasks| The decorator interface now works as expected when stacking (:issue:`2154`) + +Miscellaneous +~~~~~~~~~~~~~~~ + +- Improve performance of all Enum related code significantly. + - This was done by replacing the ``enum.Enum`` code with an API compatible one. + - This should not be a breaking change for most users due to duck-typing. +- Improve performance of message creation by about 1.5x. +- Improve performance of message editing by about 1.5-4x depending on payload size. +- Improve performance of attribute access on :class:`Member` about by 2x. +- Improve performance of :func:`utils.get` by around 4-6x depending on usage. +- Improve performance of event parsing lookup by around 2.5x. +- Keyword arguments in :meth:`Client.start` and :meth:`Client.run` are now validated (:issue:`953`, :issue:`2170`) +- The Discord error code is now shown in the exception message for :exc:`HTTPException`. +- Internal tasks launched by the library will now have their own custom ``__repr__``. +- All public facing types should now have a proper and more detailed ``__repr__``. +- |tasks| Errors are now logged via the standard :mod:`py:logging` module. + +.. _vp1p1p1: + +v1.1.1 +-------- + +Bug Fixes +~~~~~~~~~~~~ + +- Webhooks do not overwrite data on retrying their HTTP requests (:issue:`2140`) + +Miscellaneous +~~~~~~~~~~~~~~ + +- Add back signal handling to :meth:`Client.run` due to issues some users had with proper cleanup. + +.. _vp1p1p0: + +v1.1.0 +--------- + +New Features +~~~~~~~~~~~~~~ + +- **There is a new extension dedicated to making background tasks easier.** + - You can check the documentation here: :ref:`ext_tasks_api`. +- Add :attr:`Permissions.stream` permission. (:issue:`2077`) +- Add equality comparison and hash support to :class:`Asset` +- Add ``compute_prune_members`` parameter to :meth:`Guild.prune_members` (:issue:`2085`) +- Add :attr:`Client.cached_messages` attribute to fetch the message cache (:issue:`2086`) +- Add :meth:`abc.GuildChannel.clone` to clone a guild channel. (:issue:`2093`) +- Add ``delay`` keyword-only argument to :meth:`Message.delete` (:issue:`2094`) +- Add support for ``<:name:id>`` when adding reactions (:issue:`2095`) +- Add :meth:`Asset.read` to fetch the bytes content of an asset (:issue:`2107`) +- Add :meth:`Attachment.read` to fetch the bytes content of an attachment (:issue:`2118`) +- Add support for voice kicking by passing ``None`` to :meth:`Member.move_to`. + +``discord.ext.commands`` +++++++++++++++++++++++++++ + +- Add new :func:`~.commands.dm_only` check. +- Support callable converters in :data:`~.commands.Greedy` +- Add new :class:`~.commands.MessageConverter`. + - This allows you to use :class:`Message` as a type hint in functions. +- Allow passing ``cls`` in the :func:`~.commands.group` decorator (:issue:`2061`) +- Add :attr:`.Command.parents` to fetch the parents of a command (:issue:`2104`) + + +Bug Fixes +~~~~~~~~~~~~ + +- Fix :exc:`AttributeError` when using ``__repr__`` on :class:`Widget`. +- Fix issue with :attr:`abc.GuildChannel.overwrites` returning ``None`` for keys. +- Remove incorrect legacy NSFW checks in e.g. :meth:`TextChannel.is_nsfw`. +- Fix :exc:`UnboundLocalError` when :class:`RequestsWebhookAdapter` raises an error. +- Fix bug where updating your own user did not update your member instances. +- Tighten constraints of ``__eq__`` in :class:`Spotify` objects (:issue:`2113`, :issue:`2117`) + +``discord.ext.commands`` +++++++++++++++++++++++++++ + +- Fix lambda converters in a non-module context (e.g. ``eval``). +- Use message creation time for reference time when computing cooldowns. + - This prevents cooldowns from triggering during e.g. a RESUME session. +- Fix the default :func:`on_command_error` to work with new-style cogs (:issue:`2094`) +- DM channels are now recognised as NSFW in :func:`~.commands.is_nsfw` check. +- Fix race condition with help commands (:issue:`2123`) +- Fix cog descriptions not showing in :class:`~.commands.MinimalHelpCommand` (:issue:`2139`) + +Miscellaneous +~~~~~~~~~~~~~~~ + +- Improve the performance of internal enum creation in the library by about 5x. +- Make the output of ``python -m discord --version`` a bit more useful. +- The loop cleanup facility has been rewritten again. +- The signal handling in :meth:`Client.run` has been removed. + +``discord.ext.commands`` +++++++++++++++++++++++++++ + +- Custom exception classes are now used for all default checks in the library (:issue:`2101`) + + +.. _vp1p0p1: + +v1.0.1 +-------- + +Bug Fixes +~~~~~~~~~~~ + +- Fix issue with speaking state being cast to ``int`` when it was invalid. +- Fix some issues with loop cleanup that some users experienced on Linux machines. +- Fix voice handshake race condition (:issue:`2056`, :issue:`2063`) + +.. _vp1p0p0: + +v1.0.0 +-------- + +The changeset for this version are too big to be listed here, for more information please +see :ref:`the migrating page `. + + +.. _vp0p16p6: + +v0.16.6 +-------- + +Bug Fixes +~~~~~~~~~~ + +- Fix issue with :meth:`Client.create_server` that made it stop working. +- Fix main thread being blocked upon calling ``StreamPlayer.stop``. +- Handle HEARTBEAT_ACK and resume gracefully when it occurs. +- Fix race condition when pre-emptively rate limiting that caused releasing an already released lock. +- Fix invalid state errors when immediately cancelling a coroutine. + +.. _vp0p16p1: + +v0.16.1 +-------- + +This release is just a bug fix release with some better rate limit implementation. + +Bug Fixes +~~~~~~~~~~~ + +- Servers are now properly chunked for user bots. +- The CDN URL is now used instead of the API URL for assets. +- Rate limit implementation now tries to use header information if possible. +- Event loop is now properly propagated (:issue:`420`) +- Allow falsey values in :meth:`Client.send_message` and :meth:`Client.send_file`. + +.. _vp0p16p0: + +v0.16.0 +--------- + +New Features +~~~~~~~~~~~~~~ + +- Add :attr:`Channel.overwrites` to get all the permission overwrites of a channel. +- Add :attr:`Server.features` to get information about partnered servers. + +Bug Fixes +~~~~~~~~~~ + +- Timeout when waiting for offline members while triggering :func:`on_ready`. + + - The fact that we did not timeout caused a gigantic memory leak in the library that caused + thousands of duplicate :class:`Member` instances causing big memory spikes. + +- Discard null sequences in the gateway. + + - The fact these were not discarded meant that :func:`on_ready` kept being called instead of + :func:`on_resumed`. Since this has been corrected, in most cases :func:`on_ready` will be + called once or twice with :func:`on_resumed` being called much more often. + +.. _vp0p15p1: + +v0.15.1 +--------- + +- Fix crash on duplicate or out of order reactions. + +.. _vp0p15p0: + +v0.15.0 +-------- + +New Features +~~~~~~~~~~~~~~ + +- Rich Embeds for messages are now supported. + + - To do so, create your own :class:`Embed` and pass the instance to the ``embed`` keyword argument to :meth:`Client.send_message` or :meth:`Client.edit_message`. +- Add :meth:`Client.clear_reactions` to remove all reactions from a message. +- Add support for MESSAGE_REACTION_REMOVE_ALL event, under :func:`on_reaction_clear`. +- Add :meth:`Permissions.update` and :meth:`PermissionOverwrite.update` for bulk permission updates. + + - This allows you to use e.g. ``p.update(read_messages=True, send_messages=False)`` in a single line. +- Add :meth:`PermissionOverwrite.is_empty` to check if the overwrite is empty (i.e. has no overwrites set explicitly as true or false). + +For the command extension, the following changed: + +- ``Context`` is no longer slotted to facilitate setting dynamic attributes. + +.. _vp0p14p3: + +v0.14.3 +--------- + +Bug Fixes +~~~~~~~~~~~ + +- Fix crash when dealing with MESSAGE_REACTION_REMOVE +- Fix incorrect buckets for reactions. + +.. _v0p14p2: + +v0.14.2 +--------- + +New Features +~~~~~~~~~~~~~~ + +- :meth:`Client.wait_for_reaction` now returns a namedtuple with ``reaction`` and ``user`` attributes. + - This is for better support in the case that ``None`` is returned since tuple unpacking can lead to issues. + +Bug Fixes +~~~~~~~~~~ + +- Fix bug that disallowed ``None`` to be passed for ``emoji`` parameter in :meth:`Client.wait_for_reaction`. + +.. _v0p14p1: + +v0.14.1 +--------- + +Bug fixes +~~~~~~~~~~ + +- Fix bug with `Reaction` not being visible at import. + - This was also breaking the documentation. + +.. _v0p14p0: + +v0.14.0 +-------- + +This update adds new API features and a couple of bug fixes. + +New Features +~~~~~~~~~~~~~ + +- Add support for Manage Webhooks permission under :attr:`Permissions.manage_webhooks` +- Add support for ``around`` argument in 3.5+ :meth:`Client.logs_from`. +- Add support for reactions. + - :meth:`Client.add_reaction` to add a reactions + - :meth:`Client.remove_reaction` to remove a reaction. + - :meth:`Client.get_reaction_users` to get the users that reacted to a message. + - :attr:`Permissions.add_reactions` permission bit support. + - Two new events, :func:`on_reaction_add` and :func:`on_reaction_remove`. + - :attr:`Message.reactions` to get reactions from a message. + - :meth:`Client.wait_for_reaction` to wait for a reaction from a user. + +Bug Fixes +~~~~~~~~~~ + +- Fix bug with Paginator still allowing lines that are too long. +- Fix the :attr:`Permissions.manage_emojis` bit being incorrect. + +.. _v0p13p0: + +v0.13.0 +--------- + +This is a backwards compatible update with new features. + +New Features +~~~~~~~~~~~~~ + +- Add the ability to manage emojis. + + - :meth:`Client.create_custom_emoji` to create new emoji. + - :meth:`Client.edit_custom_emoji` to edit an old emoji. + - :meth:`Client.delete_custom_emoji` to delete a custom emoji. +- Add new :attr:`Permissions.manage_emojis` toggle. + + - This applies for :class:`PermissionOverwrite` as well. +- Add new statuses for :class:`Status`. + + - :attr:`Status.dnd` (aliased with :attr:`Status.do_not_disturb`\) for Do Not Disturb. + - :attr:`Status.invisible` for setting your status to invisible (please see the docs for a caveat). +- Deprecate :meth:`Client.change_status` + + - Use :meth:`Client.change_presence` instead for better more up to date functionality. + - This method is subject for removal in a future API version. +- Add :meth:`Client.change_presence` for changing your status with the new Discord API change. + + - This is the only method that allows changing your status to invisible or do not disturb. + +Bug Fixes +~~~~~~~~~~ + +- Paginator pages do not exceed their max_size anymore (:issue:`340`) +- Do Not Disturb users no longer show up offline due to the new :class:`Status` changes. + +.. _v0p12p0: + +v0.12.0 +--------- + +This is a bug fix update that also comes with new features. + +New Features +~~~~~~~~~~~~~ + +- Add custom emoji support. + + - Adds a new class to represent a custom Emoji named :class:`Emoji` + - Adds a utility generator function, :meth:`Client.get_all_emojis`. + - Adds a list of emojis on a server, :attr:`Server.emojis`. + - Adds a new event, :func:`on_server_emojis_update`. +- Add new server regions to :class:`ServerRegion` + + - :attr:`ServerRegion.eu_central` and :attr:`ServerRegion.eu_west`. +- Add support for new pinned system message under :attr:`MessageType.pins_add`. +- Add order comparisons for :class:`Role` to allow it to be compared with regards to hierarchy. + + - This means that you can now do ``role_a > role_b`` etc to check if ``role_b`` is lower in the hierarchy. + +- Add :attr:`Server.role_hierarchy` to get the server's role hierarchy. +- Add :attr:`Member.server_permissions` to get a member's server permissions without their channel specific overwrites. +- Add :meth:`Client.get_user_info` to retrieve a user's info from their ID. +- Add a new ``Player`` property, ``Player.error`` to fetch the error that stopped the player. + + - To help with this change, a player's ``after`` function can now take a single parameter denoting the current player. +- Add support for server verification levels. + + - Adds a new enum called :class:`VerificationLevel`. + - This enum can be used in :meth:`Client.edit_server` under the ``verification_level`` keyword argument. + - Adds a new attribute in the server, :attr:`Server.verification_level`. +- Add :attr:`Server.voice_client` shortcut property for :meth:`Client.voice_client_in`. + + - This is technically old (was added in v0.10.0) but was undocumented until v0.12.0. + +For the command extension, the following are new: + +- Add custom emoji converter. +- All default converters that can take IDs can now convert via ID. +- Add coroutine support for ``Bot.command_prefix``. +- Add a method to reset command cooldown. + +Bug Fixes +~~~~~~~~~~ + +- Fix bug that caused the library to not work with the latest ``websockets`` library. +- Fix bug that leaked keep alive threads (:issue:`309`) +- Fix bug that disallowed :class:`ServerRegion` from being used in :meth:`Client.edit_server`. +- Fix bug in :meth:`Channel.permissions_for` that caused permission resolution to happen out of order. +- Fix bug in :attr:`Member.top_role` that did not account for same-position roles. + +.. _v0p11p0: + +v0.11.0 +-------- + +This is a minor bug fix update that comes with a gateway update (v5 -> v6). + +Breaking Changes +~~~~~~~~~~~~~~~~~ + +- ``Permissions.change_nicknames`` has been renamed to :attr:`Permissions.change_nickname` to match the UI. + +New Features +~~~~~~~~~~~~~ + +- Add the ability to prune members via :meth:`Client.prune_members`. +- Switch the websocket gateway version to v6 from v5. This allows the library to work with group DMs and 1-on-1 calls. +- Add :attr:`AppInfo.owner` attribute. +- Add :class:`CallMessage` for group voice call messages. +- Add :class:`GroupCall` for group voice call information. +- Add :attr:`Message.system_content` to get the system message. +- Add the remaining VIP servers and the Brazil servers into :class:`ServerRegion` enum. +- Add ``stderr`` argument to :meth:`VoiceClient.create_ffmpeg_player` to redirect stderr. +- The library now handles implicit permission resolution in :meth:`Channel.permissions_for`. +- Add :attr:`Server.mfa_level` to query a server's 2FA requirement. +- Add :attr:`Permissions.external_emojis` permission. +- Add :attr:`Member.voice` attribute that refers to a :class:`VoiceState`. + + - For backwards compatibility, the member object will have properties mirroring the old behaviour. + +For the command extension, the following are new: + +- Command cooldown system with the ``cooldown`` decorator. +- ``UserInputError`` exception for the hierarchy for user input related errors. + +Bug Fixes +~~~~~~~~~~ + +- :attr:`Client.email` is now saved when using a token for user accounts. +- Fix issue when removing roles out of order. +- Fix bug where discriminators would not update. +- Handle cases where ``HEARTBEAT`` opcode is received. This caused bots to disconnect seemingly randomly. + +For the command extension, the following bug fixes apply: + +- ``Bot.check`` decorator is actually a decorator not requiring parentheses. +- ``Bot.remove_command`` and ``Group.remove_command`` no longer throw if the command doesn't exist. +- Command names are no longer forced to be ``lower()``. +- Fix a bug where Member and User converters failed to work in private message contexts. +- ``HelpFormatter`` now ignores hidden commands when deciding the maximum width. + +.. _v0p10p0: + +v0.10.0 +------- + +For breaking changes, see :ref:`migrating-to-async`. The breaking changes listed there will not be enumerated below. Since this version is rather a big departure from v0.9.2, this change log will be non-exhaustive. + +New Features +~~~~~~~~~~~~~ + +- The library is now fully ``asyncio`` compatible, allowing you to write non-blocking code a lot more easily. +- The library now fully handles 429s and unconditionally retries on 502s. +- A new command extension module was added but is currently undocumented. Figuring it out is left as an exercise to the reader. +- Two new exception types, :exc:`Forbidden` and :exc:`NotFound` to denote permission errors or 404 errors. +- Added :meth:`Client.delete_invite` to revoke invites. +- Added support for sending voice. Check :class:`VoiceClient` for more details. +- Added :meth:`Client.wait_for_message` coroutine to aid with follow up commands. +- Added :data:`version_info` named tuple to check version info of the library. +- Login credentials are now cached to have a faster login experience. You can disable this by passing in ``cache_auth=False`` + when constructing a :class:`Client`. +- New utility function, :func:`discord.utils.get` to simplify retrieval of items based on attributes. +- All data classes now support ``!=``, ``==``, ``hash(obj)`` and ``str(obj)``. +- Added :meth:`Client.get_bans` to get banned members from a server. +- Added :meth:`Client.invites_from` to get currently active invites in a server. +- Added :attr:`Server.me` attribute to get the :class:`Member` version of :attr:`Client.user`. +- Most data classes now support a ``hash(obj)`` function to allow you to use them in ``set`` or ``dict`` classes or subclasses. +- Add :meth:`Message.clean_content` to get a text version of the content with the user and channel mentioned changed into their names. +- Added a way to remove the messages of the user that just got banned in :meth:`Client.ban`. +- Added :meth:`Client.wait_until_ready` to facilitate easy creation of tasks that require the client cache to be ready. +- Added :meth:`Client.wait_until_login` to facilitate easy creation of tasks that require the client to be logged in. +- Add :class:`discord.Game` to represent any game with custom text to send to :meth:`Client.change_status`. +- Add :attr:`Message.nonce` attribute. +- Add :meth:`Member.permissions_in` as another way of doing :meth:`Channel.permissions_for`. +- Add :meth:`Client.move_member` to move a member to another voice channel. +- You can now create a server via :meth:`Client.create_server`. +- Added :meth:`Client.edit_server` to edit existing servers. +- Added :meth:`Client.server_voice_state` to server mute or server deafen a member. +- If you are being rate limited, the library will now handle it for you. +- Add :func:`on_member_ban` and :func:`on_member_unban` events that trigger when a member is banned/unbanned. + +Performance Improvements +~~~~~~~~~~~~~~~~~~~~~~~~~ + +- All data classes now use ``__slots__`` which greatly reduce the memory usage of things kept in cache. +- Due to the usage of ``asyncio``, the CPU usage of the library has gone down significantly. +- A lot of the internal cache lists were changed into dictionaries to change the ``O(n)`` lookup into ``O(1)``. +- Compressed READY is now on by default. This means if you're on a lot of servers (or maybe even a few) you would + receive performance improvements by having to download and process less data. +- While minor, change regex from ``\d+`` to ``[0-9]+`` to avoid unnecessary unicode character lookups. + +Bug Fixes +~~~~~~~~~~ + +- Fix bug where guilds being updated did not edit the items in cache. +- Fix bug where ``member.roles`` were empty upon joining instead of having the ``@everyone`` role. +- Fix bug where :meth:`Role.is_everyone` was not being set properly when the role was being edited. +- :meth:`Client.logs_from` now handles cases where limit > 100 to sidestep the discord API limitation. +- Fix bug where a role being deleted would trigger a ``ValueError``. +- Fix bug where :meth:`Permissions.kick_members` and :meth:`Permissions.ban_members` were flipped. +- Mentions are now triggered normally. This was changed due to the way discord handles it internally. +- Fix issue when a :class:`Message` would attempt to upgrade a :attr:`Message.server` when the channel is + a :class:`Object`. +- Unavailable servers were not being added into cache, this has been corrected. \ No newline at end of file diff --git a/docs/Python/html/_static/basic.css b/docs/Python/html/_static/basic.css new file mode 100644 index 00000000..912859b5 --- /dev/null +++ b/docs/Python/html/_static/basic.css @@ -0,0 +1,904 @@ +/* + * basic.css + * ~~~~~~~~~ + * + * Sphinx stylesheet -- basic theme. + * + * :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/* -- main layout ----------------------------------------------------------- */ + +div.clearer { + clear: both; +} + +div.section::after { + display: block; + content: ''; + clear: left; +} + +/* -- relbar ---------------------------------------------------------------- */ + +div.related { + width: 100%; + font-size: 90%; +} + +div.related h3 { + display: none; +} + +div.related ul { + margin: 0; + padding: 0 0 0 10px; + list-style: none; +} + +div.related li { + display: inline; +} + +div.related li.right { + float: right; + margin-right: 5px; +} + +/* -- sidebar --------------------------------------------------------------- */ + +div.sphinxsidebarwrapper { + padding: 10px 5px 0 10px; +} + +div.sphinxsidebar { + float: left; + width: 230px; + margin-left: -100%; + font-size: 90%; + word-wrap: break-word; + overflow-wrap : break-word; +} + +div.sphinxsidebar ul { + list-style: none; +} + +div.sphinxsidebar ul ul, +div.sphinxsidebar ul.want-points { + margin-left: 20px; + list-style: square; +} + +div.sphinxsidebar ul ul { + margin-top: 0; + margin-bottom: 0; +} + +div.sphinxsidebar form { + margin-top: 10px; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + +div.sphinxsidebar #searchbox form.search { + overflow: hidden; +} + +div.sphinxsidebar #searchbox input[type="text"] { + float: left; + width: 80%; + padding: 0.25em; + box-sizing: border-box; +} + +div.sphinxsidebar #searchbox input[type="submit"] { + float: left; + width: 20%; + border-left: none; + padding: 0.25em; + box-sizing: border-box; +} + + +img { + border: 0; + max-width: 100%; +} + +/* -- search page ----------------------------------------------------------- */ + +ul.search { + margin: 10px 0 0 20px; + padding: 0; +} + +ul.search li { + padding: 5px 0 5px 20px; + background-image: url(file.png); + background-repeat: no-repeat; + background-position: 0 7px; +} + +ul.search li a { + font-weight: bold; +} + +ul.search li p.context { + color: #888; + margin: 2px 0 0 30px; + text-align: left; +} + +ul.keywordmatches li.goodmatch a { + font-weight: bold; +} + +/* -- index page ------------------------------------------------------------ */ + +table.contentstable { + width: 90%; + margin-left: auto; + margin-right: auto; +} + +table.contentstable p.biglink { + line-height: 150%; +} + +a.biglink { + font-size: 1.3em; +} + +span.linkdescr { + font-style: italic; + padding-top: 5px; + font-size: 90%; +} + +/* -- general index --------------------------------------------------------- */ + +table.indextable { + width: 100%; +} + +table.indextable td { + text-align: left; + vertical-align: top; +} + +table.indextable ul { + margin-top: 0; + margin-bottom: 0; + list-style-type: none; +} + +table.indextable > tbody > tr > td > ul { + padding-left: 0em; +} + +table.indextable tr.pcap { + height: 10px; +} + +table.indextable tr.cap { + margin-top: 10px; + background-color: #f2f2f2; +} + +img.toggler { + margin-right: 3px; + margin-top: 3px; + cursor: pointer; +} + +div.modindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +div.genindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +/* -- domain module index --------------------------------------------------- */ + +table.modindextable td { + padding: 2px; + border-collapse: collapse; +} + +/* -- general body styles --------------------------------------------------- */ + +div.body { + min-width: 450px; + max-width: 800px; +} + +div.body p, div.body dd, div.body li, div.body blockquote { + -moz-hyphens: auto; + -ms-hyphens: auto; + -webkit-hyphens: auto; + hyphens: auto; +} + +a.headerlink { + visibility: hidden; +} + +a.brackets:before, +span.brackets > a:before{ + content: "["; +} + +a.brackets:after, +span.brackets > a:after { + content: "]"; +} + +h1:hover > a.headerlink, +h2:hover > a.headerlink, +h3:hover > a.headerlink, +h4:hover > a.headerlink, +h5:hover > a.headerlink, +h6:hover > a.headerlink, +dt:hover > a.headerlink, +caption:hover > a.headerlink, +p.caption:hover > a.headerlink, +div.code-block-caption:hover > a.headerlink { + visibility: visible; +} + +div.body p.caption { + text-align: inherit; +} + +div.body td { + text-align: left; +} + +.first { + margin-top: 0 !important; +} + +p.rubric { + margin-top: 30px; + font-weight: bold; +} + +img.align-left, figure.align-left, .figure.align-left, object.align-left { + clear: left; + float: left; + margin-right: 1em; +} + +img.align-right, figure.align-right, .figure.align-right, object.align-right { + clear: right; + float: right; + margin-left: 1em; +} + +img.align-center, figure.align-center, .figure.align-center, object.align-center { + display: block; + margin-left: auto; + margin-right: auto; +} + +img.align-default, figure.align-default, .figure.align-default { + display: block; + margin-left: auto; + margin-right: auto; +} + +.align-left { + text-align: left; +} + +.align-center { + text-align: center; +} + +.align-default { + text-align: center; +} + +.align-right { + text-align: right; +} + +/* -- sidebars -------------------------------------------------------------- */ + +div.sidebar, +aside.sidebar { + margin: 0 0 0.5em 1em; + border: 1px solid #ddb; + padding: 7px; + background-color: #ffe; + width: 40%; + float: right; + clear: right; + overflow-x: auto; +} + +p.sidebar-title { + font-weight: bold; +} + +div.admonition, div.topic, blockquote { + clear: left; +} + +/* -- topics ---------------------------------------------------------------- */ + +div.topic { + border: 1px solid #ccc; + padding: 7px; + margin: 10px 0 10px 0; +} + +p.topic-title { + font-size: 1.1em; + font-weight: bold; + margin-top: 10px; +} + +/* -- admonitions ----------------------------------------------------------- */ + +div.admonition { + margin-top: 10px; + margin-bottom: 10px; + padding: 7px; +} + +div.admonition dt { + font-weight: bold; +} + +p.admonition-title { + margin: 0px 10px 5px 0px; + font-weight: bold; +} + +div.body p.centered { + text-align: center; + margin-top: 25px; +} + +/* -- content of sidebars/topics/admonitions -------------------------------- */ + +div.sidebar > :last-child, +aside.sidebar > :last-child, +div.topic > :last-child, +div.admonition > :last-child { + margin-bottom: 0; +} + +div.sidebar::after, +aside.sidebar::after, +div.topic::after, +div.admonition::after, +blockquote::after { + display: block; + content: ''; + clear: both; +} + +/* -- tables ---------------------------------------------------------------- */ + +table.docutils { + margin-top: 10px; + margin-bottom: 10px; + border: 0; + border-collapse: collapse; +} + +table.align-center { + margin-left: auto; + margin-right: auto; +} + +table.align-default { + margin-left: auto; + margin-right: auto; +} + +table caption span.caption-number { + font-style: italic; +} + +table caption span.caption-text { +} + +table.docutils td, table.docutils th { + padding: 1px 8px 1px 5px; + border-top: 0; + border-left: 0; + border-right: 0; + border-bottom: 1px solid #aaa; +} + +table.footnote td, table.footnote th { + border: 0 !important; +} + +th { + text-align: left; + padding-right: 5px; +} + +table.citation { + border-left: solid 1px gray; + margin-left: 1px; +} + +table.citation td { + border-bottom: none; +} + +th > :first-child, +td > :first-child { + margin-top: 0px; +} + +th > :last-child, +td > :last-child { + margin-bottom: 0px; +} + +/* -- figures --------------------------------------------------------------- */ + +div.figure, figure { + margin: 0.5em; + padding: 0.5em; +} + +div.figure p.caption, figcaption { + padding: 0.3em; +} + +div.figure p.caption span.caption-number, +figcaption span.caption-number { + font-style: italic; +} + +div.figure p.caption span.caption-text, +figcaption span.caption-text { +} + +/* -- field list styles ----------------------------------------------------- */ + +table.field-list td, table.field-list th { + border: 0 !important; +} + +.field-list ul { + margin: 0; + padding-left: 1em; +} + +.field-list p { + margin: 0; +} + +.field-name { + -moz-hyphens: manual; + -ms-hyphens: manual; + -webkit-hyphens: manual; + hyphens: manual; +} + +/* -- hlist styles ---------------------------------------------------------- */ + +table.hlist { + margin: 1em 0; +} + +table.hlist td { + vertical-align: top; +} + +/* -- object description styles --------------------------------------------- */ + +.sig { + font-family: 'Consolas', 'Menlo', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace; +} + +.sig-name, code.descname { + background-color: transparent; + font-weight: bold; +} + +.sig-name { + font-size: 1.1em; +} + +code.descname { + font-size: 1.2em; +} + +.sig-prename, code.descclassname { + background-color: transparent; +} + +.optional { + font-size: 1.3em; +} + +.sig-paren { + font-size: larger; +} + +.sig-param.n { + font-style: italic; +} + +/* C++ specific styling */ + +.sig-inline.c-texpr, +.sig-inline.cpp-texpr { + font-family: unset; +} + +.sig.c .k, .sig.c .kt, +.sig.cpp .k, .sig.cpp .kt { + color: #0033B3; +} + +.sig.c .m, +.sig.cpp .m { + color: #1750EB; +} + +.sig.c .s, .sig.c .sc, +.sig.cpp .s, .sig.cpp .sc { + color: #067D17; +} + + +/* -- other body styles ----------------------------------------------------- */ + +ol.arabic { + list-style: decimal; +} + +ol.loweralpha { + list-style: lower-alpha; +} + +ol.upperalpha { + list-style: upper-alpha; +} + +ol.lowerroman { + list-style: lower-roman; +} + +ol.upperroman { + list-style: upper-roman; +} + +:not(li) > ol > li:first-child > :first-child, +:not(li) > ul > li:first-child > :first-child { + margin-top: 0px; +} + +:not(li) > ol > li:last-child > :last-child, +:not(li) > ul > li:last-child > :last-child { + margin-bottom: 0px; +} + +ol.simple ol p, +ol.simple ul p, +ul.simple ol p, +ul.simple ul p { + margin-top: 0; +} + +ol.simple > li:not(:first-child) > p, +ul.simple > li:not(:first-child) > p { + margin-top: 0; +} + +ol.simple p, +ul.simple p { + margin-bottom: 0; +} + +dl.footnote > dt, +dl.citation > dt { + float: left; + margin-right: 0.5em; +} + +dl.footnote > dd, +dl.citation > dd { + margin-bottom: 0em; +} + +dl.footnote > dd:after, +dl.citation > dd:after { + content: ""; + clear: both; +} + +dl.field-list { + display: grid; + grid-template-columns: fit-content(30%) auto; +} + +dl.field-list > dt { + font-weight: bold; + word-break: break-word; + padding-left: 0.5em; + padding-right: 5px; +} + +dl.field-list > dt:after { + content: ":"; +} + +dl.field-list > dd { + padding-left: 0.5em; + margin-top: 0em; + margin-left: 0em; + margin-bottom: 0em; +} + +dl { + margin-bottom: 15px; +} + +dd > :first-child { + margin-top: 0px; +} + +dd ul, dd table { + margin-bottom: 10px; +} + +dd { + margin-top: 3px; + margin-bottom: 10px; + margin-left: 30px; +} + +dl > dd:last-child, +dl > dd:last-child > :last-child { + margin-bottom: 0; +} + +dt:target, span.highlighted { + background-color: #fbe54e; +} + +rect.highlighted { + fill: #fbe54e; +} + +dl.glossary dt { + font-weight: bold; + font-size: 1.1em; +} + +.versionmodified { + font-style: italic; +} + +.system-message { + background-color: #fda; + padding: 5px; + border: 3px solid red; +} + +.footnote:target { + background-color: #ffa; +} + +.line-block { + display: block; + margin-top: 1em; + margin-bottom: 1em; +} + +.line-block .line-block { + margin-top: 0; + margin-bottom: 0; + margin-left: 1.5em; +} + +.guilabel, .menuselection { + font-family: sans-serif; +} + +.accelerator { + text-decoration: underline; +} + +.classifier { + font-style: oblique; +} + +.classifier:before { + font-style: normal; + margin: 0.5em; + content: ":"; +} + +abbr, acronym { + border-bottom: dotted 1px; + cursor: help; +} + +/* -- code displays --------------------------------------------------------- */ + +pre { + overflow: auto; + overflow-y: hidden; /* fixes display issues on Chrome browsers */ +} + +pre, div[class*="highlight-"] { + clear: both; +} + +span.pre { + -moz-hyphens: none; + -ms-hyphens: none; + -webkit-hyphens: none; + hyphens: none; +} + +div[class*="highlight-"] { + margin: 1em 0; +} + +td.linenos pre { + border: 0; + background-color: transparent; + color: #aaa; +} + +table.highlighttable { + display: block; +} + +table.highlighttable tbody { + display: block; +} + +table.highlighttable tr { + display: flex; +} + +table.highlighttable td { + margin: 0; + padding: 0; +} + +table.highlighttable td.linenos { + padding-right: 0.5em; +} + +table.highlighttable td.code { + flex: 1; + overflow: hidden; +} + +.highlight .hll { + display: block; +} + +div.highlight pre, +table.highlighttable pre { + margin: 0; +} + +div.code-block-caption + div { + margin-top: 0; +} + +div.code-block-caption { + margin-top: 1em; + padding: 2px 5px; + font-size: small; +} + +div.code-block-caption code { + background-color: transparent; +} + +table.highlighttable td.linenos, +span.linenos, +div.highlight span.gp { /* gp: Generic.Prompt */ + user-select: none; + -webkit-user-select: text; /* Safari fallback only */ + -webkit-user-select: none; /* Chrome/Safari */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* IE10+ */ +} + +div.code-block-caption span.caption-number { + padding: 0.1em 0.3em; + font-style: italic; +} + +div.code-block-caption span.caption-text { +} + +div.literal-block-wrapper { + margin: 1em 0; +} + +code.xref, a code { + background-color: transparent; + font-weight: bold; +} + +h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { + background-color: transparent; +} + +.viewcode-link { + float: right; +} + +.viewcode-back { + float: right; + font-family: sans-serif; +} + +div.viewcode-block:target { + margin: -1px -10px; + padding: 0 10px; +} + +/* -- math display ---------------------------------------------------------- */ + +img.math { + vertical-align: middle; +} + +div.body div.math p { + text-align: center; +} + +span.eqno { + float: right; +} + +span.eqno a.headerlink { + position: absolute; + z-index: 1; +} + +div.math:hover a.headerlink { + visibility: visible; +} + +/* -- printout stylesheet --------------------------------------------------- */ + +@media print { + div.document, + div.documentwrapper, + div.bodywrapper { + margin: 0 !important; + width: 100%; + } + + div.sphinxsidebar, + div.related, + div.footer, + #top-link { + display: none; + } +} \ No newline at end of file diff --git a/docs/Python/html/_static/codeblocks.css b/docs/Python/html/_static/codeblocks.css new file mode 100644 index 00000000..04755281 --- /dev/null +++ b/docs/Python/html/_static/codeblocks.css @@ -0,0 +1,143 @@ +/* light theme: default */ +.highlight .hll { background-color: #ffffcc } +.highlight { background: #f0f0f0; } +.highlight .c { color: #60a0b0; font-style: italic } /* Comment */ +.highlight .err { border: 1px solid #FF0000 } /* Error */ +.highlight .k { color: #007020; font-weight: bold } /* Keyword */ +.highlight .o { color: #666666 } /* Operator */ +.highlight .ch { color: #60a0b0; font-style: italic } /* Comment.Hashbang */ +.highlight .cm { color: #60a0b0; font-style: italic } /* Comment.Multiline */ +.highlight .cp { color: #007020 } /* Comment.Preproc */ +.highlight .cpf { color: #60a0b0; font-style: italic } /* Comment.PreprocFile */ +.highlight .c1 { color: #60a0b0; font-style: italic } /* Comment.Single */ +.highlight .cs { color: #60a0b0; background-color: #fff0f0 } /* Comment.Special */ +.highlight .gd { color: #A00000 } /* Generic.Deleted */ +.highlight .ge { font-style: italic } /* Generic.Emph */ +.highlight .gr { color: #FF0000 } /* Generic.Error */ +.highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */ +.highlight .gi { color: #00A000 } /* Generic.Inserted */ +.highlight .go { color: #888888 } /* Generic.Output */ +.highlight .gp { color: #c65d09; font-weight: bold } /* Generic.Prompt */ +.highlight .gs { font-weight: bold } /* Generic.Strong */ +.highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ +.highlight .gt { color: #0044DD } /* Generic.Traceback */ +.highlight .kc { color: #007020; font-weight: bold } /* Keyword.Constant */ +.highlight .kd { color: #007020; font-weight: bold } /* Keyword.Declaration */ +.highlight .kn { color: #007020; font-weight: bold } /* Keyword.Namespace */ +.highlight .kp { color: #007020 } /* Keyword.Pseudo */ +.highlight .kr { color: #007020; font-weight: bold } /* Keyword.Reserved */ +.highlight .kt { color: #902000 } /* Keyword.Type */ +.highlight .m { color: #40a070 } /* Literal.Number */ +.highlight .s { color: #4070a0 } /* Literal.String */ +.highlight .na { color: #4070a0 } /* Name.Attribute */ +.highlight .nb { color: #007020 } /* Name.Builtin */ +.highlight .nc { color: #0e84b5; font-weight: bold } /* Name.Class */ +.highlight .no { color: #60add5 } /* Name.Constant */ +.highlight .nd { color: #555555; font-weight: bold } /* Name.Decorator */ +.highlight .ni { color: #d55537; font-weight: bold } /* Name.Entity */ +.highlight .ne { color: #007020 } /* Name.Exception */ +.highlight .nf { color: #06287e } /* Name.Function */ +.highlight .nl { color: #002070; font-weight: bold } /* Name.Label */ +.highlight .nn { color: #0e84b5; font-weight: bold } /* Name.Namespace */ +.highlight .nt { color: #062873; font-weight: bold } /* Name.Tag */ +.highlight .nv { color: #bb60d5 } /* Name.Variable */ +.highlight .ow { color: #007020; font-weight: bold } /* Operator.Word */ +.highlight .w { color: #bbbbbb } /* Text.Whitespace */ +.highlight .mb { color: #40a070 } /* Literal.Number.Bin */ +.highlight .mf { color: #40a070 } /* Literal.Number.Float */ +.highlight .mh { color: #40a070 } /* Literal.Number.Hex */ +.highlight .mi { color: #40a070 } /* Literal.Number.Integer */ +.highlight .mo { color: #40a070 } /* Literal.Number.Oct */ +.highlight .sa { color: #4070a0 } /* Literal.String.Affix */ +.highlight .sb { color: #4070a0 } /* Literal.String.Backtick */ +.highlight .sc { color: #4070a0 } /* Literal.String.Char */ +.highlight .dl { color: #4070a0 } /* Literal.String.Delimiter */ +.highlight .sd { color: #4070a0; font-style: italic } /* Literal.String.Doc */ +.highlight .s2 { color: #4070a0 } /* Literal.String.Double */ +.highlight .se { color: #4070a0; font-weight: bold } /* Literal.String.Escape */ +.highlight .sh { color: #4070a0 } /* Literal.String.Heredoc */ +.highlight .si { color: #70a0d0; font-style: italic } /* Literal.String.Interpol */ +.highlight .sx { color: #c65d09 } /* Literal.String.Other */ +.highlight .sr { color: #235388 } /* Literal.String.Regex */ +.highlight .s1 { color: #4070a0 } /* Literal.String.Single */ +.highlight .ss { color: #517918 } /* Literal.String.Symbol */ +.highlight .bp { color: #007020 } /* Name.Builtin.Pseudo */ +.highlight .fm { color: #06287e } /* Name.Function.Magic */ +.highlight .vc { color: #bb60d5 } /* Name.Variable.Class */ +.highlight .vg { color: #bb60d5 } /* Name.Variable.Global */ +.highlight .vi { color: #bb60d5 } /* Name.Variable.Instance */ +.highlight .vm { color: #bb60d5 } /* Name.Variable.Magic */ +.highlight .il { color: #40a070 } /* Literal.Number.Integer.Long */ + +/* dark theme: modified "native" */ +:root[data-theme="dark"] .highlight pre { background-color: #2a2a2e } +:root[data-theme="dark"] .highlight .hll { background-color: #2a2a2e } +:root[data-theme="dark"] .highlight .c { color: #999999; font-style: italic } /* Comment */ +:root[data-theme="dark"] .highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ +:root[data-theme="dark"] .highlight .g { color: #d0d0d0 } /* Generic */ +:root[data-theme="dark"] .highlight .k { color: #6ab825; font-weight: bold } /* Keyword */ +:root[data-theme="dark"] .highlight .l { color: #d0d0d0 } /* Literal */ +:root[data-theme="dark"] .highlight .n { color: #d0d0d0 } /* Name */ +:root[data-theme="dark"] .highlight .o { color: #d0d0d0 } /* Operator */ +:root[data-theme="dark"] .highlight .x { color: #d0d0d0 } /* Other */ +:root[data-theme="dark"] .highlight .p { color: #d0d0d0 } /* Punctuation */ +:root[data-theme="dark"] .highlight .cm { color: #999999; font-style: italic } /* Comment.Multiline */ +:root[data-theme="dark"] .highlight .cp { color: #cd2828; font-weight: bold } /* Comment.Preproc */ +:root[data-theme="dark"] .highlight .c1 { color: #999999; font-style: italic } /* Comment.Single */ +:root[data-theme="dark"] .highlight .cs { color: #e50808; font-weight: bold; background-color: #520000 } /* Comment.Special */ +:root[data-theme="dark"] .highlight .gd { color: #d22323 } /* Generic.Deleted */ +:root[data-theme="dark"] .highlight .ge { color: #d0d0d0; font-style: italic } /* Generic.Emph */ +:root[data-theme="dark"] .highlight .gr { color: #d22323 } /* Generic.Error */ +:root[data-theme="dark"] .highlight .gh { color: #ffffff; font-weight: bold } /* Generic.Heading */ +:root[data-theme="dark"] .highlight .gi { color: #589819 } /* Generic.Inserted */ +:root[data-theme="dark"] .highlight .go { color: #cccccc } /* Generic.Output */ +:root[data-theme="dark"] .highlight .gp { color: #aaaaaa } /* Generic.Prompt */ +:root[data-theme="dark"] .highlight .gs { color: #d0d0d0; font-weight: bold } /* Generic.Strong */ +:root[data-theme="dark"] .highlight .gu { color: #ffffff; text-decoration: underline } /* Generic.Subheading */ +:root[data-theme="dark"] .highlight .gt { color: #d22323 } /* Generic.Traceback */ +:root[data-theme="dark"] .highlight .kc { color: #6ab825; font-weight: bold } /* Keyword.Constant */ +:root[data-theme="dark"] .highlight .kd { color: #6ab825; font-weight: bold } /* Keyword.Declaration */ +:root[data-theme="dark"] .highlight .kn { color: #6ab825; font-weight: bold } /* Keyword.Namespace */ +:root[data-theme="dark"] .highlight .kp { color: #6ab825 } /* Keyword.Pseudo */ +:root[data-theme="dark"] .highlight .kr { color: #6ab825; font-weight: bold } /* Keyword.Reserved */ +:root[data-theme="dark"] .highlight .kt { color: #6ab825; font-weight: bold } /* Keyword.Type */ +:root[data-theme="dark"] .highlight .ld { color: #d0d0d0 } /* Literal.Date */ +:root[data-theme="dark"] .highlight .m { color: #7fb1d7 } /* Literal.Number */ +:root[data-theme="dark"] .highlight .s { color: #ed9d13 } /* Literal.String */ +:root[data-theme="dark"] .highlight .na { color: #bbbbbb; } /* Name.Attribute */ +:root[data-theme="dark"] .highlight .nb { color: #29a5b3; } /* Name.Builtin */ +:root[data-theme="dark"] .highlight .nc { color: #6494d8;} /* Name.Class */ +:root[data-theme="dark"] .highlight .no { color: #40ffff; } /* Name.Constant */ +:root[data-theme="dark"] .highlight .nd { color: #ffa500; } /* Name.Decorator */ +:root[data-theme="dark"] .highlight .ni { color: #d0d0d0; } /* Name.Entity */ +:root[data-theme="dark"] .highlight .ne { color: #bbbbbb; } /* Name.Exception */ +:root[data-theme="dark"] .highlight .nf { color: #6494d8; } /* Name.Function */ +:root[data-theme="dark"] .highlight .fm { color: #6494d8; } /* Name.Function.Magic */ +:root[data-theme="dark"] .highlight .nl { color: #d0d0d0; } /* Name.Label */ +:root[data-theme="dark"] .highlight .nn { color: #6494d8;} /* Name.Namespace */ +:root[data-theme="dark"] .highlight .nx { color: #d0d0d0; } /* Name.Other */ +:root[data-theme="dark"] .highlight .py { color: #d0d0d0; } /* Name.Property */ +:root[data-theme="dark"] .highlight .nt { color: #6ab825; font-weight: bold } /* Name.Tag */ +:root[data-theme="dark"] .highlight .nv { color: #40ffff; } /* Name.Variable */ +:root[data-theme="dark"] .highlight .ow { color: #6ab825; font-weight: bold } /* Operator.Word */ +:root[data-theme="dark"] .highlight .w { color: #666666; } /* Text.Whitespace */ +:root[data-theme="dark"] .highlight .mf { color: #7fb1d7; } /* Literal.Number.Float */ +:root[data-theme="dark"] .highlight .mh { color: #7fb1d7; } /* Literal.Number.Hex */ +:root[data-theme="dark"] .highlight .mi { color: #7fb1d7; } /* Literal.Number.Integer */ +:root[data-theme="dark"] .highlight .mo { color: #7fb1d7; } /* Literal.Number.Oct */ +:root[data-theme="dark"] .highlight .sb { color: #ed9d13; } /* Literal.String.Backtick */ +:root[data-theme="dark"] .highlight .sc { color: #ed9d13; } /* Literal.String.Char */ +:root[data-theme="dark"] .highlight .sd { color: #ed9d13; } /* Literal.String.Doc */ +:root[data-theme="dark"] .highlight .s2 { color: #ed9d13; } /* Literal.String.Double */ +:root[data-theme="dark"] .highlight .se { color: #ed9d13; } /* Literal.String.Escape */ +:root[data-theme="dark"] .highlight .sh { color: #ed9d13; } /* Literal.String.Heredoc */ +:root[data-theme="dark"] .highlight .si { color: #ed9d13; } /* Literal.String.Interpol */ +:root[data-theme="dark"] .highlight .sx { color: #ffa500; } /* Literal.String.Other */ +:root[data-theme="dark"] .highlight .sr { color: #ed9d13; } /* Literal.String.Regex */ +:root[data-theme="dark"] .highlight .s1 { color: #ed9d13; } /* Literal.String.Single */ +:root[data-theme="dark"] .highlight .ss { color: #ed9d13; } /* Literal.String.Symbol */ +:root[data-theme="dark"] .highlight .bp { color: #29a5b3; } /* Name.Builtin.Pseudo */ +:root[data-theme="dark"] .highlight .vc { color: #40ffff; } /* Name.Variable.Class */ +:root[data-theme="dark"] .highlight .vg { color: #40ffff; } /* Name.Variable.Global */ +:root[data-theme="dark"] .highlight .vi { color: #40ffff; } /* Name.Variable.Instance */ +:root[data-theme="dark"] .highlight .il { color: #7fb1d7; } /* Literal.Number.Integer.Long */ diff --git a/docs/Python/html/_static/copy.js b/docs/Python/html/_static/copy.js new file mode 100644 index 00000000..f70e3d67 --- /dev/null +++ b/docs/Python/html/_static/copy.js @@ -0,0 +1,34 @@ +const COPY = "content_copy"; +const COPIED = "done"; + +const copy = async (obj) => { + // {{text}} + await navigator.clipboard.writeText(obj.children[1].innerText).then( + () => { + let icon = obj.children[0].children[0]; + icon.textContent = COPIED; + setTimeout(() => (icon.textContent = COPY), 2500); + }, + (r) => alert('Could not copy codeblock:\n' + r.toString()) + ); +}; + +document.addEventListener("DOMContentLoaded", () => { + let allCodeblocks = document.querySelectorAll("div[class='highlight']"); + + for (let codeblock of allCodeblocks) { + codeblock.parentNode.className += " relative-copy"; + let copyEl = document.createElement("span"); + copyEl.addEventListener('click', () => copy(codeblock)); + copyEl.className = "copy"; + copyEl.setAttribute("aria-label", "Copy Code"); + copyEl.setAttribute("title", "Copy Code"); + + let copyIcon = document.createElement("span"); + copyIcon.className = "material-icons"; + copyIcon.textContent = COPY; + copyEl.append(copyIcon); + + codeblock.prepend(copyEl); + } +}); diff --git a/docs/Python/html/_static/custom.js b/docs/Python/html/_static/custom.js new file mode 100644 index 00000000..f3cfa461 --- /dev/null +++ b/docs/Python/html/_static/custom.js @@ -0,0 +1,97 @@ +'use-strict'; + +let activeModal = null; +let bottomHeightThreshold, sections; +let hamburgerToggle; +let mobileSearch; +let sidebar; +let toTop; + +class Modal { + constructor(element) { + this.element = element; + } + + close() { + activeModal = null; + this.element.style.display = 'none' + } + + open() { + if (activeModal) { + activeModal.close(); + } + activeModal = this; + this.element.style.display = 'flex' + } +} + +class SearchBar { + + constructor() { + this.box = document.querySelector('nav.mobile-only'); + this.bar = document.querySelector('nav.mobile-only input[type="search"]'); + this.openButton = document.getElementById('open-search'); + this.closeButton = document.getElementById('close-search'); + } + + open() { + this.openButton.hidden = true; + this.closeButton.hidden = false; + this.box.style.top = "100%"; + this.bar.focus(); + } + + close() { + this.openButton.hidden = false; + this.closeButton.hidden = true; + this.box.style.top = "0"; + } + +} + +function scrollToTop() { + window.scrollTo({ top: 0, behavior: 'smooth' }); +} + +document.addEventListener('DOMContentLoaded', () => { + mobileSearch = new SearchBar(); + + bottomHeightThreshold = document.documentElement.scrollHeight - 30; + sections = document.querySelectorAll('section'); + hamburgerToggle = document.getElementById('hamburger-toggle'); + + toTop = document.getElementById('to-top'); + toTop.hidden = !(window.scrollY > 0); + + if (hamburgerToggle) { + hamburgerToggle.addEventListener('click', (e) => { + sidebar.element.classList.toggle('sidebar-toggle'); + let button = hamburgerToggle.firstElementChild; + if (button.textContent == 'menu') { + button.textContent = 'close'; + } + else { + button.textContent = 'menu'; + } + }); + } + + const tables = document.querySelectorAll('.py-attribute-table[data-move-to-id]'); + tables.forEach(table => { + let element = document.getElementById(table.getAttribute('data-move-to-id')); + let parent = element.parentNode; + // insert ourselves after the element + parent.insertBefore(table, element.nextSibling); + }); + + window.addEventListener('scroll', () => { + toTop.hidden = !(window.scrollY > 0); + }); +}); + +document.addEventListener('keydown', (event) => { + if (event.code == "Escape" && activeModal) { + activeModal.close(); + } +}); diff --git a/docs/Python/html/_static/discord_py_logo.ico b/docs/Python/html/_static/discord_py_logo.ico new file mode 100644 index 00000000..209ba4ef Binary files /dev/null and b/docs/Python/html/_static/discord_py_logo.ico differ diff --git a/docs/Python/html/_static/doctools.js b/docs/Python/html/_static/doctools.js new file mode 100644 index 00000000..8cbf1b16 --- /dev/null +++ b/docs/Python/html/_static/doctools.js @@ -0,0 +1,323 @@ +/* + * doctools.js + * ~~~~~~~~~~~ + * + * Sphinx JavaScript utilities for all documentation. + * + * :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/** + * select a different prefix for underscore + */ +$u = _.noConflict(); + +/** + * make the code below compatible with browsers without + * an installed firebug like debugger +if (!window.console || !console.firebug) { + var names = ["log", "debug", "info", "warn", "error", "assert", "dir", + "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", + "profile", "profileEnd"]; + window.console = {}; + for (var i = 0; i < names.length; ++i) + window.console[names[i]] = function() {}; +} + */ + +/** + * small helper function to urldecode strings + * + * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent#Decoding_query_parameters_from_a_URL + */ +jQuery.urldecode = function(x) { + if (!x) { + return x + } + return decodeURIComponent(x.replace(/\+/g, ' ')); +}; + +/** + * small helper function to urlencode strings + */ +jQuery.urlencode = encodeURIComponent; + +/** + * This function returns the parsed url parameters of the + * current request. Multiple values per key are supported, + * it will always return arrays of strings for the value parts. + */ +jQuery.getQueryParameters = function(s) { + if (typeof s === 'undefined') + s = document.location.search; + var parts = s.substr(s.indexOf('?') + 1).split('&'); + var result = {}; + for (var i = 0; i < parts.length; i++) { + var tmp = parts[i].split('=', 2); + var key = jQuery.urldecode(tmp[0]); + var value = jQuery.urldecode(tmp[1]); + if (key in result) + result[key].push(value); + else + result[key] = [value]; + } + return result; +}; + +/** + * highlight a given string on a jquery object by wrapping it in + * span elements with the given class name. + */ +jQuery.fn.highlightText = function(text, className) { + function highlight(node, addItems) { + if (node.nodeType === 3) { + var val = node.nodeValue; + var pos = val.toLowerCase().indexOf(text); + if (pos >= 0 && + !jQuery(node.parentNode).hasClass(className) && + !jQuery(node.parentNode).hasClass("nohighlight")) { + var span; + var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg"); + if (isInSVG) { + span = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); + } else { + span = document.createElement("span"); + span.className = className; + } + span.appendChild(document.createTextNode(val.substr(pos, text.length))); + node.parentNode.insertBefore(span, node.parentNode.insertBefore( + document.createTextNode(val.substr(pos + text.length)), + node.nextSibling)); + node.nodeValue = val.substr(0, pos); + if (isInSVG) { + var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); + var bbox = node.parentElement.getBBox(); + rect.x.baseVal.value = bbox.x; + rect.y.baseVal.value = bbox.y; + rect.width.baseVal.value = bbox.width; + rect.height.baseVal.value = bbox.height; + rect.setAttribute('class', className); + addItems.push({ + "parent": node.parentNode, + "target": rect}); + } + } + } + else if (!jQuery(node).is("button, select, textarea")) { + jQuery.each(node.childNodes, function() { + highlight(this, addItems); + }); + } + } + var addItems = []; + var result = this.each(function() { + highlight(this, addItems); + }); + for (var i = 0; i < addItems.length; ++i) { + jQuery(addItems[i].parent).before(addItems[i].target); + } + return result; +}; + +/* + * backward compatibility for jQuery.browser + * This will be supported until firefox bug is fixed. + */ +if (!jQuery.browser) { + jQuery.uaMatch = function(ua) { + ua = ua.toLowerCase(); + + var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || + /(webkit)[ \/]([\w.]+)/.exec(ua) || + /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || + /(msie) ([\w.]+)/.exec(ua) || + ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || + []; + + return { + browser: match[ 1 ] || "", + version: match[ 2 ] || "0" + }; + }; + jQuery.browser = {}; + jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true; +} + +/** + * Small JavaScript module for the documentation. + */ +var Documentation = { + + init : function() { + this.fixFirefoxAnchorBug(); + this.highlightSearchWords(); + this.initIndexTable(); + if (DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) { + this.initOnKeyListeners(); + } + }, + + /** + * i18n support + */ + TRANSLATIONS : {}, + PLURAL_EXPR : function(n) { return n === 1 ? 0 : 1; }, + LOCALE : 'unknown', + + // gettext and ngettext don't access this so that the functions + // can safely bound to a different name (_ = Documentation.gettext) + gettext : function(string) { + var translated = Documentation.TRANSLATIONS[string]; + if (typeof translated === 'undefined') + return string; + return (typeof translated === 'string') ? translated : translated[0]; + }, + + ngettext : function(singular, plural, n) { + var translated = Documentation.TRANSLATIONS[singular]; + if (typeof translated === 'undefined') + return (n == 1) ? singular : plural; + return translated[Documentation.PLURALEXPR(n)]; + }, + + addTranslations : function(catalog) { + for (var key in catalog.messages) + this.TRANSLATIONS[key] = catalog.messages[key]; + this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')'); + this.LOCALE = catalog.locale; + }, + + /** + * add context elements like header anchor links + */ + addContextElements : function() { + $('div[id] > :header:first').each(function() { + $('\u00B6'). + attr('href', '#' + this.id). + attr('title', _('Permalink to this headline')). + appendTo(this); + }); + $('dt[id]').each(function() { + $('\u00B6'). + attr('href', '#' + this.id). + attr('title', _('Permalink to this definition')). + appendTo(this); + }); + }, + + /** + * workaround a firefox stupidity + * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075 + */ + fixFirefoxAnchorBug : function() { + if (document.location.hash && $.browser.mozilla) + window.setTimeout(function() { + document.location.href += ''; + }, 10); + }, + + /** + * highlight the search words provided in the url in the text + */ + highlightSearchWords : function() { + var params = $.getQueryParameters(); + var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : []; + if (terms.length) { + var body = $('div.body'); + if (!body.length) { + body = $('body'); + } + window.setTimeout(function() { + $.each(terms, function() { + body.highlightText(this.toLowerCase(), 'highlighted'); + }); + }, 10); + $('') + .appendTo($('#searchbox')); + } + }, + + /** + * init the domain index toggle buttons + */ + initIndexTable : function() { + var togglers = $('img.toggler').click(function() { + var src = $(this).attr('src'); + var idnum = $(this).attr('id').substr(7); + $('tr.cg-' + idnum).toggle(); + if (src.substr(-9) === 'minus.png') + $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); + else + $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); + }).css('display', ''); + if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) { + togglers.click(); + } + }, + + /** + * helper function to hide the search marks again + */ + hideSearchWords : function() { + $('#searchbox .highlight-link').fadeOut(300); + $('span.highlighted').removeClass('highlighted'); + }, + + /** + * make the url absolute + */ + makeURL : function(relativeURL) { + return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL; + }, + + /** + * get the current relative url + */ + getCurrentURL : function() { + var path = document.location.pathname; + var parts = path.split(/\//); + $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { + if (this === '..') + parts.pop(); + }); + var url = parts.join('/'); + return path.substring(url.lastIndexOf('/') + 1, path.length - 1); + }, + + initOnKeyListeners: function() { + $(document).keydown(function(event) { + var activeElementType = document.activeElement.tagName; + // don't navigate when in search box, textarea, dropdown or button + if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT' + && activeElementType !== 'BUTTON' && !event.altKey && !event.ctrlKey && !event.metaKey + && !event.shiftKey) { + switch (event.keyCode) { + case 37: // left + var prevHref = $('link[rel="prev"]').prop('href'); + if (prevHref) { + window.location.href = prevHref; + return false; + } + break; + case 39: // right + var nextHref = $('link[rel="next"]').prop('href'); + if (nextHref) { + window.location.href = nextHref; + return false; + } + break; + } + } + }); + } +}; + +// quick alias for translations +_ = Documentation.gettext; + +$(document).ready(function() { + Documentation.init(); +}); diff --git a/docs/Python/html/_static/documentation_options.js b/docs/Python/html/_static/documentation_options.js new file mode 100644 index 00000000..0a278a4e --- /dev/null +++ b/docs/Python/html/_static/documentation_options.js @@ -0,0 +1,12 @@ +var DOCUMENTATION_OPTIONS = { + URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), + VERSION: '2.0.0a', + LANGUAGE: 'None', + COLLAPSE_INDEX: false, + BUILDER: 'html', + FILE_SUFFIX: '.html', + LINK_SUFFIX: '.html', + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt', + NAVIGATION_WITH_KEYS: false +}; \ No newline at end of file diff --git a/docs/Python/html/_static/icons.css b/docs/Python/html/_static/icons.css new file mode 100644 index 00000000..b237f109 --- /dev/null +++ b/docs/Python/html/_static/icons.css @@ -0,0 +1,10 @@ +@font-face { + font-family: 'Custom Icons'; + font-style: normal; + font-weight: 400; + src: url('icons.woff') format('woff2'); +} + +.custom-icons { + font-family: 'Custom Icons' !important; +} diff --git a/docs/Python/html/_static/icons.woff b/docs/Python/html/_static/icons.woff new file mode 100644 index 00000000..50a340c4 Binary files /dev/null and b/docs/Python/html/_static/icons.woff differ diff --git a/docs/Python/html/_static/jquery-3.5.1.js b/docs/Python/html/_static/jquery-3.5.1.js new file mode 100644 index 00000000..50937333 --- /dev/null +++ b/docs/Python/html/_static/jquery-3.5.1.js @@ -0,0 +1,10872 @@ +/*! + * jQuery JavaScript Library v3.5.1 + * https://jquery.com/ + * + * Includes Sizzle.js + * https://sizzlejs.com/ + * + * Copyright JS Foundation and other contributors + * Released under the MIT license + * https://jquery.org/license + * + * Date: 2020-05-04T22:49Z + */ +( function( global, factory ) { + + "use strict"; + + if ( typeof module === "object" && typeof module.exports === "object" ) { + + // For CommonJS and CommonJS-like environments where a proper `window` + // is present, execute the factory and get jQuery. + // For environments that do not have a `window` with a `document` + // (such as Node.js), expose a factory as module.exports. + // This accentuates the need for the creation of a real `window`. + // e.g. var jQuery = require("jquery")(window); + // See ticket #14549 for more info. + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 +// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode +// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common +// enough that all such attempts are guarded in a try block. +"use strict"; + +var arr = []; + +var getProto = Object.getPrototypeOf; + +var slice = arr.slice; + +var flat = arr.flat ? function( array ) { + return arr.flat.call( array ); +} : function( array ) { + return arr.concat.apply( [], array ); +}; + + +var push = arr.push; + +var indexOf = arr.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var fnToString = hasOwn.toString; + +var ObjectFunctionString = fnToString.call( Object ); + +var support = {}; + +var isFunction = function isFunction( obj ) { + + // Support: Chrome <=57, Firefox <=52 + // In some browsers, typeof returns "function" for HTML elements + // (i.e., `typeof document.createElement( "object" ) === "function"`). + // We don't want to classify *any* DOM node as a function. + return typeof obj === "function" && typeof obj.nodeType !== "number"; + }; + + +var isWindow = function isWindow( obj ) { + return obj != null && obj === obj.window; + }; + + +var document = window.document; + + + + var preservedScriptAttributes = { + type: true, + src: true, + nonce: true, + noModule: true + }; + + function DOMEval( code, node, doc ) { + doc = doc || document; + + var i, val, + script = doc.createElement( "script" ); + + script.text = code; + if ( node ) { + for ( i in preservedScriptAttributes ) { + + // Support: Firefox 64+, Edge 18+ + // Some browsers don't support the "nonce" property on scripts. + // On the other hand, just using `getAttribute` is not enough as + // the `nonce` attribute is reset to an empty string whenever it + // becomes browsing-context connected. + // See https://github.com/whatwg/html/issues/2369 + // See https://html.spec.whatwg.org/#nonce-attributes + // The `node.getAttribute` check was added for the sake of + // `jQuery.globalEval` so that it can fake a nonce-containing node + // via an object. + val = node[ i ] || node.getAttribute && node.getAttribute( i ); + if ( val ) { + script.setAttribute( i, val ); + } + } + } + doc.head.appendChild( script ).parentNode.removeChild( script ); + } + + +function toType( obj ) { + if ( obj == null ) { + return obj + ""; + } + + // Support: Android <=2.3 only (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call( obj ) ] || "object" : + typeof obj; +} +/* global Symbol */ +// Defining this global in .eslintrc.json would create a danger of using the global +// unguarded in another place, it seems safer to define global only for this module + + + +var + version = "3.5.1", + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }; + +jQuery.fn = jQuery.prototype = { + + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + + // Return all the elements in a clean array + if ( num == null ) { + return slice.call( this ); + } + + // Return just the one element from the set + return num < 0 ? this[ num + this.length ] : this[ num ]; + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + each: function( callback ) { + return jQuery.each( this, callback ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map( this, function( elem, i ) { + return callback.call( elem, i, elem ); + } ) ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + even: function() { + return this.pushStack( jQuery.grep( this, function( _elem, i ) { + return ( i + 1 ) % 2; + } ) ); + }, + + odd: function() { + return this.pushStack( jQuery.grep( this, function( _elem, i ) { + return i % 2; + } ) ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: arr.sort, + splice: arr.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[ 0 ] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // Skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !isFunction( target ) ) { + target = {}; + } + + // Extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + + // Only deal with non-null/undefined values + if ( ( options = arguments[ i ] ) != null ) { + + // Extend the base object + for ( name in options ) { + copy = options[ name ]; + + // Prevent Object.prototype pollution + // Prevent never-ending loop + if ( name === "__proto__" || target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject( copy ) || + ( copyIsArray = Array.isArray( copy ) ) ) ) { + src = target[ name ]; + + // Ensure proper type for the source value + if ( copyIsArray && !Array.isArray( src ) ) { + clone = []; + } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { + clone = {}; + } else { + clone = src; + } + copyIsArray = false; + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend( { + + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + isPlainObject: function( obj ) { + var proto, Ctor; + + // Detect obvious negatives + // Use toString instead of jQuery.type to catch host objects + if ( !obj || toString.call( obj ) !== "[object Object]" ) { + return false; + } + + proto = getProto( obj ); + + // Objects with no prototype (e.g., `Object.create( null )`) are plain + if ( !proto ) { + return true; + } + + // Objects with prototype are plain iff they were constructed by a global Object function + Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; + return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; + }, + + isEmptyObject: function( obj ) { + var name; + + for ( name in obj ) { + return false; + } + return true; + }, + + // Evaluates a script in a provided context; falls back to the global one + // if not specified. + globalEval: function( code, options, doc ) { + DOMEval( code, { nonce: options && options.nonce }, doc ); + }, + + each: function( obj, callback ) { + var length, i = 0; + + if ( isArrayLike( obj ) ) { + length = obj.length; + for ( ; i < length; i++ ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } else { + for ( i in obj ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } + + return obj; + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArrayLike( Object( arr ) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + return arr == null ? -1 : indexOf.call( arr, elem, i ); + }, + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + for ( ; j < len; j++ ) { + first[ i++ ] = second[ j ]; + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var length, value, + i = 0, + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArrayLike( elems ) ) { + length = elems.length; + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return flat( ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +} ); + +if ( typeof Symbol === "function" ) { + jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; +} + +// Populate the class2type map +jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), +function( _i, name ) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +} ); + +function isArrayLike( obj ) { + + // Support: real iOS 8.2 only (not reproducible in simulator) + // `in` check used to prevent JIT error (gh-2145) + // hasOwn isn't used here due to false negatives + // regarding Nodelist length in IE + var length = !!obj && "length" in obj && obj.length, + type = toType( obj ); + + if ( isFunction( obj ) || isWindow( obj ) ) { + return false; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v2.3.5 + * https://sizzlejs.com/ + * + * Copyright JS Foundation and other contributors + * Released under the MIT license + * https://js.foundation/ + * + * Date: 2020-03-14 + */ +( function( window ) { +var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + 1 * new Date(), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + nonnativeSelectorCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // Instance methods + hasOwn = ( {} ).hasOwnProperty, + arr = [], + pop = arr.pop, + pushNative = arr.push, + push = arr.push, + slice = arr.slice, + + // Use a stripped-down indexOf as it's faster than native + // https://jsperf.com/thor-indexof-vs-for/5 + indexOf = function( list, elem ) { + var i = 0, + len = list.length; + for ( ; i < len; i++ ) { + if ( list[ i ] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" + + "ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + + // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram + identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + + // "Attribute values must be CSS identifiers [capture 5] + // or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + + whitespace + "*\\]", + + pseudos = ":(" + identifier + ")(?:\\((" + + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + + "*" ), + rdescend = new RegExp( whitespace + "|>" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + identifier + ")" ), + "CLASS": new RegExp( "^\\.(" + identifier + ")" ), + "TAG": new RegExp( "^(" + identifier + "|[*])" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rhtml = /HTML$/i, + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + + // CSS escapes + // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ), + funescape = function( escape, nonHex ) { + var high = "0x" + escape.slice( 1 ) - 0x10000; + + return nonHex ? + + // Strip the backslash prefix from a non-hex escape sequence + nonHex : + + // Replace a hexadecimal escape sequence with the encoded Unicode code point + // Support: IE <=11+ + // For values outside the Basic Multilingual Plane (BMP), manually construct a + // surrogate pair + high < 0 ? + String.fromCharCode( high + 0x10000 ) : + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, + + // CSS string/identifier serialization + // https://drafts.csswg.org/cssom/#common-serializing-idioms + rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, + fcssescape = function( ch, asCodePoint ) { + if ( asCodePoint ) { + + // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER + if ( ch === "\0" ) { + return "\uFFFD"; + } + + // Control characters and (dependent upon position) numbers get escaped as code points + return ch.slice( 0, -1 ) + "\\" + + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; + } + + // Other potentially-special ASCII characters get backslash-escaped + return "\\" + ch; + }, + + // Used for iframes + // See setDocument() + // Removing the function wrapper causes a "Permission Denied" + // error in IE + unloadHandler = function() { + setDocument(); + }, + + inDisabledFieldset = addCombinator( + function( elem ) { + return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; + }, + { dir: "parentNode", next: "legend" } + ); + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + ( arr = slice.call( preferredDoc.childNodes ) ), + preferredDoc.childNodes + ); + + // Support: Android<4.0 + // Detect silently failing push.apply + // eslint-disable-next-line no-unused-expressions + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + pushNative.apply( target, slice.call( els ) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + + // Can't trust NodeList.length + while ( ( target[ j++ ] = els[ i++ ] ) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var m, i, elem, nid, match, groups, newSelector, + newContext = context && context.ownerDocument, + + // nodeType defaults to 9, since context defaults to document + nodeType = context ? context.nodeType : 9; + + results = results || []; + + // Return early from calls with invalid selector or context + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + + return results; + } + + // Try to shortcut find operations (as opposed to filters) in HTML documents + if ( !seed ) { + setDocument( context ); + context = context || document; + + if ( documentIsHTML ) { + + // If the selector is sufficiently simple, try using a "get*By*" DOM method + // (excepting DocumentFragment context, where the methods don't exist) + if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) { + + // ID selector + if ( ( m = match[ 1 ] ) ) { + + // Document context + if ( nodeType === 9 ) { + if ( ( elem = context.getElementById( m ) ) ) { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + + // Element context + } else { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( newContext && ( elem = newContext.getElementById( m ) ) && + contains( context, elem ) && + elem.id === m ) { + + results.push( elem ); + return results; + } + } + + // Type selector + } else if ( match[ 2 ] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Class selector + } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName && + context.getElementsByClassName ) { + + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // Take advantage of querySelectorAll + if ( support.qsa && + !nonnativeSelectorCache[ selector + " " ] && + ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) && + + // Support: IE 8 only + // Exclude object elements + ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) { + + newSelector = selector; + newContext = context; + + // qSA considers elements outside a scoping root when evaluating child or + // descendant combinators, which is not what we want. + // In such cases, we work around the behavior by prefixing every selector in the + // list with an ID selector referencing the scope context. + // The technique has to be used as well when a leading combinator is used + // as such selectors are not recognized by querySelectorAll. + // Thanks to Andrew Dupont for this technique. + if ( nodeType === 1 && + ( rdescend.test( selector ) || rcombinators.test( selector ) ) ) { + + // Expand context for sibling selectors + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || + context; + + // We can use :scope instead of the ID hack if the browser + // supports it & if we're not changing the context. + if ( newContext !== context || !support.scope ) { + + // Capture the context ID, setting it first if necessary + if ( ( nid = context.getAttribute( "id" ) ) ) { + nid = nid.replace( rcssescape, fcssescape ); + } else { + context.setAttribute( "id", ( nid = expando ) ); + } + } + + // Prefix every selector in the list + groups = tokenize( selector ); + i = groups.length; + while ( i-- ) { + groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " + + toSelector( groups[ i ] ); + } + newSelector = groups.join( "," ); + } + + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + nonnativeSelectorCache( selector, true ); + } finally { + if ( nid === expando ) { + context.removeAttribute( "id" ); + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {function(string, object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return ( cache[ key + " " ] = value ); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created element and returns a boolean result + */ +function assert( fn ) { + var el = document.createElement( "fieldset" ); + + try { + return !!fn( el ); + } catch ( e ) { + return false; + } finally { + + // Remove from its parent by default + if ( el.parentNode ) { + el.parentNode.removeChild( el ); + } + + // release memory in IE + el = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split( "|" ), + i = arr.length; + + while ( i-- ) { + Expr.attrHandle[ arr[ i ] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + a.sourceIndex - b.sourceIndex; + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( ( cur = cur.nextSibling ) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return ( name === "input" || name === "button" ) && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for :enabled/:disabled + * @param {Boolean} disabled true for :disabled; false for :enabled + */ +function createDisabledPseudo( disabled ) { + + // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable + return function( elem ) { + + // Only certain elements can match :enabled or :disabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled + if ( "form" in elem ) { + + // Check for inherited disabledness on relevant non-disabled elements: + // * listed form-associated elements in a disabled fieldset + // https://html.spec.whatwg.org/multipage/forms.html#category-listed + // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled + // * option elements in a disabled optgroup + // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled + // All such elements have a "form" property. + if ( elem.parentNode && elem.disabled === false ) { + + // Option elements defer to a parent optgroup if present + if ( "label" in elem ) { + if ( "label" in elem.parentNode ) { + return elem.parentNode.disabled === disabled; + } else { + return elem.disabled === disabled; + } + } + + // Support: IE 6 - 11 + // Use the isDisabled shortcut property to check for disabled fieldset ancestors + return elem.isDisabled === disabled || + + // Where there is no isDisabled, check manually + /* jshint -W018 */ + elem.isDisabled !== !disabled && + inDisabledFieldset( elem ) === disabled; + } + + return elem.disabled === disabled; + + // Try to winnow out elements that can't be disabled before trusting the disabled property. + // Some victims get caught in our net (label, legend, menu, track), but it shouldn't + // even exist on them, let alone have a boolean value. + } else if ( "label" in elem ) { + return elem.disabled === disabled; + } + + // Remaining elements are neither :enabled nor :disabled + return false; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction( function( argument ) { + argument = +argument; + return markFunction( function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ ( j = matchIndexes[ i ] ) ] ) { + seed[ j ] = !( matches[ j ] = seed[ j ] ); + } + } + } ); + } ); +} + +/** + * Checks a node for validity as a Sizzle context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ +function testContext( context ) { + return context && typeof context.getElementsByTagName !== "undefined" && context; +} + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Detects XML nodes + * @param {Element|Object} elem An element or a document + * @returns {Boolean} True iff elem is a non-HTML XML node + */ +isXML = Sizzle.isXML = function( elem ) { + var namespace = elem.namespaceURI, + docElem = ( elem.ownerDocument || elem ).documentElement; + + // Support: IE <=8 + // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes + // https://bugs.jquery.com/ticket/4833 + return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var hasCompare, subWindow, + doc = node ? node.ownerDocument || node : preferredDoc; + + // Return early if doc is invalid or already selected + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Update global variables + document = doc; + docElem = document.documentElement; + documentIsHTML = !isXML( document ); + + // Support: IE 9 - 11+, Edge 12 - 18+ + // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( preferredDoc != document && + ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { + + // Support: IE 11, Edge + if ( subWindow.addEventListener ) { + subWindow.addEventListener( "unload", unloadHandler, false ); + + // Support: IE 9 - 10 only + } else if ( subWindow.attachEvent ) { + subWindow.attachEvent( "onunload", unloadHandler ); + } + } + + // Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only, + // Safari 4 - 5 only, Opera <=11.6 - 12.x only + // IE/Edge & older browsers don't support the :scope pseudo-class. + // Support: Safari 6.0 only + // Safari 6.0 supports :scope but it's an alias of :root there. + support.scope = assert( function( el ) { + docElem.appendChild( el ).appendChild( document.createElement( "div" ) ); + return typeof el.querySelectorAll !== "undefined" && + !el.querySelectorAll( ":scope fieldset div" ).length; + } ); + + /* Attributes + ---------------------------------------------------------------------- */ + + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties + // (excepting IE8 booleans) + support.attributes = assert( function( el ) { + el.className = "i"; + return !el.getAttribute( "className" ); + } ); + + /* getElement(s)By* + ---------------------------------------------------------------------- */ + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert( function( el ) { + el.appendChild( document.createComment( "" ) ); + return !el.getElementsByTagName( "*" ).length; + } ); + + // Support: IE<9 + support.getElementsByClassName = rnative.test( document.getElementsByClassName ); + + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programmatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert( function( el ) { + docElem.appendChild( el ).id = expando; + return !document.getElementsByName || !document.getElementsByName( expando ).length; + } ); + + // ID filter and find + if ( support.getById ) { + Expr.filter[ "ID" ] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute( "id" ) === attrId; + }; + }; + Expr.find[ "ID" ] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var elem = context.getElementById( id ); + return elem ? [ elem ] : []; + } + }; + } else { + Expr.filter[ "ID" ] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== "undefined" && + elem.getAttributeNode( "id" ); + return node && node.value === attrId; + }; + }; + + // Support: IE 6 - 7 only + // getElementById is not reliable as a find shortcut + Expr.find[ "ID" ] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var node, i, elems, + elem = context.getElementById( id ); + + if ( elem ) { + + // Verify the id attribute + node = elem.getAttributeNode( "id" ); + if ( node && node.value === id ) { + return [ elem ]; + } + + // Fall back on getElementsByName + elems = context.getElementsByName( id ); + i = 0; + while ( ( elem = elems[ i++ ] ) ) { + node = elem.getAttributeNode( "id" ); + if ( node && node.value === id ) { + return [ elem ]; + } + } + } + + return []; + } + }; + } + + // Tag + Expr.find[ "TAG" ] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( tag ); + + // DocumentFragment nodes don't have gEBTN + } else if ( support.qsa ) { + return context.querySelectorAll( tag ); + } + } : + + function( tag, context ) { + var elem, + tmp = [], + i = 0, + + // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( ( elem = results[ i++ ] ) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Class + Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; + + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See https://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) { + + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert( function( el ) { + + var input; + + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // https://bugs.jquery.com/ticket/12359 + docElem.appendChild( el ).innerHTML = "" + + ""; + + // Support: IE8, Opera 11-12.16 + // Nothing should be selected when empty strings follow ^= or $= or *= + // The test attribute must be unknown in Opera but "safe" for WinRT + // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !el.querySelectorAll( "[selected]" ).length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ + if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { + rbuggyQSA.push( "~=" ); + } + + // Support: IE 11+, Edge 15 - 18+ + // IE 11/Edge don't find elements on a `[name='']` query in some cases. + // Adding a temporary attribute to the document before the selection works + // around the issue. + // Interestingly, IE 10 & older don't seem to have the issue. + input = document.createElement( "input" ); + input.setAttribute( "name", "" ); + el.appendChild( input ); + if ( !el.querySelectorAll( "[name='']" ).length ) { + rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" + + whitespace + "*(?:''|\"\")" ); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !el.querySelectorAll( ":checked" ).length ) { + rbuggyQSA.push( ":checked" ); + } + + // Support: Safari 8+, iOS 8+ + // https://bugs.webkit.org/show_bug.cgi?id=136851 + // In-page `selector#id sibling-combinator selector` fails + if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { + rbuggyQSA.push( ".#.+[+~]" ); + } + + // Support: Firefox <=3.6 - 5 only + // Old Firefox doesn't throw on a badly-escaped identifier. + el.querySelectorAll( "\\\f" ); + rbuggyQSA.push( "[\\r\\n\\f]" ); + } ); + + assert( function( el ) { + el.innerHTML = "" + + ""; + + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + var input = document.createElement( "input" ); + input.setAttribute( "type", "hidden" ); + el.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( el.querySelectorAll( "[name=d]" ).length ) { + rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( el.querySelectorAll( ":enabled" ).length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Support: IE9-11+ + // IE's :disabled selector does not pick up the children of disabled fieldsets + docElem.appendChild( el ).disabled = true; + if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Support: Opera 10 - 11 only + // Opera 10-11 does not throw on post-comma invalid pseudos + el.querySelectorAll( "*,:x" ); + rbuggyQSA.push( ",.*:" ); + } ); + } + + if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches || + docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector ) ) ) ) { + + assert( function( el ) { + + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( el, "*" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( el, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + } ); + } + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) ); + + /* Contains + ---------------------------------------------------------------------- */ + hasCompare = rnative.test( docElem.compareDocumentPosition ); + + // Element contains another + // Purposefully self-exclusive + // As in, an element does not contain itself + contains = hasCompare || rnative.test( docElem.contains ) ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + ) ); + } : + function( a, b ) { + if ( b ) { + while ( ( b = b.parentNode ) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = hasCompare ? + function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } + + // Calculate position if both inputs belong to the same document + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) { + + // Choose the first element that is related to our preferred document + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( a == document || a.ownerDocument == preferredDoc && + contains( preferredDoc, a ) ) { + return -1; + } + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( b == document || b.ownerDocument == preferredDoc && + contains( preferredDoc, b ) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } : + function( a, b ) { + + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Parentless nodes are either documents or disconnected + if ( !aup || !bup ) { + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + /* eslint-disable eqeqeq */ + return a == document ? -1 : + b == document ? 1 : + /* eslint-enable eqeqeq */ + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( ( cur = cur.parentNode ) ) { + ap.unshift( cur ); + } + cur = b; + while ( ( cur = cur.parentNode ) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[ i ] === bp[ i ] ) { + i++; + } + + return i ? + + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[ i ], bp[ i ] ) : + + // Otherwise nodes in our document sort first + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + /* eslint-disable eqeqeq */ + ap[ i ] == preferredDoc ? -1 : + bp[ i ] == preferredDoc ? 1 : + /* eslint-enable eqeqeq */ + 0; + }; + + return document; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + setDocument( elem ); + + if ( support.matchesSelector && documentIsHTML && + !nonnativeSelectorCache[ expr + " " ] && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch ( e ) { + nonnativeSelectorCache( expr, true ); + } + } + + return Sizzle( expr, document, null, [ elem ] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + + // Set document vars if needed + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( ( context.ownerDocument || context ) != document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + + // Set document vars if needed + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( ( elem.ownerDocument || elem ) != document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val !== undefined ? + val : + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + ( val = elem.getAttributeNode( name ) ) && val.specified ? + val.value : + null; +}; + +Sizzle.escape = function( sel ) { + return ( sel + "" ).replace( rcssescape, fcssescape ); +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( ( elem = results[ i++ ] ) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; + + return results; +}; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + + // If no nodeType, this is expected to be an array + while ( ( node = elem[ i++ ] ) ) { + + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + + // Use textContent for elements + // innerText usage removed for consistency of new lines (jQuery #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[ 1 ] = match[ 1 ].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[ 3 ] = ( match[ 3 ] || match[ 4 ] || + match[ 5 ] || "" ).replace( runescape, funescape ); + + if ( match[ 2 ] === "~=" ) { + match[ 3 ] = " " + match[ 3 ] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[ 1 ] = match[ 1 ].toLowerCase(); + + if ( match[ 1 ].slice( 0, 3 ) === "nth" ) { + + // nth-* requires argument + if ( !match[ 3 ] ) { + Sizzle.error( match[ 0 ] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[ 4 ] = +( match[ 4 ] ? + match[ 5 ] + ( match[ 6 ] || 1 ) : + 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) ); + match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" ); + + // other types prohibit arguments + } else if ( match[ 3 ] ) { + Sizzle.error( match[ 0 ] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[ 6 ] && match[ 2 ]; + + if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[ 3 ] ) { + match[ 2 ] = match[ 4 ] || match[ 5 ] || ""; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + + // Get excess from tokenize (recursively) + ( excess = tokenize( unquoted, true ) ) && + + // advance to the next closing parenthesis + ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) { + + // excess is a negative index + match[ 0 ] = match[ 0 ].slice( 0, excess ); + match[ 2 ] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { + return true; + } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + ( pattern = new RegExp( "(^|" + whitespace + + ")" + className + "(" + whitespace + "|$)" ) ) && classCache( + className, function( elem ) { + return pattern.test( + typeof elem.className === "string" && elem.className || + typeof elem.getAttribute !== "undefined" && + elem.getAttribute( "class" ) || + "" + ); + } ); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + /* eslint-disable max-len */ + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + /* eslint-enable max-len */ + + }; + }, + + "CHILD": function( type, what, _argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, _context, xml ) { + var cache, uniqueCache, outerCache, node, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType, + diff = false; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( ( node = node[ dir ] ) ) { + if ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) { + + return false; + } + } + + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + + // Seek `elem` from a previously-cached index + + // ...in a gzip-friendly way + node = parent; + outerCache = node[ expando ] || ( node[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + ( outerCache[ node.uniqueID ] = {} ); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex && cache[ 2 ]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( ( node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + ( diff = nodeIndex = 0 ) || start.pop() ) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + } else { + + // Use previously-cached element index if available + if ( useCache ) { + + // ...in a gzip-friendly way + node = elem; + outerCache = node[ expando ] || ( node[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + ( outerCache[ node.uniqueID ] = {} ); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex; + } + + // xml :nth-child(...) + // or :nth-last-child(...) or :nth(-last)?-of-type(...) + if ( diff === false ) { + + // Use the same loop as above to seek `elem` from the start + while ( ( node = ++nodeIndex && node && node[ dir ] || + ( diff = nodeIndex = 0 ) || start.pop() ) ) { + + if ( ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) && + ++diff ) { + + // Cache the index of each encountered element + if ( useCache ) { + outerCache = node[ expando ] || + ( node[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + ( outerCache[ node.uniqueID ] = {} ); + + uniqueCache[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction( function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf( seed, matched[ i ] ); + seed[ idx ] = !( matches[ idx ] = matched[ i ] ); + } + } ) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + + // Potentially complex pseudos + "not": markFunction( function( selector ) { + + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction( function( seed, matches, _context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( ( elem = unmatched[ i ] ) ) { + seed[ i ] = !( matches[ i ] = elem ); + } + } + } ) : + function( elem, _context, xml ) { + input[ 0 ] = elem; + matcher( input, null, xml, results ); + + // Don't keep the element (issue #299) + input[ 0 ] = null; + return !results.pop(); + }; + } ), + + "has": markFunction( function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + } ), + + "contains": markFunction( function( text ) { + text = text.replace( runescape, funescape ); + return function( elem ) { + return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1; + }; + } ), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + + // lang value must be a valid identifier + if ( !ridentifier.test( lang || "" ) ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( ( elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 ); + return false; + }; + } ), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && + ( !document.hasFocus || document.hasFocus() ) && + !!( elem.type || elem.href || ~elem.tabIndex ); + }, + + // Boolean properties + "enabled": createDisabledPseudo( false ), + "disabled": createDisabledPseudo( true ), + + "checked": function( elem ) { + + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return ( nodeName === "input" && !!elem.checked ) || + ( nodeName === "option" && !!elem.selected ); + }, + + "selected": function( elem ) { + + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + // eslint-disable-next-line no-unused-expressions + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos[ "empty" ]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( ( attr = elem.getAttribute( "type" ) ) == null || + attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + "first": createPositionalPseudo( function() { + return [ 0 ]; + } ), + + "last": createPositionalPseudo( function( _matchIndexes, length ) { + return [ length - 1 ]; + } ), + + "eq": createPositionalPseudo( function( _matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + } ), + + "even": createPositionalPseudo( function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ), + + "odd": createPositionalPseudo( function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ), + + "lt": createPositionalPseudo( function( matchIndexes, length, argument ) { + var i = argument < 0 ? + argument + length : + argument > length ? + length : + argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ), + + "gt": createPositionalPseudo( function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ) + } +}; + +Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +tokenize = Sizzle.tokenize = function( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || ( match = rcomma.exec( soFar ) ) ) { + if ( match ) { + + // Don't consume trailing commas as valid + soFar = soFar.slice( match[ 0 ].length ) || soFar; + } + groups.push( ( tokens = [] ) ); + } + + matched = false; + + // Combinators + if ( ( match = rcombinators.exec( soFar ) ) ) { + matched = match.shift(); + tokens.push( { + value: matched, + + // Cast descendant combinators to space + type: match[ 0 ].replace( rtrim, " " ) + } ); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] || + ( match = preFilters[ type ]( match ) ) ) ) { + matched = match.shift(); + tokens.push( { + value: matched, + type: type, + matches: match + } ); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +}; + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[ i ].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + skip = combinator.next, + key = skip || dir, + checkNonElements = base && key === "parentNode", + doneName = done++; + + return combinator.first ? + + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( ( elem = elem[ dir ] ) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + return false; + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, uniqueCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching + if ( xml ) { + while ( ( elem = elem[ dir ] ) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( ( elem = elem[ dir ] ) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || ( elem[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ elem.uniqueID ] || + ( outerCache[ elem.uniqueID ] = {} ); + + if ( skip && skip === elem.nodeName.toLowerCase() ) { + elem = elem[ dir ] || elem; + } else if ( ( oldCache = uniqueCache[ key ] ) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return ( newCache[ 2 ] = oldCache[ 2 ] ); + } else { + + // Reuse newcache so results back-propagate to previous elements + uniqueCache[ key ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) { + return true; + } + } + } + } + } + return false; + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[ i ]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[ 0 ]; +} + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[ i ], results ); + } + return results; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( ( elem = unmatched[ i ] ) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction( function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( + selector || "*", + context.nodeType ? [ context ] : context, + [] + ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( ( elem = temp[ i ] ) ) { + matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem ); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( ( elem = matcherOut[ i ] ) ) { + + // Restore matcherIn since elem is not yet a final match + temp.push( ( matcherIn[ i ] = elem ) ); + } + } + postFinder( null, ( matcherOut = [] ), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( ( elem = matcherOut[ i ] ) && + ( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) { + + seed[ temp ] = !( results[ temp ] = elem ); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + } ); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[ 0 ].type ], + implicitRelative = leadingRelative || Expr.relative[ " " ], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + ( checkContext = context ).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + + // Avoid hanging onto element (issue #299) + checkContext = null; + return ret; + } ]; + + for ( ; i < len; i++ ) { + if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) { + matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; + } else { + matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[ j ].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens + .slice( 0, i - 1 ) + .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } ) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ), + + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ), + len = elems.length; + + if ( outermost ) { + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + outermostContext = context == document || context || outermost; + } + + // Add elements passing elementMatchers directly to results + // Support: IE<9, Safari + // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id + for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( !context && elem.ownerDocument != document ) { + setDocument( elem ); + xml = !documentIsHTML; + } + while ( ( matcher = elementMatchers[ j++ ] ) ) { + if ( matcher( elem, context || document, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + + // They will have gone through all possible matchers + if ( ( elem = !matcher && elem ) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // `i` is now the count of elements visited above, and adding it to `matchedCount` + // makes the latter nonnegative. + matchedCount += i; + + // Apply set filters to unmatched elements + // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` + // equals `i`), unless we didn't visit _any_ elements in the above loop because we have + // no element matchers and no seed. + // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that + // case, which will result in a "00" `matchedCount` that differs from `i` but is also + // numerically zero. + if ( bySet && i !== matchedCount ) { + j = 0; + while ( ( matcher = setMatchers[ j++ ] ) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !( unmatched[ i ] || setMatched[ i ] ) ) { + setMatched[ i ] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[ i ] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( + selector, + matcherFromGroupMatchers( elementMatchers, setMatchers ) + ); + + // Save selector and tokenization + cached.selector = selector; + } + return cached; +}; + +/** + * A low-level selection function that works with Sizzle's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with Sizzle.compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +select = Sizzle.select = function( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( ( selector = compiled.selector || selector ) ); + + results = results || []; + + // Try to minimize operations if there is only one selector in the list and no seed + // (the latter of which guarantees us context) + if ( match.length === 1 ) { + + // Reduce context if the leading compound selector is an ID + tokens = match[ 0 ] = match[ 0 ].slice( 0 ); + if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" && + context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) { + + context = ( Expr.find[ "ID" ]( token.matches[ 0 ] + .replace( runescape, funescape ), context ) || [] )[ 0 ]; + if ( !context ) { + return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[ i ]; + + // Abort if we hit a combinator + if ( Expr.relative[ ( type = token.type ) ] ) { + break; + } + if ( ( find = Expr.find[ type ] ) ) { + + // Search, expanding context for leading sibling combinators + if ( ( seed = find( + token.matches[ 0 ].replace( runescape, funescape ), + rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) || + context + ) ) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + !context || rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; +}; + +// One-time assignments + +// Sort stability +support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando; + +// Support: Chrome 14-35+ +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = !!hasDuplicate; + +// Initialize against the default document +setDocument(); + +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert( function( el ) { + + // Should return 1, but returns 4 (following) + return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1; +} ); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert( function( el ) { + el.innerHTML = ""; + return el.firstChild.getAttribute( "href" ) === "#"; +} ) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + } ); +} + +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert( function( el ) { + el.innerHTML = ""; + el.firstChild.setAttribute( "value", "" ); + return el.firstChild.getAttribute( "value" ) === ""; +} ) ) { + addHandle( "value", function( elem, _name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + } ); +} + +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert( function( el ) { + return el.getAttribute( "disabled" ) == null; +} ) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return elem[ name ] === true ? name.toLowerCase() : + ( val = elem.getAttributeNode( name ) ) && val.specified ? + val.value : + null; + } + } ); +} + +return Sizzle; + +} )( window ); + + + +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; + +// Deprecated +jQuery.expr[ ":" ] = jQuery.expr.pseudos; +jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; +jQuery.escapeSelector = Sizzle.escape; + + + + +var dir = function( elem, dir, until ) { + var matched = [], + truncate = until !== undefined; + + while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { + if ( elem.nodeType === 1 ) { + if ( truncate && jQuery( elem ).is( until ) ) { + break; + } + matched.push( elem ); + } + } + return matched; +}; + + +var siblings = function( n, elem ) { + var matched = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + matched.push( n ); + } + } + + return matched; +}; + + +var rneedsContext = jQuery.expr.match.needsContext; + + + +function nodeName( elem, name ) { + + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + +}; +var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); + + + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + return !!qualifier.call( elem, i, elem ) !== not; + } ); + } + + // Single element + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + } ); + } + + // Arraylike of elements (jQuery, arguments, Array) + if ( typeof qualifier !== "string" ) { + return jQuery.grep( elements, function( elem ) { + return ( indexOf.call( qualifier, elem ) > -1 ) !== not; + } ); + } + + // Filtered directly for both simple and complex selectors + return jQuery.filter( qualifier, elements, not ); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + if ( elems.length === 1 && elem.nodeType === 1 ) { + return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; + } + + return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + } ) ); +}; + +jQuery.fn.extend( { + find: function( selector ) { + var i, ret, + len = this.length, + self = this; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter( function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + } ) ); + } + + ret = this.pushStack( [] ); + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + return len > 1 ? jQuery.uniqueSort( ret ) : ret; + }, + filter: function( selector ) { + return this.pushStack( winnow( this, selector || [], false ) ); + }, + not: function( selector ) { + return this.pushStack( winnow( this, selector || [], true ) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +} ); + + +// Initialize a jQuery object + + +// A central reference to the root jQuery(document) +var rootjQuery, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + // Shortcut simple #id case for speed + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, + + init = jQuery.fn.init = function( selector, context, root ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Method init() accepts an alternate rootjQuery + // so migrate can support jQuery.sub (gh-2101) + root = root || rootjQuery; + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector[ 0 ] === "<" && + selector[ selector.length - 1 ] === ">" && + selector.length >= 3 ) { + + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && ( match[ 1 ] || !context ) ) { + + // HANDLE: $(html) -> $(array) + if ( match[ 1 ] ) { + context = context instanceof jQuery ? context[ 0 ] : context; + + // Option to run scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[ 1 ], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + + // Properties of context are called as methods if possible + if ( isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[ 2 ] ); + + if ( elem ) { + + // Inject the element directly into the jQuery object + this[ 0 ] = elem; + this.length = 1; + } + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || root ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this[ 0 ] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( isFunction( selector ) ) { + return root.ready !== undefined ? + root.ready( selector ) : + + // Execute immediately if ready is not present + selector( jQuery ); + } + + return jQuery.makeArray( selector, this ); + }; + +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; + +// Initialize central reference +rootjQuery = jQuery( document ); + + +var rparentsprev = /^(?:parents|prev(?:Until|All))/, + + // Methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend( { + has: function( target ) { + var targets = jQuery( target, this ), + l = targets.length; + + return this.filter( function() { + var i = 0; + for ( ; i < l; i++ ) { + if ( jQuery.contains( this, targets[ i ] ) ) { + return true; + } + } + } ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + targets = typeof selectors !== "string" && jQuery( selectors ); + + // Positional selectors never match, since there's no _selection_ context + if ( !rneedsContext.test( selectors ) ) { + for ( ; i < l; i++ ) { + for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { + + // Always skip document fragments + if ( cur.nodeType < 11 && ( targets ? + targets.index( cur ) > -1 : + + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector( cur, selectors ) ) ) { + + matched.push( cur ); + break; + } + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); + }, + + // Determine the position of an element within the set + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; + } + + // Index in selector + if ( typeof elem === "string" ) { + return indexOf.call( jQuery( elem ), this[ 0 ] ); + } + + // Locate the position of the desired element + return indexOf.call( this, + + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[ 0 ] : elem + ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.uniqueSort( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter( selector ) + ); + } +} ); + +function sibling( cur, dir ) { + while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} + return cur; +} + +jQuery.each( { + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, _i, until ) { + return dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, _i, until ) { + return dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, _i, until ) { + return dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return siblings( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return siblings( elem.firstChild ); + }, + contents: function( elem ) { + if ( elem.contentDocument != null && + + // Support: IE 11+ + // elements with no `data` attribute has an object + // `contentDocument` with a `null` prototype. + getProto( elem.contentDocument ) ) { + + return elem.contentDocument; + } + + // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only + // Treat the template element as a regular one in browsers that + // don't support it. + if ( nodeName( elem, "template" ) ) { + elem = elem.content || elem; + } + + return jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var matched = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + matched = jQuery.filter( selector, matched ); + } + + if ( this.length > 1 ) { + + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + jQuery.uniqueSort( matched ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + matched.reverse(); + } + } + + return this.pushStack( matched ); + }; +} ); +var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); + + + +// Convert String-formatted options into Object-formatted ones +function createOptions( options ) { + var object = {}; + jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { + object[ flag ] = true; + } ); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + createOptions( options ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + + // Last fire value for non-forgettable lists + memory, + + // Flag to know if list was already fired + fired, + + // Flag to prevent firing + locked, + + // Actual callback list + list = [], + + // Queue of execution data for repeatable lists + queue = [], + + // Index of currently firing callback (modified by add/remove as needed) + firingIndex = -1, + + // Fire callbacks + fire = function() { + + // Enforce single-firing + locked = locked || options.once; + + // Execute callbacks for all pending executions, + // respecting firingIndex overrides and runtime changes + fired = firing = true; + for ( ; queue.length; firingIndex = -1 ) { + memory = queue.shift(); + while ( ++firingIndex < list.length ) { + + // Run callback and check for early termination + if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && + options.stopOnFalse ) { + + // Jump to end and forget the data so .add doesn't re-fire + firingIndex = list.length; + memory = false; + } + } + } + + // Forget the data if we're done with it + if ( !options.memory ) { + memory = false; + } + + firing = false; + + // Clean up if we're done firing for good + if ( locked ) { + + // Keep an empty list if we have data for future add calls + if ( memory ) { + list = []; + + // Otherwise, this object is spent + } else { + list = ""; + } + } + }, + + // Actual Callbacks object + self = { + + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + + // If we have memory from a past run, we should fire after adding + if ( memory && !firing ) { + firingIndex = list.length - 1; + queue.push( memory ); + } + + ( function add( args ) { + jQuery.each( args, function( _, arg ) { + if ( isFunction( arg ) ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && toType( arg ) !== "string" ) { + + // Inspect recursively + add( arg ); + } + } ); + } )( arguments ); + + if ( memory && !firing ) { + fire(); + } + } + return this; + }, + + // Remove a callback from the list + remove: function() { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + + // Handle firing indexes + if ( index <= firingIndex ) { + firingIndex--; + } + } + } ); + return this; + }, + + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? + jQuery.inArray( fn, list ) > -1 : + list.length > 0; + }, + + // Remove all callbacks from the list + empty: function() { + if ( list ) { + list = []; + } + return this; + }, + + // Disable .fire and .add + // Abort any current/pending executions + // Clear all callbacks and values + disable: function() { + locked = queue = []; + list = memory = ""; + return this; + }, + disabled: function() { + return !list; + }, + + // Disable .fire + // Also disable .add unless we have memory (since it would have no effect) + // Abort any pending executions + lock: function() { + locked = queue = []; + if ( !memory && !firing ) { + list = memory = ""; + } + return this; + }, + locked: function() { + return !!locked; + }, + + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( !locked ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + queue.push( args ); + if ( !firing ) { + fire(); + } + } + return this; + }, + + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; + + +function Identity( v ) { + return v; +} +function Thrower( ex ) { + throw ex; +} + +function adoptValue( value, resolve, reject, noValue ) { + var method; + + try { + + // Check for promise aspect first to privilege synchronous behavior + if ( value && isFunction( ( method = value.promise ) ) ) { + method.call( value ).done( resolve ).fail( reject ); + + // Other thenables + } else if ( value && isFunction( ( method = value.then ) ) ) { + method.call( value, resolve, reject ); + + // Other non-thenables + } else { + + // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: + // * false: [ value ].slice( 0 ) => resolve( value ) + // * true: [ value ].slice( 1 ) => resolve() + resolve.apply( undefined, [ value ].slice( noValue ) ); + } + + // For Promises/A+, convert exceptions into rejections + // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in + // Deferred#then to conditionally suppress rejection. + } catch ( value ) { + + // Support: Android 4.0 only + // Strict mode functions invoked without .call/.apply get global-object context + reject.apply( undefined, [ value ] ); + } +} + +jQuery.extend( { + + Deferred: function( func ) { + var tuples = [ + + // action, add listener, callbacks, + // ... .then handlers, argument index, [final state] + [ "notify", "progress", jQuery.Callbacks( "memory" ), + jQuery.Callbacks( "memory" ), 2 ], + [ "resolve", "done", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 0, "resolved" ], + [ "reject", "fail", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 1, "rejected" ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + "catch": function( fn ) { + return promise.then( null, fn ); + }, + + // Keep pipe for back-compat + pipe: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + + return jQuery.Deferred( function( newDefer ) { + jQuery.each( tuples, function( _i, tuple ) { + + // Map tuples (progress, done, fail) to arguments (done, fail, progress) + var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; + + // deferred.progress(function() { bind to newDefer or newDefer.notify }) + // deferred.done(function() { bind to newDefer or newDefer.resolve }) + // deferred.fail(function() { bind to newDefer or newDefer.reject }) + deferred[ tuple[ 1 ] ]( function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && isFunction( returned.promise ) ) { + returned.promise() + .progress( newDefer.notify ) + .done( newDefer.resolve ) + .fail( newDefer.reject ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( + this, + fn ? [ returned ] : arguments + ); + } + } ); + } ); + fns = null; + } ).promise(); + }, + then: function( onFulfilled, onRejected, onProgress ) { + var maxDepth = 0; + function resolve( depth, deferred, handler, special ) { + return function() { + var that = this, + args = arguments, + mightThrow = function() { + var returned, then; + + // Support: Promises/A+ section 2.3.3.3.3 + // https://promisesaplus.com/#point-59 + // Ignore double-resolution attempts + if ( depth < maxDepth ) { + return; + } + + returned = handler.apply( that, args ); + + // Support: Promises/A+ section 2.3.1 + // https://promisesaplus.com/#point-48 + if ( returned === deferred.promise() ) { + throw new TypeError( "Thenable self-resolution" ); + } + + // Support: Promises/A+ sections 2.3.3.1, 3.5 + // https://promisesaplus.com/#point-54 + // https://promisesaplus.com/#point-75 + // Retrieve `then` only once + then = returned && + + // Support: Promises/A+ section 2.3.4 + // https://promisesaplus.com/#point-64 + // Only check objects and functions for thenability + ( typeof returned === "object" || + typeof returned === "function" ) && + returned.then; + + // Handle a returned thenable + if ( isFunction( then ) ) { + + // Special processors (notify) just wait for resolution + if ( special ) { + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ) + ); + + // Normal processors (resolve) also hook into progress + } else { + + // ...and disregard older resolution values + maxDepth++; + + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ), + resolve( maxDepth, deferred, Identity, + deferred.notifyWith ) + ); + } + + // Handle all other returned values + } else { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Identity ) { + that = undefined; + args = [ returned ]; + } + + // Process the value(s) + // Default process is resolve + ( special || deferred.resolveWith )( that, args ); + } + }, + + // Only normal processors (resolve) catch and reject exceptions + process = special ? + mightThrow : + function() { + try { + mightThrow(); + } catch ( e ) { + + if ( jQuery.Deferred.exceptionHook ) { + jQuery.Deferred.exceptionHook( e, + process.stackTrace ); + } + + // Support: Promises/A+ section 2.3.3.3.4.1 + // https://promisesaplus.com/#point-61 + // Ignore post-resolution exceptions + if ( depth + 1 >= maxDepth ) { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Thrower ) { + that = undefined; + args = [ e ]; + } + + deferred.rejectWith( that, args ); + } + } + }; + + // Support: Promises/A+ section 2.3.3.3.1 + // https://promisesaplus.com/#point-57 + // Re-resolve promises immediately to dodge false rejection from + // subsequent errors + if ( depth ) { + process(); + } else { + + // Call an optional hook to record the stack, in case of exception + // since it's otherwise lost when execution goes async + if ( jQuery.Deferred.getStackHook ) { + process.stackTrace = jQuery.Deferred.getStackHook(); + } + window.setTimeout( process ); + } + }; + } + + return jQuery.Deferred( function( newDefer ) { + + // progress_handlers.add( ... ) + tuples[ 0 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onProgress ) ? + onProgress : + Identity, + newDefer.notifyWith + ) + ); + + // fulfilled_handlers.add( ... ) + tuples[ 1 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onFulfilled ) ? + onFulfilled : + Identity + ) + ); + + // rejected_handlers.add( ... ) + tuples[ 2 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onRejected ) ? + onRejected : + Thrower + ) + ); + } ).promise(); + }, + + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 5 ]; + + // promise.progress = list.add + // promise.done = list.add + // promise.fail = list.add + promise[ tuple[ 1 ] ] = list.add; + + // Handle state + if ( stateString ) { + list.add( + function() { + + // state = "resolved" (i.e., fulfilled) + // state = "rejected" + state = stateString; + }, + + // rejected_callbacks.disable + // fulfilled_callbacks.disable + tuples[ 3 - i ][ 2 ].disable, + + // rejected_handlers.disable + // fulfilled_handlers.disable + tuples[ 3 - i ][ 3 ].disable, + + // progress_callbacks.lock + tuples[ 0 ][ 2 ].lock, + + // progress_handlers.lock + tuples[ 0 ][ 3 ].lock + ); + } + + // progress_handlers.fire + // fulfilled_handlers.fire + // rejected_handlers.fire + list.add( tuple[ 3 ].fire ); + + // deferred.notify = function() { deferred.notifyWith(...) } + // deferred.resolve = function() { deferred.resolveWith(...) } + // deferred.reject = function() { deferred.rejectWith(...) } + deferred[ tuple[ 0 ] ] = function() { + deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); + return this; + }; + + // deferred.notifyWith = list.fireWith + // deferred.resolveWith = list.fireWith + // deferred.rejectWith = list.fireWith + deferred[ tuple[ 0 ] + "With" ] = list.fireWith; + } ); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( singleValue ) { + var + + // count of uncompleted subordinates + remaining = arguments.length, + + // count of unprocessed arguments + i = remaining, + + // subordinate fulfillment data + resolveContexts = Array( i ), + resolveValues = slice.call( arguments ), + + // the master Deferred + master = jQuery.Deferred(), + + // subordinate callback factory + updateFunc = function( i ) { + return function( value ) { + resolveContexts[ i ] = this; + resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( !( --remaining ) ) { + master.resolveWith( resolveContexts, resolveValues ); + } + }; + }; + + // Single- and empty arguments are adopted like Promise.resolve + if ( remaining <= 1 ) { + adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, + !remaining ); + + // Use .then() to unwrap secondary thenables (cf. gh-3000) + if ( master.state() === "pending" || + isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { + + return master.then(); + } + } + + // Multiple arguments are aggregated like Promise.all array elements + while ( i-- ) { + adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); + } + + return master.promise(); + } +} ); + + +// These usually indicate a programmer mistake during development, +// warn about them ASAP rather than swallowing them by default. +var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; + +jQuery.Deferred.exceptionHook = function( error, stack ) { + + // Support: IE 8 - 9 only + // Console exists when dev tools are open, which can happen at any time + if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { + window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); + } +}; + + + + +jQuery.readyException = function( error ) { + window.setTimeout( function() { + throw error; + } ); +}; + + + + +// The deferred used on DOM ready +var readyList = jQuery.Deferred(); + +jQuery.fn.ready = function( fn ) { + + readyList + .then( fn ) + + // Wrap jQuery.readyException in a function so that the lookup + // happens at the time of error handling instead of callback + // registration. + .catch( function( error ) { + jQuery.readyException( error ); + } ); + + return this; +}; + +jQuery.extend( { + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + } +} ); + +jQuery.ready.then = readyList.then; + +// The ready event handler and self cleanup method +function completed() { + document.removeEventListener( "DOMContentLoaded", completed ); + window.removeEventListener( "load", completed ); + jQuery.ready(); +} + +// Catch cases where $(document).ready() is called +// after the browser event has already occurred. +// Support: IE <=9 - 10 only +// Older IE sometimes signals "interactive" too soon +if ( document.readyState === "complete" || + ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { + + // Handle it asynchronously to allow scripts the opportunity to delay ready + window.setTimeout( jQuery.ready ); + +} else { + + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed ); +} + + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + len = elems.length, + bulk = key == null; + + // Sets many values + if ( toType( key ) === "object" ) { + chainable = true; + for ( i in key ) { + access( elems, fn, i, key[ i ], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, _key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < len; i++ ) { + fn( + elems[ i ], key, raw ? + value : + value.call( elems[ i ], i, fn( elems[ i ], key ) ) + ); + } + } + } + + if ( chainable ) { + return elems; + } + + // Gets + if ( bulk ) { + return fn.call( elems ); + } + + return len ? fn( elems[ 0 ], key ) : emptyGet; +}; + + +// Matches dashed string for camelizing +var rmsPrefix = /^-ms-/, + rdashAlpha = /-([a-z])/g; + +// Used by camelCase as callback to replace() +function fcamelCase( _all, letter ) { + return letter.toUpperCase(); +} + +// Convert dashed to camelCase; used by the css and data modules +// Support: IE <=9 - 11, Edge 12 - 15 +// Microsoft forgot to hump their vendor prefix (#9572) +function camelCase( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); +} +var acceptData = function( owner ) { + + // Accepts only: + // - Node + // - Node.ELEMENT_NODE + // - Node.DOCUMENT_NODE + // - Object + // - Any + return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); +}; + + + + +function Data() { + this.expando = jQuery.expando + Data.uid++; +} + +Data.uid = 1; + +Data.prototype = { + + cache: function( owner ) { + + // Check if the owner object already has a cache + var value = owner[ this.expando ]; + + // If not, create one + if ( !value ) { + value = {}; + + // We can accept data for non-element nodes in modern browsers, + // but we should not, see #8335. + // Always return an empty object. + if ( acceptData( owner ) ) { + + // If it is a node unlikely to be stringify-ed or looped over + // use plain assignment + if ( owner.nodeType ) { + owner[ this.expando ] = value; + + // Otherwise secure it in a non-enumerable property + // configurable must be true to allow the property to be + // deleted when data is removed + } else { + Object.defineProperty( owner, this.expando, { + value: value, + configurable: true + } ); + } + } + } + + return value; + }, + set: function( owner, data, value ) { + var prop, + cache = this.cache( owner ); + + // Handle: [ owner, key, value ] args + // Always use camelCase key (gh-2257) + if ( typeof data === "string" ) { + cache[ camelCase( data ) ] = value; + + // Handle: [ owner, { properties } ] args + } else { + + // Copy the properties one-by-one to the cache object + for ( prop in data ) { + cache[ camelCase( prop ) ] = data[ prop ]; + } + } + return cache; + }, + get: function( owner, key ) { + return key === undefined ? + this.cache( owner ) : + + // Always use camelCase key (gh-2257) + owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; + }, + access: function( owner, key, value ) { + + // In cases where either: + // + // 1. No key was specified + // 2. A string key was specified, but no value provided + // + // Take the "read" path and allow the get method to determine + // which value to return, respectively either: + // + // 1. The entire cache object + // 2. The data stored at the key + // + if ( key === undefined || + ( ( key && typeof key === "string" ) && value === undefined ) ) { + + return this.get( owner, key ); + } + + // When the key is not a string, or both a key and value + // are specified, set or extend (existing objects) with either: + // + // 1. An object of properties + // 2. A key and value + // + this.set( owner, key, value ); + + // Since the "set" path can have two possible entry points + // return the expected data based on which path was taken[*] + return value !== undefined ? value : key; + }, + remove: function( owner, key ) { + var i, + cache = owner[ this.expando ]; + + if ( cache === undefined ) { + return; + } + + if ( key !== undefined ) { + + // Support array or space separated string of keys + if ( Array.isArray( key ) ) { + + // If key is an array of keys... + // We always set camelCase keys, so remove that. + key = key.map( camelCase ); + } else { + key = camelCase( key ); + + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + key = key in cache ? + [ key ] : + ( key.match( rnothtmlwhite ) || [] ); + } + + i = key.length; + + while ( i-- ) { + delete cache[ key[ i ] ]; + } + } + + // Remove the expando if there's no more data + if ( key === undefined || jQuery.isEmptyObject( cache ) ) { + + // Support: Chrome <=35 - 45 + // Webkit & Blink performance suffers when deleting properties + // from DOM nodes, so set to undefined instead + // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) + if ( owner.nodeType ) { + owner[ this.expando ] = undefined; + } else { + delete owner[ this.expando ]; + } + } + }, + hasData: function( owner ) { + var cache = owner[ this.expando ]; + return cache !== undefined && !jQuery.isEmptyObject( cache ); + } +}; +var dataPriv = new Data(); + +var dataUser = new Data(); + + + +// Implementation Summary +// +// 1. Enforce API surface and semantic compatibility with 1.9.x branch +// 2. Improve the module's maintainability by reducing the storage +// paths to a single mechanism. +// 3. Use the same single mechanism to support "private" and "user" data. +// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) +// 5. Avoid exposing implementation details on user objects (eg. expando properties) +// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /[A-Z]/g; + +function getData( data ) { + if ( data === "true" ) { + return true; + } + + if ( data === "false" ) { + return false; + } + + if ( data === "null" ) { + return null; + } + + // Only convert to a number if it doesn't change the string + if ( data === +data + "" ) { + return +data; + } + + if ( rbrace.test( data ) ) { + return JSON.parse( data ); + } + + return data; +} + +function dataAttr( elem, key, data ) { + var name; + + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = getData( data ); + } catch ( e ) {} + + // Make sure we set the data so it isn't changed later + dataUser.set( elem, key, data ); + } else { + data = undefined; + } + } + return data; +} + +jQuery.extend( { + hasData: function( elem ) { + return dataUser.hasData( elem ) || dataPriv.hasData( elem ); + }, + + data: function( elem, name, data ) { + return dataUser.access( elem, name, data ); + }, + + removeData: function( elem, name ) { + dataUser.remove( elem, name ); + }, + + // TODO: Now that all calls to _data and _removeData have been replaced + // with direct calls to dataPriv methods, these can be deprecated. + _data: function( elem, name, data ) { + return dataPriv.access( elem, name, data ); + }, + + _removeData: function( elem, name ) { + dataPriv.remove( elem, name ); + } +} ); + +jQuery.fn.extend( { + data: function( key, value ) { + var i, name, data, + elem = this[ 0 ], + attrs = elem && elem.attributes; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = dataUser.get( elem ); + + if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE 11 only + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = camelCase( name.slice( 5 ) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + dataPriv.set( elem, "hasDataAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each( function() { + dataUser.set( this, key ); + } ); + } + + return access( this, function( value ) { + var data; + + // The calling jQuery object (element matches) is not empty + // (and therefore has an element appears at this[ 0 ]) and the + // `value` parameter was not undefined. An empty jQuery object + // will result in `undefined` for elem = this[ 0 ] which will + // throw an exception if an attempt to read a data cache is made. + if ( elem && value === undefined ) { + + // Attempt to get data from the cache + // The key will always be camelCased in Data + data = dataUser.get( elem, key ); + if ( data !== undefined ) { + return data; + } + + // Attempt to "discover" the data in + // HTML5 custom data-* attrs + data = dataAttr( elem, key ); + if ( data !== undefined ) { + return data; + } + + // We tried really hard, but the data doesn't exist. + return; + } + + // Set the data... + this.each( function() { + + // We always store the camelCased key + dataUser.set( this, key, value ); + } ); + }, null, value, arguments.length > 1, null, true ); + }, + + removeData: function( key ) { + return this.each( function() { + dataUser.remove( this, key ); + } ); + } +} ); + + +jQuery.extend( { + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = dataPriv.get( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || Array.isArray( data ) ) { + queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // Clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // Not public - generate a queueHooks object, or return the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { + empty: jQuery.Callbacks( "once memory" ).add( function() { + dataPriv.remove( elem, [ type + "queue", key ] ); + } ) + } ); + } +} ); + +jQuery.fn.extend( { + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[ 0 ], type ); + } + + return data === undefined ? + this : + this.each( function() { + var queue = jQuery.queue( this, type, data ); + + // Ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + } ); + }, + dequeue: function( type ) { + return this.each( function() { + jQuery.dequeue( this, type ); + } ); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while ( i-- ) { + tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +} ); +var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; + +var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); + + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +var documentElement = document.documentElement; + + + + var isAttached = function( elem ) { + return jQuery.contains( elem.ownerDocument, elem ); + }, + composed = { composed: true }; + + // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only + // Check attachment across shadow DOM boundaries when possible (gh-3504) + // Support: iOS 10.0-10.2 only + // Early iOS 10 versions support `attachShadow` but not `getRootNode`, + // leading to errors. We need to check for `getRootNode`. + if ( documentElement.getRootNode ) { + isAttached = function( elem ) { + return jQuery.contains( elem.ownerDocument, elem ) || + elem.getRootNode( composed ) === elem.ownerDocument; + }; + } +var isHiddenWithinTree = function( elem, el ) { + + // isHiddenWithinTree might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + + // Inline style trumps all + return elem.style.display === "none" || + elem.style.display === "" && + + // Otherwise, check computed style + // Support: Firefox <=43 - 45 + // Disconnected elements can have computed display: none, so first confirm that elem is + // in the document. + isAttached( elem ) && + + jQuery.css( elem, "display" ) === "none"; + }; + + + +function adjustCSS( elem, prop, valueParts, tween ) { + var adjusted, scale, + maxIterations = 20, + currentValue = tween ? + function() { + return tween.cur(); + } : + function() { + return jQuery.css( elem, prop, "" ); + }, + initial = currentValue(), + unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), + + // Starting value computation is required for potential unit mismatches + initialInUnit = elem.nodeType && + ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && + rcssNum.exec( jQuery.css( elem, prop ) ); + + if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { + + // Support: Firefox <=54 + // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144) + initial = initial / 2; + + // Trust units reported by jQuery.css + unit = unit || initialInUnit[ 3 ]; + + // Iteratively approximate from a nonzero starting point + initialInUnit = +initial || 1; + + while ( maxIterations-- ) { + + // Evaluate and update our best guess (doubling guesses that zero out). + // Finish if the scale equals or crosses 1 (making the old*new product non-positive). + jQuery.style( elem, prop, initialInUnit + unit ); + if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) { + maxIterations = 0; + } + initialInUnit = initialInUnit / scale; + + } + + initialInUnit = initialInUnit * 2; + jQuery.style( elem, prop, initialInUnit + unit ); + + // Make sure we update the tween properties later on + valueParts = valueParts || []; + } + + if ( valueParts ) { + initialInUnit = +initialInUnit || +initial || 0; + + // Apply relative offset (+=/-=) if specified + adjusted = valueParts[ 1 ] ? + initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : + +valueParts[ 2 ]; + if ( tween ) { + tween.unit = unit; + tween.start = initialInUnit; + tween.end = adjusted; + } + } + return adjusted; +} + + +var defaultDisplayMap = {}; + +function getDefaultDisplay( elem ) { + var temp, + doc = elem.ownerDocument, + nodeName = elem.nodeName, + display = defaultDisplayMap[ nodeName ]; + + if ( display ) { + return display; + } + + temp = doc.body.appendChild( doc.createElement( nodeName ) ); + display = jQuery.css( temp, "display" ); + + temp.parentNode.removeChild( temp ); + + if ( display === "none" ) { + display = "block"; + } + defaultDisplayMap[ nodeName ] = display; + + return display; +} + +function showHide( elements, show ) { + var display, elem, + values = [], + index = 0, + length = elements.length; + + // Determine new display value for elements that need to change + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + + display = elem.style.display; + if ( show ) { + + // Since we force visibility upon cascade-hidden elements, an immediate (and slow) + // check is required in this first loop unless we have a nonempty display value (either + // inline or about-to-be-restored) + if ( display === "none" ) { + values[ index ] = dataPriv.get( elem, "display" ) || null; + if ( !values[ index ] ) { + elem.style.display = ""; + } + } + if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { + values[ index ] = getDefaultDisplay( elem ); + } + } else { + if ( display !== "none" ) { + values[ index ] = "none"; + + // Remember what we're overwriting + dataPriv.set( elem, "display", display ); + } + } + } + + // Set the display of the elements in a second loop to avoid constant reflow + for ( index = 0; index < length; index++ ) { + if ( values[ index ] != null ) { + elements[ index ].style.display = values[ index ]; + } + } + + return elements; +} + +jQuery.fn.extend( { + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state ) { + if ( typeof state === "boolean" ) { + return state ? this.show() : this.hide(); + } + + return this.each( function() { + if ( isHiddenWithinTree( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + } ); + } +} ); +var rcheckableType = ( /^(?:checkbox|radio)$/i ); + +var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i ); + +var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); + + + +( function() { + var fragment = document.createDocumentFragment(), + div = fragment.appendChild( document.createElement( "div" ) ), + input = document.createElement( "input" ); + + // Support: Android 4.0 - 4.3 only + // Check state lost if the name is set (#11217) + // Support: Windows Web Apps (WWA) + // `name` and `type` must use .setAttribute for WWA (#14901) + input.setAttribute( "type", "radio" ); + input.setAttribute( "checked", "checked" ); + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + + // Support: Android <=4.1 only + // Older WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE <=11 only + // Make sure textarea (and checkbox) defaultValue is properly cloned + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; + + // Support: IE <=9 only + // IE <=9 replaces "; + support.option = !!div.lastChild; +} )(); + + +// We have to close these tags to support XHTML (#13200) +var wrapMap = { + + // XHTML parsers do not magically insert elements in the + // same way that tag soup parsers do. So we cannot shorten + // this by omitting or other required elements. + thead: [ 1, "", "
" ], + col: [ 2, "", "
" ], + tr: [ 2, "", "
" ], + td: [ 3, "", "
" ], + + _default: [ 0, "", "" ] +}; + +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// Support: IE <=9 only +if ( !support.option ) { + wrapMap.optgroup = wrapMap.option = [ 1, "" ]; +} + + +function getAll( context, tag ) { + + // Support: IE <=9 - 11 only + // Use typeof to avoid zero-argument method invocation on host objects (#15151) + var ret; + + if ( typeof context.getElementsByTagName !== "undefined" ) { + ret = context.getElementsByTagName( tag || "*" ); + + } else if ( typeof context.querySelectorAll !== "undefined" ) { + ret = context.querySelectorAll( tag || "*" ); + + } else { + ret = []; + } + + if ( tag === undefined || tag && nodeName( context, tag ) ) { + return jQuery.merge( [ context ], ret ); + } + + return ret; +} + + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + dataPriv.set( + elems[ i ], + "globalEval", + !refElements || dataPriv.get( refElements[ i ], "globalEval" ) + ); + } +} + + +var rhtml = /<|&#?\w+;/; + +function buildFragment( elems, context, scripts, selection, ignored ) { + var elem, tmp, tag, wrap, attached, j, + fragment = context.createDocumentFragment(), + nodes = [], + i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( toType( elem ) === "object" ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; + + // Descend through wrappers to the right content + j = wrap[ 0 ]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, tmp.childNodes ); + + // Remember the top-level container + tmp = fragment.firstChild; + + // Ensure the created nodes are orphaned (#12392) + tmp.textContent = ""; + } + } + } + + // Remove wrapper from fragment + fragment.textContent = ""; + + i = 0; + while ( ( elem = nodes[ i++ ] ) ) { + + // Skip elements already in the context collection (trac-4087) + if ( selection && jQuery.inArray( elem, selection ) > -1 ) { + if ( ignored ) { + ignored.push( elem ); + } + continue; + } + + attached = isAttached( elem ); + + // Append to fragment + tmp = getAll( fragment.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( attached ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( ( elem = tmp[ j++ ] ) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + return fragment; +} + + +var + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +// Support: IE <=9 - 11+ +// focus() and blur() are asynchronous, except when they are no-op. +// So expect focus to be synchronous when the element is already active, +// and blur to be synchronous when the element is not already active. +// (focus and blur are always synchronous in other supported browsers, +// this just defines when we can count on it). +function expectSync( elem, type ) { + return ( elem === safeActiveElement() ) === ( type === "focus" ); +} + +// Support: IE <=9 only +// Accessing document.activeElement can throw unexpectedly +// https://bugs.jquery.com/ticket/13393 +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +function on( elem, types, selector, data, fn, one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + on( elem, type, selector, data, types[ type ], one ); + } + return elem; + } + + if ( data == null && fn == null ) { + + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return elem; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return elem.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + } ); +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + + var handleObjIn, eventHandle, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.get( elem ); + + // Only attach events to objects that accept data + if ( !acceptData( elem ) ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Ensure that invalid selectors throw exceptions at attach time + // Evaluate against documentElement in case elem is a non-element node (e.g., document) + if ( selector ) { + jQuery.find.matchesSelector( documentElement, selector ); + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !( events = elemData.events ) ) { + events = elemData.events = Object.create( null ); + } + if ( !( eventHandle = elemData.handle ) ) { + eventHandle = elemData.handle = function( e ) { + + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? + jQuery.event.dispatch.apply( elem, arguments ) : undefined; + }; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend( { + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join( "." ) + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !( handlers = events[ type ] ) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener if the special events handler returns false + if ( !special.setup || + special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var j, origCount, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); + + if ( !elemData || !( events = elemData.events ) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[ 2 ] && + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || + selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || + special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove data and the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + dataPriv.remove( elem, "handle events" ); + } + }, + + dispatch: function( nativeEvent ) { + + var i, j, ret, matched, handleObj, handlerQueue, + args = new Array( arguments.length ), + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( nativeEvent ), + + handlers = ( + dataPriv.get( this, "events" ) || Object.create( null ) + )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[ 0 ] = event; + + for ( i = 1; i < arguments.length; i++ ) { + args[ i ] = arguments[ i ]; + } + + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( ( handleObj = matched.handlers[ j++ ] ) && + !event.isImmediatePropagationStopped() ) { + + // If the event is namespaced, then each handler is only invoked if it is + // specially universal or its namespaces are a superset of the event's. + if ( !event.rnamespace || handleObj.namespace === false || + event.rnamespace.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || + handleObj.handler ).apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( ( event.result = ret ) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var i, handleObj, sel, matchedHandlers, matchedSelectors, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + if ( delegateCount && + + // Support: IE <=9 + // Black-hole SVG instance trees (trac-13180) + cur.nodeType && + + // Support: Firefox <=42 + // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) + // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click + // Support: IE 11 only + // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) + !( event.type === "click" && event.button >= 1 ) ) { + + for ( ; cur !== this; cur = cur.parentNode || this ) { + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { + matchedHandlers = []; + matchedSelectors = {}; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matchedSelectors[ sel ] === undefined ) { + matchedSelectors[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) > -1 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matchedSelectors[ sel ] ) { + matchedHandlers.push( handleObj ); + } + } + if ( matchedHandlers.length ) { + handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); + } + } + } + } + + // Add the remaining (directly-bound) handlers + cur = this; + if ( delegateCount < handlers.length ) { + handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); + } + + return handlerQueue; + }, + + addProp: function( name, hook ) { + Object.defineProperty( jQuery.Event.prototype, name, { + enumerable: true, + configurable: true, + + get: isFunction( hook ) ? + function() { + if ( this.originalEvent ) { + return hook( this.originalEvent ); + } + } : + function() { + if ( this.originalEvent ) { + return this.originalEvent[ name ]; + } + }, + + set: function( value ) { + Object.defineProperty( this, name, { + enumerable: true, + configurable: true, + writable: true, + value: value + } ); + } + } ); + }, + + fix: function( originalEvent ) { + return originalEvent[ jQuery.expando ] ? + originalEvent : + new jQuery.Event( originalEvent ); + }, + + special: { + load: { + + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + click: { + + // Utilize native event to ensure correct state for checkable inputs + setup: function( data ) { + + // For mutual compressibility with _default, replace `this` access with a local var. + // `|| data` is dead code meant only to preserve the variable through minification. + var el = this || data; + + // Claim the first handler + if ( rcheckableType.test( el.type ) && + el.click && nodeName( el, "input" ) ) { + + // dataPriv.set( el, "click", ... ) + leverageNative( el, "click", returnTrue ); + } + + // Return false to allow normal processing in the caller + return false; + }, + trigger: function( data ) { + + // For mutual compressibility with _default, replace `this` access with a local var. + // `|| data` is dead code meant only to preserve the variable through minification. + var el = this || data; + + // Force setup before triggering a click + if ( rcheckableType.test( el.type ) && + el.click && nodeName( el, "input" ) ) { + + leverageNative( el, "click" ); + } + + // Return non-false to allow normal event-path propagation + return true; + }, + + // For cross-browser consistency, suppress native .click() on links + // Also prevent it if we're currently inside a leveraged native-event stack + _default: function( event ) { + var target = event.target; + return rcheckableType.test( target.type ) && + target.click && nodeName( target, "input" ) && + dataPriv.get( target, "click" ) || + nodeName( target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + } +}; + +// Ensure the presence of an event listener that handles manually-triggered +// synthetic events by interrupting progress until reinvoked in response to +// *native* events that it fires directly, ensuring that state changes have +// already occurred before other listeners are invoked. +function leverageNative( el, type, expectSync ) { + + // Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add + if ( !expectSync ) { + if ( dataPriv.get( el, type ) === undefined ) { + jQuery.event.add( el, type, returnTrue ); + } + return; + } + + // Register the controller as a special universal handler for all event namespaces + dataPriv.set( el, type, false ); + jQuery.event.add( el, type, { + namespace: false, + handler: function( event ) { + var notAsync, result, + saved = dataPriv.get( this, type ); + + if ( ( event.isTrigger & 1 ) && this[ type ] ) { + + // Interrupt processing of the outer synthetic .trigger()ed event + // Saved data should be false in such cases, but might be a leftover capture object + // from an async native handler (gh-4350) + if ( !saved.length ) { + + // Store arguments for use when handling the inner native event + // There will always be at least one argument (an event object), so this array + // will not be confused with a leftover capture object. + saved = slice.call( arguments ); + dataPriv.set( this, type, saved ); + + // Trigger the native event and capture its result + // Support: IE <=9 - 11+ + // focus() and blur() are asynchronous + notAsync = expectSync( this, type ); + this[ type ](); + result = dataPriv.get( this, type ); + if ( saved !== result || notAsync ) { + dataPriv.set( this, type, false ); + } else { + result = {}; + } + if ( saved !== result ) { + + // Cancel the outer synthetic event + event.stopImmediatePropagation(); + event.preventDefault(); + return result.value; + } + + // If this is an inner synthetic event for an event with a bubbling surrogate + // (focus or blur), assume that the surrogate already propagated from triggering the + // native event and prevent that from happening again here. + // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the + // bubbling surrogate propagates *after* the non-bubbling base), but that seems + // less bad than duplication. + } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) { + event.stopPropagation(); + } + + // If this is a native event triggered above, everything is now in order + // Fire an inner synthetic event with the original arguments + } else if ( saved.length ) { + + // ...and capture the result + dataPriv.set( this, type, { + value: jQuery.event.trigger( + + // Support: IE <=9 - 11+ + // Extend with the prototype to reset the above stopImmediatePropagation() + jQuery.extend( saved[ 0 ], jQuery.Event.prototype ), + saved.slice( 1 ), + this + ) + } ); + + // Abort handling of the native event + event.stopImmediatePropagation(); + } + } + } ); +} + +jQuery.removeEvent = function( elem, type, handle ) { + + // This "if" is needed for plain objects + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle ); + } +}; + +jQuery.Event = function( src, props ) { + + // Allow instantiation without the 'new' keyword + if ( !( this instanceof jQuery.Event ) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + + // Support: Android <=2.3 only + src.returnValue === false ? + returnTrue : + returnFalse; + + // Create target properties + // Support: Safari <=6 - 7 only + // Target should not be a text node (#504, #13143) + this.target = ( src.target && src.target.nodeType === 3 ) ? + src.target.parentNode : + src.target; + + this.currentTarget = src.currentTarget; + this.relatedTarget = src.relatedTarget; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || Date.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + constructor: jQuery.Event, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + isSimulated: false, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + + if ( e && !this.isSimulated ) { + e.preventDefault(); + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopPropagation(); + } + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Includes all common event props including KeyEvent and MouseEvent specific props +jQuery.each( { + altKey: true, + bubbles: true, + cancelable: true, + changedTouches: true, + ctrlKey: true, + detail: true, + eventPhase: true, + metaKey: true, + pageX: true, + pageY: true, + shiftKey: true, + view: true, + "char": true, + code: true, + charCode: true, + key: true, + keyCode: true, + button: true, + buttons: true, + clientX: true, + clientY: true, + offsetX: true, + offsetY: true, + pointerId: true, + pointerType: true, + screenX: true, + screenY: true, + targetTouches: true, + toElement: true, + touches: true, + + which: function( event ) { + var button = event.button; + + // Add which for key events + if ( event.which == null && rkeyEvent.test( event.type ) ) { + return event.charCode != null ? event.charCode : event.keyCode; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { + if ( button & 1 ) { + return 1; + } + + if ( button & 2 ) { + return 3; + } + + if ( button & 4 ) { + return 2; + } + + return 0; + } + + return event.which; + } +}, jQuery.event.addProp ); + +jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) { + jQuery.event.special[ type ] = { + + // Utilize native event if possible so blur/focus sequence is correct + setup: function() { + + // Claim the first handler + // dataPriv.set( this, "focus", ... ) + // dataPriv.set( this, "blur", ... ) + leverageNative( this, type, expectSync ); + + // Return false to allow normal processing in the caller + return false; + }, + trigger: function() { + + // Force setup before trigger + leverageNative( this, type ); + + // Return non-false to allow normal event-path propagation + return true; + }, + + delegateType: delegateType + }; +} ); + +// Create mouseenter/leave events using mouseover/out and event-time checks +// so that event delegation works in jQuery. +// Do the same for pointerenter/pointerleave and pointerover/pointerout +// +// Support: Safari 7 only +// Safari sends mouseenter too often; see: +// https://bugs.chromium.org/p/chromium/issues/detail?id=470258 +// for the description of the bug (it existed in older Chrome versions as well). +jQuery.each( { + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mouseenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +} ); + +jQuery.fn.extend( { + + on: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn ); + }, + one: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? + handleObj.origType + "." + handleObj.namespace : + handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each( function() { + jQuery.event.remove( this, types, fn, selector ); + } ); + } +} ); + + +var + + // Support: IE <=10 - 11, Edge 12 - 13 only + // In IE/Edge using regex groups here causes severe slowdowns. + // See https://connect.microsoft.com/IE/feedback/details/1736512/ + rnoInnerhtml = /\s*$/g; + +// Prefer a tbody over its parent table for containing new rows +function manipulationTarget( elem, content ) { + if ( nodeName( elem, "table" ) && + nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { + + return jQuery( elem ).children( "tbody" )[ 0 ] || elem; + } + + return elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { + elem.type = elem.type.slice( 5 ); + } else { + elem.removeAttribute( "type" ); + } + + return elem; +} + +function cloneCopyEvent( src, dest ) { + var i, l, type, pdataOld, udataOld, udataCur, events; + + if ( dest.nodeType !== 1 ) { + return; + } + + // 1. Copy private data: events, handlers, etc. + if ( dataPriv.hasData( src ) ) { + pdataOld = dataPriv.get( src ); + events = pdataOld.events; + + if ( events ) { + dataPriv.remove( dest, "handle events" ); + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + } + + // 2. Copy user data + if ( dataUser.hasData( src ) ) { + udataOld = dataUser.access( src ); + udataCur = jQuery.extend( {}, udataOld ); + + dataUser.set( dest, udataCur ); + } +} + +// Fix IE bugs, see support tests +function fixInput( src, dest ) { + var nodeName = dest.nodeName.toLowerCase(); + + // Fails to persist the checked state of a cloned checkbox or radio button. + if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + dest.checked = src.checked; + + // Fails to return the selected option to the default selected state when cloning options + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +function domManip( collection, args, callback, ignored ) { + + // Flatten any nested arrays + args = flat( args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = collection.length, + iNoClone = l - 1, + value = args[ 0 ], + valueIsFunction = isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( valueIsFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return collection.each( function( index ) { + var self = collection.eq( index ); + if ( valueIsFunction ) { + args[ 0 ] = value.call( this, index, self.html() ); + } + domManip( self, args, callback, ignored ); + } ); + } + + if ( l ) { + fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + // Require either new content or an interest in ignored elements to invoke the callback + if ( first || ignored ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item + // instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( collection[ i ], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !dataPriv.access( node, "globalEval" ) && + jQuery.contains( doc, node ) ) { + + if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { + + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl && !node.noModule ) { + jQuery._evalUrl( node.src, { + nonce: node.nonce || node.getAttribute( "nonce" ) + }, doc ); + } + } else { + DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc ); + } + } + } + } + } + } + + return collection; +} + +function remove( elem, selector, keepData ) { + var node, + nodes = selector ? jQuery.filter( selector, elem ) : elem, + i = 0; + + for ( ; ( node = nodes[ i ] ) != null; i++ ) { + if ( !keepData && node.nodeType === 1 ) { + jQuery.cleanData( getAll( node ) ); + } + + if ( node.parentNode ) { + if ( keepData && isAttached( node ) ) { + setGlobalEval( getAll( node, "script" ) ); + } + node.parentNode.removeChild( node ); + } + } + + return elem; +} + +jQuery.extend( { + htmlPrefilter: function( html ) { + return html; + }, + + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var i, l, srcElements, destElements, + clone = elem.cloneNode( true ), + inPage = isAttached( elem ); + + // Fix IE cloning issues + if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && + !jQuery.isXMLDoc( elem ) ) { + + // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + fixInput( srcElements[ i ], destElements[ i ] ); + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + cloneCopyEvent( srcElements[ i ], destElements[ i ] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + // Return the cloned set + return clone; + }, + + cleanData: function( elems ) { + var data, elem, type, + special = jQuery.event.special, + i = 0; + + for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { + if ( acceptData( elem ) ) { + if ( ( data = elem[ dataPriv.expando ] ) ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataPriv.expando ] = undefined; + } + if ( elem[ dataUser.expando ] ) { + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataUser.expando ] = undefined; + } + } + } + } +} ); + +jQuery.fn.extend( { + detach: function( selector ) { + return remove( this, selector, true ); + }, + + remove: function( selector ) { + return remove( this, selector ); + }, + + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().each( function() { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.textContent = value; + } + } ); + }, null, value, arguments.length ); + }, + + append: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + } ); + }, + + prepend: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + } ); + }, + + before: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + } ); + }, + + after: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + } ); + }, + + empty: function() { + var elem, + i = 0; + + for ( ; ( elem = this[ i ] ) != null; i++ ) { + if ( elem.nodeType === 1 ) { + + // Prevent memory leaks + jQuery.cleanData( getAll( elem, false ) ); + + // Remove any remaining nodes + elem.textContent = ""; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + } ); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined && elem.nodeType === 1 ) { + return elem.innerHTML; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { + + value = jQuery.htmlPrefilter( value ); + + try { + for ( ; i < l; i++ ) { + elem = this[ i ] || {}; + + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch ( e ) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var ignored = []; + + // Make the changes, replacing each non-ignored context element with the new content + return domManip( this, arguments, function( elem ) { + var parent = this.parentNode; + + if ( jQuery.inArray( this, ignored ) < 0 ) { + jQuery.cleanData( getAll( this ) ); + if ( parent ) { + parent.replaceChild( elem, this ); + } + } + + // Force callback invocation + }, ignored ); + } +} ); + +jQuery.each( { + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1, + i = 0; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone( true ); + jQuery( insert[ i ] )[ original ]( elems ); + + // Support: Android <=4.0 only, PhantomJS 1 only + // .get() because push.apply(_, arraylike) throws on ancient WebKit + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +} ); +var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); + +var getStyles = function( elem ) { + + // Support: IE <=11 only, Firefox <=30 (#15098, #14150) + // IE throws on elements created in popups + // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" + var view = elem.ownerDocument.defaultView; + + if ( !view || !view.opener ) { + view = window; + } + + return view.getComputedStyle( elem ); + }; + +var swap = function( elem, options, callback ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.call( elem ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; +}; + + +var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); + + + +( function() { + + // Executing both pixelPosition & boxSizingReliable tests require only one layout + // so they're executed at the same time to save the second computation. + function computeStyleTests() { + + // This is a singleton, we need to execute it only once + if ( !div ) { + return; + } + + container.style.cssText = "position:absolute;left:-11111px;width:60px;" + + "margin-top:1px;padding:0;border:0"; + div.style.cssText = + "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + + "margin:auto;border:1px;padding:1px;" + + "width:60%;top:1%"; + documentElement.appendChild( container ).appendChild( div ); + + var divStyle = window.getComputedStyle( div ); + pixelPositionVal = divStyle.top !== "1%"; + + // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 + reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; + + // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3 + // Some styles come back with percentage values, even though they shouldn't + div.style.right = "60%"; + pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36; + + // Support: IE 9 - 11 only + // Detect misreporting of content dimensions for box-sizing:border-box elements + boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36; + + // Support: IE 9 only + // Detect overflow:scroll screwiness (gh-3699) + // Support: Chrome <=64 + // Don't get tricked when zoom affects offsetWidth (gh-4029) + div.style.position = "absolute"; + scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12; + + documentElement.removeChild( container ); + + // Nullify the div so it wouldn't be stored in the memory and + // it will also be a sign that checks already performed + div = null; + } + + function roundPixelMeasures( measure ) { + return Math.round( parseFloat( measure ) ); + } + + var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, + reliableTrDimensionsVal, reliableMarginLeftVal, + container = document.createElement( "div" ), + div = document.createElement( "div" ); + + // Finish early in limited (non-browser) environments + if ( !div.style ) { + return; + } + + // Support: IE <=9 - 11 only + // Style of cloned element affects source element cloned (#8908) + div.style.backgroundClip = "content-box"; + div.cloneNode( true ).style.backgroundClip = ""; + support.clearCloneStyle = div.style.backgroundClip === "content-box"; + + jQuery.extend( support, { + boxSizingReliable: function() { + computeStyleTests(); + return boxSizingReliableVal; + }, + pixelBoxStyles: function() { + computeStyleTests(); + return pixelBoxStylesVal; + }, + pixelPosition: function() { + computeStyleTests(); + return pixelPositionVal; + }, + reliableMarginLeft: function() { + computeStyleTests(); + return reliableMarginLeftVal; + }, + scrollboxSize: function() { + computeStyleTests(); + return scrollboxSizeVal; + }, + + // Support: IE 9 - 11+, Edge 15 - 18+ + // IE/Edge misreport `getComputedStyle` of table rows with width/height + // set in CSS while `offset*` properties report correct values. + // Behavior in IE 9 is more subtle than in newer versions & it passes + // some versions of this test; make sure not to make it pass there! + reliableTrDimensions: function() { + var table, tr, trChild, trStyle; + if ( reliableTrDimensionsVal == null ) { + table = document.createElement( "table" ); + tr = document.createElement( "tr" ); + trChild = document.createElement( "div" ); + + table.style.cssText = "position:absolute;left:-11111px"; + tr.style.height = "1px"; + trChild.style.height = "9px"; + + documentElement + .appendChild( table ) + .appendChild( tr ) + .appendChild( trChild ); + + trStyle = window.getComputedStyle( tr ); + reliableTrDimensionsVal = parseInt( trStyle.height ) > 3; + + documentElement.removeChild( table ); + } + return reliableTrDimensionsVal; + } + } ); +} )(); + + +function curCSS( elem, name, computed ) { + var width, minWidth, maxWidth, ret, + + // Support: Firefox 51+ + // Retrieving style before computed somehow + // fixes an issue with getting wrong values + // on detached elements + style = elem.style; + + computed = computed || getStyles( elem ); + + // getPropertyValue is needed for: + // .css('filter') (IE 9 only, #12537) + // .css('--customProperty) (#3144) + if ( computed ) { + ret = computed.getPropertyValue( name ) || computed[ name ]; + + if ( ret === "" && !isAttached( elem ) ) { + ret = jQuery.style( elem, name ); + } + + // A tribute to the "awesome hack by Dean Edwards" + // Android Browser returns percentage for some values, + // but width seems to be reliably pixels. + // This is against the CSSOM draft spec: + // https://drafts.csswg.org/cssom/#resolved-values + if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) { + + // Remember the original values + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + // Put in the new values to get a computed value out + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + // Revert the changed values + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret !== undefined ? + + // Support: IE <=9 - 11 only + // IE returns zIndex value as an integer. + ret + "" : + ret; +} + + +function addGetHookIf( conditionFn, hookFn ) { + + // Define the hook, we'll check on the first run if it's really needed. + return { + get: function() { + if ( conditionFn() ) { + + // Hook not needed (or it's not possible to use it due + // to missing dependency), remove it. + delete this.get; + return; + } + + // Hook needed; redefine it so that the support test is not executed again. + return ( this.get = hookFn ).apply( this, arguments ); + } + }; +} + + +var cssPrefixes = [ "Webkit", "Moz", "ms" ], + emptyStyle = document.createElement( "div" ).style, + vendorProps = {}; + +// Return a vendor-prefixed property or undefined +function vendorPropName( name ) { + + // Check for vendor prefixed names + var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in emptyStyle ) { + return name; + } + } +} + +// Return a potentially-mapped jQuery.cssProps or vendor prefixed property +function finalPropName( name ) { + var final = jQuery.cssProps[ name ] || vendorProps[ name ]; + + if ( final ) { + return final; + } + if ( name in emptyStyle ) { + return name; + } + return vendorProps[ name ] = vendorPropName( name ) || name; +} + + +var + + // Swappable if display is none or starts with table + // except "table", "table-cell", or "table-caption" + // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + rcustomProp = /^--/, + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: "0", + fontWeight: "400" + }; + +function setPositiveNumber( _elem, value, subtract ) { + + // Any relative (+/-) values have already been + // normalized at this point + var matches = rcssNum.exec( value ); + return matches ? + + // Guard against undefined "subtract", e.g., when used as in cssHooks + Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : + value; +} + +function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { + var i = dimension === "width" ? 1 : 0, + extra = 0, + delta = 0; + + // Adjustment may not be necessary + if ( box === ( isBorderBox ? "border" : "content" ) ) { + return 0; + } + + for ( ; i < 4; i += 2 ) { + + // Both box models exclude margin + if ( box === "margin" ) { + delta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); + } + + // If we get here with a content-box, we're seeking "padding" or "border" or "margin" + if ( !isBorderBox ) { + + // Add padding + delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + + // For "border" or "margin", add border + if ( box !== "padding" ) { + delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + + // But still keep track of it otherwise + } else { + extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + + // If we get here with a border-box (content + padding + border), we're seeking "content" or + // "padding" or "margin" + } else { + + // For "content", subtract padding + if ( box === "content" ) { + delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } + + // For "content" or "padding", subtract border + if ( box !== "margin" ) { + delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } + } + + // Account for positive content-box scroll gutter when requested by providing computedVal + if ( !isBorderBox && computedVal >= 0 ) { + + // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border + // Assuming integer scroll gutter, subtract the rest and round down + delta += Math.max( 0, Math.ceil( + elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - + computedVal - + delta - + extra - + 0.5 + + // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter + // Use an explicit zero to avoid NaN (gh-3964) + ) ) || 0; + } + + return delta; +} + +function getWidthOrHeight( elem, dimension, extra ) { + + // Start with computed style + var styles = getStyles( elem ), + + // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322). + // Fake content-box until we know it's needed to know the true value. + boxSizingNeeded = !support.boxSizingReliable() || extra, + isBorderBox = boxSizingNeeded && + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + valueIsBorderBox = isBorderBox, + + val = curCSS( elem, dimension, styles ), + offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ); + + // Support: Firefox <=54 + // Return a confounding non-pixel value or feign ignorance, as appropriate. + if ( rnumnonpx.test( val ) ) { + if ( !extra ) { + return val; + } + val = "auto"; + } + + + // Support: IE 9 - 11 only + // Use offsetWidth/offsetHeight for when box sizing is unreliable. + // In those cases, the computed value can be trusted to be border-box. + if ( ( !support.boxSizingReliable() && isBorderBox || + + // Support: IE 10 - 11+, Edge 15 - 18+ + // IE/Edge misreport `getComputedStyle` of table rows with width/height + // set in CSS while `offset*` properties report correct values. + // Interestingly, in some cases IE 9 doesn't suffer from this issue. + !support.reliableTrDimensions() && nodeName( elem, "tr" ) || + + // Fall back to offsetWidth/offsetHeight when value is "auto" + // This happens for inline elements with no explicit setting (gh-3571) + val === "auto" || + + // Support: Android <=4.1 - 4.3 only + // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) + !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) && + + // Make sure the element is visible & connected + elem.getClientRects().length ) { + + isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + + // Where available, offsetWidth/offsetHeight approximate border box dimensions. + // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the + // retrieved value as a content box dimension. + valueIsBorderBox = offsetProp in elem; + if ( valueIsBorderBox ) { + val = elem[ offsetProp ]; + } + } + + // Normalize "" and auto + val = parseFloat( val ) || 0; + + // Adjust for the element's box model + return ( val + + boxModelAdjustment( + elem, + dimension, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox, + styles, + + // Provide the current computed size to request scroll gutter calculation (gh-3589) + val + ) + ) + "px"; +} + +jQuery.extend( { + + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity" ); + return ret === "" ? "1" : ret; + } + } + } + }, + + // Don't automatically add "px" to these possibly-unitless properties + cssNumber: { + "animationIterationCount": true, + "columnCount": true, + "fillOpacity": true, + "flexGrow": true, + "flexShrink": true, + "fontWeight": true, + "gridArea": true, + "gridColumn": true, + "gridColumnEnd": true, + "gridColumnStart": true, + "gridRow": true, + "gridRowEnd": true, + "gridRowStart": true, + "lineHeight": true, + "opacity": true, + "order": true, + "orphans": true, + "widows": true, + "zIndex": true, + "zoom": true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: {}, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = camelCase( name ), + isCustomProp = rcustomProp.test( name ), + style = elem.style; + + // Make sure that we're working with the right name. We don't + // want to query the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Gets hook for the prefixed version, then unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // Convert "+=" or "-=" to relative numbers (#7345) + if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { + value = adjustCSS( elem, name, ret ); + + // Fixes bug #9237 + type = "number"; + } + + // Make sure that null and NaN values aren't set (#7116) + if ( value == null || value !== value ) { + return; + } + + // If a number was passed in, add the unit (except for certain CSS properties) + // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append + // "px" to a few hardcoded values. + if ( type === "number" && !isCustomProp ) { + value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); + } + + // background-* props affect original clone's values + if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { + style[ name ] = "inherit"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !( "set" in hooks ) || + ( value = hooks.set( elem, value, extra ) ) !== undefined ) { + + if ( isCustomProp ) { + style.setProperty( name, value ); + } else { + style[ name ] = value; + } + } + + } else { + + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && + ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { + + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra, styles ) { + var val, num, hooks, + origName = camelCase( name ), + isCustomProp = rcustomProp.test( name ); + + // Make sure that we're working with the right name. We don't + // want to modify the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Try prefixed name followed by the unprefixed name + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name, styles ); + } + + // Convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Make numeric if forced or a qualifier was provided and val looks numeric + if ( extra === "" || extra ) { + num = parseFloat( val ); + return extra === true || isFinite( num ) ? num || 0 : val; + } + + return val; + } +} ); + +jQuery.each( [ "height", "width" ], function( _i, dimension ) { + jQuery.cssHooks[ dimension ] = { + get: function( elem, computed, extra ) { + if ( computed ) { + + // Certain elements can have dimension info if we invisibly show them + // but it must have a current display style that would benefit + return rdisplayswap.test( jQuery.css( elem, "display" ) ) && + + // Support: Safari 8+ + // Table columns in Safari have non-zero offsetWidth & zero + // getBoundingClientRect().width unless display is changed. + // Support: IE <=11 only + // Running getBoundingClientRect on a disconnected node + // in IE throws an error. + ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? + swap( elem, cssShow, function() { + return getWidthOrHeight( elem, dimension, extra ); + } ) : + getWidthOrHeight( elem, dimension, extra ); + } + }, + + set: function( elem, value, extra ) { + var matches, + styles = getStyles( elem ), + + // Only read styles.position if the test has a chance to fail + // to avoid forcing a reflow. + scrollboxSizeBuggy = !support.scrollboxSize() && + styles.position === "absolute", + + // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991) + boxSizingNeeded = scrollboxSizeBuggy || extra, + isBorderBox = boxSizingNeeded && + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + subtract = extra ? + boxModelAdjustment( + elem, + dimension, + extra, + isBorderBox, + styles + ) : + 0; + + // Account for unreliable border-box dimensions by comparing offset* to computed and + // faking a content-box to get border and padding (gh-3699) + if ( isBorderBox && scrollboxSizeBuggy ) { + subtract -= Math.ceil( + elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - + parseFloat( styles[ dimension ] ) - + boxModelAdjustment( elem, dimension, "border", false, styles ) - + 0.5 + ); + } + + // Convert to pixels if value adjustment is needed + if ( subtract && ( matches = rcssNum.exec( value ) ) && + ( matches[ 3 ] || "px" ) !== "px" ) { + + elem.style[ dimension ] = value; + value = jQuery.css( elem, dimension ); + } + + return setPositiveNumber( elem, value, subtract ); + } + }; +} ); + +jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, + function( elem, computed ) { + if ( computed ) { + return ( parseFloat( curCSS( elem, "marginLeft" ) ) || + elem.getBoundingClientRect().left - + swap( elem, { marginLeft: 0 }, function() { + return elem.getBoundingClientRect().left; + } ) + ) + "px"; + } + } +); + +// These hooks are used by animate to expand properties +jQuery.each( { + margin: "", + padding: "", + border: "Width" +}, function( prefix, suffix ) { + jQuery.cssHooks[ prefix + suffix ] = { + expand: function( value ) { + var i = 0, + expanded = {}, + + // Assumes a single number if not a string + parts = typeof value === "string" ? value.split( " " ) : [ value ]; + + for ( ; i < 4; i++ ) { + expanded[ prefix + cssExpand[ i ] + suffix ] = + parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; + } + + return expanded; + } + }; + + if ( prefix !== "margin" ) { + jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; + } +} ); + +jQuery.fn.extend( { + css: function( name, value ) { + return access( this, function( elem, name, value ) { + var styles, len, + map = {}, + i = 0; + + if ( Array.isArray( name ) ) { + styles = getStyles( elem ); + len = name.length; + + for ( ; i < len; i++ ) { + map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); + } + + return map; + } + + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + } +} ); + + +function Tween( elem, options, prop, end, easing ) { + return new Tween.prototype.init( elem, options, prop, end, easing ); +} +jQuery.Tween = Tween; + +Tween.prototype = { + constructor: Tween, + init: function( elem, options, prop, end, easing, unit ) { + this.elem = elem; + this.prop = prop; + this.easing = easing || jQuery.easing._default; + this.options = options; + this.start = this.now = this.cur(); + this.end = end; + this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); + }, + cur: function() { + var hooks = Tween.propHooks[ this.prop ]; + + return hooks && hooks.get ? + hooks.get( this ) : + Tween.propHooks._default.get( this ); + }, + run: function( percent ) { + var eased, + hooks = Tween.propHooks[ this.prop ]; + + if ( this.options.duration ) { + this.pos = eased = jQuery.easing[ this.easing ]( + percent, this.options.duration * percent, 0, 1, this.options.duration + ); + } else { + this.pos = eased = percent; + } + this.now = ( this.end - this.start ) * eased + this.start; + + if ( this.options.step ) { + this.options.step.call( this.elem, this.now, this ); + } + + if ( hooks && hooks.set ) { + hooks.set( this ); + } else { + Tween.propHooks._default.set( this ); + } + return this; + } +}; + +Tween.prototype.init.prototype = Tween.prototype; + +Tween.propHooks = { + _default: { + get: function( tween ) { + var result; + + // Use a property on the element directly when it is not a DOM element, + // or when there is no matching style property that exists. + if ( tween.elem.nodeType !== 1 || + tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { + return tween.elem[ tween.prop ]; + } + + // Passing an empty string as a 3rd parameter to .css will automatically + // attempt a parseFloat and fallback to a string if the parse fails. + // Simple values such as "10px" are parsed to Float; + // complex values such as "rotate(1rad)" are returned as-is. + result = jQuery.css( tween.elem, tween.prop, "" ); + + // Empty strings, null, undefined and "auto" are converted to 0. + return !result || result === "auto" ? 0 : result; + }, + set: function( tween ) { + + // Use step hook for back compat. + // Use cssHook if its there. + // Use .style if available and use plain properties where available. + if ( jQuery.fx.step[ tween.prop ] ) { + jQuery.fx.step[ tween.prop ]( tween ); + } else if ( tween.elem.nodeType === 1 && ( + jQuery.cssHooks[ tween.prop ] || + tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) { + jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); + } else { + tween.elem[ tween.prop ] = tween.now; + } + } + } +}; + +// Support: IE <=9 only +// Panic based approach to setting things on disconnected nodes +Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { + set: function( tween ) { + if ( tween.elem.nodeType && tween.elem.parentNode ) { + tween.elem[ tween.prop ] = tween.now; + } + } +}; + +jQuery.easing = { + linear: function( p ) { + return p; + }, + swing: function( p ) { + return 0.5 - Math.cos( p * Math.PI ) / 2; + }, + _default: "swing" +}; + +jQuery.fx = Tween.prototype.init; + +// Back compat <1.8 extension point +jQuery.fx.step = {}; + + + + +var + fxNow, inProgress, + rfxtypes = /^(?:toggle|show|hide)$/, + rrun = /queueHooks$/; + +function schedule() { + if ( inProgress ) { + if ( document.hidden === false && window.requestAnimationFrame ) { + window.requestAnimationFrame( schedule ); + } else { + window.setTimeout( schedule, jQuery.fx.interval ); + } + + jQuery.fx.tick(); + } +} + +// Animations created synchronously will run synchronously +function createFxNow() { + window.setTimeout( function() { + fxNow = undefined; + } ); + return ( fxNow = Date.now() ); +} + +// Generate parameters to create a standard animation +function genFx( type, includeWidth ) { + var which, + i = 0, + attrs = { height: type }; + + // If we include width, step value is 1 to do all cssExpand values, + // otherwise step value is 2 to skip over Left and Right + includeWidth = includeWidth ? 1 : 0; + for ( ; i < 4; i += 2 - includeWidth ) { + which = cssExpand[ i ]; + attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; + } + + if ( includeWidth ) { + attrs.opacity = attrs.width = type; + } + + return attrs; +} + +function createTween( value, prop, animation ) { + var tween, + collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), + index = 0, + length = collection.length; + for ( ; index < length; index++ ) { + if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { + + // We're done with this property + return tween; + } + } +} + +function defaultPrefilter( elem, props, opts ) { + var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, + isBox = "width" in props || "height" in props, + anim = this, + orig = {}, + style = elem.style, + hidden = elem.nodeType && isHiddenWithinTree( elem ), + dataShow = dataPriv.get( elem, "fxshow" ); + + // Queue-skipping animations hijack the fx hooks + if ( !opts.queue ) { + hooks = jQuery._queueHooks( elem, "fx" ); + if ( hooks.unqueued == null ) { + hooks.unqueued = 0; + oldfire = hooks.empty.fire; + hooks.empty.fire = function() { + if ( !hooks.unqueued ) { + oldfire(); + } + }; + } + hooks.unqueued++; + + anim.always( function() { + + // Ensure the complete handler is called before this completes + anim.always( function() { + hooks.unqueued--; + if ( !jQuery.queue( elem, "fx" ).length ) { + hooks.empty.fire(); + } + } ); + } ); + } + + // Detect show/hide animations + for ( prop in props ) { + value = props[ prop ]; + if ( rfxtypes.test( value ) ) { + delete props[ prop ]; + toggle = toggle || value === "toggle"; + if ( value === ( hidden ? "hide" : "show" ) ) { + + // Pretend to be hidden if this is a "show" and + // there is still data from a stopped show/hide + if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { + hidden = true; + + // Ignore all other no-op show/hide data + } else { + continue; + } + } + orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); + } + } + + // Bail out if this is a no-op like .hide().hide() + propTween = !jQuery.isEmptyObject( props ); + if ( !propTween && jQuery.isEmptyObject( orig ) ) { + return; + } + + // Restrict "overflow" and "display" styles during box animations + if ( isBox && elem.nodeType === 1 ) { + + // Support: IE <=9 - 11, Edge 12 - 15 + // Record all 3 overflow attributes because IE does not infer the shorthand + // from identically-valued overflowX and overflowY and Edge just mirrors + // the overflowX value there. + opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; + + // Identify a display type, preferring old show/hide data over the CSS cascade + restoreDisplay = dataShow && dataShow.display; + if ( restoreDisplay == null ) { + restoreDisplay = dataPriv.get( elem, "display" ); + } + display = jQuery.css( elem, "display" ); + if ( display === "none" ) { + if ( restoreDisplay ) { + display = restoreDisplay; + } else { + + // Get nonempty value(s) by temporarily forcing visibility + showHide( [ elem ], true ); + restoreDisplay = elem.style.display || restoreDisplay; + display = jQuery.css( elem, "display" ); + showHide( [ elem ] ); + } + } + + // Animate inline elements as inline-block + if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { + if ( jQuery.css( elem, "float" ) === "none" ) { + + // Restore the original display value at the end of pure show/hide animations + if ( !propTween ) { + anim.done( function() { + style.display = restoreDisplay; + } ); + if ( restoreDisplay == null ) { + display = style.display; + restoreDisplay = display === "none" ? "" : display; + } + } + style.display = "inline-block"; + } + } + } + + if ( opts.overflow ) { + style.overflow = "hidden"; + anim.always( function() { + style.overflow = opts.overflow[ 0 ]; + style.overflowX = opts.overflow[ 1 ]; + style.overflowY = opts.overflow[ 2 ]; + } ); + } + + // Implement show/hide animations + propTween = false; + for ( prop in orig ) { + + // General show/hide setup for this element animation + if ( !propTween ) { + if ( dataShow ) { + if ( "hidden" in dataShow ) { + hidden = dataShow.hidden; + } + } else { + dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); + } + + // Store hidden/visible for toggle so `.stop().toggle()` "reverses" + if ( toggle ) { + dataShow.hidden = !hidden; + } + + // Show elements before animating them + if ( hidden ) { + showHide( [ elem ], true ); + } + + /* eslint-disable no-loop-func */ + + anim.done( function() { + + /* eslint-enable no-loop-func */ + + // The final step of a "hide" animation is actually hiding the element + if ( !hidden ) { + showHide( [ elem ] ); + } + dataPriv.remove( elem, "fxshow" ); + for ( prop in orig ) { + jQuery.style( elem, prop, orig[ prop ] ); + } + } ); + } + + // Per-property setup + propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); + if ( !( prop in dataShow ) ) { + dataShow[ prop ] = propTween.start; + if ( hidden ) { + propTween.end = propTween.start; + propTween.start = 0; + } + } + } +} + +function propFilter( props, specialEasing ) { + var index, name, easing, value, hooks; + + // camelCase, specialEasing and expand cssHook pass + for ( index in props ) { + name = camelCase( index ); + easing = specialEasing[ name ]; + value = props[ index ]; + if ( Array.isArray( value ) ) { + easing = value[ 1 ]; + value = props[ index ] = value[ 0 ]; + } + + if ( index !== name ) { + props[ name ] = value; + delete props[ index ]; + } + + hooks = jQuery.cssHooks[ name ]; + if ( hooks && "expand" in hooks ) { + value = hooks.expand( value ); + delete props[ name ]; + + // Not quite $.extend, this won't overwrite existing keys. + // Reusing 'index' because we have the correct "name" + for ( index in value ) { + if ( !( index in props ) ) { + props[ index ] = value[ index ]; + specialEasing[ index ] = easing; + } + } + } else { + specialEasing[ name ] = easing; + } + } +} + +function Animation( elem, properties, options ) { + var result, + stopped, + index = 0, + length = Animation.prefilters.length, + deferred = jQuery.Deferred().always( function() { + + // Don't match elem in the :animated selector + delete tick.elem; + } ), + tick = function() { + if ( stopped ) { + return false; + } + var currentTime = fxNow || createFxNow(), + remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), + + // Support: Android 2.3 only + // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) + temp = remaining / animation.duration || 0, + percent = 1 - temp, + index = 0, + length = animation.tweens.length; + + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( percent ); + } + + deferred.notifyWith( elem, [ animation, percent, remaining ] ); + + // If there's more to do, yield + if ( percent < 1 && length ) { + return remaining; + } + + // If this was an empty animation, synthesize a final progress notification + if ( !length ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + } + + // Resolve the animation and report its conclusion + deferred.resolveWith( elem, [ animation ] ); + return false; + }, + animation = deferred.promise( { + elem: elem, + props: jQuery.extend( {}, properties ), + opts: jQuery.extend( true, { + specialEasing: {}, + easing: jQuery.easing._default + }, options ), + originalProperties: properties, + originalOptions: options, + startTime: fxNow || createFxNow(), + duration: options.duration, + tweens: [], + createTween: function( prop, end ) { + var tween = jQuery.Tween( elem, animation.opts, prop, end, + animation.opts.specialEasing[ prop ] || animation.opts.easing ); + animation.tweens.push( tween ); + return tween; + }, + stop: function( gotoEnd ) { + var index = 0, + + // If we are going to the end, we want to run all the tweens + // otherwise we skip this part + length = gotoEnd ? animation.tweens.length : 0; + if ( stopped ) { + return this; + } + stopped = true; + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( 1 ); + } + + // Resolve when we played the last frame; otherwise, reject + if ( gotoEnd ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + deferred.resolveWith( elem, [ animation, gotoEnd ] ); + } else { + deferred.rejectWith( elem, [ animation, gotoEnd ] ); + } + return this; + } + } ), + props = animation.props; + + propFilter( props, animation.opts.specialEasing ); + + for ( ; index < length; index++ ) { + result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); + if ( result ) { + if ( isFunction( result.stop ) ) { + jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = + result.stop.bind( result ); + } + return result; + } + } + + jQuery.map( props, createTween, animation ); + + if ( isFunction( animation.opts.start ) ) { + animation.opts.start.call( elem, animation ); + } + + // Attach callbacks from options + animation + .progress( animation.opts.progress ) + .done( animation.opts.done, animation.opts.complete ) + .fail( animation.opts.fail ) + .always( animation.opts.always ); + + jQuery.fx.timer( + jQuery.extend( tick, { + elem: elem, + anim: animation, + queue: animation.opts.queue + } ) + ); + + return animation; +} + +jQuery.Animation = jQuery.extend( Animation, { + + tweeners: { + "*": [ function( prop, value ) { + var tween = this.createTween( prop, value ); + adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); + return tween; + } ] + }, + + tweener: function( props, callback ) { + if ( isFunction( props ) ) { + callback = props; + props = [ "*" ]; + } else { + props = props.match( rnothtmlwhite ); + } + + var prop, + index = 0, + length = props.length; + + for ( ; index < length; index++ ) { + prop = props[ index ]; + Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; + Animation.tweeners[ prop ].unshift( callback ); + } + }, + + prefilters: [ defaultPrefilter ], + + prefilter: function( callback, prepend ) { + if ( prepend ) { + Animation.prefilters.unshift( callback ); + } else { + Animation.prefilters.push( callback ); + } + } +} ); + +jQuery.speed = function( speed, easing, fn ) { + var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { + complete: fn || !fn && easing || + isFunction( speed ) && speed, + duration: speed, + easing: fn && easing || easing && !isFunction( easing ) && easing + }; + + // Go to the end state if fx are off + if ( jQuery.fx.off ) { + opt.duration = 0; + + } else { + if ( typeof opt.duration !== "number" ) { + if ( opt.duration in jQuery.fx.speeds ) { + opt.duration = jQuery.fx.speeds[ opt.duration ]; + + } else { + opt.duration = jQuery.fx.speeds._default; + } + } + } + + // Normalize opt.queue - true/undefined/null -> "fx" + if ( opt.queue == null || opt.queue === true ) { + opt.queue = "fx"; + } + + // Queueing + opt.old = opt.complete; + + opt.complete = function() { + if ( isFunction( opt.old ) ) { + opt.old.call( this ); + } + + if ( opt.queue ) { + jQuery.dequeue( this, opt.queue ); + } + }; + + return opt; +}; + +jQuery.fn.extend( { + fadeTo: function( speed, to, easing, callback ) { + + // Show any hidden elements after setting opacity to 0 + return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() + + // Animate to the value specified + .end().animate( { opacity: to }, speed, easing, callback ); + }, + animate: function( prop, speed, easing, callback ) { + var empty = jQuery.isEmptyObject( prop ), + optall = jQuery.speed( speed, easing, callback ), + doAnimation = function() { + + // Operate on a copy of prop so per-property easing won't be lost + var anim = Animation( this, jQuery.extend( {}, prop ), optall ); + + // Empty animations, or finishing resolves immediately + if ( empty || dataPriv.get( this, "finish" ) ) { + anim.stop( true ); + } + }; + doAnimation.finish = doAnimation; + + return empty || optall.queue === false ? + this.each( doAnimation ) : + this.queue( optall.queue, doAnimation ); + }, + stop: function( type, clearQueue, gotoEnd ) { + var stopQueue = function( hooks ) { + var stop = hooks.stop; + delete hooks.stop; + stop( gotoEnd ); + }; + + if ( typeof type !== "string" ) { + gotoEnd = clearQueue; + clearQueue = type; + type = undefined; + } + if ( clearQueue ) { + this.queue( type || "fx", [] ); + } + + return this.each( function() { + var dequeue = true, + index = type != null && type + "queueHooks", + timers = jQuery.timers, + data = dataPriv.get( this ); + + if ( index ) { + if ( data[ index ] && data[ index ].stop ) { + stopQueue( data[ index ] ); + } + } else { + for ( index in data ) { + if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { + stopQueue( data[ index ] ); + } + } + } + + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && + ( type == null || timers[ index ].queue === type ) ) { + + timers[ index ].anim.stop( gotoEnd ); + dequeue = false; + timers.splice( index, 1 ); + } + } + + // Start the next in the queue if the last step wasn't forced. + // Timers currently will call their complete callbacks, which + // will dequeue but only if they were gotoEnd. + if ( dequeue || !gotoEnd ) { + jQuery.dequeue( this, type ); + } + } ); + }, + finish: function( type ) { + if ( type !== false ) { + type = type || "fx"; + } + return this.each( function() { + var index, + data = dataPriv.get( this ), + queue = data[ type + "queue" ], + hooks = data[ type + "queueHooks" ], + timers = jQuery.timers, + length = queue ? queue.length : 0; + + // Enable finishing flag on private data + data.finish = true; + + // Empty the queue first + jQuery.queue( this, type, [] ); + + if ( hooks && hooks.stop ) { + hooks.stop.call( this, true ); + } + + // Look for any active animations, and finish them + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && timers[ index ].queue === type ) { + timers[ index ].anim.stop( true ); + timers.splice( index, 1 ); + } + } + + // Look for any animations in the old queue and finish them + for ( index = 0; index < length; index++ ) { + if ( queue[ index ] && queue[ index ].finish ) { + queue[ index ].finish.call( this ); + } + } + + // Turn off finishing flag + delete data.finish; + } ); + } +} ); + +jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) { + var cssFn = jQuery.fn[ name ]; + jQuery.fn[ name ] = function( speed, easing, callback ) { + return speed == null || typeof speed === "boolean" ? + cssFn.apply( this, arguments ) : + this.animate( genFx( name, true ), speed, easing, callback ); + }; +} ); + +// Generate shortcuts for custom animations +jQuery.each( { + slideDown: genFx( "show" ), + slideUp: genFx( "hide" ), + slideToggle: genFx( "toggle" ), + fadeIn: { opacity: "show" }, + fadeOut: { opacity: "hide" }, + fadeToggle: { opacity: "toggle" } +}, function( name, props ) { + jQuery.fn[ name ] = function( speed, easing, callback ) { + return this.animate( props, speed, easing, callback ); + }; +} ); + +jQuery.timers = []; +jQuery.fx.tick = function() { + var timer, + i = 0, + timers = jQuery.timers; + + fxNow = Date.now(); + + for ( ; i < timers.length; i++ ) { + timer = timers[ i ]; + + // Run the timer and safely remove it when done (allowing for external removal) + if ( !timer() && timers[ i ] === timer ) { + timers.splice( i--, 1 ); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + fxNow = undefined; +}; + +jQuery.fx.timer = function( timer ) { + jQuery.timers.push( timer ); + jQuery.fx.start(); +}; + +jQuery.fx.interval = 13; +jQuery.fx.start = function() { + if ( inProgress ) { + return; + } + + inProgress = true; + schedule(); +}; + +jQuery.fx.stop = function() { + inProgress = null; +}; + +jQuery.fx.speeds = { + slow: 600, + fast: 200, + + // Default speed + _default: 400 +}; + + +// Based off of the plugin by Clint Helfers, with permission. +// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ +jQuery.fn.delay = function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = window.setTimeout( next, time ); + hooks.stop = function() { + window.clearTimeout( timeout ); + }; + } ); +}; + + +( function() { + var input = document.createElement( "input" ), + select = document.createElement( "select" ), + opt = select.appendChild( document.createElement( "option" ) ); + + input.type = "checkbox"; + + // Support: Android <=4.3 only + // Default value for a checkbox should be "on" + support.checkOn = input.value !== ""; + + // Support: IE <=11 only + // Must access selectedIndex to make default options select + support.optSelected = opt.selected; + + // Support: IE <=11 only + // An input loses its value after becoming a radio + input = document.createElement( "input" ); + input.value = "t"; + input.type = "radio"; + support.radioValue = input.value === "t"; +} )(); + + +var boolHook, + attrHandle = jQuery.expr.attrHandle; + +jQuery.fn.extend( { + attr: function( name, value ) { + return access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each( function() { + jQuery.removeAttr( this, name ); + } ); + } +} ); + +jQuery.extend( { + attr: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set attributes on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + // Attribute hooks are determined by the lowercase version + // Grab necessary hook if one is defined + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + hooks = jQuery.attrHooks[ name.toLowerCase() ] || + ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); + } + + if ( value !== undefined ) { + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + } + + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + elem.setAttribute( name, value + "" ); + return value; + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + ret = jQuery.find.attr( elem, name ); + + // Non-existent attributes return null, we normalize to undefined + return ret == null ? undefined : ret; + }, + + attrHooks: { + type: { + set: function( elem, value ) { + if ( !support.radioValue && value === "radio" && + nodeName( elem, "input" ) ) { + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + } + }, + + removeAttr: function( elem, value ) { + var name, + i = 0, + + // Attribute names can contain non-HTML whitespace characters + // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 + attrNames = value && value.match( rnothtmlwhite ); + + if ( attrNames && elem.nodeType === 1 ) { + while ( ( name = attrNames[ i++ ] ) ) { + elem.removeAttribute( name ); + } + } + } +} ); + +// Hooks for boolean attributes +boolHook = { + set: function( elem, value, name ) { + if ( value === false ) { + + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + elem.setAttribute( name, name ); + } + return name; + } +}; + +jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) { + var getter = attrHandle[ name ] || jQuery.find.attr; + + attrHandle[ name ] = function( elem, name, isXML ) { + var ret, handle, + lowercaseName = name.toLowerCase(); + + if ( !isXML ) { + + // Avoid an infinite loop by temporarily removing this function from the getter + handle = attrHandle[ lowercaseName ]; + attrHandle[ lowercaseName ] = ret; + ret = getter( elem, name, isXML ) != null ? + lowercaseName : + null; + attrHandle[ lowercaseName ] = handle; + } + return ret; + }; +} ); + + + + +var rfocusable = /^(?:input|select|textarea|button)$/i, + rclickable = /^(?:a|area)$/i; + +jQuery.fn.extend( { + prop: function( name, value ) { + return access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + return this.each( function() { + delete this[ jQuery.propFix[ name ] || name ]; + } ); + } +} ); + +jQuery.extend( { + prop: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set properties on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + return ( elem[ name ] = value ); + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + return elem[ name ]; + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + + // Support: IE <=9 - 11 only + // elem.tabIndex doesn't always return the + // correct value when it hasn't been explicitly set + // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + // Use proper attribute retrieval(#12072) + var tabindex = jQuery.find.attr( elem, "tabindex" ); + + if ( tabindex ) { + return parseInt( tabindex, 10 ); + } + + if ( + rfocusable.test( elem.nodeName ) || + rclickable.test( elem.nodeName ) && + elem.href + ) { + return 0; + } + + return -1; + } + } + }, + + propFix: { + "for": "htmlFor", + "class": "className" + } +} ); + +// Support: IE <=11 only +// Accessing the selectedIndex property +// forces the browser to respect setting selected +// on the option +// The getter ensures a default option is selected +// when in an optgroup +// eslint rule "no-unused-expressions" is disabled for this code +// since it considers such accessions noop +if ( !support.optSelected ) { + jQuery.propHooks.selected = { + get: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent && parent.parentNode ) { + parent.parentNode.selectedIndex; + } + return null; + }, + set: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent ) { + parent.selectedIndex; + + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + } + }; +} + +jQuery.each( [ + "tabIndex", + "readOnly", + "maxLength", + "cellSpacing", + "cellPadding", + "rowSpan", + "colSpan", + "useMap", + "frameBorder", + "contentEditable" +], function() { + jQuery.propFix[ this.toLowerCase() ] = this; +} ); + + + + + // Strip and collapse whitespace according to HTML spec + // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace + function stripAndCollapse( value ) { + var tokens = value.match( rnothtmlwhite ) || []; + return tokens.join( " " ); + } + + +function getClass( elem ) { + return elem.getAttribute && elem.getAttribute( "class" ) || ""; +} + +function classesToArray( value ) { + if ( Array.isArray( value ) ) { + return value; + } + if ( typeof value === "string" ) { + return value.match( rnothtmlwhite ) || []; + } + return []; +} + +jQuery.fn.extend( { + addClass: function( value ) { + var classes, elem, cur, curValue, clazz, j, finalValue, + i = 0; + + if ( isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + classes = classesToArray( value ); + + if ( classes.length ) { + while ( ( elem = this[ i++ ] ) ) { + curValue = getClass( elem ); + cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + j = 0; + while ( ( clazz = classes[ j++ ] ) ) { + if ( cur.indexOf( " " + clazz + " " ) < 0 ) { + cur += clazz + " "; + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + elem.setAttribute( "class", finalValue ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classes, elem, cur, curValue, clazz, j, finalValue, + i = 0; + + if ( isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + if ( !arguments.length ) { + return this.attr( "class", "" ); + } + + classes = classesToArray( value ); + + if ( classes.length ) { + while ( ( elem = this[ i++ ] ) ) { + curValue = getClass( elem ); + + // This expression is here for better compressibility (see addClass) + cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + j = 0; + while ( ( clazz = classes[ j++ ] ) ) { + + // Remove *all* instances + while ( cur.indexOf( " " + clazz + " " ) > -1 ) { + cur = cur.replace( " " + clazz + " ", " " ); + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + elem.setAttribute( "class", finalValue ); + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isValidValue = type === "string" || Array.isArray( value ); + + if ( typeof stateVal === "boolean" && isValidValue ) { + return stateVal ? this.addClass( value ) : this.removeClass( value ); + } + + if ( isFunction( value ) ) { + return this.each( function( i ) { + jQuery( this ).toggleClass( + value.call( this, i, getClass( this ), stateVal ), + stateVal + ); + } ); + } + + return this.each( function() { + var className, i, self, classNames; + + if ( isValidValue ) { + + // Toggle individual class names + i = 0; + self = jQuery( this ); + classNames = classesToArray( value ); + + while ( ( className = classNames[ i++ ] ) ) { + + // Check each className given, space separated list + if ( self.hasClass( className ) ) { + self.removeClass( className ); + } else { + self.addClass( className ); + } + } + + // Toggle whole class name + } else if ( value === undefined || type === "boolean" ) { + className = getClass( this ); + if ( className ) { + + // Store className if set + dataPriv.set( this, "__className__", className ); + } + + // If the element has a class name or if we're passed `false`, + // then remove the whole classname (if there was one, the above saved it). + // Otherwise bring back whatever was previously saved (if anything), + // falling back to the empty string if nothing was stored. + if ( this.setAttribute ) { + this.setAttribute( "class", + className || value === false ? + "" : + dataPriv.get( this, "__className__" ) || "" + ); + } + } + } ); + }, + + hasClass: function( selector ) { + var className, elem, + i = 0; + + className = " " + selector + " "; + while ( ( elem = this[ i++ ] ) ) { + if ( elem.nodeType === 1 && + ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { + return true; + } + } + + return false; + } +} ); + + + + +var rreturn = /\r/g; + +jQuery.fn.extend( { + val: function( value ) { + var hooks, ret, valueIsFunction, + elem = this[ 0 ]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || + jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && + "get" in hooks && + ( ret = hooks.get( elem, "value" ) ) !== undefined + ) { + return ret; + } + + ret = elem.value; + + // Handle most common string cases + if ( typeof ret === "string" ) { + return ret.replace( rreturn, "" ); + } + + // Handle cases where value is null/undef or number + return ret == null ? "" : ret; + } + + return; + } + + valueIsFunction = isFunction( value ); + + return this.each( function( i ) { + var val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( valueIsFunction ) { + val = value.call( this, i, jQuery( this ).val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + + } else if ( typeof val === "number" ) { + val += ""; + + } else if ( Array.isArray( val ) ) { + val = jQuery.map( val, function( value ) { + return value == null ? "" : value + ""; + } ); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + } ); + } +} ); + +jQuery.extend( { + valHooks: { + option: { + get: function( elem ) { + + var val = jQuery.find.attr( elem, "value" ); + return val != null ? + val : + + // Support: IE <=10 - 11 only + // option.text throws exceptions (#14686, #14858) + // Strip and collapse whitespace + // https://html.spec.whatwg.org/#strip-and-collapse-whitespace + stripAndCollapse( jQuery.text( elem ) ); + } + }, + select: { + get: function( elem ) { + var value, option, i, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one", + values = one ? null : [], + max = one ? index + 1 : options.length; + + if ( index < 0 ) { + i = max; + + } else { + i = one ? index : 0; + } + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Support: IE <=9 only + // IE8-9 doesn't update selected after form reset (#2551) + if ( ( option.selected || i === index ) && + + // Don't return options that are disabled or in a disabled optgroup + !option.disabled && + ( !option.parentNode.disabled || + !nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var optionSet, option, + options = elem.options, + values = jQuery.makeArray( value ), + i = options.length; + + while ( i-- ) { + option = options[ i ]; + + /* eslint-disable no-cond-assign */ + + if ( option.selected = + jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 + ) { + optionSet = true; + } + + /* eslint-enable no-cond-assign */ + } + + // Force browsers to behave consistently when non-matching value is set + if ( !optionSet ) { + elem.selectedIndex = -1; + } + return values; + } + } + } +} ); + +// Radios and checkboxes getter/setter +jQuery.each( [ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + set: function( elem, value ) { + if ( Array.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); + } + } + }; + if ( !support.checkOn ) { + jQuery.valHooks[ this ].get = function( elem ) { + return elem.getAttribute( "value" ) === null ? "on" : elem.value; + }; + } +} ); + + + + +// Return jQuery for attributes-only inclusion + + +support.focusin = "onfocusin" in window; + + +var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + stopPropagationCallback = function( e ) { + e.stopPropagation(); + }; + +jQuery.extend( jQuery.event, { + + trigger: function( event, data, elem, onlyHandlers ) { + + var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; + + cur = lastElement = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "." ) > -1 ) { + + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split( "." ); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf( ":" ) < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join( "." ); + event.rnamespace = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === ( elem.ownerDocument || document ) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { + lastElement = cur; + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( + dataPriv.get( cur, "events" ) || Object.create( null ) + )[ event.type ] && + dataPriv.get( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( ( !special._default || + special._default.apply( eventPath.pop(), data ) === false ) && + acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name as the event. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + + if ( event.isPropagationStopped() ) { + lastElement.addEventListener( type, stopPropagationCallback ); + } + + elem[ type ](); + + if ( event.isPropagationStopped() ) { + lastElement.removeEventListener( type, stopPropagationCallback ); + } + + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + // Piggyback on a donor event to simulate a different one + // Used only for `focus(in | out)` events + simulate: function( type, elem, event ) { + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true + } + ); + + jQuery.event.trigger( e, null, elem ); + } + +} ); + +jQuery.fn.extend( { + + trigger: function( type, data ) { + return this.each( function() { + jQuery.event.trigger( type, data, this ); + } ); + }, + triggerHandler: function( type, data ) { + var elem = this[ 0 ]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +} ); + + +// Support: Firefox <=44 +// Firefox doesn't have focus(in | out) events +// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 +// +// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 +// focus(in | out) events fire after focus & blur events, +// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order +// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 +if ( !support.focusin ) { + jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler on the document while someone wants focusin/focusout + var handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + + // Handle: regular nodes (via `this.ownerDocument`), window + // (via `this.document`) & document (via `this`). + var doc = this.ownerDocument || this.document || this, + attaches = dataPriv.access( doc, fix ); + + if ( !attaches ) { + doc.addEventListener( orig, handler, true ); + } + dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this.document || this, + attaches = dataPriv.access( doc, fix ) - 1; + + if ( !attaches ) { + doc.removeEventListener( orig, handler, true ); + dataPriv.remove( doc, fix ); + + } else { + dataPriv.access( doc, fix, attaches ); + } + } + }; + } ); +} +var location = window.location; + +var nonce = { guid: Date.now() }; + +var rquery = ( /\?/ ); + + + +// Cross-browser xml parsing +jQuery.parseXML = function( data ) { + var xml; + if ( !data || typeof data !== "string" ) { + return null; + } + + // Support: IE 9 - 11 only + // IE throws on parseFromString with invalid input. + try { + xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); + } catch ( e ) { + xml = undefined; + } + + if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; +}; + + +var + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, + rsubmittable = /^(?:input|select|textarea|keygen)/i; + +function buildParams( prefix, obj, traditional, add ) { + var name; + + if ( Array.isArray( obj ) ) { + + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional || rbracket.test( prefix ) ) { + + // Treat each array item as a scalar. + add( prefix, v ); + + } else { + + // Item is non-scalar (array or object), encode its numeric index. + buildParams( + prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", + v, + traditional, + add + ); + } + } ); + + } else if ( !traditional && toType( obj ) === "object" ) { + + // Serialize object item. + for ( name in obj ) { + buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); + } + + } else { + + // Serialize scalar item. + add( prefix, obj ); + } +} + +// Serialize an array of form elements or a set of +// key/values into a query string +jQuery.param = function( a, traditional ) { + var prefix, + s = [], + add = function( key, valueOrFunction ) { + + // If value is a function, invoke it and use its return value + var value = isFunction( valueOrFunction ) ? + valueOrFunction() : + valueOrFunction; + + s[ s.length ] = encodeURIComponent( key ) + "=" + + encodeURIComponent( value == null ? "" : value ); + }; + + if ( a == null ) { + return ""; + } + + // If an array was passed in, assume that it is an array of form elements. + if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { + + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + } ); + + } else { + + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( prefix in a ) { + buildParams( prefix, a[ prefix ], traditional, add ); + } + } + + // Return the resulting serialization + return s.join( "&" ); +}; + +jQuery.fn.extend( { + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + serializeArray: function() { + return this.map( function() { + + // Can add propHook for "elements" to filter or add form elements + var elements = jQuery.prop( this, "elements" ); + return elements ? jQuery.makeArray( elements ) : this; + } ) + .filter( function() { + var type = this.type; + + // Use .is( ":disabled" ) so that fieldset[disabled] works + return this.name && !jQuery( this ).is( ":disabled" ) && + rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && + ( this.checked || !rcheckableType.test( type ) ); + } ) + .map( function( _i, elem ) { + var val = jQuery( this ).val(); + + if ( val == null ) { + return null; + } + + if ( Array.isArray( val ) ) { + return jQuery.map( val, function( val ) { + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ); + } + + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ).get(); + } +} ); + + +var + r20 = /%20/g, + rhash = /#.*$/, + rantiCache = /([?&])_=[^&]*/, + rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, + + // #7653, #8125, #8152: local protocol detection + rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, + rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, + + /* Prefilters + * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) + * 2) These are called: + * - BEFORE asking for a transport + * - AFTER param serialization (s.data is a string if s.processData is true) + * 3) key is the dataType + * 4) the catchall symbol "*" can be used + * 5) execution will start with transport dataType and THEN continue down to "*" if needed + */ + prefilters = {}, + + /* Transports bindings + * 1) key is the dataType + * 2) the catchall symbol "*" can be used + * 3) selection will start with transport dataType and THEN go to "*" if needed + */ + transports = {}, + + // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression + allTypes = "*/".concat( "*" ), + + // Anchor tag for parsing the document origin + originAnchor = document.createElement( "a" ); + originAnchor.href = location.href; + +// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport +function addToPrefiltersOrTransports( structure ) { + + // dataTypeExpression is optional and defaults to "*" + return function( dataTypeExpression, func ) { + + if ( typeof dataTypeExpression !== "string" ) { + func = dataTypeExpression; + dataTypeExpression = "*"; + } + + var dataType, + i = 0, + dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; + + if ( isFunction( func ) ) { + + // For each dataType in the dataTypeExpression + while ( ( dataType = dataTypes[ i++ ] ) ) { + + // Prepend if requested + if ( dataType[ 0 ] === "+" ) { + dataType = dataType.slice( 1 ) || "*"; + ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); + + // Otherwise append + } else { + ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); + } + } + } + }; +} + +// Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { + + var inspected = {}, + seekingTransport = ( structure === transports ); + + function inspect( dataType ) { + var selected; + inspected[ dataType ] = true; + jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { + var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); + if ( typeof dataTypeOrTransport === "string" && + !seekingTransport && !inspected[ dataTypeOrTransport ] ) { + + options.dataTypes.unshift( dataTypeOrTransport ); + inspect( dataTypeOrTransport ); + return false; + } else if ( seekingTransport ) { + return !( selected = dataTypeOrTransport ); + } + } ); + return selected; + } + + return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); +} + +// A special extend for ajax options +// that takes "flat" options (not to be deep extended) +// Fixes #9887 +function ajaxExtend( target, src ) { + var key, deep, + flatOptions = jQuery.ajaxSettings.flatOptions || {}; + + for ( key in src ) { + if ( src[ key ] !== undefined ) { + ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; + } + } + if ( deep ) { + jQuery.extend( true, target, deep ); + } + + return target; +} + +/* Handles responses to an ajax request: + * - finds the right dataType (mediates between content-type and expected dataType) + * - returns the corresponding response + */ +function ajaxHandleResponses( s, jqXHR, responses ) { + + var ct, type, finalDataType, firstDataType, + contents = s.contents, + dataTypes = s.dataTypes; + + // Remove auto dataType and get content-type in the process + while ( dataTypes[ 0 ] === "*" ) { + dataTypes.shift(); + if ( ct === undefined ) { + ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); + } + } + + // Check if we're dealing with a known content-type + if ( ct ) { + for ( type in contents ) { + if ( contents[ type ] && contents[ type ].test( ct ) ) { + dataTypes.unshift( type ); + break; + } + } + } + + // Check to see if we have a response for the expected dataType + if ( dataTypes[ 0 ] in responses ) { + finalDataType = dataTypes[ 0 ]; + } else { + + // Try convertible dataTypes + for ( type in responses ) { + if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { + finalDataType = type; + break; + } + if ( !firstDataType ) { + firstDataType = type; + } + } + + // Or just use first one + finalDataType = finalDataType || firstDataType; + } + + // If we found a dataType + // We add the dataType to the list if needed + // and return the corresponding response + if ( finalDataType ) { + if ( finalDataType !== dataTypes[ 0 ] ) { + dataTypes.unshift( finalDataType ); + } + return responses[ finalDataType ]; + } +} + +/* Chain conversions given the request and the original response + * Also sets the responseXXX fields on the jqXHR instance + */ +function ajaxConvert( s, response, jqXHR, isSuccess ) { + var conv2, current, conv, tmp, prev, + converters = {}, + + // Work with a copy of dataTypes in case we need to modify it for conversion + dataTypes = s.dataTypes.slice(); + + // Create converters map with lowercased keys + if ( dataTypes[ 1 ] ) { + for ( conv in s.converters ) { + converters[ conv.toLowerCase() ] = s.converters[ conv ]; + } + } + + current = dataTypes.shift(); + + // Convert to each sequential dataType + while ( current ) { + + if ( s.responseFields[ current ] ) { + jqXHR[ s.responseFields[ current ] ] = response; + } + + // Apply the dataFilter if provided + if ( !prev && isSuccess && s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + prev = current; + current = dataTypes.shift(); + + if ( current ) { + + // There's only work to do if current dataType is non-auto + if ( current === "*" ) { + + current = prev; + + // Convert response if prev dataType is non-auto and differs from current + } else if ( prev !== "*" && prev !== current ) { + + // Seek a direct converter + conv = converters[ prev + " " + current ] || converters[ "* " + current ]; + + // If none found, seek a pair + if ( !conv ) { + for ( conv2 in converters ) { + + // If conv2 outputs current + tmp = conv2.split( " " ); + if ( tmp[ 1 ] === current ) { + + // If prev can be converted to accepted input + conv = converters[ prev + " " + tmp[ 0 ] ] || + converters[ "* " + tmp[ 0 ] ]; + if ( conv ) { + + // Condense equivalence converters + if ( conv === true ) { + conv = converters[ conv2 ]; + + // Otherwise, insert the intermediate dataType + } else if ( converters[ conv2 ] !== true ) { + current = tmp[ 0 ]; + dataTypes.unshift( tmp[ 1 ] ); + } + break; + } + } + } + } + + // Apply converter (if not an equivalence) + if ( conv !== true ) { + + // Unless errors are allowed to bubble, catch and return them + if ( conv && s.throws ) { + response = conv( response ); + } else { + try { + response = conv( response ); + } catch ( e ) { + return { + state: "parsererror", + error: conv ? e : "No conversion from " + prev + " to " + current + }; + } + } + } + } + } + } + + return { state: "success", data: response }; +} + +jQuery.extend( { + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {}, + + ajaxSettings: { + url: location.href, + type: "GET", + isLocal: rlocalProtocol.test( location.protocol ), + global: true, + processData: true, + async: true, + contentType: "application/x-www-form-urlencoded; charset=UTF-8", + + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + throws: false, + traditional: false, + headers: {}, + */ + + accepts: { + "*": allTypes, + text: "text/plain", + html: "text/html", + xml: "application/xml, text/xml", + json: "application/json, text/javascript" + }, + + contents: { + xml: /\bxml\b/, + html: /\bhtml/, + json: /\bjson\b/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText", + json: "responseJSON" + }, + + // Data converters + // Keys separate source (or catchall "*") and destination types with a single space + converters: { + + // Convert anything to text + "* text": String, + + // Text to html (true = no transformation) + "text html": true, + + // Evaluate text as a json expression + "text json": JSON.parse, + + // Parse text as xml + "text xml": jQuery.parseXML + }, + + // For options that shouldn't be deep extended: + // you can add your own custom options here if + // and when you create one that shouldn't be + // deep extended (see ajaxExtend) + flatOptions: { + url: true, + context: true + } + }, + + // Creates a full fledged settings object into target + // with both ajaxSettings and settings fields. + // If target is omitted, writes into ajaxSettings. + ajaxSetup: function( target, settings ) { + return settings ? + + // Building a settings object + ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : + + // Extending ajaxSettings + ajaxExtend( jQuery.ajaxSettings, target ); + }, + + ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), + ajaxTransport: addToPrefiltersOrTransports( transports ), + + // Main method + ajax: function( url, options ) { + + // If url is an object, simulate pre-1.5 signature + if ( typeof url === "object" ) { + options = url; + url = undefined; + } + + // Force options to be an object + options = options || {}; + + var transport, + + // URL without anti-cache param + cacheURL, + + // Response headers + responseHeadersString, + responseHeaders, + + // timeout handle + timeoutTimer, + + // Url cleanup var + urlAnchor, + + // Request state (becomes false upon send and true upon completion) + completed, + + // To know if global events are to be dispatched + fireGlobals, + + // Loop variable + i, + + // uncached part of the url + uncached, + + // Create the final options object + s = jQuery.ajaxSetup( {}, options ), + + // Callbacks context + callbackContext = s.context || s, + + // Context for global events is callbackContext if it is a DOM node or jQuery collection + globalEventContext = s.context && + ( callbackContext.nodeType || callbackContext.jquery ) ? + jQuery( callbackContext ) : + jQuery.event, + + // Deferreds + deferred = jQuery.Deferred(), + completeDeferred = jQuery.Callbacks( "once memory" ), + + // Status-dependent callbacks + statusCode = s.statusCode || {}, + + // Headers (they are sent all at once) + requestHeaders = {}, + requestHeadersNames = {}, + + // Default abort message + strAbort = "canceled", + + // Fake xhr + jqXHR = { + readyState: 0, + + // Builds headers hashtable if needed + getResponseHeader: function( key ) { + var match; + if ( completed ) { + if ( !responseHeaders ) { + responseHeaders = {}; + while ( ( match = rheaders.exec( responseHeadersString ) ) ) { + responseHeaders[ match[ 1 ].toLowerCase() + " " ] = + ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] ) + .concat( match[ 2 ] ); + } + } + match = responseHeaders[ key.toLowerCase() + " " ]; + } + return match == null ? null : match.join( ", " ); + }, + + // Raw string + getAllResponseHeaders: function() { + return completed ? responseHeadersString : null; + }, + + // Caches the header + setRequestHeader: function( name, value ) { + if ( completed == null ) { + name = requestHeadersNames[ name.toLowerCase() ] = + requestHeadersNames[ name.toLowerCase() ] || name; + requestHeaders[ name ] = value; + } + return this; + }, + + // Overrides response content-type header + overrideMimeType: function( type ) { + if ( completed == null ) { + s.mimeType = type; + } + return this; + }, + + // Status-dependent callbacks + statusCode: function( map ) { + var code; + if ( map ) { + if ( completed ) { + + // Execute the appropriate callbacks + jqXHR.always( map[ jqXHR.status ] ); + } else { + + // Lazy-add the new callbacks in a way that preserves old ones + for ( code in map ) { + statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; + } + } + } + return this; + }, + + // Cancel the request + abort: function( statusText ) { + var finalText = statusText || strAbort; + if ( transport ) { + transport.abort( finalText ); + } + done( 0, finalText ); + return this; + } + }; + + // Attach deferreds + deferred.promise( jqXHR ); + + // Add protocol if not provided (prefilters might expect it) + // Handle falsy url in the settings object (#10093: consistency with old signature) + // We also use the url parameter if available + s.url = ( ( url || s.url || location.href ) + "" ) + .replace( rprotocol, location.protocol + "//" ); + + // Alias method option to type as per ticket #12004 + s.type = options.method || options.type || s.method || s.type; + + // Extract dataTypes list + s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; + + // A cross-domain request is in order when the origin doesn't match the current origin. + if ( s.crossDomain == null ) { + urlAnchor = document.createElement( "a" ); + + // Support: IE <=8 - 11, Edge 12 - 15 + // IE throws exception on accessing the href property if url is malformed, + // e.g. http://example.com:80x/ + try { + urlAnchor.href = s.url; + + // Support: IE <=8 - 11 only + // Anchor's host property isn't correctly set when s.url is relative + urlAnchor.href = urlAnchor.href; + s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== + urlAnchor.protocol + "//" + urlAnchor.host; + } catch ( e ) { + + // If there is an error parsing the URL, assume it is crossDomain, + // it can be rejected by the transport if it is invalid + s.crossDomain = true; + } + } + + // Convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // Apply prefilters + inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); + + // If request was aborted inside a prefilter, stop there + if ( completed ) { + return jqXHR; + } + + // We can fire global events as of now if asked to + // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) + fireGlobals = jQuery.event && s.global; + + // Watch for a new set of requests + if ( fireGlobals && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Save the URL in case we're toying with the If-Modified-Since + // and/or If-None-Match header later on + // Remove hash to simplify url manipulation + cacheURL = s.url.replace( rhash, "" ); + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // Remember the hash so we can put it back + uncached = s.url.slice( cacheURL.length ); + + // If data is available and should be processed, append data to url + if ( s.data && ( s.processData || typeof s.data === "string" ) ) { + cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; + + // #9682: remove data so that it's not used in an eventual retry + delete s.data; + } + + // Add or update anti-cache param if needed + if ( s.cache === false ) { + cacheURL = cacheURL.replace( rantiCache, "$1" ); + uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) + + uncached; + } + + // Put hash and anti-cache on the URL that will be requested (gh-1732) + s.url = cacheURL + uncached; + + // Change '%20' to '+' if this is encoded form body content (gh-2658) + } else if ( s.data && s.processData && + ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { + s.data = s.data.replace( r20, "+" ); + } + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + if ( jQuery.lastModified[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); + } + if ( jQuery.etag[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); + } + } + + // Set the correct header, if data is being sent + if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { + jqXHR.setRequestHeader( "Content-Type", s.contentType ); + } + + // Set the Accepts header for the server, depending on the dataType + jqXHR.setRequestHeader( + "Accept", + s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? + s.accepts[ s.dataTypes[ 0 ] ] + + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : + s.accepts[ "*" ] + ); + + // Check for headers option + for ( i in s.headers ) { + jqXHR.setRequestHeader( i, s.headers[ i ] ); + } + + // Allow custom headers/mimetypes and early abort + if ( s.beforeSend && + ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { + + // Abort if not done already and return + return jqXHR.abort(); + } + + // Aborting is no longer a cancellation + strAbort = "abort"; + + // Install callbacks on deferreds + completeDeferred.add( s.complete ); + jqXHR.done( s.success ); + jqXHR.fail( s.error ); + + // Get transport + transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); + + // If no transport, we auto-abort + if ( !transport ) { + done( -1, "No Transport" ); + } else { + jqXHR.readyState = 1; + + // Send global event + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); + } + + // If request was aborted inside ajaxSend, stop there + if ( completed ) { + return jqXHR; + } + + // Timeout + if ( s.async && s.timeout > 0 ) { + timeoutTimer = window.setTimeout( function() { + jqXHR.abort( "timeout" ); + }, s.timeout ); + } + + try { + completed = false; + transport.send( requestHeaders, done ); + } catch ( e ) { + + // Rethrow post-completion exceptions + if ( completed ) { + throw e; + } + + // Propagate others as results + done( -1, e ); + } + } + + // Callback for when everything is done + function done( status, nativeStatusText, responses, headers ) { + var isSuccess, success, error, response, modified, + statusText = nativeStatusText; + + // Ignore repeat invocations + if ( completed ) { + return; + } + + completed = true; + + // Clear timeout if it exists + if ( timeoutTimer ) { + window.clearTimeout( timeoutTimer ); + } + + // Dereference transport for early garbage collection + // (no matter how long the jqXHR object will be used) + transport = undefined; + + // Cache response headers + responseHeadersString = headers || ""; + + // Set readyState + jqXHR.readyState = status > 0 ? 4 : 0; + + // Determine if successful + isSuccess = status >= 200 && status < 300 || status === 304; + + // Get response data + if ( responses ) { + response = ajaxHandleResponses( s, jqXHR, responses ); + } + + // Use a noop converter for missing script + if ( !isSuccess && jQuery.inArray( "script", s.dataTypes ) > -1 ) { + s.converters[ "text script" ] = function() {}; + } + + // Convert no matter what (that way responseXXX fields are always set) + response = ajaxConvert( s, response, jqXHR, isSuccess ); + + // If successful, handle type chaining + if ( isSuccess ) { + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + modified = jqXHR.getResponseHeader( "Last-Modified" ); + if ( modified ) { + jQuery.lastModified[ cacheURL ] = modified; + } + modified = jqXHR.getResponseHeader( "etag" ); + if ( modified ) { + jQuery.etag[ cacheURL ] = modified; + } + } + + // if no content + if ( status === 204 || s.type === "HEAD" ) { + statusText = "nocontent"; + + // if not modified + } else if ( status === 304 ) { + statusText = "notmodified"; + + // If we have data, let's convert it + } else { + statusText = response.state; + success = response.data; + error = response.error; + isSuccess = !error; + } + } else { + + // Extract error from statusText and normalize for non-aborts + error = statusText; + if ( status || !statusText ) { + statusText = "error"; + if ( status < 0 ) { + status = 0; + } + } + } + + // Set data for the fake xhr object + jqXHR.status = status; + jqXHR.statusText = ( nativeStatusText || statusText ) + ""; + + // Success/Error + if ( isSuccess ) { + deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); + } else { + deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); + } + + // Status-dependent callbacks + jqXHR.statusCode( statusCode ); + statusCode = undefined; + + if ( fireGlobals ) { + globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", + [ jqXHR, s, isSuccess ? success : error ] ); + } + + // Complete + completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); + + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); + + // Handle the global AJAX counter + if ( !( --jQuery.active ) ) { + jQuery.event.trigger( "ajaxStop" ); + } + } + } + + return jqXHR; + }, + + getJSON: function( url, data, callback ) { + return jQuery.get( url, data, callback, "json" ); + }, + + getScript: function( url, callback ) { + return jQuery.get( url, undefined, callback, "script" ); + } +} ); + +jQuery.each( [ "get", "post" ], function( _i, method ) { + jQuery[ method ] = function( url, data, callback, type ) { + + // Shift arguments if data argument was omitted + if ( isFunction( data ) ) { + type = type || callback; + callback = data; + data = undefined; + } + + // The url can be an options object (which then must have .url) + return jQuery.ajax( jQuery.extend( { + url: url, + type: method, + dataType: type, + data: data, + success: callback + }, jQuery.isPlainObject( url ) && url ) ); + }; +} ); + +jQuery.ajaxPrefilter( function( s ) { + var i; + for ( i in s.headers ) { + if ( i.toLowerCase() === "content-type" ) { + s.contentType = s.headers[ i ] || ""; + } + } +} ); + + +jQuery._evalUrl = function( url, options, doc ) { + return jQuery.ajax( { + url: url, + + // Make this explicit, since user can override this through ajaxSetup (#11264) + type: "GET", + dataType: "script", + cache: true, + async: false, + global: false, + + // Only evaluate the response if it is successful (gh-4126) + // dataFilter is not invoked for failure responses, so using it instead + // of the default converter is kludgy but it works. + converters: { + "text script": function() {} + }, + dataFilter: function( response ) { + jQuery.globalEval( response, options, doc ); + } + } ); +}; + + +jQuery.fn.extend( { + wrapAll: function( html ) { + var wrap; + + if ( this[ 0 ] ) { + if ( isFunction( html ) ) { + html = html.call( this[ 0 ] ); + } + + // The elements to wrap the target around + wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); + + if ( this[ 0 ].parentNode ) { + wrap.insertBefore( this[ 0 ] ); + } + + wrap.map( function() { + var elem = this; + + while ( elem.firstElementChild ) { + elem = elem.firstElementChild; + } + + return elem; + } ).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( isFunction( html ) ) { + return this.each( function( i ) { + jQuery( this ).wrapInner( html.call( this, i ) ); + } ); + } + + return this.each( function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + } ); + }, + + wrap: function( html ) { + var htmlIsFunction = isFunction( html ); + + return this.each( function( i ) { + jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); + } ); + }, + + unwrap: function( selector ) { + this.parent( selector ).not( "body" ).each( function() { + jQuery( this ).replaceWith( this.childNodes ); + } ); + return this; + } +} ); + + +jQuery.expr.pseudos.hidden = function( elem ) { + return !jQuery.expr.pseudos.visible( elem ); +}; +jQuery.expr.pseudos.visible = function( elem ) { + return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); +}; + + + + +jQuery.ajaxSettings.xhr = function() { + try { + return new window.XMLHttpRequest(); + } catch ( e ) {} +}; + +var xhrSuccessStatus = { + + // File protocol always yields status code 0, assume 200 + 0: 200, + + // Support: IE <=9 only + // #1450: sometimes IE returns 1223 when it should be 204 + 1223: 204 + }, + xhrSupported = jQuery.ajaxSettings.xhr(); + +support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); +support.ajax = xhrSupported = !!xhrSupported; + +jQuery.ajaxTransport( function( options ) { + var callback, errorCallback; + + // Cross domain only allowed if supported through XMLHttpRequest + if ( support.cors || xhrSupported && !options.crossDomain ) { + return { + send: function( headers, complete ) { + var i, + xhr = options.xhr(); + + xhr.open( + options.type, + options.url, + options.async, + options.username, + options.password + ); + + // Apply custom fields if provided + if ( options.xhrFields ) { + for ( i in options.xhrFields ) { + xhr[ i ] = options.xhrFields[ i ]; + } + } + + // Override mime type if needed + if ( options.mimeType && xhr.overrideMimeType ) { + xhr.overrideMimeType( options.mimeType ); + } + + // X-Requested-With header + // For cross-domain requests, seeing as conditions for a preflight are + // akin to a jigsaw puzzle, we simply never set it to be sure. + // (it can always be set on a per-request basis or even using ajaxSetup) + // For same-domain requests, won't change header if already provided. + if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { + headers[ "X-Requested-With" ] = "XMLHttpRequest"; + } + + // Set headers + for ( i in headers ) { + xhr.setRequestHeader( i, headers[ i ] ); + } + + // Callback + callback = function( type ) { + return function() { + if ( callback ) { + callback = errorCallback = xhr.onload = + xhr.onerror = xhr.onabort = xhr.ontimeout = + xhr.onreadystatechange = null; + + if ( type === "abort" ) { + xhr.abort(); + } else if ( type === "error" ) { + + // Support: IE <=9 only + // On a manual native abort, IE9 throws + // errors on any property access that is not readyState + if ( typeof xhr.status !== "number" ) { + complete( 0, "error" ); + } else { + complete( + + // File: protocol always yields status 0; see #8605, #14207 + xhr.status, + xhr.statusText + ); + } + } else { + complete( + xhrSuccessStatus[ xhr.status ] || xhr.status, + xhr.statusText, + + // Support: IE <=9 only + // IE9 has no XHR2 but throws on binary (trac-11426) + // For XHR2 non-text, let the caller handle it (gh-2498) + ( xhr.responseType || "text" ) !== "text" || + typeof xhr.responseText !== "string" ? + { binary: xhr.response } : + { text: xhr.responseText }, + xhr.getAllResponseHeaders() + ); + } + } + }; + }; + + // Listen to events + xhr.onload = callback(); + errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" ); + + // Support: IE 9 only + // Use onreadystatechange to replace onabort + // to handle uncaught aborts + if ( xhr.onabort !== undefined ) { + xhr.onabort = errorCallback; + } else { + xhr.onreadystatechange = function() { + + // Check readyState before timeout as it changes + if ( xhr.readyState === 4 ) { + + // Allow onerror to be called first, + // but that will not handle a native abort + // Also, save errorCallback to a variable + // as xhr.onerror cannot be accessed + window.setTimeout( function() { + if ( callback ) { + errorCallback(); + } + } ); + } + }; + } + + // Create the abort callback + callback = callback( "abort" ); + + try { + + // Do send the request (this may raise an exception) + xhr.send( options.hasContent && options.data || null ); + } catch ( e ) { + + // #14683: Only rethrow if this hasn't been notified as an error yet + if ( callback ) { + throw e; + } + } + }, + + abort: function() { + if ( callback ) { + callback(); + } + } + }; + } +} ); + + + + +// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) +jQuery.ajaxPrefilter( function( s ) { + if ( s.crossDomain ) { + s.contents.script = false; + } +} ); + +// Install script dataType +jQuery.ajaxSetup( { + accepts: { + script: "text/javascript, application/javascript, " + + "application/ecmascript, application/x-ecmascript" + }, + contents: { + script: /\b(?:java|ecma)script\b/ + }, + converters: { + "text script": function( text ) { + jQuery.globalEval( text ); + return text; + } + } +} ); + +// Handle cache's special case and crossDomain +jQuery.ajaxPrefilter( "script", function( s ) { + if ( s.cache === undefined ) { + s.cache = false; + } + if ( s.crossDomain ) { + s.type = "GET"; + } +} ); + +// Bind script tag hack transport +jQuery.ajaxTransport( "script", function( s ) { + + // This transport only deals with cross domain or forced-by-attrs requests + if ( s.crossDomain || s.scriptAttrs ) { + var script, callback; + return { + send: function( _, complete ) { + script = jQuery( " + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

API Reference

+

The following section outlines the API of discord.py.

+
+

Note

+

This module uses the Python logging module to log diagnostic and errors +in an output independent way. If the logging module is not configured, +these logs will not be output anywhere. See Setting Up Logging for +more information on how to set up and use the logging module with +discord.py.

+
+ +
+

Clients

+
+

Client

+
+
+class discord.Client(*, intents, loop=None, **options)
+

Represents a client connection that connects to Discord. +This class is used to interact with the Discord WebSocket and API.

+

A number of options can be passed to the Client.

+
+
Parameters
+
    +
  • max_messages (Optional[int]) –

    The maximum number of messages to store in the internal message cache. +This defaults to 1000. Passing in None disables the message cache.

    +
    +

    Changed in version 1.3: Allow disabling the message cache and change the default size to 1000.

    +
    +

  • +
  • loop (Optional[asyncio.AbstractEventLoop]) – The asyncio.AbstractEventLoop to use for asynchronous operations. +Defaults to None, in which case the default event loop is used via +asyncio.get_event_loop().

  • +
  • connector (Optional[aiohttp.BaseConnector]) – The connector to use for connection pooling.

  • +
  • proxy (Optional[str]) – Proxy URL.

  • +
  • proxy_auth (Optional[aiohttp.BasicAuth]) – An object that represents proxy HTTP Basic Authorization.

  • +
  • shard_id (Optional[int]) – Integer starting at 0 and less than shard_count.

  • +
  • shard_count (Optional[int]) – The total number of shards.

  • +
  • application_id (int) – The client’s application ID.

  • +
  • intents (Intents) –

    The intents that you want to enable for the session. This is a way of +disabling and enabling certain gateway events from triggering and being sent.

    +
    +

    New in version 1.5.

    +
    +

  • +
  • member_cache_flags (MemberCacheFlags) –

    Allows for finer control over how the library caches members. +If not given, defaults to cache as much as possible with the +currently selected intents.

    +
    +

    New in version 1.5.

    +
    +

  • +
  • chunk_guilds_at_startup (bool) –

    Indicates if on_ready() should be delayed to chunk all guilds +at start-up if necessary. This operation is incredibly slow for large +amounts of guilds. The default is True if Intents.members +is True.

    +
    +

    New in version 1.5.

    +
    +

  • +
  • status (Optional[Status]) – A status to start your presence with upon logging on to Discord.

  • +
  • activity (Optional[BaseActivity]) – An activity to start your presence with upon logging on to Discord.

  • +
  • allowed_mentions (Optional[AllowedMentions]) –

    Control how the client handles mentions by default on every message sent.

    +
    +

    New in version 1.4.

    +
    +

  • +
  • heartbeat_timeout (float) – The maximum numbers of seconds before timing out and restarting the +WebSocket in the case of not receiving a HEARTBEAT_ACK. Useful if +processing the initial packets take too long to the point of disconnecting +you. The default timeout is 60 seconds.

  • +
  • guild_ready_timeout (float) –

    The maximum number of seconds to wait for the GUILD_CREATE stream to end before +preparing the member cache and firing READY. The default timeout is 2 seconds.

    +
    +

    New in version 1.4.

    +
    +

  • +
  • assume_unsync_clock (bool) –

    Whether to assume the system clock is unsynced. This applies to the ratelimit handling +code. If this is set to True, the default, then the library uses the time to reset +a rate limit bucket given by Discord. If this is False then your system clock is +used to calculate how long to sleep for. If this is set to False it is recommended to +sync your system clock to Google’s NTP server.

    +
    +

    New in version 1.3.

    +
    +

  • +
  • enable_debug_events (bool) –

    Whether to enable events that are useful only for debugging gateway related information.

    +

    Right now this involves on_socket_raw_receive() and on_socket_raw_send(). If +this is False then those events will not be dispatched (due to performance considerations). +To enable these events, this must be set to True. Defaults to False.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
+
+
+ws
+

The websocket gateway the client is currently connected to. Could be None.

+
+ +
+
+loop
+

The event loop that the client uses for asynchronous operations.

+
+
Type
+

asyncio.AbstractEventLoop

+
+
+
+ +
+
+@event
+

A decorator that registers an event to listen to.

+

You can find more info about the events on the documentation below.

+

The events must be a coroutine, if not, TypeError is raised.

+

Example

+
@client.event
+async def on_ready():
+    print('Ready!')
+
+
+
+
Raises
+

TypeError – The coroutine passed is not actually a coroutine.

+
+
+
+ +
+
+async for ... in fetch_guilds(*, limit=100, before=None, after=None)
+

Retrieves an AsyncIterator that enables receiving your guilds.

+
+

Note

+

Using this, you will only receive Guild.owner, Guild.icon, +Guild.id, and Guild.name per Guild.

+
+
+

Note

+

This method is an API call. For general usage, consider guilds instead.

+
+

Examples

+

Usage

+
async for guild in client.fetch_guilds(limit=150):
+    print(guild.name)
+
+
+

Flattening into a list

+
guilds = await client.fetch_guilds(limit=150).flatten()
+# guilds is now a list of Guild...
+
+
+

All parameters are optional.

+
+
Parameters
+
    +
  • limit (Optional[int]) – The number of guilds to retrieve. +If None, it retrieves every guild you have access to. Note, however, +that this would make it a slow operation. +Defaults to 100.

  • +
  • before (Union[abc.Snowflake, datetime.datetime]) – Retrieves guilds before this date or object. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • after (Union[abc.Snowflake, datetime.datetime]) – Retrieve guilds after this date or object. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
+
+
Raises
+

HTTPException – Getting the guilds failed.

+
+
Yields
+

Guild – The guild with the guild data parsed.

+
+
+
+ +
+
+property latency
+

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

+

This could be referred to as the Discord WebSocket protocol latency.

+
+
Type
+

float

+
+
+
+ +
+
+is_ws_ratelimited()
+

bool: Whether the websocket is currently rate limited.

+

This can be useful to know when deciding whether you should query members +using HTTP or via the gateway.

+
+

New in version 1.6.

+
+
+ +
+
+property user
+

Represents the connected client. None if not logged in.

+
+
Type
+

Optional[ClientUser]

+
+
+
+ +
+
+property guilds
+

The guilds that the connected client is a member of.

+
+
Type
+

List[Guild]

+
+
+
+ +
+
+property emojis
+

The emojis that the connected client has.

+
+
Type
+

List[Emoji]

+
+
+
+ +
+
+property stickers
+

The stickers that the connected client has.

+
+

New in version 2.0.

+
+
+
Type
+

List[GuildSticker]

+
+
+
+ +
+
+property cached_messages
+

Read-only list of messages the connected client has cached.

+
+

New in version 1.1.

+
+
+
Type
+

Sequence[Message]

+
+
+
+ +
+
+property private_channels
+

The private channels that the connected client is participating on.

+
+

Note

+

This returns only up to 128 most recent private channels due to an internal working +on how Discord deals with private channels.

+
+
+
Type
+

List[abc.PrivateChannel]

+
+
+
+ +
+
+property voice_clients
+

Represents a list of voice connections.

+

These are usually VoiceClient instances.

+
+
Type
+

List[VoiceProtocol]

+
+
+
+ +
+
+property application_id
+

The client’s application ID.

+

If this is not passed via __init__ then this is retrieved +through the gateway when an event contains the data. Usually +after on_connect() is called.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[int]

+
+
+
+ +
+
+property application_flags
+

The client’s application flags.

+
+

New in version 2.0.

+
+
+
Type
+

ApplicationFlags

+
+
+
+ +
+
+is_ready()
+

bool: Specifies if the client’s internal cache is ready for use.

+
+ +
+
+await on_error(event_method, *args, **kwargs)
+

This function is a coroutine.

+

The default error handler provided by the client.

+

By default this prints to sys.stderr however it could be +overridden to have a different implementation. +Check on_error() for more details.

+
+ +
+
+await before_identify_hook(shard_id, *, initial=False)
+

This function is a coroutine.

+

A hook that is called before IDENTIFYing a session. This is useful +if you wish to have more control over the synchronization of multiple +IDENTIFYing clients.

+

The default implementation sleeps for 5 seconds.

+
+

New in version 1.4.

+
+
+
Parameters
+
    +
  • shard_id (int) – The shard ID that requested being IDENTIFY’d

  • +
  • initial (bool) – Whether this IDENTIFY is the first initial IDENTIFY.

  • +
+
+
+
+ +
+
+await login(token)
+

This function is a coroutine.

+

Logs in the client with the specified credentials.

+
+
Parameters
+

token (str) – The authentication token. Do not prefix this token with +anything as the library will do it for you.

+
+
Raises
+
    +
  • LoginFailure – The wrong credentials are passed.

  • +
  • HTTPException – An unknown HTTP related error occurred, + usually when it isn’t 200 or the known incorrect credentials + passing status code.

  • +
+
+
+
+ +
+
+await connect(*, reconnect=True)
+

This function is a coroutine.

+

Creates a websocket connection and lets the websocket listen +to messages from Discord. This is a loop that runs the entire +event system and miscellaneous aspects of the library. Control +is not resumed until the WebSocket connection is terminated.

+
+
Parameters
+

reconnect (bool) – If we should attempt reconnecting, either due to internet +failure or a specific failure on Discord’s part. Certain +disconnects that lead to bad state will not be handled (such as +invalid sharding payloads or bad tokens).

+
+
Raises
+
    +
  • GatewayNotFound – If the gateway to connect to Discord is not found. Usually if this + is thrown then there is a Discord API outage.

  • +
  • ConnectionClosed – The websocket connection has been terminated.

  • +
+
+
+
+ +
+
+await close()
+

This function is a coroutine.

+

Closes the connection to Discord.

+
+ +
+
+clear()
+

Clears the internal state of the bot.

+

After this, the bot can be considered “re-opened”, i.e. is_closed() +and is_ready() both return False along with the bot’s internal +cache cleared.

+
+ +
+
+await start(token, *, reconnect=True)
+

This function is a coroutine.

+

A shorthand coroutine for login() + setup() + connect().

+
+
Raises
+

TypeError – An unexpected keyword argument was received.

+
+
+
+ +
+
+await setup()
+

This function is a coroutine.

+

A coroutine to be called to setup the bot, by default this is blank.

+

To perform asynchronous setup after the bot is logged in but before +it has connected to the Websocket, overwrite this coroutine.

+
+

New in version 2.0.

+
+
+ +
+
+run(*args, **kwargs)
+

A blocking call that abstracts away the event loop +initialisation from you.

+

If you want more control over the event loop then this +function should not be used. Use start() coroutine +or connect() + login().

+

Roughly Equivalent to:

+
try:
+    loop.run_until_complete(start(*args, **kwargs))
+except KeyboardInterrupt:
+    loop.run_until_complete(close())
+    # cancel all tasks lingering
+finally:
+    loop.close()
+
+
+
+

Warning

+

This function must be the last function to call due to the fact that it +is blocking. That means that registration of events or anything being +called after this function call will not execute until it returns.

+
+
+ +
+
+is_closed()
+

bool: Indicates if the websocket connection is closed.

+
+ +
+
+property activity
+

The activity being used upon +logging in.

+
+
Type
+

Optional[BaseActivity]

+
+
+
+ +
+
+property status
+

Status: +The status being used upon logging on to Discord.

+
+

New in version 2.0.

+
+
+ +
+
+property allowed_mentions
+

The allowed mention configuration.

+
+

New in version 1.4.

+
+
+
Type
+

Optional[AllowedMentions]

+
+
+
+ +
+
+property intents
+

The intents configured for this connection.

+
+

New in version 1.5.

+
+
+
Type
+

Intents

+
+
+
+ +
+
+property users
+

Returns a list of all the users the bot can see.

+
+
Type
+

List[User]

+
+
+
+ +
+
+get_channel(id, /)
+

Returns a channel or thread with the given ID.

+
+
Parameters
+

id (int) – The ID to search for.

+
+
Returns
+

The returned channel or None if not found.

+
+
Return type
+

Optional[Union[abc.GuildChannel, Thread, abc.PrivateChannel]]

+
+
+
+ +
+
+get_partial_messageable(id, *, type=None)
+

Returns a partial messageable with the given channel ID.

+

This is useful if you have a channel_id but don’t want to do an API call +to send messages to it.

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • id (int) – The channel ID to create a partial messageable for.

  • +
  • type (Optional[ChannelType]) – The underlying channel type for the partial messageable.

  • +
+
+
Returns
+

The partial messageable

+
+
Return type
+

PartialMessageable

+
+
+
+ +
+
+get_stage_instance(id, /)
+

Returns a stage instance with the given stage channel ID.

+
+

New in version 2.0.

+
+
+
Parameters
+

id (int) – The ID to search for.

+
+
Returns
+

The returns stage instance of None if not found.

+
+
Return type
+

Optional[StageInstance]

+
+
+
+ +
+
+get_guild(id, /)
+

Returns a guild with the given ID.

+
+
Parameters
+

id (int) – The ID to search for.

+
+
Returns
+

The guild or None if not found.

+
+
Return type
+

Optional[Guild]

+
+
+
+ +
+
+get_user(id, /)
+

Returns a user with the given ID.

+
+
Parameters
+

id (int) – The ID to search for.

+
+
Returns
+

The user or None if not found.

+
+
Return type
+

Optional[User]

+
+
+
+ +
+
+await try_user(id, /)
+

This function is a coroutine. +Returns a user with the given ID. If not from cache, the user will be requested from the API.

+

You do not have to share any guilds with the user to get this information from the API, +however many operations do require that you do.

+
+

Note

+

This method is an API call. If you have discord.Intents.members and member cache enabled, consider get_user() instead.

+
+
+

New in version 2.0.

+
+
+
Parameters
+

id (int) – The ID to search for.

+
+
Returns
+

The user or None if not found.

+
+
Return type
+

Optional[User]

+
+
+
+ +
+
+get_emoji(id, /)
+

Returns an emoji with the given ID.

+
+
Parameters
+

id (int) – The ID to search for.

+
+
Returns
+

The custom emoji or None if not found.

+
+
Return type
+

Optional[Emoji]

+
+
+
+ +
+
+get_sticker(id, /)
+

Returns a guild sticker with the given ID.

+
+

New in version 2.0.

+
+
+

Note

+

To retrieve standard stickers, use fetch_sticker(). +or fetch_premium_sticker_packs().

+
+
+
Returns
+

The sticker or None if not found.

+
+
Return type
+

Optional[GuildSticker]

+
+
+
+ +
+
+for ... in get_all_channels()
+

A generator that retrieves every abc.GuildChannel the client can ‘access’.

+

This is equivalent to:

+
for guild in client.guilds:
+    for channel in guild.channels:
+        yield channel
+
+
+
+

Note

+

Just because you receive a abc.GuildChannel does not mean that +you can communicate in said channel. abc.GuildChannel.permissions_for() should +be used for that.

+
+
+
Yields
+

abc.GuildChannel – A channel the client can ‘access’.

+
+
+
+ +
+
+for ... in get_all_members()
+

Returns a generator with every Member the client can see.

+

This is equivalent to:

+
for guild in client.guilds:
+    for member in guild.members:
+        yield member
+
+
+
+
Yields
+

Member – A member the client can see.

+
+
+
+ +
+
+await wait_until_ready()
+

This function is a coroutine.

+

Waits until the client’s internal cache is all ready.

+
+ +
+
+wait_for(event, *, check=None, timeout=None)
+

This function is a coroutine.

+

Waits for a WebSocket event to be dispatched.

+

This could be used to wait for a user to reply to a message, +or to react to a message, or to edit a message in a self-contained +way.

+

The timeout parameter is passed onto asyncio.wait_for(). By default, +it does not timeout. Note that this does propagate the +asyncio.TimeoutError for you in case of timeout and is provided for +ease of use.

+

In case the event returns multiple arguments, a tuple containing those +arguments is returned instead. Please check the +documentation for a list of events and their +parameters.

+

This function returns the first event that meets the requirements.

+

Examples

+

Waiting for a user reply:

+
@client.event
+async def on_message(message):
+    if message.content.startswith('$greet'):
+        channel = message.channel
+        await channel.send('Say hello!')
+
+        def check(m):
+            return m.content == 'hello' and m.channel == channel
+
+        msg = await client.wait_for('message', check=check)
+        await channel.send(f'Hello {msg.author}!')
+
+
+

Waiting for a thumbs up reaction from the message author:

+
@client.event
+async def on_message(message):
+    if message.content.startswith('$thumb'):
+        channel = message.channel
+        await channel.send('Send me that 👍 reaction, mate')
+
+        def check(reaction, user):
+            return user == message.author and str(reaction.emoji) == '👍'
+
+        try:
+            reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
+        except asyncio.TimeoutError:
+            await channel.send('👎')
+        else:
+            await channel.send('👍')
+
+
+
+
Parameters
+
    +
  • event (str) – The event name, similar to the event reference, +but without the on_ prefix, to wait for.

  • +
  • check (Optional[Callable[…, bool]]) – A predicate to check what to wait for. The arguments must meet the +parameters of the event being waited for.

  • +
  • timeout (Optional[float]) – The number of seconds to wait before timing out and raising +asyncio.TimeoutError.

  • +
+
+
Raises
+

asyncio.TimeoutError – If a timeout is provided and it was reached.

+
+
Returns
+

Returns no arguments, a single argument, or a tuple of multiple +arguments that mirrors the parameters passed in the +event reference.

+
+
Return type
+

Any

+
+
+
+ +
+
+await change_presence(*, activity=None, status=None)
+

This function is a coroutine.

+

Changes the client’s presence.

+

Example

+
game = discord.Game("with the API")
+await client.change_presence(status=discord.Status.idle, activity=game)
+
+
+
+

Changed in version 2.0: Removed the afk keyword-only parameter.

+
+
+
Parameters
+
    +
  • activity (Optional[BaseActivity]) – The activity being done. None if no currently active activity is done.

  • +
  • status (Optional[Status]) – Indicates what status to change to. If None, then +Status.online is used.

  • +
+
+
Raises
+

InvalidArgument – If the activity parameter is not the proper type.

+
+
+
+ +
+
+await fetch_template(code)
+

This function is a coroutine.

+

Gets a Template from a discord.new URL or code.

+
+
Parameters
+

code (Union[Template, str]) – The Discord Template Code or URL (must be a discord.new URL).

+
+
Raises
+
+
+
Returns
+

The template from the URL/code.

+
+
Return type
+

Template

+
+
+
+ +
+
+await fetch_guild(guild_id, /)
+

This function is a coroutine.

+

Retrieves a Guild from an ID.

+
+

Note

+

Using this, you will not receive Guild.channels, Guild.members, +Member.activity and Member.voice per Member.

+
+
+

Note

+

This method is an API call. For general usage, consider get_guild() instead.

+
+
+
Parameters
+

guild_id (int) – The guild’s ID to fetch from.

+
+
Raises
+
+
+
Returns
+

The guild from the ID.

+
+
Return type
+

Guild

+
+
+
+ +
+
+await create_guild(*, name, region=<VoiceRegion.us_west: 'us-west'>, icon=..., code=...)
+

This function is a coroutine.

+

Creates a Guild.

+

Bot accounts in more than 10 guilds are not allowed to create guilds.

+
+
Parameters
+
    +
  • name (str) – The name of the guild.

  • +
  • region (VoiceRegion) – The region for the voice communication server. +Defaults to VoiceRegion.us_west.

  • +
  • icon (Optional[bytes]) – The bytes-like object representing the icon. See ClientUser.edit() +for more details on what is expected.

  • +
  • code (str) –

    The code for a template to create the guild with.

    +
    +

    New in version 1.4.

    +
    +

  • +
+
+
Raises
+
+
+
Returns
+

The guild created. This is not the same guild that is +added to cache.

+
+
Return type
+

Guild

+
+
+
+ +
+
+await fetch_stage_instance(channel_id, /)
+

This function is a coroutine.

+

Gets a StageInstance for a stage channel id.

+
+

New in version 2.0.

+
+
+
Parameters
+

channel_id (int) – The stage channel ID.

+
+
Raises
+
    +
  • NotFound – The stage instance or channel could not be found.

  • +
  • HTTPException – Getting the stage instance failed.

  • +
+
+
Returns
+

The stage instance from the stage channel ID.

+
+
Return type
+

StageInstance

+
+
+
+ +
+
+await fetch_invite(url, *, with_counts=True, with_expiration=True)
+

This function is a coroutine.

+

Gets an Invite from a discord.gg URL or ID.

+
+

Note

+

If the invite is for a guild you have not joined, the guild and channel +attributes of the returned Invite will be PartialInviteGuild and +PartialInviteChannel respectively.

+
+
+
Parameters
+
+
+
Raises
+
+
+
Returns
+

The invite from the URL/ID.

+
+
Return type
+

Invite

+
+
+
+ +
+
+await delete_invite(invite)
+

This function is a coroutine.

+

Revokes an Invite, URL, or ID to an invite.

+

You must have the manage_channels permission in +the associated guild to do this.

+
+
Parameters
+

invite (Union[Invite, str]) – The invite to revoke.

+
+
Raises
+
    +
  • Forbidden – You do not have permissions to revoke invites.

  • +
  • NotFound – The invite is invalid or expired.

  • +
  • HTTPException – Revoking the invite failed.

  • +
+
+
+
+ +
+
+await fetch_widget(guild_id, /)
+

This function is a coroutine.

+

Gets a Widget from a guild ID.

+
+

Note

+

The guild must have the widget enabled to get this information.

+
+
+
Parameters
+

guild_id (int) – The ID of the guild.

+
+
Raises
+
+
+
Returns
+

The guild’s widget.

+
+
Return type
+

Widget

+
+
+
+ +
+
+await application_info()
+

This function is a coroutine.

+

Retrieves the bot’s application information.

+
+
Raises
+

HTTPException – Retrieving the information failed somehow.

+
+
Returns
+

The bot’s application information.

+
+
Return type
+

AppInfo

+
+
+
+ +
+
+await fetch_user(user_id, /)
+

This function is a coroutine.

+

Retrieves a User based on their ID. +You do not have to share any guilds with the user to get this information, +however many operations do require that you do.

+
+

Note

+

This method is an API call. If you have discord.Intents.members and member cache enabled, consider get_user() instead.

+
+
+
Parameters
+

user_id (int) – The user’s ID to fetch from.

+
+
Raises
+
+
+
Returns
+

The user you requested.

+
+
Return type
+

User

+
+
+
+ +
+
+await fetch_channel(channel_id, /)
+

This function is a coroutine.

+

Retrieves a abc.GuildChannel, abc.PrivateChannel, or Thread with the specified ID.

+
+

Note

+

This method is an API call. For general usage, consider get_channel() instead.

+
+
+

New in version 1.2.

+
+
+
Raises
+
    +
  • InvalidData – An unknown channel type was received from Discord.

  • +
  • HTTPException – Retrieving the channel failed.

  • +
  • NotFound – Invalid Channel ID.

  • +
  • Forbidden – You do not have permission to fetch this channel.

  • +
+
+
Returns
+

The channel from the ID.

+
+
Return type
+

Union[abc.GuildChannel, abc.PrivateChannel, Thread]

+
+
+
+ +
+
+await fetch_webhook(webhook_id, /)
+

This function is a coroutine.

+

Retrieves a Webhook with the specified ID.

+
+
Raises
+
    +
  • HTTPException – Retrieving the webhook failed.

  • +
  • NotFound – Invalid webhook ID.

  • +
  • Forbidden – You do not have permission to fetch this webhook.

  • +
+
+
Returns
+

The webhook you requested.

+
+
Return type
+

Webhook

+
+
+
+ +
+
+await fetch_sticker(sticker_id, /)
+

This function is a coroutine.

+

Retrieves a Sticker with the specified ID.

+
+

New in version 2.0.

+
+
+
Raises
+
+
+
Returns
+

The sticker you requested.

+
+
Return type
+

Union[StandardSticker, GuildSticker]

+
+
+
+ +
+
+await fetch_premium_sticker_packs()
+

This function is a coroutine.

+

Retrieves all available premium sticker packs.

+
+

New in version 2.0.

+
+
+
Raises
+

HTTPException – Retrieving the sticker packs failed.

+
+
Returns
+

All available premium sticker packs.

+
+
Return type
+

List[StickerPack]

+
+
+
+ +
+
+await create_dm(user)
+

This function is a coroutine.

+

Creates a DMChannel with this user.

+

This should be rarely called, as this is done transparently for most +people.

+
+

New in version 2.0.

+
+
+
Parameters
+

user (Snowflake) – The user to create a DM with.

+
+
Returns
+

The channel that was created.

+
+
Return type
+

DMChannel

+
+
+
+ +
+
+add_view(view, *, message_id=None)
+

Registers a View for persistent listening.

+

This method should be used for when a view is comprised of components +that last longer than the lifecycle of the program.

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • view (discord.ui.View) – The view to register for dispatching.

  • +
  • message_id (Optional[int]) – The message ID that the view is attached to. This is currently used to +refresh the view’s state during message update events. If not given +then message update events are not propagated for the view.

  • +
+
+
Raises
+
    +
  • TypeError – A view was not passed.

  • +
  • ValueError – The view is not persistent. A persistent view has no timeout + and all their components have an explicitly provided custom_id.

  • +
+
+
+
+ +
+
+property persistent_views
+

A sequence of persistent views added to the client.

+
+

New in version 2.0.

+
+
+
Type
+

Sequence[View]

+
+
+
+ +
+ +
+
+

AutoShardedClient

+
+ +Attributes +
+ +Methods +
+
+class discord.AutoShardedClient(*args, loop=None, **kwargs)
+

A client similar to Client except it handles the complications +of sharding for the user into a more manageable and transparent single +process bot.

+

When using this client, you will be able to use it as-if it was a regular +Client with a single shard when implementation wise internally it +is split up into multiple shards. This allows you to not have to deal with +IPC or other complicated infrastructure.

+

It is recommended to use this client only if you have surpassed at least +1000 guilds.

+

If no shard_count is provided, then the library will use the +Bot Gateway endpoint call to figure out how many shards to use.

+

If a shard_ids parameter is given, then those shard IDs will be used +to launch the internal shards. Note that shard_count must be provided +if this is used. By default, when omitted, the client will launch shards from +0 to shard_count - 1.

+
+
+shard_ids
+

An optional list of shard_ids to launch the shards with.

+
+
Type
+

Optional[List[int]]

+
+
+
+ +
+
+property latency
+

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

+

This operates similarly to Client.latency() except it uses the average +latency of every shard’s latency. To get a list of shard latency, check the +latencies property. Returns nan if there are no shards ready.

+
+
Type
+

float

+
+
+
+ +
+
+property latencies
+

A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

+

This returns a list of tuples with elements (shard_id, latency).

+
+
Type
+

List[Tuple[int, float]]

+
+
+
+ +
+
+get_shard(shard_id)
+

Optional[ShardInfo]: Gets the shard information at a given shard ID or None if not found.

+
+ +
+
+property shards
+

Returns a mapping of shard IDs to their respective info object.

+
+
Type
+

Mapping[int, ShardInfo]

+
+
+
+ +
+
+await connect(*, reconnect=True)
+

This function is a coroutine.

+

Creates a websocket connection and lets the websocket listen +to messages from Discord. This is a loop that runs the entire +event system and miscellaneous aspects of the library. Control +is not resumed until the WebSocket connection is terminated.

+
+
Parameters
+

reconnect (bool) – If we should attempt reconnecting, either due to internet +failure or a specific failure on Discord’s part. Certain +disconnects that lead to bad state will not be handled (such as +invalid sharding payloads or bad tokens).

+
+
Raises
+
    +
  • GatewayNotFound – If the gateway to connect to Discord is not found. Usually if this + is thrown then there is a Discord API outage.

  • +
  • ConnectionClosed – The websocket connection has been terminated.

  • +
+
+
+
+ +
+
+await close()
+

This function is a coroutine.

+

Closes the connection to Discord.

+
+ +
+
+await change_presence(*, activity=None, status=None, shard_id=None)
+

This function is a coroutine.

+

Changes the client’s presence.

+

Example:

+
game = discord.Game("with the API")
+await client.change_presence(status=discord.Status.idle, activity=game)
+
+
+
+

Changed in version 2.0: Removed the afk keyword-only parameter.

+
+
+
Parameters
+
    +
  • activity (Optional[BaseActivity]) – The activity being done. None if no currently active activity is done.

  • +
  • status (Optional[Status]) – Indicates what status to change to. If None, then +Status.online is used.

  • +
  • shard_id (Optional[int]) – The shard_id to change the presence to. If not specified +or None, then it will change the presence of every +shard the bot can see.

  • +
+
+
Raises
+

InvalidArgument – If the activity parameter is not of proper type.

+
+
+
+ +
+
+is_ws_ratelimited()
+

bool: Whether the websocket is currently rate limited.

+

This can be useful to know when deciding whether you should query members +using HTTP or via the gateway.

+

This implementation checks if any of the shards are rate limited. +For more granular control, consider ShardInfo.is_ws_ratelimited().

+
+

New in version 1.6.

+
+
+ +
+ +
+
+
+

Application Info

+
+

AppInfo

+
+
+class discord.AppInfo
+

Represents the application info for the bot provided by Discord.

+
+
+id
+

The application ID.

+
+
Type
+

int

+
+
+
+ +
+
+name
+

The application name.

+
+
Type
+

str

+
+
+
+ +
+
+owner
+

The application owner.

+
+
Type
+

User

+
+
+
+ +
+
+team
+

The application’s team.

+
+

New in version 1.3.

+
+
+
Type
+

Optional[Team]

+
+
+
+ +
+
+description
+

The application description.

+
+
Type
+

str

+
+
+
+ +
+
+bot_public
+

Whether the bot can be invited by anyone or if it is locked +to the application owner.

+
+
Type
+

bool

+
+
+
+ +
+
+bot_require_code_grant
+

Whether the bot requires the completion of the full oauth2 code +grant flow to join.

+
+
Type
+

bool

+
+
+
+ +
+
+rpc_origins
+

A list of RPC origin URLs, if RPC is enabled.

+
+
Type
+

Optional[List[str]]

+
+
+
+ +
+
+summary
+

If this application is a game sold on Discord, +this field will be the summary field for the store page of its primary SKU.

+
+

New in version 1.3.

+
+
+
Type
+

str

+
+
+
+ +
+
+verify_key
+

The hex encoded key for verification in interactions and the +GameSDK’s GetTicket.

+
+

New in version 1.3.

+
+
+
Type
+

str

+
+
+
+ +
+
+guild_id
+

If this application is a game sold on Discord, +this field will be the guild to which it has been linked to.

+
+

New in version 1.3.

+
+
+
Type
+

Optional[int]

+
+
+
+ +
+
+primary_sku_id
+

If this application is a game sold on Discord, +this field will be the id of the “Game SKU” that is created, +if it exists.

+
+

New in version 1.3.

+
+
+
Type
+

Optional[int]

+
+
+
+ +
+
+slug
+

If this application is a game sold on Discord, +this field will be the URL slug that links to the store page.

+
+

New in version 1.3.

+
+
+
Type
+

Optional[str]

+
+
+
+ +
+
+terms_of_service_url
+

The application’s terms of service URL, if set.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[str]

+
+
+
+ +
+
+privacy_policy_url
+

The application’s privacy policy URL, if set.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[str]

+
+
+
+ +
+
+property icon
+

Retrieves the application’s icon asset, if any.

+
+
Type
+

Optional[Asset]

+
+
+
+ +
+
+property cover_image
+

Retrieves the cover image on a store embed, if any.

+

This is only available if the application is a game sold on Discord.

+
+
Type
+

Optional[Asset]

+
+
+
+ +
+
+property guild
+

If this application is a game sold on Discord, +this field will be the guild to which it has been linked

+
+

New in version 1.3.

+
+
+
Type
+

Optional[Guild]

+
+
+
+ +
+ +
+
+

PartialAppInfo

+
+
+class discord.PartialAppInfo
+

Represents a partial AppInfo given by create_invite()

+
+

New in version 2.0.

+
+
+
+id
+

The application ID.

+
+
Type
+

int

+
+
+
+ +
+
+name
+

The application name.

+
+
Type
+

str

+
+
+
+ +
+
+description
+

The application description.

+
+
Type
+

str

+
+
+
+ +
+
+rpc_origins
+

A list of RPC origin URLs, if RPC is enabled.

+
+
Type
+

Optional[List[str]]

+
+
+
+ +
+
+summary
+

If this application is a game sold on Discord, +this field will be the summary field for the store page of its primary SKU.

+
+
Type
+

str

+
+
+
+ +
+
+verify_key
+

The hex encoded key for verification in interactions and the +GameSDK’s GetTicket.

+
+
Type
+

str

+
+
+
+ +
+
+terms_of_service_url
+

The application’s terms of service URL, if set.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+privacy_policy_url
+

The application’s privacy policy URL, if set.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+property icon
+

Retrieves the application’s icon asset, if any.

+
+
Type
+

Optional[Asset]

+
+
+
+ +
+ +
+
+

Team

+
+ +Attributes +
+
+class discord.Team
+

Represents an application team for a bot provided by Discord.

+
+
+id
+

The team ID.

+
+
Type
+

int

+
+
+
+ +
+
+name
+

The team name

+
+
Type
+

str

+
+
+
+ +
+
+owner_id
+

The team’s owner ID.

+
+
Type
+

int

+
+
+
+ +
+
+members
+

A list of the members in the team

+
+

New in version 1.3.

+
+
+
Type
+

List[TeamMember]

+
+
+
+ +
+
+property icon
+

Retrieves the team’s icon asset, if any.

+
+
Type
+

Optional[Asset]

+
+
+
+ +
+
+property owner
+

The team’s owner.

+
+
Type
+

Optional[TeamMember]

+
+
+
+ +
+ +
+
+

TeamMember

+
+ +Attributes +
+
+class discord.TeamMember
+

Represents a team member in a team.

+
+
+
+x == y
+

Checks if two team members are equal.

+
+ +
+
+x != y
+

Checks if two team members are not equal.

+
+ +
+
+hash(x)
+

Return the team member’s hash.

+
+ +
+
+str(x)
+

Returns the team member’s name with discriminator.

+
+ +
+
+

New in version 1.3.

+
+
+
+name
+

The team member’s username.

+
+
Type
+

str

+
+
+
+ +
+
+id
+

The team member’s unique ID.

+
+
Type
+

int

+
+
+
+ +
+
+discriminator
+

The team member’s discriminator. This is given when the username has conflicts.

+
+
Type
+

str

+
+
+
+ +
+
+avatar
+

The avatar hash the team member has. Could be None.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+bot
+

Specifies if the user is a bot account.

+
+
Type
+

bool

+
+
+
+ +
+
+team
+

The team that the member is from.

+
+
Type
+

Team

+
+
+
+ +
+
+membership_state
+

The membership state of the member (e.g. invited or accepted)

+
+
Type
+

TeamMembershipState

+
+
+
+ +
+ +
+
+ +
+

Event Reference

+

This section outlines the different types of events listened by Client.

+

There are two ways to register an event, the first way is through the use of +Client.event(). The second way is through subclassing Client and +overriding the specific events. For example:

+
import discord
+
+class MyClient(discord.Client):
+    async def on_message(self, message):
+        if message.author == self.user:
+            return
+
+        if message.content.startswith('$hello'):
+            await message.channel.send('Hello World!')
+
+
+

If an event handler raises an exception, on_error() will be called +to handle it, which defaults to print a traceback and ignoring the exception.

+
+

Warning

+

All the events must be a coroutine. If they aren’t, then you might get unexpected +errors. In order to turn a function into a coroutine they must be async def +functions.

+
+
+

Networking

+
+
+discord.on_connect()
+

Called when the client has successfully connected to Discord. This is not +the same as the client being fully prepared, see on_ready() for that.

+

The warnings on on_ready() also apply.

+
+ +
+
+discord.on_shard_connect(shard_id)
+

Similar to on_connect() except used by AutoShardedClient +to denote when a particular shard ID has connected to Discord.

+
+

New in version 1.4.

+
+
+
Parameters
+

shard_id (int) – The shard ID that has connected.

+
+
+
+ +
+
+discord.on_disconnect()
+

Called when the client has disconnected from Discord, or a connection attempt to Discord has failed. +This could happen either through the internet being disconnected, explicit calls to close, +or Discord terminating the connection one way or the other.

+

This function can be called many times without a corresponding on_connect() call.

+
+ +
+
+discord.on_shard_disconnect(shard_id)
+

Similar to on_disconnect() except used by AutoShardedClient +to denote when a particular shard ID has disconnected from Discord.

+
+

New in version 1.4.

+
+
+
Parameters
+

shard_id (int) – The shard ID that has disconnected.

+
+
+
+ +
+
+discord.on_ready()
+

Called when the client is done preparing the data received from Discord. Usually after login is successful +and the Client.guilds and co. are filled up.

+
+

Warning

+

This function is not guaranteed to be the first event called. +Likewise, this function is not guaranteed to only be called +once. This library implements reconnection logic and thus will +end up calling this event whenever a RESUME request fails.

+
+
+ +
+
+discord.on_shard_ready(shard_id)
+

Similar to on_ready() except used by AutoShardedClient +to denote when a particular shard ID has become ready.

+
+
Parameters
+

shard_id (int) – The shard ID that is ready.

+
+
+
+ +
+
+discord.on_resumed()
+

Called when the client has resumed a session.

+
+ +
+
+discord.on_shard_resumed(shard_id)
+

Similar to on_resumed() except used by AutoShardedClient +to denote when a particular shard ID has resumed a session.

+
+

New in version 1.4.

+
+
+
Parameters
+

shard_id (int) – The shard ID that has resumed.

+
+
+
+ +
+
+discord.on_error(event, *args, **kwargs)
+

Usually when an event raises an uncaught exception, a traceback is +printed to stderr and the exception is ignored. If you want to +change this behaviour and handle the exception for whatever reason +yourself, this event can be overridden. Which, when done, will +suppress the default action of printing the traceback.

+

The information of the exception raised and the exception itself can +be retrieved with a standard call to sys.exc_info().

+

If you want exception to propagate out of the Client class +you can define an on_error handler consisting of a single empty +raise statement. Exceptions raised by on_error will not be +handled in any way by Client.

+
+

Note

+

on_error will only be dispatched to Client.event().

+

It will not be received by Client.wait_for(), or, if used, +Bots listeners such as +listen() or listener().

+
+
+
Parameters
+
    +
  • event (str) – The name of the event that raised the exception.

  • +
  • args – The positional arguments for the event that raised the +exception.

  • +
  • kwargs – The keyword arguments for the event that raised the +exception.

  • +
+
+
+
+ +
+
+discord.on_socket_event_type(event_type)
+

Called whenever a websocket event is received from the WebSocket.

+

This is mainly useful for logging how many events you are receiving +from the Discord gateway.

+
+

New in version 2.0.

+
+
+
Parameters
+

event_type (str) – The event type from Discord that is received, e.g. 'READY'.

+
+
+
+ +
+
+discord.on_socket_raw_receive(msg)
+

Called whenever a message is completely received from the WebSocket, before +it’s processed and parsed. This event is always dispatched when a +complete message is received and the passed data is not parsed in any way.

+

This is only really useful for grabbing the WebSocket stream and +debugging purposes.

+

This requires setting the enable_debug_events setting in the Client.

+
+

Note

+

This is only for the messages received from the client +WebSocket. The voice WebSocket will not trigger this event.

+
+
+
Parameters
+

msg (str) – The message passed in from the WebSocket library.

+
+
+
+ +
+
+discord.on_socket_raw_send(payload)
+

Called whenever a send operation is done on the WebSocket before the +message is sent. The passed parameter is the message that is being +sent to the WebSocket.

+

This is only really useful for grabbing the WebSocket stream and +debugging purposes.

+

This requires setting the enable_debug_events setting in the Client.

+
+

Note

+

This is only for the messages sent from the client +WebSocket. The voice WebSocket will not trigger this event.

+
+
+
Parameters
+

payload – The message that is about to be passed on to the +WebSocket library. It can be bytes to denote a binary +message or str to denote a regular text message.

+
+
+
+ +
+
+discord.on_typing(channel, user, when)
+

Called when someone begins typing a message.

+

The channel parameter can be a abc.Messageable instance. +Which could either be TextChannel, GroupChannel, or +DMChannel.

+

If the channel is a TextChannel then the user parameter +is a Member, otherwise it is a User.

+

This requires Intents.typing to be enabled.

+
+
Parameters
+
    +
  • channel (abc.Messageable) – The location where the typing originated from.

  • +
  • user (Union[User, Member]) – The user that started typing.

  • +
  • when (datetime.datetime) – When the typing started as an aware datetime in UTC.

  • +
+
+
+
+ +
+
+discord.on_raw_typing(payload)
+

Called when someone begins typing a message. Unlike on_typing(), this is +called regardless if the user can be found or not. This most often happens +when a user types in DMs.

+

This requires Intents.typing to be enabled.

+
+
Parameters
+

payload (RawTypingEvent) – The raw typing payload.

+
+
+
+ +
+
+

Messages

+
+
+discord.on_message(message)
+

Called when a Message is created and sent.

+

This requires Intents.messages to be enabled.

+
+

Warning

+

Your bot’s own messages and private messages are sent through this +event. This can lead cases of ‘recursion’ depending on how your bot was +programmed. If you want the bot to not reply to itself, consider +checking the user IDs. Note that Bot does not +have this problem.

+
+
+
Parameters
+

message (Message) – The current message.

+
+
+
+ +
+
+discord.on_message_delete(message)
+

Called when a message is deleted. If the message is not found in the +internal message cache, then this event will not be called. +Messages might not be in cache if the message is too old +or the client is participating in high traffic guilds.

+

If this occurs increase the max_messages parameter +or use the on_raw_message_delete() event instead.

+

This requires Intents.messages to be enabled.

+
+
Parameters
+

message (Message) – The deleted message.

+
+
+
+ +
+
+discord.on_bulk_message_delete(messages)
+

Called when messages are bulk deleted. If none of the messages deleted +are found in the internal message cache, then this event will not be called. +If individual messages were not found in the internal message cache, +this event will still be called, but the messages not found will not be included in +the messages list. Messages might not be in cache if the message is too old +or the client is participating in high traffic guilds.

+

If this occurs increase the max_messages parameter +or use the on_raw_bulk_message_delete() event instead.

+

This requires Intents.messages to be enabled.

+
+
Parameters
+

messages (List[Message]) – The messages that have been deleted.

+
+
+
+ +
+
+discord.on_raw_message_delete(payload)
+

Called when a message is deleted. Unlike on_message_delete(), this is +called regardless of the message being in the internal message cache or not.

+

If the message is found in the message cache, +it can be accessed via RawMessageDeleteEvent.cached_message

+

This requires Intents.messages to be enabled.

+
+
Parameters
+

payload (RawMessageDeleteEvent) – The raw event payload data.

+
+
+
+ +
+
+discord.on_raw_bulk_message_delete(payload)
+

Called when a bulk delete is triggered. Unlike on_bulk_message_delete(), this is +called regardless of the messages being in the internal message cache or not.

+

If the messages are found in the message cache, +they can be accessed via RawBulkMessageDeleteEvent.cached_messages

+

This requires Intents.messages to be enabled.

+
+
Parameters
+

payload (RawBulkMessageDeleteEvent) – The raw event payload data.

+
+
+
+ +
+
+discord.on_message_edit(before, after)
+

Called when a Message receives an update event. If the message is not found +in the internal message cache, then these events will not be called. +Messages might not be in cache if the message is too old +or the client is participating in high traffic guilds.

+

If this occurs increase the max_messages parameter +or use the on_raw_message_edit() event instead.

+

The following non-exhaustive cases trigger this event:

+
    +
  • A message has been pinned or unpinned.

  • +
  • The message content has been changed.

  • +
  • The message has received an embed.

    +
    +
      +
    • For performance reasons, the embed server does not do this in a “consistent” manner.

    • +
    +
    +
  • +
  • The message’s embeds were suppressed or unsuppressed.

  • +
  • A call message has received an update to its participants or ending time.

  • +
+

This requires Intents.messages to be enabled.

+
+
Parameters
+
    +
  • before (Message) – The previous version of the message.

  • +
  • after (Message) – The current version of the message.

  • +
+
+
+
+ +
+
+discord.on_raw_message_edit(payload)
+

Called when a message is edited. Unlike on_message_edit(), this is called +regardless of the state of the internal message cache.

+

If the message is found in the message cache, +it can be accessed via RawMessageUpdateEvent.cached_message. The cached message represents +the message before it has been edited. For example, if the content of a message is modified and +triggers the on_raw_message_edit() coroutine, the RawMessageUpdateEvent.cached_message +will return a Message object that represents the message before the content was modified.

+

Due to the inherently raw nature of this event, the data parameter coincides with +the raw data given by the gateway.

+

Since the data payload can be partial, care must be taken when accessing stuff in the dictionary. +One example of a common case of partial data is when the 'content' key is inaccessible. This +denotes an “embed” only edit, which is an edit in which only the embeds are updated by the Discord +embed server.

+

This requires Intents.messages to be enabled.

+
+
Parameters
+

payload (RawMessageUpdateEvent) – The raw event payload data.

+
+
+
+ +
+
+discord.on_reaction_add(reaction, user)
+

Called when a message has a reaction added to it. Similar to on_message_edit(), +if the message is not found in the internal message cache, then this +event will not be called. Consider using on_raw_reaction_add() instead.

+
+

Note

+

To get the Message being reacted, access it via Reaction.message.

+
+

This requires Intents.reactions to be enabled.

+
+

Note

+

This doesn’t require Intents.members within a guild context, +but due to Discord not providing updated user information in a direct message +it’s required for direct messages to receive this event. +Consider using on_raw_reaction_add() if you need this and do not otherwise want +to enable the members intent.

+
+
+
Parameters
+
    +
  • reaction (Reaction) – The current state of the reaction.

  • +
  • user (Union[Member, User]) – The user who added the reaction.

  • +
+
+
+
+ +
+
+discord.on_raw_reaction_add(payload)
+

Called when a message has a reaction added. Unlike on_reaction_add(), this is +called regardless of the state of the internal message cache.

+

This requires Intents.reactions to be enabled.

+
+
Parameters
+

payload (RawReactionActionEvent) – The raw event payload data.

+
+
+
+ +
+
+discord.on_reaction_remove(reaction, user)
+

Called when a message has a reaction removed from it. Similar to on_message_edit, +if the message is not found in the internal message cache, then this event +will not be called.

+
+

Note

+

To get the message being reacted, access it via Reaction.message.

+
+

This requires both Intents.reactions and Intents.members to be enabled.

+
+

Note

+

Consider using on_raw_reaction_remove() if you need this and do not want +to enable the members intent.

+
+
+
Parameters
+
    +
  • reaction (Reaction) – The current state of the reaction.

  • +
  • user (Union[Member, User]) – The user who added the reaction.

  • +
+
+
+
+ +
+
+discord.on_raw_reaction_remove(payload)
+

Called when a message has a reaction removed. Unlike on_reaction_remove(), this is +called regardless of the state of the internal message cache.

+

This requires Intents.reactions to be enabled.

+
+
Parameters
+

payload (RawReactionActionEvent) – The raw event payload data.

+
+
+
+ +
+
+discord.on_reaction_clear(message, reactions)
+

Called when a message has all its reactions removed from it. Similar to on_message_edit(), +if the message is not found in the internal message cache, then this event +will not be called. Consider using on_raw_reaction_clear() instead.

+

This requires Intents.reactions to be enabled.

+
+
Parameters
+
    +
  • message (Message) – The message that had its reactions cleared.

  • +
  • reactions (List[Reaction]) – The reactions that were removed.

  • +
+
+
+
+ +
+
+discord.on_raw_reaction_clear(payload)
+

Called when a message has all its reactions removed. Unlike on_reaction_clear(), +this is called regardless of the state of the internal message cache.

+

This requires Intents.reactions to be enabled.

+
+
Parameters
+

payload (RawReactionClearEvent) – The raw event payload data.

+
+
+
+ +
+
+discord.on_reaction_clear_emoji(reaction)
+

Called when a message has a specific reaction removed from it. Similar to on_message_edit(), +if the message is not found in the internal message cache, then this event +will not be called. Consider using on_raw_reaction_clear_emoji() instead.

+

This requires Intents.reactions to be enabled.

+
+

New in version 1.3.

+
+
+
Parameters
+

reaction (Reaction) – The reaction that got cleared.

+
+
+
+ +
+
+discord.on_raw_reaction_clear_emoji(payload)
+

Called when a message has a specific reaction removed from it. Unlike on_reaction_clear_emoji() this is called +regardless of the state of the internal message cache.

+

This requires Intents.reactions to be enabled.

+
+

New in version 1.3.

+
+
+
Parameters
+

payload (RawReactionClearEmojiEvent) – The raw event payload data.

+
+
+
+ +
+
+discord.on_interaction(interaction)
+

Called when an interaction happened.

+

This currently happens due to slash command invocations or components being used.

+
+

Warning

+

This is a low level function that is not generally meant to be used. +If you are working with components, consider using the callbacks associated +with the View instead as it provides a nicer user experience.

+
+
+

New in version 2.0.

+
+
+
Parameters
+

interaction (Interaction) – The interaction data.

+
+
+
+ +
+
+discord.on_private_channel_update(before, after)
+

Called whenever a private group DM is updated. e.g. changed name or topic.

+

This requires Intents.messages to be enabled.

+
+
Parameters
+
    +
  • before (GroupChannel) – The updated group channel’s old info.

  • +
  • after (GroupChannel) – The updated group channel’s new info.

  • +
+
+
+
+ +
+
+discord.on_private_channel_pins_update(channel, last_pin)
+

Called whenever a message is pinned or unpinned from a private channel.

+
+
Parameters
+
    +
  • channel (abc.PrivateChannel) – The private channel that had its pins updated.

  • +
  • last_pin (Optional[datetime.datetime]) – The latest message that was pinned as an aware datetime in UTC. Could be None.

  • +
+
+
+
+ +
+
+discord.on_guild_channel_delete(channel)
+
+discord.on_guild_channel_create(channel)
+

Called whenever a guild channel is deleted or created.

+

Note that you can get the guild from guild.

+

This requires Intents.guilds to be enabled.

+
+
Parameters
+

channel (abc.GuildChannel) – The guild channel that got created or deleted.

+
+
+
+ +
+
+discord.on_guild_channel_update(before, after)
+

Called whenever a guild channel is updated. e.g. changed name, topic, permissions.

+

This requires Intents.guilds to be enabled.

+
+
Parameters
+
+
+
+
+ +
+
+discord.on_guild_channel_pins_update(channel, last_pin)
+

Called whenever a message is pinned or unpinned from a guild channel.

+

This requires Intents.guilds to be enabled.

+
+
Parameters
+
    +
  • channel (Union[abc.GuildChannel, Thread]) – The guild channel that had its pins updated.

  • +
  • last_pin (Optional[datetime.datetime]) – The latest message that was pinned as an aware datetime in UTC. Could be None.

  • +
+
+
+
+ +
+
+discord.on_thread_join(thread)
+

Called whenever a thread is joined or created. Note that from the API’s perspective there is no way to +differentiate between a thread being created or the bot joining a thread.

+

Note that you can get the guild from Thread.guild.

+

This requires Intents.guilds to be enabled.

+
+

New in version 2.0.

+
+
+
Parameters
+

thread (Thread) – The thread that got joined.

+
+
+
+ +
+
+discord.on_thread_remove(thread)
+

Called whenever a thread is removed. This is different from a thread being deleted.

+

Note that you can get the guild from Thread.guild.

+

This requires Intents.guilds to be enabled.

+
+

Warning

+

Due to technical limitations, this event might not be called +as soon as one expects. Since the library tracks thread membership +locally, the API only sends updated thread membership status upon being +synced by joining a thread.

+
+
+

New in version 2.0.

+
+
+
Parameters
+

thread (Thread) – The thread that got removed.

+
+
+
+ +
+
+discord.on_thread_delete(thread)
+

Called whenever a thread is deleted.

+

Note that you can get the guild from Thread.guild.

+

This requires Intents.guilds to be enabled.

+
+

New in version 2.0.

+
+
+
Parameters
+

thread (Thread) – The thread that got deleted.

+
+
+
+ +
+
+discord.on_thread_member_join(member)
+
+discord.on_thread_member_remove(member)
+

Called when a ThreadMember leaves or joins a Thread.

+

You can get the thread a member belongs in by accessing ThreadMember.thread.

+

This requires Intents.members to be enabled.

+
+

New in version 2.0.

+
+
+
Parameters
+

member (ThreadMember) – The member who joined or left.

+
+
+
+ +
+
+discord.on_thread_update(before, after)
+

Called whenever a thread is updated.

+

This requires Intents.guilds to be enabled.

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • before (Thread) – The updated thread’s old info.

  • +
  • after (Thread) – The updated thread’s new info.

  • +
+
+
+
+ +
+
+discord.on_guild_integrations_update(guild)
+

Called whenever an integration is created, modified, or removed from a guild.

+

This requires Intents.integrations to be enabled.

+
+

New in version 1.4.

+
+
+
Parameters
+

guild (Guild) – The guild that had its integrations updated.

+
+
+
+ +
+
+discord.on_integration_create(integration)
+

Called when an integration is created.

+

This requires Intents.integrations to be enabled.

+
+

New in version 2.0.

+
+
+
Parameters
+

integration (Integration) – The integration that was created.

+
+
+
+ +
+
+discord.on_integration_update(integration)
+

Called when an integration is updated.

+

This requires Intents.integrations to be enabled.

+
+

New in version 2.0.

+
+
+
Parameters
+

integration (Integration) – The integration that was created.

+
+
+
+ +
+
+discord.on_raw_integration_delete(payload)
+

Called when an integration is deleted.

+

This requires Intents.integrations to be enabled.

+
+

New in version 2.0.

+
+
+
Parameters
+

payload (RawIntegrationDeleteEvent) – The raw event payload data.

+
+
+
+ +
+
+discord.on_webhooks_update(channel)
+

Called whenever a webhook is created, modified, or removed from a guild channel.

+

This requires Intents.webhooks to be enabled.

+
+
Parameters
+

channel (abc.GuildChannel) – The channel that had its webhooks updated.

+
+
+
+ +
+
+discord.on_member_join(member)
+
+discord.on_member_remove(member)
+

Called when a Member leaves or joins a Guild.

+

This requires Intents.members to be enabled.

+
+
Parameters
+

member (Member) – The member who joined or left.

+
+
+
+ +
+
+discord.on_member_update(before, after)
+

Called when a Member updates their profile.

+

This is called when one or more of the following things change:

+
    +
  • nickname

  • +
  • roles

  • +
  • pending

  • +
+

This requires Intents.members to be enabled.

+
+
Parameters
+
    +
  • before (Member) – The updated member’s old info.

  • +
  • after (Member) – The updated member’s updated info.

  • +
+
+
+
+ +
+
+discord.on_presence_update(before, after)
+

Called when a Member updates their presence.

+

This is called when one or more of the following things change:

+
    +
  • status

  • +
  • activity

  • +
+

This requires Intents.presences and Intents.members to be enabled.

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • before (Member) – The updated member’s old info.

  • +
  • after (Member) – The updated member’s updated info.

  • +
+
+
+
+ +
+
+discord.on_user_update(before, after)
+

Called when a User updates their profile.

+

This is called when one or more of the following things change:

+
    +
  • avatar

  • +
  • username

  • +
  • discriminator

  • +
+

This requires Intents.members to be enabled.

+
+
Parameters
+
    +
  • before (User) – The updated user’s old info.

  • +
  • after (User) – The updated user’s updated info.

  • +
+
+
+
+ +
+
+discord.on_guild_join(guild)
+

Called when a Guild is either created by the Client or when the +Client joins a guild.

+

This requires Intents.guilds to be enabled.

+
+
Parameters
+

guild (Guild) – The guild that was joined.

+
+
+
+ +
+
+discord.on_guild_remove(guild)
+

Called when a Guild is removed from the Client.

+

This happens through, but not limited to, these circumstances:

+
    +
  • The client got banned.

  • +
  • The client got kicked.

  • +
  • The client left the guild.

  • +
  • The client or the guild owner deleted the guild.

  • +
+

In order for this event to be invoked then the Client must have +been part of the guild to begin with. (i.e. it is part of Client.guilds)

+

This requires Intents.guilds to be enabled.

+
+
Parameters
+

guild (Guild) – The guild that got removed.

+
+
+
+ +
+
+discord.on_guild_update(before, after)
+

Called when a Guild updates, for example:

+
    +
  • Changed name

  • +
  • Changed AFK channel

  • +
  • Changed AFK timeout

  • +
  • etc

  • +
+

This requires Intents.guilds to be enabled.

+
+
Parameters
+
    +
  • before (Guild) – The guild prior to being updated.

  • +
  • after (Guild) – The guild after being updated.

  • +
+
+
+
+ +
+
+discord.on_guild_role_create(role)
+
+discord.on_guild_role_delete(role)
+

Called when a Guild creates or deletes a new Role.

+

To get the guild it belongs to, use Role.guild.

+

This requires Intents.guilds to be enabled.

+
+
Parameters
+

role (Role) – The role that was created or deleted.

+
+
+
+ +
+
+discord.on_guild_role_update(before, after)
+

Called when a Role is changed guild-wide.

+

This requires Intents.guilds to be enabled.

+
+
Parameters
+
    +
  • before (Role) – The updated role’s old info.

  • +
  • after (Role) – The updated role’s updated info.

  • +
+
+
+
+ +
+
+discord.on_guild_emojis_update(guild, before, after)
+

Called when a Guild adds or removes Emoji.

+

This requires Intents.emojis_and_stickers to be enabled.

+
+
Parameters
+
    +
  • guild (Guild) – The guild who got their emojis updated.

  • +
  • before (Sequence[Emoji]) – A list of emojis before the update.

  • +
  • after (Sequence[Emoji]) – A list of emojis after the update.

  • +
+
+
+
+ +
+
+discord.on_guild_stickers_update(guild, before, after)
+

Called when a Guild updates its stickers.

+

This requires Intents.emojis_and_stickers to be enabled.

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • guild (Guild) – The guild who got their stickers updated.

  • +
  • before (Sequence[GuildSticker]) – A list of stickers before the update.

  • +
  • after (Sequence[GuildSticker]) – A list of stickers after the update.

  • +
+
+
+
+ +
+
+discord.on_guild_available(guild)
+
+discord.on_guild_unavailable(guild)
+

Called when a guild becomes available or unavailable. The guild must have +existed in the Client.guilds cache.

+

This requires Intents.guilds to be enabled.

+
+
Parameters
+

guild – The Guild that has changed availability.

+
+
+
+ +
+
+discord.on_voice_state_update(member, before, after)
+

Called when a Member changes their VoiceState.

+

The following, but not limited to, examples illustrate when this event is called:

+
    +
  • A member joins a voice or stage channel.

  • +
  • A member leaves a voice or stage channel.

  • +
  • A member is muted or deafened by their own accord.

  • +
  • A member is muted or deafened by a guild administrator.

  • +
+

This requires Intents.voice_states to be enabled.

+
+
Parameters
+
    +
  • member (Member) – The member whose voice states changed.

  • +
  • before (VoiceState) – The voice state prior to the changes.

  • +
  • after (VoiceState) – The voice state after the changes.

  • +
+
+
+
+ +
+
+discord.on_stage_instance_create(stage_instance)
+
+discord.on_stage_instance_delete(stage_instance)
+

Called when a StageInstance is created or deleted for a StageChannel.

+
+

New in version 2.0.

+
+
+
Parameters
+

stage_instance (StageInstance) – The stage instance that was created or deleted.

+
+
+
+ +
+
+discord.on_stage_instance_update(before, after)
+

Called when a StageInstance is updated.

+

The following, but not limited to, examples illustrate when this event is called:

+
    +
  • The topic is changed.

  • +
  • The privacy level is changed.

  • +
+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • before (StageInstance) – The stage instance before the update.

  • +
  • after (StageInstance) – The stage instance after the update.

  • +
+
+
+
+ +
+
+discord.on_member_ban(guild, user)
+

Called when user gets banned from a Guild.

+

This requires Intents.bans to be enabled.

+
+
Parameters
+
    +
  • guild (Guild) – The guild the user got banned from.

  • +
  • user (Union[User, Member]) – The user that got banned. +Can be either User or Member depending if +the user was in the guild or not at the time of removal.

  • +
+
+
+
+ +
+
+discord.on_member_unban(guild, user)
+

Called when a User gets unbanned from a Guild.

+

This requires Intents.bans to be enabled.

+
+
Parameters
+
    +
  • guild (Guild) – The guild the user got unbanned from.

  • +
  • user (User) – The user that got unbanned.

  • +
+
+
+
+ +
+
+discord.on_invite_create(invite)
+

Called when an Invite is created. +You must have the manage_channels permission to receive this.

+
+

New in version 1.3.

+
+
+

Note

+

There is a rare possibility that the Invite.guild and Invite.channel +attributes will be of Object rather than the respective models.

+
+

This requires Intents.invites to be enabled.

+
+
Parameters
+

invite (Invite) – The invite that was created.

+
+
+
+ +
+
+discord.on_invite_delete(invite)
+

Called when an Invite is deleted. +You must have the manage_channels permission to receive this.

+
+

New in version 1.3.

+
+
+

Note

+

There is a rare possibility that the Invite.guild and Invite.channel +attributes will be of Object rather than the respective models.

+

Outside of those two attributes, the only other attribute guaranteed to be +filled by the Discord gateway for this event is Invite.code.

+
+

This requires Intents.invites to be enabled.

+
+
Parameters
+

invite (Invite) – The invite that was deleted.

+
+
+
+ +
+
+discord.on_group_join(channel, user)
+
+discord.on_group_remove(channel, user)
+

Called when someone joins or leaves a GroupChannel.

+
+
Parameters
+
    +
  • channel (GroupChannel) – The group that the user joined or left.

  • +
  • user (User) – The user that joined or left.

  • +
+
+
+
+ +
+
+
+

Utility Functions

+
+
+discord.utils.find(predicate, seq)
+

A helper to return the first element found in the sequence +that meets the predicate. For example:

+
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
+
+
+

would find the first Member whose name is ‘Mighty’ and return it. +If an entry is not found, then None is returned.

+

This is different from filter() due to the fact it stops the moment it finds +a valid entry.

+
+
Parameters
+
    +
  • predicate – A function that returns a boolean-like result.

  • +
  • seq (collections.abc.Iterable) – The iterable to search through.

  • +
+
+
+
+ +
+
+discord.utils.get(iterable, **attrs)
+

A helper that returns the first element in the iterable that meets +all the traits passed in attrs. This is an alternative for +find().

+

When multiple attributes are specified, they are checked using +logical AND, not logical OR. Meaning they have to meet every +attribute passed in and not one of them.

+

To have a nested attribute search (i.e. search by x.y) then +pass in x__y as the keyword argument.

+

If nothing is found that matches the attributes passed, then +None is returned.

+

Examples

+

Basic usage:

+
member = discord.utils.get(message.guild.members, name='Foo')
+
+
+

Multiple attribute matching:

+
channel = discord.utils.get(guild.voice_channels, name='Foo', bitrate=64000)
+
+
+

Nested attribute matching:

+
channel = discord.utils.get(client.get_all_channels(), guild__name='Cool', name='general')
+
+
+
+
Parameters
+
    +
  • iterable – An iterable to search through.

  • +
  • **attrs – Keyword arguments that denote attributes to search with.

  • +
+
+
+
+ +
+
+discord.utils.snowflake_time(id)
+
+
Parameters
+

id (int) – The snowflake ID.

+
+
Returns
+

An aware datetime in UTC representing the creation time of the snowflake.

+
+
Return type
+

datetime.datetime

+
+
+
+ +
+
+discord.utils.oauth_url(client_id, *, permissions=..., guild=..., redirect_uri=..., scopes=..., disable_guild_select=False)
+

A helper function that returns the OAuth2 URL for inviting the bot +into guilds.

+
+
Parameters
+
    +
  • client_id (Union[int, str]) – The client ID for your bot.

  • +
  • permissions (Permissions) – The permissions you’re requesting. If not given then you won’t be requesting any +permissions.

  • +
  • guild (Snowflake) – The guild to pre-select in the authorization screen, if available.

  • +
  • redirect_uri (str) – An optional valid redirect URI.

  • +
  • scopes (Iterable[str]) –

    An optional valid list of scopes. Defaults to ('bot',).

    +
    +

    New in version 1.7.

    +
    +

  • +
  • disable_guild_select (bool) –

    Whether to disallow the user from changing the guild dropdown.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Returns
+

The OAuth2 URL for inviting the bot into guilds.

+
+
Return type
+

str

+
+
+
+ +
+
+discord.utils.remove_markdown(text, *, ignore_links=True)
+

A helper function that removes markdown characters.

+
+

New in version 1.7.

+
+
+

Note

+

This function is not markdown aware and may remove meaning from the original text. For example, +if the input contains 10 * 5 then it will be converted into 10  5.

+
+
+
Parameters
+
    +
  • text (str) – The text to remove markdown from.

  • +
  • ignore_links (bool) – Whether to leave links alone when removing markdown. For example, +if a URL in the text contains characters such as _ then it will +be left alone. Defaults to True.

  • +
+
+
Returns
+

The text with the markdown special characters removed.

+
+
Return type
+

str

+
+
+
+ +
+
+discord.utils.escape_markdown(text, *, as_needed=False, ignore_links=True)
+

A helper function that escapes Discord’s markdown.

+
+
Parameters
+
    +
  • text (str) – The text to escape markdown from.

  • +
  • as_needed (bool) – Whether to escape the markdown characters as needed. This +means that it does not escape extraneous characters if it’s +not necessary, e.g. **hello** is escaped into \*\*hello** +instead of \*\*hello\*\*. Note however that this can open +you up to some clever syntax abuse. Defaults to False.

  • +
  • ignore_links (bool) – Whether to leave links alone when escaping markdown. For example, +if a URL in the text contains characters such as _ then it will +be left alone. This option is not supported with as_needed. +Defaults to True.

  • +
+
+
Returns
+

The text with the markdown special characters escaped with a slash.

+
+
Return type
+

str

+
+
+
+ +
+
+discord.utils.escape_mentions(text)
+

A helper function that escapes everyone, here, role, and user mentions.

+
+

Note

+

This does not include channel mentions.

+
+
+

Note

+

For more granular control over what mentions should be escaped +within messages, refer to the AllowedMentions +class.

+
+
+
Parameters
+

text (str) – The text to escape mentions from.

+
+
Returns
+

The text with the mentions removed.

+
+
Return type
+

str

+
+
+
+ +
+
+discord.utils.resolve_invite(invite)
+

Resolves an invite from a Invite, URL or code.

+
+
Parameters
+

invite (Union[Invite, str]) – The invite.

+
+
Returns
+

The invite code.

+
+
Return type
+

str

+
+
+
+ +
+
+discord.utils.resolve_template(code)
+

Resolves a template code from a Template, URL or code.

+
+

New in version 1.4.

+
+
+
Parameters
+

code (Union[Template, str]) – The code.

+
+
Returns
+

The template code.

+
+
Return type
+

str

+
+
+
+ +
+
+await discord.utils.sleep_until(when, result=None)
+

This function is a coroutine.

+

Sleep until a specified time.

+

If the time supplied is in the past this function will yield instantly.

+
+

New in version 1.3.

+
+
+
Parameters
+
    +
  • when (datetime.datetime) – The timestamp in which to sleep until. If the datetime is naive then +it is assumed to be local time.

  • +
  • result (Any) – If provided is returned to the caller when the coroutine completes.

  • +
+
+
+
+ +
+
+discord.utils.utcnow()
+

A helper function to return an aware UTC datetime representing the current time.

+

This should be preferred to datetime.datetime.utcnow() since it is an aware +datetime, compared to the naive datetime in the standard library.

+
+

New in version 2.0.

+
+
+
Returns
+

The current aware datetime in UTC.

+
+
Return type
+

datetime.datetime

+
+
+
+ +
+
+discord.utils.format_dt(dt, /, style=None)
+

A helper function to format a datetime.datetime for presentation within Discord.

+

This allows for a locale-independent way of presenting data using Discord specific Markdown.

+
+++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Style

Example Output

Description

t

22:57

Short Time

T

22:57:58

Long Time

d

17/05/2016

Short Date

D

17 May 2016

Long Date

f (default)

17 May 2016 22:57

Short Date Time

F

Tuesday, 17 May 2016 22:57

Long Date Time

R

5 years ago

Relative Time

+

Note that the exact output depends on the user’s locale setting in the client. The example output +presented is using the en-GB locale.

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • dt (datetime.datetime) – The datetime to format.

  • +
  • style (str) – The style to format the datetime with.

  • +
+
+
Returns
+

The formatted string.

+
+
Return type
+

str

+
+
+
+ +
+
+discord.utils.as_chunks(iterator, max_size)
+

A helper function that collects an iterator into chunks of a given size.

+
+

New in version 2.0.

+
+
+
Parameters
+
+
+
+
+

Warning

+

The last chunk collected may not be as large as max_size.

+
+
+
Returns
+

A new iterator which yields chunks of a given size.

+
+
Return type
+

Union[Iterator, AsyncIterator]

+
+
+
+ +
+
+

Enumerations

+

The API provides some enumerations for certain types of strings to avoid the API +from being stringly typed in case the strings change in the future.

+

All enumerations are subclasses of an internal class which mimics the behaviour +of enum.Enum.

+
+
+class discord.ChannelType
+

Specifies the type of channel.

+
+
+text
+

A text channel.

+
+ +
+
+voice
+

A voice channel.

+
+ +
+
+private
+

A private text channel. Also called a direct message.

+
+ +
+
+group
+

A private group text channel.

+
+ +
+
+category
+

A category channel.

+
+ +
+
+news
+

A guild news channel.

+
+ +
+
+store
+

A guild store channel.

+
+ +
+
+stage_voice
+

A guild stage voice channel.

+
+

New in version 1.7.

+
+
+ +
+
+news_thread
+

A news thread

+
+

New in version 2.0.

+
+
+ +
+
+public_thread
+

A public thread

+
+

New in version 2.0.

+
+
+ +
+
+private_thread
+

A private thread

+
+

New in version 2.0.

+
+
+ +
+ +
+
+class discord.MessageType
+

Specifies the type of Message. This is used to denote if a message +is to be interpreted as a system message or a regular message.

+
+
+
+x == y
+

Checks if two messages are equal.

+
+ +
+
+x != y
+

Checks if two messages are not equal.

+
+ +
+
+
+default
+

The default message type. This is the same as regular messages.

+
+ +
+
+recipient_add
+

The system message when a user is added to a group private +message or a thread.

+
+ +
+
+recipient_remove
+

The system message when a user is removed from a group private +message or a thread.

+
+ +
+
+call
+

The system message denoting call state, e.g. missed call, started call, +etc.

+
+ +
+
+channel_name_change
+

The system message denoting that a channel’s name has been changed.

+
+ +
+
+channel_icon_change
+

The system message denoting that a channel’s icon has been changed.

+
+ +
+
+pins_add
+

The system message denoting that a pinned message has been added to a channel.

+
+ +
+
+new_member
+

The system message denoting that a new member has joined a Guild.

+
+ +
+
+premium_guild_subscription
+

The system message denoting that a member has “nitro boosted” a guild.

+
+ +
+
+premium_guild_tier_1
+

The system message denoting that a member has “nitro boosted” a guild +and it achieved level 1.

+
+ +
+
+premium_guild_tier_2
+

The system message denoting that a member has “nitro boosted” a guild +and it achieved level 2.

+
+ +
+
+premium_guild_tier_3
+

The system message denoting that a member has “nitro boosted” a guild +and it achieved level 3.

+
+ +
+
+channel_follow_add
+

The system message denoting that an announcement channel has been followed.

+
+

New in version 1.3.

+
+
+ +
+
+guild_stream
+

The system message denoting that a member is streaming in the guild.

+
+

New in version 1.7.

+
+
+ +
+
+guild_discovery_disqualified
+

The system message denoting that the guild is no longer eligible for Server +Discovery.

+
+

New in version 1.7.

+
+
+ +
+
+guild_discovery_requalified
+

The system message denoting that the guild has become eligible again for Server +Discovery.

+
+

New in version 1.7.

+
+
+ +
+
+guild_discovery_grace_period_initial_warning
+

The system message denoting that the guild has failed to meet the Server +Discovery requirements for one week.

+
+

New in version 1.7.

+
+
+ +
+
+guild_discovery_grace_period_final_warning
+

The system message denoting that the guild has failed to meet the Server +Discovery requirements for 3 weeks in a row.

+
+

New in version 1.7.

+
+
+ +
+
+thread_created
+

The system message denoting that a thread has been created. This is only +sent if the thread has been created from an older message. The period of time +required for a message to be considered old cannot be relied upon and is up to +Discord.

+
+

New in version 2.0.

+
+
+ +
+
+reply
+

The system message denoting that the author is replying to a message.

+
+

New in version 2.0.

+
+
+ +
+
+application_command
+

The system message denoting that an application (or “slash”) command was executed.

+
+

New in version 2.0.

+
+
+ +
+
+guild_invite_reminder
+

The system message sent as a reminder to invite people to the guild.

+
+

New in version 2.0.

+
+
+ +
+
+thread_starter_message
+

The system message denoting the message in the thread that is the one that started the +thread’s conversation topic.

+
+

New in version 2.0.

+
+
+ +
+ +
+
+class discord.UserFlags
+

Represents Discord User flags.

+
+
+staff
+

The user is a Discord Employee.

+
+ +
+
+partner
+

The user is a Discord Partner.

+
+ +
+
+hypesquad
+

The user is a HypeSquad Events member.

+
+ +
+
+bug_hunter
+

The user is a Bug Hunter.

+
+ +
+
+mfa_sms
+

The user has SMS recovery for Multi Factor Authentication enabled.

+
+ +
+
+premium_promo_dismissed
+

The user has dismissed the Discord Nitro promotion.

+
+ +
+
+hypesquad_bravery
+

The user is a HypeSquad Bravery member.

+
+ +
+
+hypesquad_brilliance
+

The user is a HypeSquad Brilliance member.

+
+ +
+
+hypesquad_balance
+

The user is a HypeSquad Balance member.

+
+ +
+
+early_supporter
+

The user is an Early Supporter.

+
+ +
+
+team_user
+

The user is a Team User.

+
+ +
+
+system
+

The user is a system user (i.e. represents Discord officially).

+
+ +
+
+has_unread_urgent_messages
+

The user has an unread system message.

+
+ +
+
+bug_hunter_level_2
+

The user is a Bug Hunter Level 2.

+
+ +
+
+verified_bot
+

The user is a Verified Bot.

+
+ +
+
+verified_bot_developer
+

The user is an Early Verified Bot Developer.

+
+ +
+
+discord_certified_moderator
+

The user is a Discord Certified Moderator.

+
+ +
+ +
+
+class discord.ActivityType
+

Specifies the type of Activity. This is used to check how to +interpret the activity itself.

+
+
+unknown
+

An unknown activity type. This should generally not happen.

+
+ +
+
+playing
+

A “Playing” activity type.

+
+ +
+
+streaming
+

A “Streaming” activity type.

+
+ +
+
+listening
+

A “Listening” activity type.

+
+ +
+
+watching
+

A “Watching” activity type.

+
+ +
+
+custom
+

A custom activity type.

+
+ +
+
+competing
+

A competing activity type.

+
+

New in version 1.5.

+
+
+ +
+ +
+
+class discord.InteractionType
+

Specifies the type of Interaction.

+
+

New in version 2.0.

+
+
+
+ping
+

Represents Discord pinging to see if the interaction response server is alive.

+
+ +
+
+application_command
+

Represents a slash command interaction.

+
+ +
+
+component
+

Represents a component based interaction, i.e. using the Discord Bot UI Kit.

+
+ +
+ +
+
+class discord.InteractionResponseType
+

Specifies the response type for the interaction.

+
+

New in version 2.0.

+
+
+
+pong
+

Pongs the interaction when given a ping.

+

See also InteractionResponse.pong()

+
+ +
+
+channel_message
+

Respond to the interaction with a message.

+

See also InteractionResponse.send_message()

+
+ +
+
+deferred_channel_message
+

Responds to the interaction with a message at a later time.

+

See also InteractionResponse.defer()

+
+ +
+
+deferred_message_update
+

Acknowledges the component interaction with a promise that +the message will update later (though there is no need to actually update the message).

+

See also InteractionResponse.defer()

+
+ +
+
+message_update
+

Responds to the interaction by editing the message.

+

See also InteractionResponse.edit_message()

+
+ +
+ +
+
+class discord.ComponentType
+

Represents the component type of a component.

+
+

New in version 2.0.

+
+
+
+action_row
+

Represents the group component which holds different components in a row.

+
+ +
+
+button
+

Represents a button component.

+
+ +
+
+select
+

Represents a select component.

+
+ +
+ +
+
+class discord.ButtonStyle
+

Represents the style of the button component.

+
+

New in version 2.0.

+
+
+
+primary
+

Represents a blurple button for the primary action.

+
+ +
+
+secondary
+

Represents a grey button for the secondary action.

+
+ +
+
+success
+

Represents a green button for a successful action.

+
+ +
+
+danger
+

Represents a red button for a dangerous action.

+
+ +
+ +

Represents a link button.

+
+ +
+
+blurple
+

An alias for primary.

+
+ +
+
+grey
+

An alias for secondary.

+
+ +
+
+gray
+

An alias for secondary.

+
+ +
+
+green
+

An alias for success.

+
+ +
+
+red
+

An alias for danger.

+
+ +
+
+url
+

An alias for link.

+
+ +
+ +
+
+class discord.VoiceRegion
+

Specifies the region a voice server belongs to.

+
+
+amsterdam
+

The Amsterdam region.

+
+ +
+
+brazil
+

The Brazil region.

+
+ +
+
+dubai
+

The Dubai region.

+
+

New in version 1.3.

+
+
+ +
+
+eu_central
+

The EU Central region.

+
+ +
+
+eu_west
+

The EU West region.

+
+ +
+
+europe
+

The Europe region.

+
+

New in version 1.3.

+
+
+ +
+
+frankfurt
+

The Frankfurt region.

+
+ +
+
+hongkong
+

The Hong Kong region.

+
+ +
+
+india
+

The India region.

+
+

New in version 1.2.

+
+
+ +
+
+japan
+

The Japan region.

+
+ +
+
+london
+

The London region.

+
+ +
+
+russia
+

The Russia region.

+
+ +
+
+singapore
+

The Singapore region.

+
+ +
+
+southafrica
+

The South Africa region.

+
+ +
+
+south_korea
+

The South Korea region.

+
+ +
+
+sydney
+

The Sydney region.

+
+ +
+
+us_central
+

The US Central region.

+
+ +
+
+us_east
+

The US East region.

+
+ +
+
+us_south
+

The US South region.

+
+ +
+
+us_west
+

The US West region.

+
+ +
+
+vip_amsterdam
+

The Amsterdam region for VIP guilds.

+
+ +
+
+vip_us_east
+

The US East region for VIP guilds.

+
+ +
+
+vip_us_west
+

The US West region for VIP guilds.

+
+ +
+ +
+
+class discord.VerificationLevel
+

Specifies a Guild's verification level, which is the criteria in +which a member must meet before being able to send messages to the guild.

+
+
+

New in version 2.0.

+
+
+
+x == y
+

Checks if two verification levels are equal.

+
+ +
+
+x != y
+

Checks if two verification levels are not equal.

+
+ +
+
+x > y
+

Checks if a verification level is higher than another.

+
+ +
+
+x < y
+

Checks if a verification level is lower than another.

+
+ +
+
+x >= y
+

Checks if a verification level is higher or equal to another.

+
+ +
+
+x <= y
+

Checks if a verification level is lower or equal to another.

+
+ +
+
+
+none
+

No criteria set.

+
+ +
+
+low
+

Member must have a verified email on their Discord account.

+
+ +
+
+medium
+

Member must have a verified email and be registered on Discord for more +than five minutes.

+
+ +
+
+high
+

Member must have a verified email, be registered on Discord for more +than five minutes, and be a member of the guild itself for more than +ten minutes.

+
+ +
+
+highest
+

Member must have a verified phone on their Discord account.

+
+ +
+ +
+
+class discord.NotificationLevel
+

Specifies whether a Guild has notifications on for all messages or mentions only by default.

+
+
+

New in version 2.0.

+
+
+
+x == y
+

Checks if two notification levels are equal.

+
+ +
+
+x != y
+

Checks if two notification levels are not equal.

+
+ +
+
+x > y
+

Checks if a notification level is higher than another.

+
+ +
+
+x < y
+

Checks if a notification level is lower than another.

+
+ +
+
+x >= y
+

Checks if a notification level is higher or equal to another.

+
+ +
+
+x <= y
+

Checks if a notification level is lower or equal to another.

+
+ +
+
+
+all_messages
+

Members receive notifications for every message regardless of them being mentioned.

+
+ +
+
+only_mentions
+

Members receive notifications for messages they are mentioned in.

+
+ +
+ +
+
+class discord.ContentFilter
+

Specifies a Guild's explicit content filter, which is the machine +learning algorithms that Discord uses to detect if an image contains +pornography or otherwise explicit content.

+
+
+

New in version 2.0.

+
+
+
+x == y
+

Checks if two content filter levels are equal.

+
+ +
+
+x != y
+

Checks if two content filter levels are not equal.

+
+ +
+
+x > y
+

Checks if a content filter level is higher than another.

+
+ +
+
+x < y
+

Checks if a content filter level is lower than another.

+
+ +
+
+x >= y
+

Checks if a content filter level is higher or equal to another.

+
+ +
+
+x <= y
+

Checks if a content filter level is lower or equal to another.

+
+ +
+
+
+disabled
+

The guild does not have the content filter enabled.

+
+ +
+
+no_role
+

The guild has the content filter enabled for members without a role.

+
+ +
+
+all_members
+

The guild has the content filter enabled for every member.

+
+ +
+ +
+
+class discord.Status
+

Specifies a Member ‘s status.

+
+
+online
+

The member is online.

+
+ +
+
+offline
+

The member is offline.

+
+ +
+
+idle
+

The member is idle.

+
+ +
+
+dnd
+

The member is “Do Not Disturb”.

+
+ +
+
+do_not_disturb
+

An alias for dnd.

+
+ +
+
+invisible
+

The member is “invisible”. In reality, this is only used in sending +a presence a la Client.change_presence(). When you receive a +user’s presence this will be offline instead.

+
+ +
+ +
+
+class discord.AuditLogAction
+

Represents the type of action being done for a AuditLogEntry, +which is retrievable via Guild.audit_logs().

+
+
+guild_update
+

The guild has updated. Things that trigger this include:

+
    +
  • Changing the guild vanity URL

  • +
  • Changing the guild invite splash

  • +
  • Changing the guild AFK channel or timeout

  • +
  • Changing the guild voice server region

  • +
  • Changing the guild icon, banner, or discovery splash

  • +
  • Changing the guild moderation settings

  • +
  • Changing things related to the guild widget

  • +
+

When this is the action, the type of target is +the Guild.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+channel_create
+

A new channel was created.

+

When this is the action, the type of target is +either a abc.GuildChannel or Object with an ID.

+

A more filled out object in the Object case can be found +by using after.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+channel_update
+

A channel was updated. Things that trigger this include:

+
    +
  • The channel name or topic was changed

  • +
  • The channel bitrate was changed

  • +
+

When this is the action, the type of target is +the abc.GuildChannel or Object with an ID.

+

A more filled out object in the Object case can be found +by using after or before.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+channel_delete
+

A channel was deleted.

+

When this is the action, the type of target is +an Object with an ID.

+

A more filled out object can be found by using the +before object.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+overwrite_create
+

A channel permission overwrite was created.

+

When this is the action, the type of target is +the abc.GuildChannel or Object with an ID.

+

When this is the action, the type of extra is +either a Role or Member. If the object is not found +then it is a Object with an ID being filled, a name, and a +type attribute set to either 'role' or 'member' to help +dictate what type of ID it is.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+overwrite_update
+

A channel permission overwrite was changed, this is typically +when the permission values change.

+

See overwrite_create for more information on how the +target and extra fields +are set.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+overwrite_delete
+

A channel permission overwrite was deleted.

+

See overwrite_create for more information on how the +target and extra fields +are set.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+kick
+

A member was kicked.

+

When this is the action, the type of target is +the User who got kicked.

+

When this is the action, changes is empty.

+
+ +
+
+member_prune
+

A member prune was triggered.

+

When this is the action, the type of target is +set to None.

+

When this is the action, the type of extra is +set to an unspecified proxy object with two attributes:

+
    +
  • delete_members_days: An integer specifying how far the prune was.

  • +
  • members_removed: An integer specifying how many members were removed.

  • +
+

When this is the action, changes is empty.

+
+ +
+
+ban
+

A member was banned.

+

When this is the action, the type of target is +the User who got banned.

+

When this is the action, changes is empty.

+
+ +
+
+unban
+

A member was unbanned.

+

When this is the action, the type of target is +the User who got unbanned.

+

When this is the action, changes is empty.

+
+ +
+
+member_update
+

A member has updated. This triggers in the following situations:

+
    +
  • A nickname was changed

  • +
  • They were server muted or deafened (or it was undo’d)

  • +
+

When this is the action, the type of target is +the Member or User who got updated.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+member_role_update
+

A member’s role has been updated. This triggers when a member +either gains a role or loses a role.

+

When this is the action, the type of target is +the Member or User who got the role.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+member_move
+

A member’s voice channel has been updated. This triggers when a +member is moved to a different voice channel.

+

When this is the action, the type of extra is +set to an unspecified proxy object with two attributes:

+
    +
  • channel: A TextChannel or Object with the channel ID where the members were moved.

  • +
  • count: An integer specifying how many members were moved.

  • +
+
+

New in version 1.3.

+
+
+ +
+
+member_disconnect
+

A member’s voice state has changed. This triggers when a +member is force disconnected from voice.

+

When this is the action, the type of extra is +set to an unspecified proxy object with one attribute:

+
    +
  • count: An integer specifying how many members were disconnected.

  • +
+
+

New in version 1.3.

+
+
+ +
+
+bot_add
+

A bot was added to the guild.

+

When this is the action, the type of target is +the Member or User which was added to the guild.

+
+

New in version 1.3.

+
+
+ +
+
+role_create
+

A new role was created.

+

When this is the action, the type of target is +the Role or a Object with the ID.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+role_update
+

A role was updated. This triggers in the following situations:

+
    +
  • The name has changed

  • +
  • The permissions have changed

  • +
  • The colour has changed

  • +
  • Its hoist/mentionable state has changed

  • +
+

When this is the action, the type of target is +the Role or a Object with the ID.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+role_delete
+

A role was deleted.

+

When this is the action, the type of target is +the Role or a Object with the ID.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+invite_create
+

An invite was created.

+

When this is the action, the type of target is +the Invite that was created.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+invite_update
+

An invite was updated.

+

When this is the action, the type of target is +the Invite that was updated.

+
+ +
+
+invite_delete
+

An invite was deleted.

+

When this is the action, the type of target is +the Invite that was deleted.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+webhook_create
+

A webhook was created.

+

When this is the action, the type of target is +the Object with the webhook ID.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+webhook_update
+

A webhook was updated. This trigger in the following situations:

+
    +
  • The webhook name changed

  • +
  • The webhook channel changed

  • +
+

When this is the action, the type of target is +the Object with the webhook ID.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+webhook_delete
+

A webhook was deleted.

+

When this is the action, the type of target is +the Object with the webhook ID.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+emoji_create
+

An emoji was created.

+

When this is the action, the type of target is +the Emoji or Object with the emoji ID.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+emoji_update
+

An emoji was updated. This triggers when the name has changed.

+

When this is the action, the type of target is +the Emoji or Object with the emoji ID.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+emoji_delete
+

An emoji was deleted.

+

When this is the action, the type of target is +the Object with the emoji ID.

+

Possible attributes for AuditLogDiff:

+ +
+ +
+
+message_delete
+

A message was deleted by a moderator. Note that this +only triggers if the message was deleted by someone other than the author.

+

When this is the action, the type of target is +the Member or User who had their message deleted.

+

When this is the action, the type of extra is +set to an unspecified proxy object with two attributes:

+
    +
  • count: An integer specifying how many messages were deleted.

  • +
  • channel: A TextChannel or Object with the channel ID where the message got deleted.

  • +
+
+ +
+
+message_bulk_delete
+

Messages were bulk deleted by a moderator.

+

When this is the action, the type of target is +the TextChannel or Object with the ID of the channel that was purged.

+

When this is the action, the type of extra is +set to an unspecified proxy object with one attribute:

+
    +
  • count: An integer specifying how many messages were deleted.

  • +
+
+

New in version 1.3.

+
+
+ +
+
+message_pin
+

A message was pinned in a channel.

+

When this is the action, the type of target is +the Member or User who had their message pinned.

+

When this is the action, the type of extra is +set to an unspecified proxy object with two attributes:

+
    +
  • channel: A TextChannel or Object with the channel ID where the message was pinned.

  • +
  • message_id: the ID of the message which was pinned.

  • +
+
+

New in version 1.3.

+
+
+ +
+
+message_unpin
+

A message was unpinned in a channel.

+

When this is the action, the type of target is +the Member or User who had their message unpinned.

+

When this is the action, the type of extra is +set to an unspecified proxy object with two attributes:

+
    +
  • channel: A TextChannel or Object with the channel ID where the message was unpinned.

  • +
  • message_id: the ID of the message which was unpinned.

  • +
+
+

New in version 1.3.

+
+
+ +
+
+integration_create
+

A guild integration was created.

+

When this is the action, the type of target is +the Object with the integration ID of the integration which was created.

+
+

New in version 1.3.

+
+
+ +
+
+integration_update
+

A guild integration was updated.

+

When this is the action, the type of target is +the Object with the integration ID of the integration which was updated.

+
+

New in version 1.3.

+
+
+ +
+
+integration_delete
+

A guild integration was deleted.

+

When this is the action, the type of target is +the Object with the integration ID of the integration which was deleted.

+
+

New in version 1.3.

+
+
+ +
+
+stage_instance_create
+

A stage instance was started.

+

When this is the action, the type of target is +the StageInstance or Object with the ID of the stage +instance which was created.

+

Possible attributes for AuditLogDiff:

+ +
+

New in version 2.0.

+
+
+ +
+
+stage_instance_update
+

A stage instance was updated.

+

When this is the action, the type of target is +the StageInstance or Object with the ID of the stage +instance which was updated.

+

Possible attributes for AuditLogDiff:

+ +
+

New in version 2.0.

+
+
+ +
+
+stage_instance_delete
+

A stage instance was ended.

+
+

New in version 2.0.

+
+
+ +
+
+sticker_create
+

A sticker was created.

+

When this is the action, the type of target is +the GuildSticker or Object with the ID of the sticker +which was updated.

+

Possible attributes for AuditLogDiff:

+ +
+

New in version 2.0.

+
+
+ +
+
+sticker_update
+

A sticker was updated.

+

When this is the action, the type of target is +the GuildSticker or Object with the ID of the sticker +which was updated.

+

Possible attributes for AuditLogDiff:

+ +
+

New in version 2.0.

+
+
+ +
+
+sticker_delete
+

A sticker was deleted.

+

When this is the action, the type of target is +the GuildSticker or Object with the ID of the sticker +which was updated.

+

Possible attributes for AuditLogDiff:

+ +
+

New in version 2.0.

+
+
+ +
+
+thread_create
+

A thread was created.

+

When this is the action, the type of target is +the Thread or Object with the ID of the thread which +was created.

+

Possible attributes for AuditLogDiff:

+ +
+

New in version 2.0.

+
+
+ +
+
+thread_update
+

A thread was updated.

+

When this is the action, the type of target is +the Thread or Object with the ID of the thread which +was updated.

+

Possible attributes for AuditLogDiff:

+ +
+

New in version 2.0.

+
+
+ +
+
+thread_delete
+

A thread was deleted.

+

When this is the action, the type of target is +the Thread or Object with the ID of the thread which +was deleted.

+

Possible attributes for AuditLogDiff:

+ +
+

New in version 2.0.

+
+
+ +
+ +
+
+class discord.AuditLogActionCategory
+

Represents the category that the AuditLogAction belongs to.

+

This can be retrieved via AuditLogEntry.category.

+
+
+create
+

The action is the creation of something.

+
+ +
+
+delete
+

The action is the deletion of something.

+
+ +
+
+update
+

The action is the update of something.

+
+ +
+ +
+
+class discord.TeamMembershipState
+

Represents the membership state of a team member retrieved through Client.application_info().

+
+

New in version 1.3.

+
+
+
+invited
+

Represents an invited member.

+
+ +
+
+accepted
+

Represents a member currently in the team.

+
+ +
+ +
+
+class discord.WebhookType
+

Represents the type of webhook that can be received.

+
+

New in version 1.3.

+
+
+
+incoming
+

Represents a webhook that can post messages to channels with a token.

+
+ +
+
+channel_follower
+

Represents a webhook that is internally managed by Discord, used for following channels.

+
+ +
+
+application
+

Represents a webhook that is used for interactions or applications.

+
+

New in version 2.0.

+
+
+ +
+ +
+
+class discord.ExpireBehaviour
+

Represents the behaviour the Integration should perform +when a user’s subscription has finished.

+

There is an alias for this called ExpireBehavior.

+
+

New in version 1.4.

+
+
+
+remove_role
+

This will remove the StreamIntegration.role from the user +when their subscription is finished.

+
+ +
+
+kick
+

This will kick the user when their subscription is finished.

+
+ +
+ +
+
+class discord.DefaultAvatar
+

Represents the default avatar of a Discord User

+
+
+blurple
+

Represents the default avatar with the color blurple. +See also Colour.blurple

+
+ +
+
+grey
+

Represents the default avatar with the color grey. +See also Colour.greyple

+
+ +
+
+gray
+

An alias for grey.

+
+ +
+
+green
+

Represents the default avatar with the color green. +See also Colour.green

+
+ +
+
+orange
+

Represents the default avatar with the color orange. +See also Colour.orange

+
+ +
+
+red
+

Represents the default avatar with the color red. +See also Colour.red

+
+ +
+ +
+
+class discord.StickerType
+

Represents the type of sticker.

+
+

New in version 2.0.

+
+
+
+standard
+

Represents a standard sticker that all Nitro users can use.

+
+ +
+
+guild
+

Represents a custom sticker created in a guild.

+
+ +
+ +
+
+class discord.StickerFormatType
+

Represents the type of sticker images.

+
+

New in version 1.6.

+
+
+
+png
+

Represents a sticker with a png image.

+
+ +
+
+apng
+

Represents a sticker with an apng image.

+
+ +
+
+lottie
+

Represents a sticker with a lottie image.

+
+ +
+ +
+
+class discord.InviteTarget
+

Represents the invite type for voice channel invites.

+
+

New in version 2.0.

+
+
+
+unknown
+

The invite doesn’t target anyone or anything.

+
+ +
+
+stream
+

A stream invite that targets a user.

+
+ +
+
+embedded_application
+

A stream invite that targets an embedded application.

+
+ +
+ +
+
+class discord.VideoQualityMode
+

Represents the camera video quality mode for voice channel participants.

+
+

New in version 2.0.

+
+
+
+auto
+

Represents auto camera video quality.

+
+ +
+
+full
+

Represents full camera video quality.

+
+ +
+ +
+
+class discord.StagePrivacyLevel
+

Represents a stage instance’s privacy level.

+
+

New in version 2.0.

+
+
+
+public
+

The stage instance can be joined by external users.

+
+ +
+
+closed
+

The stage instance can only be joined by members of the guild.

+
+ +
+
+guild_only
+

Alias for closed

+
+ +
+ +
+
+class discord.NSFWLevel
+

Represents the NSFW level of a guild.

+
+

New in version 2.0.

+
+
+
+
+x == y
+

Checks if two NSFW levels are equal.

+
+ +
+
+x != y
+

Checks if two NSFW levels are not equal.

+
+ +
+
+x > y
+

Checks if a NSFW level is higher than another.

+
+ +
+
+x < y
+

Checks if a NSFW level is lower than another.

+
+ +
+
+x >= y
+

Checks if a NSFW level is higher or equal to another.

+
+ +
+
+x <= y
+

Checks if a NSFW level is lower or equal to another.

+
+ +
+
+
+default
+

The guild has not been categorised yet.

+
+ +
+
+explicit
+

The guild contains NSFW content.

+
+ +
+
+safe
+

The guild does not contain any NSFW content.

+
+ +
+
+age_restricted
+

The guild may contain NSFW content.

+
+ +
+ +
+
+

Async Iterator

+

Some API functions return an “async iterator”. An async iterator is something that is +capable of being used in an async for statement.

+

These async iterators can be used as follows:

+
async for elem in channel.history():
+    # do stuff with elem here
+
+
+

Certain utilities make working with async iterators easier, detailed below.

+
+
+class discord.AsyncIterator
+

Represents the “AsyncIterator” concept. Note that no such class exists, +it is purely abstract.

+
+
+
+async for x in y
+

Iterates over the contents of the async iterator.

+
+ +
+
+
+await next()
+

This function is a coroutine.

+

Advances the iterator by one, if possible. If no more items are found +then this raises NoMoreItems.

+
+ +
+
+await get(**attrs)
+

This function is a coroutine.

+

Similar to utils.get() except run over the async iterator.

+

Getting the last message by a user named ‘Dave’ or None:

+
msg = await channel.history().get(author__name='Dave')
+
+
+
+ +
+
+await find(predicate)
+

This function is a coroutine.

+

Similar to utils.find() except run over the async iterator.

+

Unlike utils.find(), the predicate provided can be a +coroutine.

+

Getting the last audit log with a reason or None:

+
def predicate(event):
+    return event.reason is not None
+
+event = await guild.audit_logs().find(predicate)
+
+
+
+
Parameters
+

predicate – The predicate to use. Could be a coroutine.

+
+
Returns
+

The first element that returns True for the predicate or None.

+
+
+
+ +
+
+await flatten()
+

This function is a coroutine.

+

Flattens the async iterator into a list with all the elements.

+
+
Returns
+

A list of every element in the async iterator.

+
+
Return type
+

list

+
+
+
+ +
+
+chunk(max_size)
+

Collects items into chunks of up to a given maximum size. +Another AsyncIterator is returned which collects items into +lists of a given size. The maximum chunk size must be a positive integer.

+
+

New in version 1.6.

+
+

Collecting groups of users:

+
async for leader, *users in reaction.users().chunk(3):
+    ...
+
+
+
+

Warning

+

The last chunk collected may not be as large as max_size.

+
+
+
Parameters
+

max_size – The size of individual chunks.

+
+
Return type
+

AsyncIterator

+
+
+
+ +
+
+map(func)
+

This is similar to the built-in map function. Another +AsyncIterator is returned that executes the function on +every element it is iterating over. This function can either be a +regular function or a coroutine.

+

Creating a content iterator:

+
def transform(message):
+    return message.content
+
+async for content in channel.history().map(transform):
+    message_length = len(content)
+
+
+
+
Parameters
+

func – The function to call on every element. Could be a coroutine.

+
+
Return type
+

AsyncIterator

+
+
+
+ +
+
+filter(predicate)
+

This is similar to the built-in filter function. Another +AsyncIterator is returned that filters over the original +async iterator. This predicate can be a regular function or a coroutine.

+

Getting messages by non-bot accounts:

+
def predicate(message):
+    return not message.author.bot
+
+async for elem in channel.history().filter(predicate):
+    ...
+
+
+
+
Parameters
+

predicate – The predicate to call on every element. Could be a coroutine.

+
+
Return type
+

AsyncIterator

+
+
+
+ +
+ +
+
+

Audit Log Data

+

Working with Guild.audit_logs() is a complicated process with a lot of machinery +involved. The library attempts to make it easy to use and friendly. In order to accomplish +this goal, it must make use of a couple of data classes that aid in this goal.

+
+

AuditLogEntry

+
+
+class discord.AuditLogEntry(*, users, data, guild)
+

Represents an Audit Log entry.

+

You retrieve these via Guild.audit_logs().

+
+
+
+x == y
+

Checks if two entries are equal.

+
+ +
+
+x != y
+

Checks if two entries are not equal.

+
+ +
+
+hash(x)
+

Returns the entry’s hash.

+
+ +
+
+int(x)
+

Returns the entry’s ID.

+
+ +
+
+

Changed in version 1.7: Audit log entries are now comparable and hashable.

+
+
+
+action
+

The action that was done.

+
+
Type
+

AuditLogAction

+
+
+
+ +
+
+user
+

The user who initiated this action. Usually a Member, unless gone +then it’s a User.

+
+
Type
+

abc.User

+
+
+
+ +
+
+id
+

The entry ID.

+
+
Type
+

int

+
+
+
+ +
+
+target
+

The target that got changed. The exact type of this depends on +the action being done.

+
+
Type
+

Any

+
+
+
+ +
+
+reason
+

The reason this action was done.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+extra
+

Extra information that this entry has that might be useful. +For most actions, this is None. However in some cases it +contains extra information. See AuditLogAction for +which actions have this field filled out.

+
+
Type
+

Any

+
+
+
+ +
+
+created_at
+

Returns the entry’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+category
+

The category of the action, if applicable.

+
+
Type
+

Optional[AuditLogActionCategory]

+
+
+
+ +
+
+changes
+

The list of changes this entry has.

+
+
Type
+

AuditLogChanges

+
+
+
+ +
+
+before
+

The target’s prior state.

+
+
Type
+

AuditLogDiff

+
+
+
+ +
+
+after
+

The target’s subsequent state.

+
+
Type
+

AuditLogDiff

+
+
+
+ +
+ +
+
+

AuditLogChanges

+
+ +Attributes +
+
+class discord.AuditLogChanges
+

An audit log change set.

+
+
+before
+

The old value. The attribute has the type of AuditLogDiff.

+

Depending on the AuditLogActionCategory retrieved by +category, the data retrieved by this +attribute differs:

+
++++ + + + + + + + + + + + + + + + + + +

Category

Description

create

All attributes are set to None.

delete

All attributes are set the value before deletion.

update

All attributes are set the value before updating.

None

No attributes are set.

+
+ +
+
+after
+

The new value. The attribute has the type of AuditLogDiff.

+

Depending on the AuditLogActionCategory retrieved by +category, the data retrieved by this +attribute differs:

+
++++ + + + + + + + + + + + + + + + + + +

Category

Description

create

All attributes are set to the created value

delete

All attributes are set to None

update

All attributes are set the value after updating.

None

No attributes are set.

+
+ +
+ +
+
+

AuditLogDiff

+
+
+class discord.AuditLogDiff
+

Represents an audit log “change” object. A change object has dynamic +attributes that depend on the type of action being done. Certain actions +map to certain attributes being set.

+

Note that accessing an attribute that does not match the specified action +will lead to an attribute error.

+

To get a list of attributes that have been set, you can iterate over +them. To see a list of all possible attributes that could be set based +on the action being done, check the documentation for AuditLogAction, +otherwise check the documentation below for all attributes that are possible.

+
+
+
+iter(diff)
+

Returns an iterator over (attribute, value) tuple of this diff.

+
+ +
+
+
+name
+

A name of something.

+
+
Type
+

str

+
+
+
+ +
+
+icon
+

A guild’s icon. See also Guild.icon.

+
+
Type
+

Asset

+
+
+
+ +
+
+splash
+

The guild’s invite splash. See also Guild.splash.

+
+
Type
+

Asset

+
+
+
+ +
+
+discovery_splash
+

The guild’s discovery splash. See also Guild.discovery_splash.

+
+
Type
+

Asset

+
+
+
+ +
+
+banner
+

The guild’s banner. See also Guild.banner.

+
+
Type
+

Asset

+
+
+
+ +
+
+owner
+

The guild’s owner. See also Guild.owner

+
+
Type
+

Union[Member, User]

+
+
+
+ +
+
+region
+

The guild’s voice region. See also Guild.region.

+
+
Type
+

VoiceRegion

+
+
+
+ +
+
+afk_channel
+

The guild’s AFK channel.

+

If this could not be found, then it falls back to a Object +with the ID being set.

+

See Guild.afk_channel.

+
+
Type
+

Union[VoiceChannel, Object]

+
+
+
+ +
+
+system_channel
+

The guild’s system channel.

+

If this could not be found, then it falls back to a Object +with the ID being set.

+

See Guild.system_channel.

+
+
Type
+

Union[TextChannel, Object]

+
+
+
+ +
+
+rules_channel
+

The guild’s rules channel.

+

If this could not be found then it falls back to a Object +with the ID being set.

+

See Guild.rules_channel.

+
+
Type
+

Union[TextChannel, Object]

+
+
+
+ +
+
+public_updates_channel
+

The guild’s public updates channel.

+

If this could not be found then it falls back to a Object +with the ID being set.

+

See Guild.public_updates_channel.

+
+
Type
+

Union[TextChannel, Object]

+
+
+
+ +
+
+afk_timeout
+

The guild’s AFK timeout. See Guild.afk_timeout.

+
+
Type
+

int

+
+
+
+ +
+
+mfa_level
+

The guild’s MFA level. See Guild.mfa_level.

+
+
Type
+

int

+
+
+
+ +
+
+widget_enabled
+

The guild’s widget has been enabled or disabled.

+
+
Type
+

bool

+
+
+
+ +
+
+widget_channel
+

The widget’s channel.

+

If this could not be found then it falls back to a Object +with the ID being set.

+
+
Type
+

Union[TextChannel, Object]

+
+
+
+ +
+
+verification_level
+

The guild’s verification level.

+

See also Guild.verification_level.

+
+
Type
+

VerificationLevel

+
+
+
+ +
+
+default_notifications
+

The guild’s default notification level.

+

See also Guild.default_notifications.

+
+
Type
+

NotificationLevel

+
+
+
+ +
+
+explicit_content_filter
+

The guild’s content filter.

+

See also Guild.explicit_content_filter.

+
+
Type
+

ContentFilter

+
+
+
+ +
+
+default_message_notifications
+

The guild’s default message notification setting.

+
+
Type
+

int

+
+
+
+ +
+
+vanity_url_code
+

The guild’s vanity URL.

+

See also Guild.vanity_invite() and Guild.edit().

+
+
Type
+

str

+
+
+
+ +
+
+position
+

The position of a Role or abc.GuildChannel.

+
+
Type
+

int

+
+
+
+ +
+
+type
+

The type of channel or sticker.

+
+
Type
+

Union[ChannelType, StickerType]

+
+
+
+ +
+
+topic
+

The topic of a TextChannel or StageChannel.

+

See also TextChannel.topic or StageChannel.topic.

+
+
Type
+

str

+
+
+
+ +
+
+bitrate
+

The bitrate of a VoiceChannel.

+

See also VoiceChannel.bitrate.

+
+
Type
+

int

+
+
+
+ +
+
+overwrites
+

A list of permission overwrite tuples that represents a target and a +PermissionOverwrite for said target.

+

The first element is the object being targeted, which can either +be a Member or User or Role. If this object +is not found then it is a Object with an ID being filled and +a type attribute set to either 'role' or 'member' to help +decide what type of ID it is.

+
+
Type
+

List[Tuple[target, PermissionOverwrite]]

+
+
+
+ +
+
+privacy_level
+

The privacy level of the stage instance.

+
+
Type
+

StagePrivacyLevel

+
+
+
+ +
+
+roles
+

A list of roles being added or removed from a member.

+

If a role is not found then it is a Object with the ID and name being +filled in.

+
+
Type
+

List[Union[Role, Object]]

+
+
+
+ +
+
+nick
+

The nickname of a member.

+

See also Member.nick

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+deaf
+

Whether the member is being server deafened.

+

See also VoiceState.deaf.

+
+
Type
+

bool

+
+
+
+ +
+
+mute
+

Whether the member is being server muted.

+

See also VoiceState.mute.

+
+
Type
+

bool

+
+
+
+ +
+
+permissions
+

The permissions of a role.

+

See also Role.permissions.

+
+
Type
+

Permissions

+
+
+
+ +
+
+colour
+
+color
+

The colour of a role.

+

See also Role.colour

+
+
Type
+

Colour

+
+
+
+ +
+
+hoist
+

Whether the role is being hoisted or not.

+

See also Role.hoist

+
+
Type
+

bool

+
+
+
+ +
+
+mentionable
+

Whether the role is mentionable or not.

+

See also Role.mentionable

+
+
Type
+

bool

+
+
+
+ +
+
+code
+

The invite’s code.

+

See also Invite.code

+
+
Type
+

str

+
+
+
+ +
+
+channel
+

A guild channel.

+

If the channel is not found then it is a Object with the ID +being set. In some cases the channel name is also set.

+
+
Type
+

Union[abc.GuildChannel, Object]

+
+
+
+ +
+
+inviter
+

The user who created the invite.

+

See also Invite.inviter.

+
+
Type
+

Optional[User]

+
+
+
+ +
+
+max_uses
+

The invite’s max uses.

+

See also Invite.max_uses.

+
+
Type
+

int

+
+
+
+ +
+
+uses
+

The invite’s current uses.

+

See also Invite.uses.

+
+
Type
+

int

+
+
+
+ +
+
+max_age
+

The invite’s max age in seconds.

+

See also Invite.max_age.

+
+
Type
+

int

+
+
+
+ +
+
+temporary
+

If the invite is a temporary invite.

+

See also Invite.temporary.

+
+
Type
+

bool

+
+
+
+ +
+
+allow
+
+deny
+

The permissions being allowed or denied.

+
+
Type
+

Permissions

+
+
+
+ +
+
+id
+

The ID of the object being changed.

+
+
Type
+

int

+
+
+
+ +
+
+avatar
+

The avatar of a member.

+

See also User.avatar.

+
+
Type
+

Asset

+
+
+
+ +
+
+slowmode_delay
+

The number of seconds members have to wait before +sending another message in the channel.

+

See also TextChannel.slowmode_delay.

+
+
Type
+

int

+
+
+
+ +
+
+rtc_region
+

The region for the voice channel’s voice communication. +A value of None indicates automatic voice region detection.

+

See also VoiceChannel.rtc_region.

+
+
Type
+

VoiceRegion

+
+
+
+ +
+
+video_quality_mode
+

The camera video quality for the voice channel’s participants.

+

See also VoiceChannel.video_quality_mode.

+
+
Type
+

VideoQualityMode

+
+
+
+ +
+
+format_type
+

The format type of a sticker being changed.

+

See also GuildSticker.format

+
+
Type
+

StickerFormatType

+
+
+
+ +
+
+emoji
+

The name of the emoji that represents a sticker being changed.

+

See also GuildSticker.emoji

+
+
Type
+

str

+
+
+
+ +
+
+description
+

The description of a sticker being changed.

+

See also GuildSticker.description

+
+
Type
+

str

+
+
+
+ +
+
+available
+

The availability of a sticker being changed.

+

See also GuildSticker.available

+
+
Type
+

bool

+
+
+
+ +
+
+archived
+

The thread is now archived.

+
+
Type
+

bool

+
+
+
+ +
+
+locked
+

The thread is being locked or unlocked.

+
+
Type
+

bool

+
+
+
+ +
+
+auto_archive_duration
+

The thread’s auto archive duration being changed.

+

See also Thread.auto_archive_duration

+
+
Type
+

int

+
+
+
+ +
+
+default_auto_archive_duration
+

The default auto archive duration for newly created threads being changed.

+
+
Type
+

int

+
+
+
+ +
+ +
+
+
+

Webhook Support

+

discord.py offers support for creating, editing, and executing webhooks through the Webhook class.

+
+

Webhook

+
+ +Methods +
+
+class discord.Webhook
+

Represents an asynchronous Discord webhook.

+

Webhooks are a form to send messages to channels in Discord without a +bot user or authentication.

+

There are two main ways to use Webhooks. The first is through the ones +received by the library such as Guild.webhooks() and +TextChannel.webhooks(). The ones received by the library will +automatically be bound using the library’s internal HTTP session.

+

The second form involves creating a webhook object manually using the +from_url() or partial() classmethods.

+

For example, creating a webhook from a URL and using aiohttp:

+
from discord import Webhook
+import aiohttp
+
+async def foo():
+    async with aiohttp.ClientSession() as session:
+        webhook = Webhook.from_url('url-here', session=session)
+        await webhook.send('Hello World', username='Foo')
+
+
+

For a synchronous counterpart, see SyncWebhook.

+
+
+
+x == y
+

Checks if two webhooks are equal.

+
+ +
+
+x != y
+

Checks if two webhooks are not equal.

+
+ +
+
+hash(x)
+

Returns the webhooks’s hash.

+
+ +
+
+int(x)
+

Returns the webhooks’s ID.

+
+ +
+
+

Changed in version 1.4: Webhooks are now comparable and hashable.

+
+
+
+id
+

The webhook’s ID

+
+
Type
+

int

+
+
+
+ +
+
+type
+

The type of the webhook.

+
+

New in version 1.3.

+
+
+
Type
+

WebhookType

+
+
+
+ +
+
+token
+

The authentication token of the webhook. If this is None +then the webhook cannot be used to make requests.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+guild_id
+

The guild ID this webhook is for.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+channel_id
+

The channel ID this webhook is for.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+user
+

The user this webhook was created by. If the webhook was +received without authentication then this will be None.

+
+
Type
+

Optional[abc.User]

+
+
+
+ +
+
+name
+

The default name of the webhook.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+source_guild
+

The guild of the channel that this webhook is following. +Only given if type is WebhookType.channel_follower.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[PartialWebhookGuild]

+
+
+
+ +
+
+source_channel
+

The channel that this webhook is following. +Only given if type is WebhookType.channel_follower.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[PartialWebhookChannel]

+
+
+
+ +
+
+property url
+

Returns the webhook’s url.

+
+
Type
+

str

+
+
+
+ +
+
+classmethod partial(id, token, *, session, bot_token=None)
+

Creates a partial Webhook.

+
+
Parameters
+
    +
  • id (int) – The ID of the webhook.

  • +
  • token (str) – The authentication token of the webhook.

  • +
  • session (aiohttp.ClientSession) –

    The session to use to send requests with. Note +that the library does not manage the session and +will not close it.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • bot_token (Optional[str]) –

    The bot authentication token for authenticated requests +involving the webhook.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Returns
+

A partial Webhook. +A partial webhook is just a webhook object with an ID and a token.

+
+
Return type
+

Webhook

+
+
+
+ +
+
+classmethod from_url(url, *, session, bot_token=None)
+

Creates a partial Webhook from a webhook URL.

+
+
Parameters
+
    +
  • url (str) – The URL of the webhook.

  • +
  • session (aiohttp.ClientSession) –

    The session to use to send requests with. Note +that the library does not manage the session and +will not close it.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • bot_token (Optional[str]) –

    The bot authentication token for authenticated requests +involving the webhook.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+

InvalidArgument – The URL is invalid.

+
+
Returns
+

A partial Webhook. +A partial webhook is just a webhook object with an ID and a token.

+
+
Return type
+

Webhook

+
+
+
+ +
+
+await fetch(*, prefer_auth=True)
+

This function is a coroutine.

+

Fetches the current webhook.

+

This could be used to get a full webhook from a partial webhook.

+
+

New in version 2.0.

+
+
+

Note

+

When fetching with an unauthenticated webhook, i.e. +is_authenticated() returns False, then the +returned webhook does not contain any user information.

+
+
+
Parameters
+

prefer_auth (bool) – Whether to use the bot token over the webhook token +if available. Defaults to True.

+
+
Raises
+
+
+
Returns
+

The fetched webhook.

+
+
Return type
+

Webhook

+
+
+
+ +
+
+await delete(*, reason=None, prefer_auth=True)
+

This function is a coroutine.

+

Deletes this Webhook.

+
+
Parameters
+
    +
  • reason (Optional[str]) –

    The reason for deleting this webhook. Shows up on the audit log.

    +
    +

    New in version 1.4.

    +
    +

  • +
  • prefer_auth (bool) –

    Whether to use the bot token over the webhook token +if available. Defaults to True.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
    +
  • HTTPException – Deleting the webhook failed.

  • +
  • NotFound – This webhook does not exist.

  • +
  • Forbidden – You do not have permissions to delete this webhook.

  • +
  • InvalidArgument – This webhook does not have a token associated with it.

  • +
+
+
+
+ +
+
+await edit(*, reason=None, name=..., avatar=..., channel=None, prefer_auth=True)
+

This function is a coroutine.

+

Edits this Webhook.

+
+
Parameters
+
    +
  • name (Optional[str]) – The webhook’s new default name.

  • +
  • avatar (Optional[bytes]) – A bytes-like object representing the webhook’s new default avatar.

  • +
  • channel (Optional[abc.Snowflake]) –

    The webhook’s new channel. This requires an authenticated webhook.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • reason (Optional[str]) –

    The reason for editing this webhook. Shows up on the audit log.

    +
    +

    New in version 1.4.

    +
    +

  • +
  • prefer_auth (bool) –

    Whether to use the bot token over the webhook token +if available. Defaults to True.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
    +
  • HTTPException – Editing the webhook failed.

  • +
  • NotFound – This webhook does not exist.

  • +
  • InvalidArgument – This webhook does not have a token associated with it + or it tried editing a channel without authentication.

  • +
+
+
+
+ +
+
+property avatar
+

Returns an Asset for the avatar the webhook has.

+

If the webhook does not have a traditional avatar, an asset for +the default avatar is returned instead.

+
+
Type
+

Asset

+
+
+
+ +
+
+property channel
+

The text channel this webhook belongs to.

+

If this is a partial webhook, then this will always return None.

+
+
Type
+

Optional[TextChannel]

+
+
+
+ +
+
+property created_at
+

Returns the webhook’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+property guild
+

The guild this webhook belongs to.

+

If this is a partial webhook, then this will always return None.

+
+
Type
+

Optional[Guild]

+
+
+
+ +
+
+is_authenticated()
+

bool: Whether the webhook is authenticated with a bot token.

+
+

New in version 2.0.

+
+
+ +
+
+is_partial()
+

bool: Whether the webhook is a “partial” webhook.

+
+

New in version 2.0.

+
+
+ +
+
+await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., wait=False)
+

This function is a coroutine.

+

Sends a message using the webhook.

+

The content must be a type that can convert to a string through str(content).

+

To upload a single file, the file parameter should be used with a +single File object.

+

If the embed parameter is provided, it must be of type Embed and +it must be a rich embed type. You cannot mix the embed parameter with the +embeds parameter, which must be a list of Embed objects to send.

+
+
Parameters
+
    +
  • content (str) – The content of the message to send.

  • +
  • wait (bool) – Whether the server should wait before sending a response. This essentially +means that the return type of this function changes from None to +a WebhookMessage if set to True. If the type of webhook +is WebhookType.application then this is always set to True.

  • +
  • username (str) – The username to send with this message. If no username is provided +then the default username for the webhook is used.

  • +
  • avatar_url (str) – The avatar URL to send with this message. If no avatar URL is provided +then the default avatar for the webhook is used. If this is not a +string then it is explicitly cast using str.

  • +
  • tts (bool) – Indicates if the message should be sent using text-to-speech.

  • +
  • ephemeral (bool) –

    Indicates if the message should only be visible to the user. +This is only available to WebhookType.application webhooks. +If a view is sent with an ephemeral message and it has no timeout set +then the timeout is set to 15 minutes.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • file (File) – The file to upload. This cannot be mixed with files parameter.

  • +
  • files (List[File]) – A list of files to send with the content. This cannot be mixed with the +file parameter.

  • +
  • embed (Embed) – The rich embed for the content to send. This cannot be mixed with +embeds parameter.

  • +
  • embeds (List[Embed]) – A list of embeds to send with the content. Maximum of 10. This cannot +be mixed with the embed parameter.

  • +
  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message.

    +
    +

    New in version 1.4.

    +
    +

  • +
  • view (discord.ui.View) –

    The view to send with the message. You can only send a view +if this webhook is not partial and has state attached. A +webhook has state attached if the webhook is managed by the +library.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • thread (Snowflake) –

    The thread to send this webhook to.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
    +
  • HTTPException – Sending the message failed.

  • +
  • NotFound – This webhook was not found.

  • +
  • Forbidden – The authorization token for the webhook is incorrect.

  • +
  • TypeError – You specified both embed and embeds or file and files.

  • +
  • ValueError – The length of embeds was invalid.

  • +
  • InvalidArgument – There was no token associated with this webhook or ephemeral + was passed with the improper webhook type or there was no state + attached with this webhook when giving it a view.

  • +
+
+
Returns
+

If wait is True then the message that was sent, otherwise None.

+
+
Return type
+

Optional[WebhookMessage]

+
+
+
+ +
+
+await fetch_message(id)
+

This function is a coroutine.

+

Retrieves a single WebhookMessage owned by this webhook.

+
+

New in version 2.0.

+
+
+
Parameters
+

id (int) – The message ID to look for.

+
+
Raises
+
    +
  • NotFound – The specified message was not found.

  • +
  • Forbidden – You do not have the permissions required to get a message.

  • +
  • HTTPException – Retrieving the message failed.

  • +
  • InvalidArgument – There was no token associated with this webhook.

  • +
+
+
Returns
+

The message asked for.

+
+
Return type
+

WebhookMessage

+
+
+
+ +
+
+await edit_message(message_id, *, content=..., embeds=..., embed=..., file=..., files=..., view=..., allowed_mentions=None)
+

This function is a coroutine.

+

Edits a message owned by this webhook.

+

This is a lower level interface to WebhookMessage.edit() in case +you only have an ID.

+
+

New in version 1.6.

+
+
+

Changed in version 2.0: The edit is no longer in-place, instead the newly edited message is returned.

+
+
+
Parameters
+
    +
  • message_id (int) – The message ID to edit.

  • +
  • content (Optional[str]) – The content to edit the message with or None to clear it.

  • +
  • embeds (List[Embed]) – A list of embeds to edit the message with.

  • +
  • embed (Optional[Embed]) – The embed to edit the message with. None suppresses the embeds. +This should not be mixed with the embeds parameter.

  • +
  • file (File) –

    The file to upload. This cannot be mixed with files parameter.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • files (List[File]) –

    A list of files to send with the content. This cannot be mixed with the +file parameter.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • allowed_mentions (AllowedMentions) – Controls the mentions being processed in this message. +See abc.Messageable.send() for more information.

  • +
  • view (Optional[View]) –

    The updated view to update this message with. If None is passed then +the view is removed. The webhook must have state attached, similar to +send().

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
    +
  • HTTPException – Editing the message failed.

  • +
  • Forbidden – Edited a message that is not yours.

  • +
  • TypeError – You specified both embed and embeds or file and files

  • +
  • ValueError – The length of embeds was invalid

  • +
  • InvalidArgument – There was no token associated with this webhook or the webhook had + no state.

  • +
+
+
Returns
+

The newly edited webhook message.

+
+
Return type
+

WebhookMessage

+
+
+
+ +
+
+await delete_message(message_id, /)
+

This function is a coroutine.

+

Deletes a message owned by this webhook.

+

This is a lower level interface to WebhookMessage.delete() in case +you only have an ID.

+
+

New in version 1.6.

+
+
+
Parameters
+

message_id (int) – The message ID to delete.

+
+
Raises
+
+
+
+
+ +
+ +
+
+

WebhookMessage

+
+ +Methods +
+
+class discord.WebhookMessage
+

Represents a message sent from your webhook.

+

This allows you to edit or delete a message sent by your +webhook.

+

This inherits from discord.Message with changes to +edit() and delete() to work.

+
+

New in version 1.6.

+
+
+
+await edit(content=..., embeds=..., embed=..., file=..., files=..., view=..., allowed_mentions=None)
+

This function is a coroutine.

+

Edits the message.

+
+

New in version 1.6.

+
+
+

Changed in version 2.0: The edit is no longer in-place, instead the newly edited message is returned.

+
+
+
Parameters
+
    +
  • content (Optional[str]) – The content to edit the message with or None to clear it.

  • +
  • embeds (List[Embed]) – A list of embeds to edit the message with.

  • +
  • embed (Optional[Embed]) – The embed to edit the message with. None suppresses the embeds. +This should not be mixed with the embeds parameter.

  • +
  • file (File) –

    The file to upload. This cannot be mixed with files parameter.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • files (List[File]) –

    A list of files to send with the content. This cannot be mixed with the +file parameter.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • allowed_mentions (AllowedMentions) – Controls the mentions being processed in this message. +See abc.Messageable.send() for more information.

  • +
  • view (Optional[View]) –

    The updated view to update this message with. If None is passed then +the view is removed.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
    +
  • HTTPException – Editing the message failed.

  • +
  • Forbidden – Edited a message that is not yours.

  • +
  • TypeError – You specified both embed and embeds or file and files

  • +
  • ValueError – The length of embeds was invalid

  • +
  • InvalidArgument – There was no token associated with this webhook.

  • +
+
+
Returns
+

The newly edited message.

+
+
Return type
+

WebhookMessage

+
+
+
+ +
+
+await delete(*, delay=None)
+

This function is a coroutine.

+

Deletes the message.

+
+
Parameters
+

delay (Optional[float]) – If provided, the number of seconds to wait before deleting the message. +The waiting is done in the background and deletion failures are ignored.

+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to delete the message.

  • +
  • NotFound – The message was deleted already.

  • +
  • HTTPException – Deleting the message failed.

  • +
+
+
+
+ +
+ +
+
+

SyncWebhook

+
+
+class discord.SyncWebhook
+

Represents a synchronous Discord webhook.

+

For an asynchronous counterpart, see Webhook.

+
+
+
+x == y
+

Checks if two webhooks are equal.

+
+ +
+
+x != y
+

Checks if two webhooks are not equal.

+
+ +
+
+hash(x)
+

Returns the webhooks’s hash.

+
+ +
+
+int(x)
+

Returns the webhooks’s ID.

+
+ +
+
+

Changed in version 1.4: Webhooks are now comparable and hashable.

+
+
+
+id
+

The webhook’s ID

+
+
Type
+

int

+
+
+
+ +
+
+type
+

The type of the webhook.

+
+

New in version 1.3.

+
+
+
Type
+

WebhookType

+
+
+
+ +
+
+token
+

The authentication token of the webhook. If this is None +then the webhook cannot be used to make requests.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+guild_id
+

The guild ID this webhook is for.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+channel_id
+

The channel ID this webhook is for.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+user
+

The user this webhook was created by. If the webhook was +received without authentication then this will be None.

+
+
Type
+

Optional[abc.User]

+
+
+
+ +
+
+name
+

The default name of the webhook.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+source_guild
+

The guild of the channel that this webhook is following. +Only given if type is WebhookType.channel_follower.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[PartialWebhookGuild]

+
+
+
+ +
+
+source_channel
+

The channel that this webhook is following. +Only given if type is WebhookType.channel_follower.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[PartialWebhookChannel]

+
+
+
+ +
+
+property url
+

Returns the webhook’s url.

+
+
Type
+

str

+
+
+
+ +
+
+classmethod partial(id, token, *, session=..., bot_token=None)
+

Creates a partial Webhook.

+
+
Parameters
+
    +
  • id (int) – The ID of the webhook.

  • +
  • token (str) – The authentication token of the webhook.

  • +
  • session (requests.Session) – The session to use to send requests with. Note +that the library does not manage the session and +will not close it. If not given, the requests +auto session creation functions are used instead.

  • +
  • bot_token (Optional[str]) – The bot authentication token for authenticated requests +involving the webhook.

  • +
+
+
Returns
+

A partial Webhook. +A partial webhook is just a webhook object with an ID and a token.

+
+
Return type
+

Webhook

+
+
+
+ +
+
+classmethod from_url(url, *, session=..., bot_token=None)
+

Creates a partial Webhook from a webhook URL.

+
+
Parameters
+
    +
  • url (str) – The URL of the webhook.

  • +
  • session (requests.Session) – The session to use to send requests with. Note +that the library does not manage the session and +will not close it. If not given, the requests +auto session creation functions are used instead.

  • +
  • bot_token (Optional[str]) – The bot authentication token for authenticated requests +involving the webhook.

  • +
+
+
Raises
+

InvalidArgument – The URL is invalid.

+
+
Returns
+

A partial Webhook. +A partial webhook is just a webhook object with an ID and a token.

+
+
Return type
+

Webhook

+
+
+
+ +
+
+fetch(*, prefer_auth=True)
+

Fetches the current webhook.

+

This could be used to get a full webhook from a partial webhook.

+
+

Note

+

When fetching with an unauthenticated webhook, i.e. +is_authenticated() returns False, then the +returned webhook does not contain any user information.

+
+
+
Parameters
+

prefer_auth (bool) – Whether to use the bot token over the webhook token +if available. Defaults to True.

+
+
Raises
+
+
+
Returns
+

The fetched webhook.

+
+
Return type
+

SyncWebhook

+
+
+
+ +
+
+delete(*, reason=None, prefer_auth=True)
+

Deletes this Webhook.

+
+
Parameters
+
    +
  • reason (Optional[str]) –

    The reason for deleting this webhook. Shows up on the audit log.

    +
    +

    New in version 1.4.

    +
    +

  • +
  • prefer_auth (bool) – Whether to use the bot token over the webhook token +if available. Defaults to True.

  • +
+
+
Raises
+
    +
  • HTTPException – Deleting the webhook failed.

  • +
  • NotFound – This webhook does not exist.

  • +
  • Forbidden – You do not have permissions to delete this webhook.

  • +
  • InvalidArgument – This webhook does not have a token associated with it.

  • +
+
+
+
+ +
+
+edit(*, reason=None, name=..., avatar=..., channel=None, prefer_auth=True)
+

Edits this Webhook.

+
+
Parameters
+
    +
  • name (Optional[str]) – The webhook’s new default name.

  • +
  • avatar (Optional[bytes]) – A bytes-like object representing the webhook’s new default avatar.

  • +
  • channel (Optional[abc.Snowflake]) – The webhook’s new channel. This requires an authenticated webhook.

  • +
  • reason (Optional[str]) –

    The reason for editing this webhook. Shows up on the audit log.

    +
    +

    New in version 1.4.

    +
    +

  • +
  • prefer_auth (bool) – Whether to use the bot token over the webhook token +if available. Defaults to True.

  • +
+
+
Raises
+
    +
  • HTTPException – Editing the webhook failed.

  • +
  • NotFound – This webhook does not exist.

  • +
  • InvalidArgument – This webhook does not have a token associated with it + or it tried editing a channel without authentication.

  • +
+
+
Returns
+

The newly edited webhook.

+
+
Return type
+

SyncWebhook

+
+
+
+ +
+
+send(content=..., *, username=..., avatar_url=..., tts=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., thread=..., wait=False)
+

Sends a message using the webhook.

+

The content must be a type that can convert to a string through str(content).

+

To upload a single file, the file parameter should be used with a +single File object.

+

If the embed parameter is provided, it must be of type Embed and +it must be a rich embed type. You cannot mix the embed parameter with the +embeds parameter, which must be a list of Embed objects to send.

+
+
Parameters
+
    +
  • content (str) – The content of the message to send.

  • +
  • wait (bool) – Whether the server should wait before sending a response. This essentially +means that the return type of this function changes from None to +a WebhookMessage if set to True.

  • +
  • username (str) – The username to send with this message. If no username is provided +then the default username for the webhook is used.

  • +
  • avatar_url (str) – The avatar URL to send with this message. If no avatar URL is provided +then the default avatar for the webhook is used. If this is not a +string then it is explicitly cast using str.

  • +
  • tts (bool) – Indicates if the message should be sent using text-to-speech.

  • +
  • file (File) – The file to upload. This cannot be mixed with files parameter.

  • +
  • files (List[File]) – A list of files to send with the content. This cannot be mixed with the +file parameter.

  • +
  • embed (Embed) – The rich embed for the content to send. This cannot be mixed with +embeds parameter.

  • +
  • embeds (List[Embed]) – A list of embeds to send with the content. Maximum of 10. This cannot +be mixed with the embed parameter.

  • +
  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message.

    +
    +

    New in version 1.4.

    +
    +

  • +
  • thread (Snowflake) –

    The thread to send this message to.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
    +
  • HTTPException – Sending the message failed.

  • +
  • NotFound – This webhook was not found.

  • +
  • Forbidden – The authorization token for the webhook is incorrect.

  • +
  • TypeError – You specified both embed and embeds or file and files

  • +
  • ValueError – The length of embeds was invalid

  • +
  • InvalidArgument – There was no token associated with this webhook.

  • +
+
+
Returns
+

If wait is True then the message that was sent, otherwise None.

+
+
Return type
+

Optional[SyncWebhookMessage]

+
+
+
+ +
+
+fetch_message(id, /)
+

Retrieves a single SyncWebhookMessage owned by this webhook.

+
+

New in version 2.0.

+
+
+
Parameters
+

id (int) – The message ID to look for.

+
+
Raises
+
    +
  • NotFound – The specified message was not found.

  • +
  • Forbidden – You do not have the permissions required to get a message.

  • +
  • HTTPException – Retrieving the message failed.

  • +
  • InvalidArgument – There was no token associated with this webhook.

  • +
+
+
Returns
+

The message asked for.

+
+
Return type
+

SyncWebhookMessage

+
+
+
+ +
+
+property avatar
+

Returns an Asset for the avatar the webhook has.

+

If the webhook does not have a traditional avatar, an asset for +the default avatar is returned instead.

+
+
Type
+

Asset

+
+
+
+ +
+
+property channel
+

The text channel this webhook belongs to.

+

If this is a partial webhook, then this will always return None.

+
+
Type
+

Optional[TextChannel]

+
+
+
+ +
+
+property created_at
+

Returns the webhook’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+edit_message(message_id, *, content=..., embeds=..., embed=..., file=..., files=..., allowed_mentions=None)
+

Edits a message owned by this webhook.

+

This is a lower level interface to WebhookMessage.edit() in case +you only have an ID.

+
+

New in version 1.6.

+
+
+
Parameters
+
    +
  • message_id (int) – The message ID to edit.

  • +
  • content (Optional[str]) – The content to edit the message with or None to clear it.

  • +
  • embeds (List[Embed]) – A list of embeds to edit the message with.

  • +
  • embed (Optional[Embed]) – The embed to edit the message with. None suppresses the embeds. +This should not be mixed with the embeds parameter.

  • +
  • file (File) – The file to upload. This cannot be mixed with files parameter.

  • +
  • files (List[File]) – A list of files to send with the content. This cannot be mixed with the +file parameter.

  • +
  • allowed_mentions (AllowedMentions) – Controls the mentions being processed in this message. +See abc.Messageable.send() for more information.

  • +
+
+
Raises
+
    +
  • HTTPException – Editing the message failed.

  • +
  • Forbidden – Edited a message that is not yours.

  • +
  • TypeError – You specified both embed and embeds or file and files

  • +
  • ValueError – The length of embeds was invalid

  • +
  • InvalidArgument – There was no token associated with this webhook.

  • +
+
+
+
+ +
+
+property guild
+

The guild this webhook belongs to.

+

If this is a partial webhook, then this will always return None.

+
+
Type
+

Optional[Guild]

+
+
+
+ +
+
+is_authenticated()
+

bool: Whether the webhook is authenticated with a bot token.

+
+

New in version 2.0.

+
+
+ +
+
+is_partial()
+

bool: Whether the webhook is a “partial” webhook.

+
+

New in version 2.0.

+
+
+ +
+
+delete_message(message_id, /)
+

Deletes a message owned by this webhook.

+

This is a lower level interface to WebhookMessage.delete() in case +you only have an ID.

+
+

New in version 1.6.

+
+
+
Parameters
+

message_id (int) – The message ID to delete.

+
+
Raises
+
+
+
+
+ +
+ +
+
+

SyncWebhookMessage

+
+ +Methods +
+
+class discord.SyncWebhookMessage
+

Represents a message sent from your webhook.

+

This allows you to edit or delete a message sent by your +webhook.

+

This inherits from discord.Message with changes to +edit() and delete() to work.

+
+

New in version 2.0.

+
+
+
+edit(content=..., embeds=..., embed=..., file=..., files=..., allowed_mentions=None)
+

Edits the message.

+
+
Parameters
+
    +
  • content (Optional[str]) – The content to edit the message with or None to clear it.

  • +
  • embeds (List[Embed]) – A list of embeds to edit the message with.

  • +
  • embed (Optional[Embed]) – The embed to edit the message with. None suppresses the embeds. +This should not be mixed with the embeds parameter.

  • +
  • file (File) – The file to upload. This cannot be mixed with files parameter.

  • +
  • files (List[File]) – A list of files to send with the content. This cannot be mixed with the +file parameter.

  • +
  • allowed_mentions (AllowedMentions) – Controls the mentions being processed in this message. +See abc.Messageable.send() for more information.

  • +
+
+
Raises
+
    +
  • HTTPException – Editing the message failed.

  • +
  • Forbidden – Edited a message that is not yours.

  • +
  • TypeError – You specified both embed and embeds or file and files

  • +
  • ValueError – The length of embeds was invalid

  • +
  • InvalidArgument – There was no token associated with this webhook.

  • +
+
+
Returns
+

The newly edited message.

+
+
Return type
+

SyncWebhookMessage

+
+
+
+ +
+
+delete(*, delay=None)
+

Deletes the message.

+
+
Parameters
+

delay (Optional[float]) – If provided, the number of seconds to wait before deleting the message. +This blocks the thread.

+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to delete the message.

  • +
  • NotFound – The message was deleted already.

  • +
  • HTTPException – Deleting the message failed.

  • +
+
+
+
+ +
+ +
+
+
+

Abstract Base Classes

+

An abstract base class (also known as an abc) is a class that models can inherit +to get their behaviour. Abstract base classes should not be instantiated. +They are mainly there for usage with isinstance() and issubclass().

+

This library has a module related to abstract base classes, in which all the ABCs are subclasses of +typing.Protocol.

+
+

Snowflake

+
+ +Attributes +
+
+class discord.abc.Snowflake
+

An ABC that details the common operations on a Discord model.

+

Almost all Discord models meet this +abstract base class.

+

If you want to create a snowflake on your own, consider using +Object.

+
+
+id
+

The model’s unique ID.

+
+
Type
+

int

+
+
+
+ +
+ +
+
+

User

+
+ +Attributes +
+
+class discord.abc.User
+

An ABC that details the common operations on a Discord user.

+

The following implement this ABC:

+ +

This ABC must also implement Snowflake.

+
+
+name
+

The user’s username.

+
+
Type
+

str

+
+
+
+ +
+
+discriminator
+

The user’s discriminator.

+
+
Type
+

str

+
+
+
+ +
+
+avatar
+

The avatar asset the user has.

+
+
Type
+

Asset

+
+
+
+ +
+
+bot
+

If the user is a bot account.

+
+
Type
+

bool

+
+
+
+ +
+
+property display_name
+

Returns the user’s display name.

+
+
Type
+

str

+
+
+
+ +
+
+property mention
+

Returns a string that allows you to mention the given user.

+
+
Type
+

str

+
+
+
+ +
+ +
+
+

PrivateChannel

+
+ +Attributes +
+
+class discord.abc.PrivateChannel
+

An ABC that details the common operations on a private Discord channel.

+

The following implement this ABC:

+ +

This ABC must also implement Snowflake.

+
+
+me
+

The user presenting yourself.

+
+
Type
+

ClientUser

+
+
+
+ +
+ +
+
+

GuildChannel

+
+ +Methods +
+
+class discord.abc.GuildChannel
+

An ABC that details the common operations on a Discord guild channel.

+

The following implement this ABC:

+ +

This ABC must also implement Snowflake.

+
+
+name
+

The channel name.

+
+
Type
+

str

+
+
+
+ +
+
+guild
+

The guild the channel belongs to.

+
+
Type
+

Guild

+
+
+
+ +
+
+position
+

The position in the channel list. This is a number that starts at 0. +e.g. the top channel is position 0.

+
+
Type
+

int

+
+
+
+ +
+
+property changed_roles
+

Returns a list of roles that have been overridden from +their default values in the roles attribute.

+
+
Type
+

List[Role]

+
+
+
+ +
+
+property mention
+

The string that allows you to mention the channel.

+
+
Type
+

str

+
+
+
+ +
+
+property created_at
+

Returns the channel’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+overwrites_for(obj)
+

Returns the channel-specific overwrites for a member or a role.

+
+
Parameters
+

obj (Union[Role, User]) – The role or user denoting +whose overwrite to get.

+
+
Returns
+

The permission overwrites for this object.

+
+
Return type
+

PermissionOverwrite

+
+
+
+ +
+
+property overwrites
+

Returns all of the channel’s overwrites.

+

This is returned as a dictionary where the key contains the target which +can be either a Role or a Member and the value is the +overwrite as a PermissionOverwrite.

+
+
Returns
+

The channel’s permission overwrites.

+
+
Return type
+

Dict[Union[Role, Member], PermissionOverwrite]

+
+
+
+ +
+
+property category
+

The category this channel belongs to.

+

If there is no category then this is None.

+
+
Type
+

Optional[CategoryChannel]

+
+
+
+ +
+
+property permissions_synced
+

Whether or not the permissions for this channel are synced with the +category it belongs to.

+

If there is no category then this is False.

+
+

New in version 1.3.

+
+
+
Type
+

bool

+
+
+
+ +
+
+permissions_for(obj, /)
+

Handles permission resolution for the Member +or Role.

+

This function takes into consideration the following cases:

+
    +
  • Guild owner

  • +
  • Guild roles

  • +
  • Channel overrides

  • +
  • Member overrides

  • +
+

If a Role is passed, then it checks the permissions +someone with that role would have, which is essentially:

+
    +
  • The default role permissions

  • +
  • The permissions of the role used as a parameter

  • +
  • The default role permission overwrites

  • +
  • The permission overwrites of the role used as a parameter

  • +
+
+

Changed in version 2.0: The object passed in can now be a role object.

+
+
+
Parameters
+

obj (Union[Member, Role]) – The object to resolve permissions for. This could be either +a member or a role. If it’s a role then member overwrites +are not computed.

+
+
Returns
+

The resolved permissions for the member or role.

+
+
Return type
+

Permissions

+
+
+
+ +
+
+await delete(*, reason=None)
+

This function is a coroutine.

+

Deletes the channel.

+

You must have manage_channels permission to use this.

+
+
Parameters
+

reason (Optional[str]) – The reason for deleting this channel. +Shows up on the audit log.

+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to delete the channel.

  • +
  • NotFound – The channel was not found or was already deleted.

  • +
  • HTTPException – Deleting the channel failed.

  • +
+
+
+
+ +
+
+await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)
+

This function is a coroutine.

+

Sets the channel specific permission overwrites for a target in the +channel.

+

The target parameter should either be a Member or a +Role that belongs to guild.

+

The overwrite parameter, if given, must either be None or +PermissionOverwrite. For convenience, you can pass in +keyword arguments denoting Permissions attributes. If this is +done, then you cannot mix the keyword arguments with the overwrite +parameter.

+

If the overwrite parameter is None, then the permission +overwrites are deleted.

+

You must have the manage_roles permission to use this.

+
+

Note

+

This method replaces the old overwrites with the ones given.

+
+

Examples

+

Setting allow and deny:

+
await message.channel.set_permissions(message.author, read_messages=True,
+                                                      send_messages=False)
+
+
+

Deleting overwrites

+
await channel.set_permissions(member, overwrite=None)
+
+
+

Using PermissionOverwrite

+
overwrite = discord.PermissionOverwrite()
+overwrite.send_messages = False
+overwrite.read_messages = True
+await channel.set_permissions(member, overwrite=overwrite)
+
+
+
+
Parameters
+
    +
  • target (Union[Member, Role]) – The member or role to overwrite permissions for.

  • +
  • overwrite (Optional[PermissionOverwrite]) – The permissions to allow and deny to the target, or None to +delete the overwrite.

  • +
  • **permissions – A keyword argument list of permissions to set for ease of use. +Cannot be mixed with overwrite.

  • +
  • reason (Optional[str]) – The reason for doing this action. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to edit channel specific permissions.

  • +
  • HTTPException – Editing channel specific permissions failed.

  • +
  • NotFound – The role or member being edited is not part of the guild.

  • +
  • InvalidArgument – The overwrite parameter invalid or the target type was not + Role or Member.

  • +
+
+
+
+ +
+
+await clone(*, name=None, reason=None)
+

This function is a coroutine.

+

Clones this channel. This creates a channel with the same properties +as this channel.

+

You must have the manage_channels permission to +do this.

+
+

New in version 1.1.

+
+
+
Parameters
+
    +
  • name (Optional[str]) – The name of the new channel. If not provided, defaults to this +channel name.

  • +
  • reason (Optional[str]) – The reason for cloning this channel. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have the proper permissions to create this channel.

  • +
  • HTTPException – Creating the channel failed.

  • +
+
+
Returns
+

The channel that was created.

+
+
Return type
+

abc.GuildChannel

+
+
+
+ +
+
+await move(**kwargs)
+

This function is a coroutine.

+

A rich interface to help move a channel relative to other channels.

+

If exact position movement is required, edit should be used instead.

+

You must have the manage_channels permission to +do this.

+
+

Note

+

Voice channels will always be sorted below text channels. +This is a Discord limitation.

+
+
+

New in version 1.7.

+
+
+
Parameters
+
    +
  • beginning (bool) – Whether to move the channel to the beginning of the +channel list (or category if given). +This is mutually exclusive with end, before, and after.

  • +
  • end (bool) – Whether to move the channel to the end of the +channel list (or category if given). +This is mutually exclusive with beginning, before, and after.

  • +
  • before (Snowflake) – The channel that should be before our current channel. +This is mutually exclusive with beginning, end, and after.

  • +
  • after (Snowflake) – The channel that should be after our current channel. +This is mutually exclusive with beginning, end, and before.

  • +
  • offset (int) – The number of channels to offset the move by. For example, +an offset of 2 with beginning=True would move +it 2 after the beginning. A positive number moves it below +while a negative number moves it above. Note that this +number is relative and computed after the beginning, +end, before, and after parameters.

  • +
  • category (Optional[Snowflake]) – The category to move this channel under. +If None is given then it moves it out of the category. +This parameter is ignored if moving a category channel.

  • +
  • sync_permissions (bool) – Whether to sync the permissions with the category (if given).

  • +
  • reason (str) – The reason for the move.

  • +
+
+
Raises
+
    +
  • InvalidArgument – An invalid position was given or a bad mix of arguments were passed.

  • +
  • Forbidden – You do not have permissions to move the channel.

  • +
  • HTTPException – Moving the channel failed.

  • +
+
+
+
+ +
+
+await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)
+

This function is a coroutine.

+

Creates an instant invite from a text or voice channel.

+

You must have the create_instant_invite permission to +do this.

+
+
Parameters
+
    +
  • max_age (int) – How long the invite should last in seconds. If it’s 0 then the invite +doesn’t expire. Defaults to 0.

  • +
  • max_uses (int) – How many uses the invite could be used for. If it’s 0 then there +are unlimited uses. Defaults to 0.

  • +
  • temporary (bool) – Denotes that the invite grants temporary membership +(i.e. they get kicked after they disconnect). Defaults to False.

  • +
  • unique (bool) – Indicates if a unique invite URL should be created. Defaults to True. +If this is set to False then it will return a previously created +invite.

  • +
  • reason (Optional[str]) – The reason for creating this invite. Shows up on the audit log.

  • +
  • target_type (Optional[InviteTarget]) –

    The type of target for the voice channel invite, if any.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • target_user (Optional[User]) –

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • target_application_id:

    Optional[int]: The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
    +
  • HTTPException – Invite creation failed.

  • +
  • NotFound – The channel that was passed is a category or an invalid channel.

  • +
+
+
Returns
+

The invite that was created.

+
+
Return type
+

Invite

+
+
+
+ +
+
+await invites()
+

This function is a coroutine.

+

Returns a list of all active instant invites from this channel.

+

You must have manage_channels to get this information.

+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to get the information.

  • +
  • HTTPException – An error occurred while fetching the information.

  • +
+
+
Returns
+

The list of invites that are currently active.

+
+
Return type
+

List[Invite]

+
+
+
+ +
+ +
+
+

Messageable

+
+ +Methods +
+
+class discord.abc.Messageable
+

An ABC that details the common operations on a model that can send messages.

+

The following implement this ABC:

+ +
+
+async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
+

Returns an AsyncIterator that enables receiving the destination’s message history.

+

You must have read_message_history permissions to use this.

+

Examples

+

Usage

+
counter = 0
+async for message in channel.history(limit=200):
+    if message.author == client.user:
+        counter += 1
+
+
+

Flattening into a list:

+
messages = await channel.history(limit=123).flatten()
+# messages is now a list of Message...
+
+
+

All parameters are optional.

+
+
Parameters
+
    +
  • limit (Optional[int]) – The number of messages to retrieve. +If None, retrieves every message in the channel. Note, however, +that this would make it a slow operation.

  • +
  • before (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • after (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • around (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time. +When using this argument, the maximum limit is 101. Note that if the limit is an +even number then this will return at most limit + 1 messages.

  • +
  • oldest_first (Optional[bool]) – If set to True, return messages in oldest->newest order. Defaults to True if +after is specified, otherwise False.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to get channel message history.

  • +
  • HTTPException – The request to get message history failed.

  • +
+
+
Yields
+

Message – The message with the message data parsed.

+
+
+
+ +
+
+async with typing()
+

Returns a context manager that allows you to type for an indefinite period of time.

+

This is useful for denoting long computations in your bot.

+
+

Note

+

This is both a regular context manager and an async context manager. +This means that both with and async with work with this.

+
+

Example Usage:

+
async with channel.typing():
+    # simulate something heavy
+    await asyncio.sleep(10)
+
+await channel.send('done!')
+
+
+
+ +
+
+await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)
+

This function is a coroutine.

+

Sends a message to the destination with the content given.

+

The content must be a type that can convert to a string through str(content). +If the content is set to None (the default), then the embed parameter must +be provided.

+

To upload a single file, the file parameter should be used with a +single File object. To upload multiple files, the files +parameter should be used with a list of File objects. +Specifying both parameters will lead to an exception.

+

To upload a single embed, the embed parameter should be used with a +single Embed object. To upload multiple embeds, the embeds +parameter should be used with a list of Embed objects. +Specifying both parameters will lead to an exception.

+
+
Parameters
+
    +
  • content (Optional[str]) – The content of the message to send.

  • +
  • tts (bool) – Indicates if the message should be sent using text-to-speech.

  • +
  • embed (Embed) – The rich embed for the content.

  • +
  • file (File) – The file to upload.

  • +
  • files (List[File]) – A list of files to upload. Must be a maximum of 10.

  • +
  • nonce (int) – The nonce to use for sending this message. If the message was successfully sent, +then the message will have a nonce with this value.

  • +
  • delete_after (float) – If provided, the number of seconds to wait in the background +before deleting the message we just sent. If the deletion fails, +then it is silently ignored.

  • +
  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is +passed, then the object is merged with allowed_mentions. +The merging behaviour only overrides attributes that have been explicitly passed +to the object, otherwise it uses the attributes set in allowed_mentions. +If no object is passed at all then the defaults given by allowed_mentions +are used instead.

    +
    +

    New in version 1.4.

    +
    +

  • +
  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using +to_reference() or passed directly as a Message. You can control +whether this mentions the author of the referenced message using the replied_user +attribute of allowed_mentions or by setting mention_author.

    +
    +

    New in version 1.6.

    +
    +

  • +
  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    +
    +

    New in version 1.6.

    +
    +

  • +
  • view (discord.ui.View) – A Discord UI View to add to the message.

  • +
  • embeds (List[Embed]) –

    A list of embeds to upload. Must be a maximum of 10.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
+
+
Returns
+

The message that was sent.

+
+
Return type
+

Message

+
+
+
+ +
+
+await trigger_typing()
+

This function is a coroutine.

+

Triggers a typing indicator to the destination.

+

Typing indicator will go away after 10 seconds, or after a message is sent.

+
+ +
+
+await fetch_message(id, /)
+

This function is a coroutine.

+

Retrieves a single Message from the destination.

+
+
Parameters
+

id (int) – The message ID to look for.

+
+
Raises
+
    +
  • NotFound – The specified message was not found.

  • +
  • Forbidden – You do not have the permissions required to get a message.

  • +
  • HTTPException – Retrieving the message failed.

  • +
+
+
Returns
+

The message asked for.

+
+
Return type
+

Message

+
+
+
+ +
+
+await pins()
+

This function is a coroutine.

+

Retrieves all messages that are currently pinned in the channel.

+
+

Note

+

Due to a limitation with the Discord API, the Message +objects returned by this method do not contain complete +Message.reactions data.

+
+
+
Raises
+

HTTPException – Retrieving the pinned messages failed.

+
+
Returns
+

The messages that are currently pinned.

+
+
Return type
+

List[Message]

+
+
+
+ +
+ +
+
+

Connectable

+
+
+class discord.abc.Connectable
+

An ABC that details the common operations on a channel that can +connect to a voice server.

+

The following implement this ABC:

+ +
+

Note

+

This ABC is not decorated with typing.runtime_checkable(), so will fail isinstance()/issubclass() +checks.

+
+
+ +
+
+
+

Discord Models

+

Models are classes that are received from Discord and are not meant to be created by +the user of the library.

+
+

Danger

+

The classes listed below are not intended to be created by users and are also +read-only.

+

For example, this means that you should not make your own User instances +nor should you modify the User instance yourself.

+

If you want to get one of these model classes instances they’d have to be through +the cache, and a common way of doing so is through the utils.find() function +or attributes of model classes that you receive from the events specified in the +Event Reference.

+
+
+

Note

+

Nearly all classes here have __slots__ defined which means that it is +impossible to have dynamic attributes to the data classes.

+
+
+

ClientUser

+
+
+class discord.ClientUser
+

Represents your Discord user.

+
+
+
+x == y
+

Checks if two users are equal.

+
+ +
+
+x != y
+

Checks if two users are not equal.

+
+ +
+
+hash(x)
+

Return the user’s hash.

+
+ +
+
+str(x)
+

Returns the user’s name with discriminator.

+
+ +
+
+
+name
+

The user’s username.

+
+
Type
+

str

+
+
+
+ +
+
+id
+

The user’s unique ID.

+
+
Type
+

int

+
+
+
+ +
+
+discriminator
+

The user’s discriminator. This is given when the username has conflicts.

+
+
Type
+

str

+
+
+
+ +
+
+bot
+

Specifies if the user is a bot account.

+
+
Type
+

bool

+
+
+
+ +
+
+system
+

Specifies if the user is a system user (i.e. represents Discord officially).

+
+

New in version 1.3.

+
+
+
Type
+

bool

+
+
+
+ +
+
+verified
+

Specifies if the user’s email is verified.

+
+
Type
+

bool

+
+
+
+ +
+
+locale
+

The IETF language tag used to identify the language the user is using.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+mfa_enabled
+

Specifies if the user has MFA turned on and working.

+
+
Type
+

bool

+
+
+
+ +
+
+await edit(*, username=..., avatar=...)
+

This function is a coroutine.

+

Edits the current profile of the client.

+
+

Note

+

To upload an avatar, a bytes-like object must be passed in that +represents the image being uploaded. If this is done through a file +then the file must be opened via open('some_filename', 'rb') and +the bytes-like object is given through the use of fp.read().

+

The only image formats supported for uploading is JPEG and PNG.

+
+
+

Changed in version 2.0: The edit is no longer in-place, instead the newly edited client user is returned.

+
+
+
Parameters
+
    +
  • username (str) – The new username you wish to change to.

  • +
  • avatar (bytes) – A bytes-like object representing the image to upload. +Could be None to denote no avatar.

  • +
+
+
Raises
+
+
+
Returns
+

The newly edited client user.

+
+
Return type
+

ClientUser

+
+
+
+ +
+
+property accent_color
+

Returns the user’s accent color, if applicable.

+

There is an alias for this named accent_colour.

+
+

New in version 2.0.

+
+
+

Note

+

This information is only available via Client.fetch_user().

+
+
+
Type
+

Optional[Colour]

+
+
+
+ +
+
+property accent_colour
+

Returns the user’s accent colour, if applicable.

+

There is an alias for this named accent_color.

+
+

New in version 2.0.

+
+
+

Note

+

This information is only available via Client.fetch_user().

+
+
+
Type
+

Optional[Colour]

+
+
+
+ +
+
+property avatar
+

Returns an Asset for the avatar the user has.

+

If the user does not have a traditional avatar, None is returned. +If you want the avatar that a user has displayed, consider display_avatar.

+
+
Type
+

Optional[Asset]

+
+
+
+ +
+
+property banner
+

Returns the user’s banner asset, if available.

+
+

New in version 2.0.

+
+
+

Note

+

This information is only available via Client.fetch_user().

+
+
+
Type
+

Optional[Asset]

+
+
+
+ +
+
+property color
+

A property that returns a color denoting the rendered color +for the user. This always returns Colour.default().

+

There is an alias for this named colour.

+
+
Type
+

Colour

+
+
+
+ +
+
+property colour
+

A property that returns a colour denoting the rendered colour +for the user. This always returns Colour.default().

+

There is an alias for this named color.

+
+
Type
+

Colour

+
+
+
+ +
+
+property created_at
+

Returns the user’s creation time in UTC.

+

This is when the user’s Discord account was created.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+property default_avatar
+

Returns the default avatar for a given user. This is calculated by the user’s discriminator.

+
+
Type
+

Asset

+
+
+
+ +
+
+property display_avatar
+

Returns the user’s display avatar.

+

For regular users this is just their default avatar or uploaded avatar.

+
+

New in version 2.0.

+
+
+
Type
+

Asset

+
+
+
+ +
+
+property display_name
+

Returns the user’s display name.

+

For regular users this is just their username, but +if they have a guild specific nickname then that +is returned instead.

+
+
Type
+

str

+
+
+
+ +
+
+property mention
+

Returns a string that allows you to mention the given user.

+
+
Type
+

str

+
+
+
+ +
+
+mentioned_in(message)
+

Checks if the user is mentioned in the specified message.

+
+
Parameters
+

message (Message) – The message to check if you’re mentioned in.

+
+
Returns
+

Indicates if the user is mentioned in the message.

+
+
Return type
+

bool

+
+
+
+ +
+
+property public_flags
+

The publicly available flags the user has.

+
+
Type
+

PublicUserFlags

+
+
+
+ +
+ +
+
+

User

+
+
+class discord.User
+

Represents a Discord user.

+
+
+
+x == y
+

Checks if two users are equal.

+
+ +
+
+x != y
+

Checks if two users are not equal.

+
+ +
+
+hash(x)
+

Return the user’s hash.

+
+ +
+
+str(x)
+

Returns the user’s name with discriminator.

+
+ +
+
+int(x)
+

Returns the user’s ID.

+
+ +
+
+
+name
+

The user’s username.

+
+
Type
+

str

+
+
+
+ +
+
+id
+

The user’s unique ID.

+
+
Type
+

int

+
+
+
+ +
+
+discriminator
+

The user’s discriminator. This is given when the username has conflicts.

+
+
Type
+

str

+
+
+
+ +
+
+bot
+

Specifies if the user is a bot account.

+
+
Type
+

bool

+
+
+
+ +
+
+system
+

Specifies if the user is a system user (i.e. represents Discord officially).

+
+
Type
+

bool

+
+
+
+ +
+
+async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
+

Returns an AsyncIterator that enables receiving the destination’s message history.

+

You must have read_message_history permissions to use this.

+

Examples

+

Usage

+
counter = 0
+async for message in channel.history(limit=200):
+    if message.author == client.user:
+        counter += 1
+
+
+

Flattening into a list:

+
messages = await channel.history(limit=123).flatten()
+# messages is now a list of Message...
+
+
+

All parameters are optional.

+
+
Parameters
+
    +
  • limit (Optional[int]) – The number of messages to retrieve. +If None, retrieves every message in the channel. Note, however, +that this would make it a slow operation.

  • +
  • before (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • after (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • around (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time. +When using this argument, the maximum limit is 101. Note that if the limit is an +even number then this will return at most limit + 1 messages.

  • +
  • oldest_first (Optional[bool]) – If set to True, return messages in oldest->newest order. Defaults to True if +after is specified, otherwise False.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to get channel message history.

  • +
  • HTTPException – The request to get message history failed.

  • +
+
+
Yields
+

Message – The message with the message data parsed.

+
+
+
+ +
+
+async with typing()
+

Returns a context manager that allows you to type for an indefinite period of time.

+

This is useful for denoting long computations in your bot.

+
+

Note

+

This is both a regular context manager and an async context manager. +This means that both with and async with work with this.

+
+

Example Usage:

+
async with channel.typing():
+    # simulate something heavy
+    await asyncio.sleep(10)
+
+await channel.send('done!')
+
+
+
+ +
+
+property dm_channel
+

Returns the channel associated with this user if it exists.

+

If this returns None, you can create a DM channel by calling the +create_dm() coroutine function.

+
+
Type
+

Optional[DMChannel]

+
+
+
+ +
+
+property mutual_guilds
+

The guilds that the user shares with the client.

+
+

Note

+

This will only return mutual guilds within the client’s internal cache.

+
+
+

New in version 1.7.

+
+
+
Type
+

List[Guild]

+
+
+
+ +
+
+property accent_color
+

Returns the user’s accent color, if applicable.

+

There is an alias for this named accent_colour.

+
+

New in version 2.0.

+
+
+

Note

+

This information is only available via Client.fetch_user().

+
+
+
Type
+

Optional[Colour]

+
+
+
+ +
+
+property accent_colour
+

Returns the user’s accent colour, if applicable.

+

There is an alias for this named accent_color.

+
+

New in version 2.0.

+
+
+

Note

+

This information is only available via Client.fetch_user().

+
+
+
Type
+

Optional[Colour]

+
+
+
+ +
+
+property avatar
+

Returns an Asset for the avatar the user has.

+

If the user does not have a traditional avatar, None is returned. +If you want the avatar that a user has displayed, consider display_avatar.

+
+
Type
+

Optional[Asset]

+
+
+
+ +
+
+property banner
+

Returns the user’s banner asset, if available.

+
+

New in version 2.0.

+
+
+

Note

+

This information is only available via Client.fetch_user().

+
+
+
Type
+

Optional[Asset]

+
+
+
+ +
+
+property color
+

A property that returns a color denoting the rendered color +for the user. This always returns Colour.default().

+

There is an alias for this named colour.

+
+
Type
+

Colour

+
+
+
+ +
+
+property colour
+

A property that returns a colour denoting the rendered colour +for the user. This always returns Colour.default().

+

There is an alias for this named color.

+
+
Type
+

Colour

+
+
+
+ +
+
+await create_dm()
+

This function is a coroutine.

+

Creates a DMChannel with this user.

+

This should be rarely called, as this is done transparently for most +people.

+
+
Returns
+

The channel that was created.

+
+
Return type
+

DMChannel

+
+
+
+ +
+
+property created_at
+

Returns the user’s creation time in UTC.

+

This is when the user’s Discord account was created.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+property default_avatar
+

Returns the default avatar for a given user. This is calculated by the user’s discriminator.

+
+
Type
+

Asset

+
+
+
+ +
+
+property display_avatar
+

Returns the user’s display avatar.

+

For regular users this is just their default avatar or uploaded avatar.

+
+

New in version 2.0.

+
+
+
Type
+

Asset

+
+
+
+ +
+
+property display_name
+

Returns the user’s display name.

+

For regular users this is just their username, but +if they have a guild specific nickname then that +is returned instead.

+
+
Type
+

str

+
+
+
+ +
+
+await fetch_message(id, /)
+

This function is a coroutine.

+

Retrieves a single Message from the destination.

+
+
Parameters
+

id (int) – The message ID to look for.

+
+
Raises
+
    +
  • NotFound – The specified message was not found.

  • +
  • Forbidden – You do not have the permissions required to get a message.

  • +
  • HTTPException – Retrieving the message failed.

  • +
+
+
Returns
+

The message asked for.

+
+
Return type
+

Message

+
+
+
+ +
+
+property mention
+

Returns a string that allows you to mention the given user.

+
+
Type
+

str

+
+
+
+ +
+
+mentioned_in(message)
+

Checks if the user is mentioned in the specified message.

+
+
Parameters
+

message (Message) – The message to check if you’re mentioned in.

+
+
Returns
+

Indicates if the user is mentioned in the message.

+
+
Return type
+

bool

+
+
+
+ +
+
+await pins()
+

This function is a coroutine.

+

Retrieves all messages that are currently pinned in the channel.

+
+

Note

+

Due to a limitation with the Discord API, the Message +objects returned by this method do not contain complete +Message.reactions data.

+
+
+
Raises
+

HTTPException – Retrieving the pinned messages failed.

+
+
Returns
+

The messages that are currently pinned.

+
+
Return type
+

List[Message]

+
+
+
+ +
+
+property public_flags
+

The publicly available flags the user has.

+
+
Type
+

PublicUserFlags

+
+
+
+ +
+
+await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)
+

This function is a coroutine.

+

Sends a message to the destination with the content given.

+

The content must be a type that can convert to a string through str(content). +If the content is set to None (the default), then the embed parameter must +be provided.

+

To upload a single file, the file parameter should be used with a +single File object. To upload multiple files, the files +parameter should be used with a list of File objects. +Specifying both parameters will lead to an exception.

+

To upload a single embed, the embed parameter should be used with a +single Embed object. To upload multiple embeds, the embeds +parameter should be used with a list of Embed objects. +Specifying both parameters will lead to an exception.

+
+
Parameters
+
    +
  • content (Optional[str]) – The content of the message to send.

  • +
  • tts (bool) – Indicates if the message should be sent using text-to-speech.

  • +
  • embed (Embed) – The rich embed for the content.

  • +
  • file (File) – The file to upload.

  • +
  • files (List[File]) – A list of files to upload. Must be a maximum of 10.

  • +
  • nonce (int) – The nonce to use for sending this message. If the message was successfully sent, +then the message will have a nonce with this value.

  • +
  • delete_after (float) – If provided, the number of seconds to wait in the background +before deleting the message we just sent. If the deletion fails, +then it is silently ignored.

  • +
  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is +passed, then the object is merged with allowed_mentions. +The merging behaviour only overrides attributes that have been explicitly passed +to the object, otherwise it uses the attributes set in allowed_mentions. +If no object is passed at all then the defaults given by allowed_mentions +are used instead.

    +
    +

    New in version 1.4.

    +
    +

  • +
  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using +to_reference() or passed directly as a Message. You can control +whether this mentions the author of the referenced message using the replied_user +attribute of allowed_mentions or by setting mention_author.

    +
    +

    New in version 1.6.

    +
    +

  • +
  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    +
    +

    New in version 1.6.

    +
    +

  • +
  • view (discord.ui.View) – A Discord UI View to add to the message.

  • +
  • embeds (List[Embed]) –

    A list of embeds to upload. Must be a maximum of 10.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
+
+
Returns
+

The message that was sent.

+
+
Return type
+

Message

+
+
+
+ +
+
+await trigger_typing()
+

This function is a coroutine.

+

Triggers a typing indicator to the destination.

+

Typing indicator will go away after 10 seconds, or after a message is sent.

+
+ +
+ +
+
+

Attachment

+
+ +Methods +
+
+class discord.Attachment
+

Represents an attachment from Discord.

+
+
+
+str(x)
+

Returns the URL of the attachment.

+
+ +
+
+x == y
+

Checks if the attachment is equal to another attachment.

+
+ +
+
+x != y
+

Checks if the attachment is not equal to another attachment.

+
+ +
+
+hash(x)
+

Returns the hash of the attachment.

+
+ +
+
+int(x)
+

Returns the attachment’s ID.

+
+ +
+
+

Changed in version 1.7: Attachment can now be casted to str and is hashable.

+
+
+
+id
+

The attachment ID.

+
+
Type
+

int

+
+
+
+ +
+
+size
+

The attachment size in bytes.

+
+
Type
+

int

+
+
+
+ +
+
+height
+

The attachment’s height, in pixels. Only applicable to images and videos.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+width
+

The attachment’s width, in pixels. Only applicable to images and videos.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+filename
+

The attachment’s filename.

+
+
Type
+

str

+
+
+
+ +
+
+url
+

The attachment URL. If the message this attachment was attached +to is deleted, then this will 404.

+
+
Type
+

str

+
+
+
+ +
+
+proxy_url
+

The proxy URL. This is a cached version of the url in the +case of images. When the message is deleted, this URL might be valid for a few +minutes or not valid at all.

+
+
Type
+

str

+
+
+
+ +
+
+content_type
+

The attachment’s media type

+
+

New in version 1.7.

+
+
+
Type
+

Optional[str]

+
+
+
+ +
+
+ephemeral
+

If the attachment is ephemeral. Ephemeral attachments are temporary and +will automatically be removed after a set period of time.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[bool]

+
+
+
+ +
+
+is_spoiler()
+

bool: Whether this attachment contains a spoiler.

+
+ +
+
+await save(fp, *, seek_begin=True, use_cached=False)
+

This function is a coroutine.

+

Saves this attachment into a file-like object.

+
+
Parameters
+
    +
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this attachment to or the filename +to use. If a filename is passed then a file is created with that +filename and used instead.

  • +
  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is +successfully done.

  • +
  • use_cached (bool) – Whether to use proxy_url rather than url when downloading +the attachment. This will allow attachments to be saved after deletion +more often, compared to the regular URL which is generally deleted right +after the message is deleted. Note that this can still fail to download +deleted attachments if too much time has passed and it does not work +on some types of attachments.

  • +
+
+
Raises
+
+
+
Returns
+

The number of bytes written.

+
+
Return type
+

int

+
+
+
+ +
+
+await read(*, use_cached=False)
+

This function is a coroutine.

+

Retrieves the content of this attachment as a bytes object.

+
+

New in version 1.1.

+
+
+
Parameters
+

use_cached (bool) – Whether to use proxy_url rather than url when downloading +the attachment. This will allow attachments to be saved after deletion +more often, compared to the regular URL which is generally deleted right +after the message is deleted. Note that this can still fail to download +deleted attachments if too much time has passed and it does not work +on some types of attachments.

+
+
Raises
+
    +
  • HTTPException – Downloading the attachment failed.

  • +
  • Forbidden – You do not have permissions to access this attachment

  • +
  • NotFound – The attachment was deleted.

  • +
+
+
Returns
+

The contents of the attachment.

+
+
Return type
+

bytes

+
+
+
+ +
+
+await to_file(*, use_cached=False, spoiler=False)
+

This function is a coroutine.

+

Converts the attachment into a File suitable for sending via +abc.Messageable.send().

+
+

New in version 1.3.

+
+
+
Parameters
+
    +
  • use_cached (bool) –

    Whether to use proxy_url rather than url when downloading +the attachment. This will allow attachments to be saved after deletion +more often, compared to the regular URL which is generally deleted right +after the message is deleted. Note that this can still fail to download +deleted attachments if too much time has passed and it does not work +on some types of attachments.

    +
    +

    New in version 1.4.

    +
    +

  • +
  • spoiler (bool) –

    Whether the file is a spoiler.

    +
    +

    New in version 1.4.

    +
    +

  • +
+
+
Raises
+
    +
  • HTTPException – Downloading the attachment failed.

  • +
  • Forbidden – You do not have permissions to access this attachment

  • +
  • NotFound – The attachment was deleted.

  • +
+
+
Returns
+

The attachment as a file suitable for sending.

+
+
Return type
+

File

+
+
+
+ +
+ +
+
+

Asset

+
+ +Attributes +
+ +Methods +
+
+class discord.Asset
+

Represents a CDN asset on Discord.

+
+
+
+str(x)
+

Returns the URL of the CDN asset.

+
+ +
+
+len(x)
+

Returns the length of the CDN asset’s URL.

+
+ +
+
+x == y
+

Checks if the asset is equal to another asset.

+
+ +
+
+x != y
+

Checks if the asset is not equal to another asset.

+
+ +
+
+hash(x)
+

Returns the hash of the asset.

+
+ +
+
+
+property url
+

Returns the underlying URL of the asset.

+
+
Type
+

str

+
+
+
+ +
+
+property key
+

Returns the identifying key of the asset.

+
+
Type
+

str

+
+
+
+ +
+
+is_animated()
+

bool: Returns whether the asset is animated.

+
+ +
+
+replace(*, size=..., format=..., static_format=...)
+

Returns a new asset with the passed components replaced.

+
+
Parameters
+
    +
  • size (int) – The new size of the asset.

  • +
  • format (str) – The new format to change it to. Must be either +‘webp’, ‘jpeg’, ‘jpg’, ‘png’, or ‘gif’ if it’s animated.

  • +
  • static_format (str) – The new format to change it to if the asset isn’t animated. +Must be either ‘webp’, ‘jpeg’, ‘jpg’, or ‘png’.

  • +
+
+
Raises
+

InvalidArgument – An invalid size or format was passed.

+
+
Returns
+

The newly updated asset.

+
+
Return type
+

Asset

+
+
+
+ +
+
+with_size(size, /)
+

Returns a new asset with the specified size.

+
+
Parameters
+

size (int) – The new size of the asset.

+
+
Raises
+

InvalidArgument – The asset had an invalid size.

+
+
Returns
+

The new updated asset.

+
+
Return type
+

Asset

+
+
+
+ +
+
+with_format(format, /)
+

Returns a new asset with the specified format.

+
+
Parameters
+

format (str) – The new format of the asset.

+
+
Raises
+

InvalidArgument – The asset had an invalid format.

+
+
Returns
+

The new updated asset.

+
+
Return type
+

Asset

+
+
+
+ +
+
+with_static_format(format, /)
+

Returns a new asset with the specified static format.

+

This only changes the format if the underlying asset is +not animated. Otherwise, the asset is not changed.

+
+
Parameters
+

format (str) – The new static format of the asset.

+
+
Raises
+

InvalidArgument – The asset had an invalid format.

+
+
Returns
+

The new updated asset.

+
+
Return type
+

Asset

+
+
+
+ +
+
+await read()
+

This function is a coroutine.

+

Retrieves the content of this asset as a bytes object.

+
+
Raises
+
+
+
Returns
+

The content of the asset.

+
+
Return type
+

bytes

+
+
+
+ +
+
+await save(fp, *, seek_begin=True)
+

This function is a coroutine.

+

Saves this asset into a file-like object.

+
+
Parameters
+
    +
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this attachment to or the filename +to use. If a filename is passed then a file is created with that +filename and used instead.

  • +
  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is +successfully done.

  • +
+
+
Raises
+
+
+
Returns
+

The number of bytes written.

+
+
Return type
+

int

+
+
+
+ +
+ +
+
+

Message

+
+
+class discord.Message
+

Represents a message from Discord.

+
+
+
+x == y
+

Checks if two messages are equal.

+
+ +
+
+x != y
+

Checks if two messages are not equal.

+
+ +
+
+hash(x)
+

Returns the message’s hash.

+
+ +
+
+str(x)
+

Returns the message’s content.

+
+ +
+
+int(x)
+

Returns the message’s ID.

+
+ +
+
+
+tts
+

Specifies if the message was done with text-to-speech. +This can only be accurately received in on_message() due to +a discord limitation.

+
+
Type
+

bool

+
+
+
+ +
+
+type
+

The type of message. In most cases this should not be checked, but it is helpful +in cases where it might be a system message for system_content.

+
+
Type
+

MessageType

+
+
+
+ +
+
+author
+

A Member that sent the message. If channel is a +private channel or the user has the left the guild, then it is a User instead.

+
+
Type
+

Union[Member, abc.User]

+
+
+
+ +
+
+content
+

The actual contents of the message.

+
+
Type
+

str

+
+
+
+ +
+
+nonce
+

The value used by the discord guild and the client to verify that the message is successfully sent. +This is not stored long term within Discord’s servers and is only used ephemerally.

+
+
Type
+

Optional[Union[str, int]]

+
+
+
+ +
+
+embeds
+

A list of embeds the message has.

+
+
Type
+

List[Embed]

+
+
+
+ +
+
+channel
+

The TextChannel or Thread that the message was sent from. +Could be a DMChannel or GroupChannel if it’s a private message.

+
+
Type
+

Union[TextChannel, Thread, DMChannel, GroupChannel, PartialMessageable]

+
+
+
+ +
+
+reference
+

The message that this message references. This is only applicable to messages of +type MessageType.pins_add, crossposted messages created by a +followed channel integration, or message replies.

+
+

New in version 1.5.

+
+
+
Type
+

Optional[MessageReference]

+
+
+
+ +
+
+mention_everyone
+

Specifies if the message mentions everyone.

+
+

Note

+

This does not check if the @everyone or the @here text is in the message itself. +Rather this boolean indicates if either the @everyone or the @here text is in the message +and it did end up mentioning.

+
+
+
Type
+

bool

+
+
+
+ +
+
+mentions
+

A list of Member that were mentioned. If the message is in a private message +then the list will be of User instead. For messages that are not of type +MessageType.default, this array can be used to aid in system messages. +For more information, see system_content.

+
+

Warning

+

The order of the mentions list is not in any particular order so you should +not rely on it. This is a Discord limitation, not one with the library.

+
+
+
Type
+

List[abc.User]

+
+
+
+ +
+
+channel_mentions
+

A list of abc.GuildChannel that were mentioned. If the message is in a private message +then the list is always empty.

+
+
Type
+

List[abc.GuildChannel]

+
+
+
+ +
+
+role_mentions
+

A list of Role that were mentioned. If the message is in a private message +then the list is always empty.

+
+
Type
+

List[Role]

+
+
+
+ +
+
+id
+

The message ID.

+
+
Type
+

int

+
+
+
+ +
+
+webhook_id
+

If this message was sent by a webhook, then this is the webhook ID’s that sent this +message.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+attachments
+

A list of attachments given to a message.

+
+
Type
+

List[Attachment]

+
+
+
+ +
+
+pinned
+

Specifies if the message is currently pinned.

+
+
Type
+

bool

+
+
+
+ +
+
+flags
+

Extra features of the message.

+
+

New in version 1.3.

+
+
+
Type
+

MessageFlags

+
+
+
+ +
+
+reactions
+

Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.

+
+
Type
+

List[Reaction]

+
+
+
+ +
+
+activity
+

The activity associated with this message. Sent with Rich-Presence related messages that for +example, request joining, spectating, or listening to or with another member.

+

It is a dictionary with the following optional keys:

+
    +
  • type: An integer denoting the type of message activity being requested.

  • +
  • party_id: The party ID associated with the party.

  • +
+
+
Type
+

Optional[dict]

+
+
+
+ +
+
+application
+

The rich presence enabled application associated with this message.

+

It is a dictionary with the following keys:

+
    +
  • id: A string representing the application’s ID.

  • +
  • name: A string representing the application’s name.

  • +
  • description: A string representing the application’s description.

  • +
  • icon: A string representing the icon ID of the application.

  • +
  • cover_image: A string representing the embed’s image asset ID.

  • +
+
+
Type
+

Optional[dict]

+
+
+
+ +
+
+stickers
+

A list of sticker items given to the message.

+
+

New in version 1.6.

+
+
+
Type
+

List[StickerItem]

+
+
+
+ +
+
+components
+

A list of components in the message.

+
+

New in version 2.0.

+
+
+
Type
+

List[Component]

+
+
+
+ +
+
+guild
+

The guild that the message belongs to, if applicable.

+
+
Type
+

Optional[Guild]

+
+
+
+ +
+
+raw_mentions
+

A property that returns an array of user IDs matched with +the syntax of <@user_id> in the message content.

+

This allows you to receive the user IDs of mentioned users +even in a private message context.

+
+
Type
+

List[int]

+
+
+
+ +
+
+raw_channel_mentions
+

A property that returns an array of channel IDs matched with +the syntax of <#channel_id> in the message content.

+
+
Type
+

List[int]

+
+
+
+ +
+
+raw_role_mentions
+

A property that returns an array of role IDs matched with +the syntax of <@&role_id> in the message content.

+
+
Type
+

List[int]

+
+
+
+ +
+
+clean_content
+

A property that returns the content in a “cleaned up” +manner. This basically means that mentions are transformed +into the way the client shows it. e.g. <#id> will transform +into #name.

+

This will also transform @everyone and @here mentions into +non-mentions.

+
+

Note

+

This does not affect markdown. If you want to escape +or remove markdown then use utils.escape_markdown() or utils.remove_markdown() +respectively, along with this function.

+
+
+
Type
+

str

+
+
+
+ +
+
+property created_at
+

The message’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+property edited_at
+

An aware UTC datetime object containing the edited time of the message.

+
+
Type
+

Optional[datetime.datetime]

+
+
+
+ +
+
+property jump_url
+

Returns a URL that allows the client to jump to this message.

+
+
Type
+

str

+
+
+
+ +
+
+is_system()
+

bool: Whether the message is a system message.

+

A system message is a message that is constructed entirely by the Discord API +in response to something.

+
+

New in version 1.3.

+
+
+ +
+
+system_content
+

A property that returns the content that is rendered +regardless of the Message.type.

+

In the case of MessageType.default and MessageType.reply, +this just returns the regular Message.content. Otherwise this +returns an English message denoting the contents of the system message.

+
+
Type
+

str

+
+
+
+ +
+
+await delete(*, delay=None, silent=False)
+

This function is a coroutine.

+

Deletes the message.

+

Your own messages could be deleted without any proper permissions. However to +delete other people’s messages, you need the manage_messages +permission.

+
+

Changed in version 1.1: Added the new delay keyword-only parameter.

+
+
+

Changed in version 2.0: Added the new silent keyword-only parameter.

+
+
+
Parameters
+
    +
  • delay (Optional[float]) – If provided, the number of seconds to wait in the background +before deleting the message. If the deletion fails then it is silently ignored.

  • +
  • silent (bool) – If silent is set to True, the error will not be raised, it will be ignored. +This defaults to False

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to delete the message.

  • +
  • NotFound – The message was deleted already

  • +
  • HTTPException – Deleting the message failed.

  • +
+
+
+
+ +
+
+await edit(content=..., embed=..., embeds=..., attachments=..., suppress=..., delete_after=None, allowed_mentions=..., view=...)
+

This function is a coroutine.

+

Edits the message.

+

The content must be able to be transformed into a string via str(content).

+
+

Changed in version 1.3: The suppress keyword-only parameter was added.

+
+
+
Parameters
+
    +
  • content (Optional[str]) – The new content to replace the message with. +Could be None to remove the content.

  • +
  • embed (Optional[Embed]) – The new embed to replace the original with. +Could be None to remove the embed.

  • +
  • embeds (List[Embed]) –

    The new embeds to replace the original with. Must be a maximum of 10. +To remove all embeds [] should be passed.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • attachments (List[Attachment]) – A list of attachments to keep in the message. If [] is passed +then all attachments are removed.

  • +
  • suppress (bool) – Whether to suppress embeds for the message. This removes +all the embeds if set to True. If set to False +this brings the embeds back if they were suppressed. +Using this parameter requires manage_messages.

  • +
  • delete_after (Optional[float]) – If provided, the number of seconds to wait in the background +before deleting the message we just edited. If the deletion fails, +then it is silently ignored.

  • +
  • allowed_mentions (Optional[AllowedMentions]) –

    Controls the mentions being processed in this message. If this is +passed, then the object is merged with allowed_mentions. +The merging behaviour only overrides attributes that have been explicitly passed +to the object, otherwise it uses the attributes set in allowed_mentions. +If no object is passed at all then the defaults given by allowed_mentions +are used instead.

    +
    +

    New in version 1.4.

    +
    +

  • +
  • view (Optional[View]) – The updated view to update this message with. If None is passed then +the view is removed.

  • +
+
+
Raises
+
    +
  • HTTPException – Editing the message failed.

  • +
  • Forbidden – Tried to suppress a message without permissions or + edited a message’s content or embed that isn’t yours.

  • +
  • InvalidArgument – You specified both embed and embeds

  • +
+
+
+
+ +
+
+await publish()
+

This function is a coroutine.

+

Publishes this message to your announcement channel.

+

You must have the send_messages permission to do this.

+

If the message is not your own then the manage_messages +permission is also needed.

+
+
Raises
+
    +
  • Forbidden – You do not have the proper permissions to publish this message.

  • +
  • HTTPException – Publishing the message failed.

  • +
+
+
+
+ +
+
+await pin(*, reason=None)
+

This function is a coroutine.

+

Pins the message.

+

You must have the manage_messages permission to do +this in a non-private channel context.

+
+
Parameters
+

reason (Optional[str]) –

The reason for pinning the message. Shows up on the audit log.

+
+

New in version 1.4.

+
+

+
+
Raises
+
    +
  • Forbidden – You do not have permissions to pin the message.

  • +
  • NotFound – The message or channel was not found or deleted.

  • +
  • HTTPException – Pinning the message failed, probably due to the channel + having more than 50 pinned messages.

  • +
+
+
+
+ +
+
+await unpin(*, reason=None)
+

This function is a coroutine.

+

Unpins the message.

+

You must have the manage_messages permission to do +this in a non-private channel context.

+
+
Parameters
+

reason (Optional[str]) –

The reason for unpinning the message. Shows up on the audit log.

+
+

New in version 1.4.

+
+

+
+
Raises
+
    +
  • Forbidden – You do not have permissions to unpin the message.

  • +
  • NotFound – The message or channel was not found or deleted.

  • +
  • HTTPException – Unpinning the message failed.

  • +
+
+
+
+ +
+
+await add_reaction(emoji)
+

This function is a coroutine.

+

Add a reaction to the message.

+

The emoji may be a unicode emoji or a custom guild Emoji.

+

You must have the read_message_history permission +to use this. If nobody else has reacted to the message using this +emoji, the add_reactions permission is required.

+
+
Parameters
+

emoji (Union[Emoji, Reaction, PartialEmoji, str]) – The emoji to react with.

+
+
Raises
+
    +
  • HTTPException – Adding the reaction failed.

  • +
  • Forbidden – You do not have the proper permissions to react to the message.

  • +
  • NotFound – The emoji you specified was not found.

  • +
  • InvalidArgument – The emoji parameter is invalid.

  • +
+
+
+
+ +
+
+await remove_reaction(emoji, member)
+

This function is a coroutine.

+

Remove a reaction by the member from the message.

+

The emoji may be a unicode emoji or a custom guild Emoji.

+

If the reaction is not your own (i.e. member parameter is not you) then +the manage_messages permission is needed.

+

The member parameter must represent a member and meet +the abc.Snowflake abc.

+
+
Parameters
+
+
+
Raises
+
    +
  • HTTPException – Removing the reaction failed.

  • +
  • Forbidden – You do not have the proper permissions to remove the reaction.

  • +
  • NotFound – The member or emoji you specified was not found.

  • +
  • InvalidArgument – The emoji parameter is invalid.

  • +
+
+
+
+ +
+
+await clear_reaction(emoji)
+

This function is a coroutine.

+

Clears a specific reaction from the message.

+

The emoji may be a unicode emoji or a custom guild Emoji.

+

You need the manage_messages permission to use this.

+
+

New in version 1.3.

+
+
+
Parameters
+

emoji (Union[Emoji, Reaction, PartialEmoji, str]) – The emoji to clear.

+
+
Raises
+
    +
  • HTTPException – Clearing the reaction failed.

  • +
  • Forbidden – You do not have the proper permissions to clear the reaction.

  • +
  • NotFound – The emoji you specified was not found.

  • +
  • InvalidArgument – The emoji parameter is invalid.

  • +
+
+
+
+ +
+
+await clear_reactions()
+

This function is a coroutine.

+

Removes all the reactions from the message.

+

You need the manage_messages permission to use this.

+
+
Raises
+
    +
  • HTTPException – Removing the reactions failed.

  • +
  • Forbidden – You do not have the proper permissions to remove all the reactions.

  • +
+
+
+
+ +
+
+await create_thread(*, name, auto_archive_duration=...)
+

This function is a coroutine.

+

Creates a public thread from this message.

+

You must have create_public_threads in order to +create a public thread from a message.

+

The channel this message belongs in must be a TextChannel.

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • name (str) – The name of the thread.

  • +
  • auto_archive_duration (int) – The duration in minutes before a thread is automatically archived for inactivity. +If not provided, the channel’s default auto archive duration is used.

  • +
+
+
Raises
+
+
+
Returns
+

The created thread.

+
+
Return type
+

Thread

+
+
+
+ +
+
+await reply(content=None, **kwargs)
+

This function is a coroutine.

+

A shortcut method to abc.Messageable.send() to reply to the +Message.

+
+

New in version 1.6.

+
+
+
Raises
+
    +
  • HTTPException – Sending the message failed.

  • +
  • Forbidden – You do not have the proper permissions to send the message.

  • +
  • InvalidArgument – The files list is not of the appropriate size or + you specified both file and files.

  • +
+
+
Returns
+

The message that was sent.

+
+
Return type
+

Message

+
+
+
+ +
+
+to_reference(*, fail_if_not_exists=True)
+

Creates a MessageReference from the current message.

+
+

New in version 1.6.

+
+
+
Parameters
+

fail_if_not_exists (bool) –

Whether replying using the message reference should raise HTTPException +if the message no longer exists or Discord could not fetch the message.

+
+

New in version 1.7.

+
+

+
+
Returns
+

The reference to this message.

+
+
Return type
+

MessageReference

+
+
+
+ +
+ +
+
+

Component

+
+ +Attributes +
+
+class discord.Component
+

Represents a Discord Bot UI Kit Component.

+

Currently, the only components supported by Discord are:

+ +

This class is abstract and cannot be instantiated.

+
+

New in version 2.0.

+
+
+
+type
+

The type of component.

+
+
Type
+

ComponentType

+
+
+
+ +
+ +
+
+

ActionRow

+
+ +Attributes +
+
+class discord.ActionRow
+

Represents a Discord Bot UI Kit Action Row.

+

This is a component that holds up to 5 children components in a row.

+

This inherits from Component.

+
+

New in version 2.0.

+
+
+
+type
+

The type of component.

+
+
Type
+

ComponentType

+
+
+
+ +
+
+children
+

The children components that this holds, if any.

+
+
Type
+

List[Component]

+
+
+
+ +
+ +
+
+

Button

+
+ +Attributes +
+
+class discord.Button
+

Represents a button from the Discord Bot UI Kit.

+

This inherits from Component.

+
+

Note

+

The user constructible and usable type to create a button is discord.ui.Button +not this one.

+
+
+

New in version 2.0.

+
+
+
+style
+

The style of the button.

+
+
Type
+

ButtonStyle

+
+
+
+ +
+
+custom_id
+

The ID of the button that gets received during an interaction. +If this button is for a URL, it does not have a custom ID.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+url
+

The URL this button sends you to.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+disabled
+

Whether the button is disabled or not.

+
+
Type
+

bool

+
+
+
+ +
+
+label
+

The label of the button, if any.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+emoji
+

The emoji of the button, if available.

+
+
Type
+

Optional[PartialEmoji]

+
+
+
+ +
+ +
+
+

SelectMenu

+
+
+class discord.SelectMenu
+

Represents a select menu from the Discord Bot UI Kit.

+

A select menu is functionally the same as a dropdown, however +on mobile it renders a bit differently.

+
+

Note

+

The user constructible and usable type to create a select menu is +discord.ui.Select not this one.

+
+
+

New in version 2.0.

+
+
+
+custom_id
+

The ID of the select menu that gets received during an interaction.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+placeholder
+

The placeholder text that is shown if nothing is selected, if any.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+min_values
+

The minimum number of items that must be chosen for this select menu. +Defaults to 1 and must be between 1 and 25.

+
+
Type
+

int

+
+
+
+ +
+
+max_values
+

The maximum number of items that must be chosen for this select menu. +Defaults to 1 and must be between 1 and 25.

+
+
Type
+

int

+
+
+
+ +
+
+options
+

A list of options that can be selected in this menu.

+
+
Type
+

List[SelectOption]

+
+
+
+ +
+
+disabled
+

Whether the select is disabled or not.

+
+
Type
+

bool

+
+
+
+ +
+ +
+
+

DeletedReferencedMessage

+
+ +Attributes +
+
+class discord.DeletedReferencedMessage
+

A special sentinel type that denotes whether the +resolved message referenced message had since been deleted.

+

The purpose of this class is to separate referenced messages that could not be +fetched and those that were previously fetched but have since been deleted.

+
+

New in version 1.6.

+
+
+
+property id
+

The message ID of the deleted referenced message.

+
+
Type
+

int

+
+
+
+ +
+
+property channel_id
+

The channel ID of the deleted referenced message.

+
+
Type
+

int

+
+
+
+ +
+
+property guild_id
+

The guild ID of the deleted referenced message.

+
+
Type
+

Optional[int]

+
+
+
+ +
+ +
+
+

Reaction

+
+ +Attributes +
+ +Methods +
+
+class discord.Reaction
+

Represents a reaction to a message.

+

Depending on the way this object was created, some of the attributes can +have a value of None.

+
+
+
+x == y
+

Checks if two reactions are equal. This works by checking if the emoji +is the same. So two messages with the same reaction will be considered +“equal”.

+
+ +
+
+x != y
+

Checks if two reactions are not equal.

+
+ +
+
+hash(x)
+

Returns the reaction’s hash.

+
+ +
+
+str(x)
+

Returns the string form of the reaction’s emoji.

+
+ +
+
+
+emoji
+

The reaction emoji. May be a custom emoji, or a unicode emoji.

+
+
Type
+

Union[Emoji, PartialEmoji, str]

+
+
+
+ +
+
+count
+

Number of times this reaction was made

+
+
Type
+

int

+
+
+
+ +
+
+me
+

If the user sent this reaction.

+
+
Type
+

bool

+
+
+
+ +
+
+message
+

Message this reaction is for.

+
+
Type
+

Message

+
+
+
+ +
+
+async for ... in users(*, limit=None, after=None)
+

Returns an AsyncIterator representing the users that have reacted to the message.

+

The after parameter must represent a member +and meet the abc.Snowflake abc.

+

Examples

+

Usage

+
# I do not actually recommend doing this.
+async for user in reaction.users():
+    await channel.send(f'{user} has reacted with {reaction.emoji}!')
+
+
+

Flattening into a list:

+
users = await reaction.users().flatten()
+# users is now a list of User...
+winner = random.choice(users)
+await channel.send(f'{winner} has won the raffle.')
+
+
+
+
Parameters
+
    +
  • limit (Optional[int]) – The maximum number of results to return. +If not provided, returns all the users who +reacted to the message.

  • +
  • after (Optional[abc.Snowflake]) – For pagination, reactions are sorted by member.

  • +
+
+
Raises
+

HTTPException – Getting the users for the reaction failed.

+
+
Yields
+

Union[User, Member] – The member (if retrievable) or the user that has reacted +to this message. The case where it can be a Member is +in a guild message context. Sometimes it can be a User +if the member has left the guild.

+
+
+
+ +
+
+is_custom_emoji()
+

bool: If this is a custom emoji.

+
+ +
+
+await remove(user)
+

This function is a coroutine.

+

Remove the reaction by the provided User from the message.

+

If the reaction is not your own (i.e. user parameter is not you) then +the manage_messages permission is needed.

+

The user parameter must represent a user or member and meet +the abc.Snowflake abc.

+
+
Parameters
+

user (abc.Snowflake) – The user or member from which to remove the reaction.

+
+
Raises
+
    +
  • HTTPException – Removing the reaction failed.

  • +
  • Forbidden – You do not have the proper permissions to remove the reaction.

  • +
  • NotFound – The user you specified, or the reaction’s message was not found.

  • +
+
+
+
+ +
+
+await clear()
+

This function is a coroutine.

+

Clears this reaction from the message.

+

You need the manage_messages permission to use this.

+
+

New in version 1.3.

+
+
+
Raises
+
    +
  • HTTPException – Clearing the reaction failed.

  • +
  • Forbidden – You do not have the proper permissions to clear the reaction.

  • +
  • NotFound – The emoji you specified was not found.

  • +
  • InvalidArgument – The emoji parameter is invalid.

  • +
+
+
+
+ +
+ +
+
+

Guild

+
+ +Methods +
+
+class discord.Guild
+

Represents a Discord guild.

+

This is referred to as a “server” in the official Discord UI.

+
+
+
+x == y
+

Checks if two guilds are equal.

+
+ +
+
+x != y
+

Checks if two guilds are not equal.

+
+ +
+
+hash(x)
+

Returns the guild’s hash.

+
+ +
+
+str(x)
+

Returns the guild’s name.

+
+ +
+
+int(x)
+

Returns the guild’s ID.

+
+ +
+
+
+name
+

The guild name.

+
+
Type
+

str

+
+
+
+ +
+
+emojis
+

All emojis that the guild owns.

+
+
Type
+

Tuple[Emoji, …]

+
+
+
+ +
+
+stickers
+

All stickers that the guild owns.

+
+

New in version 2.0.

+
+
+
Type
+

Tuple[GuildSticker, …]

+
+
+
+ +
+
+region
+

The region the guild belongs on. There is a chance that the region +will be a str if the value is not recognised by the enumerator.

+
+
Type
+

VoiceRegion

+
+
+
+ +
+
+afk_timeout
+

The timeout to get sent to the AFK channel.

+
+
Type
+

int

+
+
+
+ +
+
+afk_channel
+

The channel that denotes the AFK channel. None if it doesn’t exist.

+
+
Type
+

Optional[VoiceChannel]

+
+
+
+ +
+
+id
+

The guild’s ID.

+
+
Type
+

int

+
+
+
+ +
+
+owner_id
+

The guild owner’s ID. Use Guild.owner instead.

+
+
Type
+

int

+
+
+
+ +
+
+unavailable
+

Indicates if the guild is unavailable. If this is True then the +reliability of other attributes outside of Guild.id is slim and they might +all be None. It is best to not do anything with the guild if it is unavailable.

+

Check the on_guild_unavailable() and on_guild_available() events.

+
+
Type
+

bool

+
+
+
+ +
+
+max_presences
+

The maximum amount of presences for the guild.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+max_members
+

The maximum amount of members for the guild.

+
+

Note

+

This attribute is only available via Client.fetch_guild().

+
+
+
Type
+

Optional[int]

+
+
+
+ +
+
+max_video_channel_users
+

The maximum amount of users in a video channel.

+
+

New in version 1.4.

+
+
+
Type
+

Optional[int]

+
+
+
+ +
+
+description
+

The guild’s description.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+mfa_level
+

Indicates the guild’s two factor authorisation level. If this value is 0 then +the guild does not require 2FA for their administrative members. If the value is +1 then they do.

+
+
Type
+

int

+
+
+
+ +
+
+verification_level
+

The guild’s verification level.

+
+
Type
+

VerificationLevel

+
+
+
+ +
+
+explicit_content_filter
+

The guild’s explicit content filter.

+
+
Type
+

ContentFilter

+
+
+
+ +
+
+default_notifications
+

The guild’s notification settings.

+
+
Type
+

NotificationLevel

+
+
+
+ +
+
+features
+

A list of features that the guild has. The features that a guild can have are +subject to arbitrary change by Discord.

+

They are currently as follows:

+
    +
  • ANIMATED_ICON: Guild can upload an animated icon.

  • +
  • BANNER: Guild can upload and use a banner. (i.e. banner)

  • +
  • COMMERCE: Guild can sell things using store channels.

  • +
  • COMMUNITY: Guild is a community server.

  • +
  • DISCOVERABLE: Guild shows up in Server Discovery.

  • +
  • FEATURABLE: Guild is able to be featured in Server Discovery.

  • +
  • INVITE_SPLASH: Guild’s invite page can have a special splash.

  • +
  • MEMBER_VERIFICATION_GATE_ENABLED: Guild has Membership Screening enabled.

  • +
  • MONETIZATION_ENABLED: Guild has enabled monetization.

  • +
  • MORE_EMOJI: Guild has increased custom emoji slots.

  • +
  • MORE_STICKERS: Guild has increased custom sticker slots.

  • +
  • NEWS: Guild can create news channels.

  • +
  • PARTNERED: Guild is a partnered server.

  • +
  • PREVIEW_ENABLED: Guild can be viewed before being accepted via Membership Screening.

  • +
  • PRIVATE_THREADS: Guild has access to create private threads.

  • +
  • SEVEN_DAY_THREAD_ARCHIVE: Guild has access to the seven day archive time for threads.

  • +
  • THREE_DAY_THREAD_ARCHIVE: Guild has access to the three day archive time for threads.

  • +
  • TICKETED_EVENTS_ENABLED: Guild has enabled ticketed events.

  • +
  • VANITY_URL: Guild can have a vanity invite URL (e.g. discord.gg/discord-api).

  • +
  • VERIFIED: Guild is a verified server.

  • +
  • VIP_REGIONS: Guild has VIP voice regions.

  • +
  • WELCOME_SCREEN_ENABLED: Guild has enabled the welcome screen.

  • +
+
+
Type
+

List[str]

+
+
+
+ +
+
+premium_tier
+

The premium tier for this guild. Corresponds to “Nitro Server” in the official UI. +The number goes from 0 to 3 inclusive.

+
+
Type
+

int

+
+
+
+ +
+
+premium_subscription_count
+

The number of “boosts” this guild currently has.

+
+
Type
+

int

+
+
+
+ +
+
+preferred_locale
+

The preferred locale for the guild. Used when filtering Server Discovery +results to a specific language.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+nsfw_level
+

The guild’s NSFW level.

+
+

New in version 2.0.

+
+
+
Type
+

NSFWLevel

+
+
+
+ +
+
+async for ... in fetch_members(*, limit=1000, after=None)
+

Retrieves an AsyncIterator that enables receiving the guild’s members. In order to use this, +Intents.members() must be enabled.

+
+

Note

+

This method is an API call. For general usage, consider members instead.

+
+
+

New in version 1.3.

+
+

All parameters are optional.

+
+
Parameters
+
    +
  • limit (Optional[int]) – The number of members to retrieve. Defaults to 1000. +Pass None to fetch all members. Note that this is potentially slow.

  • +
  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve members after this date or object. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
+
+
Raises
+
+
+
Yields
+

Member – The member with the member data parsed.

+
+
+

Examples

+

Usage

+
async for member in guild.fetch_members(limit=150):
+    print(member.name)
+
+
+

Flattening into a list

+
members = await guild.fetch_members(limit=150).flatten()
+# members is now a list of Member...
+
+
+
+ +
+
+async for ... in audit_logs(*, limit=100, before=None, after=None, oldest_first=None, user=None, action=None)
+

Returns an AsyncIterator that enables receiving the guild’s audit logs.

+

You must have the view_audit_log permission to use this.

+

Examples

+

Getting the first 100 entries:

+
async for entry in guild.audit_logs(limit=100):
+    print(f'{entry.user} did {entry.action} to {entry.target}')
+
+
+

Getting entries for a specific action:

+
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban):
+    print(f'{entry.user} banned {entry.target}')
+
+
+

Getting entries made by a specific user:

+
entries = await guild.audit_logs(limit=None, user=guild.me).flatten()
+await channel.send(f'I made {len(entries)} moderation actions.')
+
+
+
+
Parameters
+
    +
  • limit (Optional[int]) – The number of entries to retrieve. If None retrieve all entries.

  • +
  • before (Union[abc.Snowflake, datetime.datetime]) – Retrieve entries before this date or entry. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • after (Union[abc.Snowflake, datetime.datetime]) – Retrieve entries after this date or entry. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • oldest_first (bool) – If set to True, return entries in oldest->newest order. Defaults to True if +after is specified, otherwise False.

  • +
  • user (abc.Snowflake) – The moderator to filter entries from.

  • +
  • action (AuditLogAction) – The action to filter with.

  • +
+
+
Raises
+
    +
  • Forbidden – You are not allowed to fetch audit logs

  • +
  • HTTPException – An error occurred while fetching the audit logs.

  • +
+
+
Yields
+

AuditLogEntry – The audit log entry.

+
+
+
+ +
+
+property channels
+

A list of channels that belongs to this guild.

+
+
Type
+

List[abc.GuildChannel]

+
+
+
+ +
+
+property threads
+

A list of threads that you have permission to view.

+
+

New in version 2.0.

+
+
+
Type
+

List[Thread]

+
+
+
+ +
+
+property large
+

Indicates if the guild is a ‘large’ guild.

+

A large guild is defined as having more than large_threshold count +members, which for this library is set to the maximum of 250.

+
+
Type
+

bool

+
+
+
+ +
+
+property voice_channels
+

A list of voice channels that belongs to this guild.

+

This is sorted by the position and are in UI order from top to bottom.

+
+
Type
+

List[VoiceChannel]

+
+
+
+ +
+
+property stage_channels
+

A list of stage channels that belongs to this guild.

+
+

New in version 1.7.

+
+

This is sorted by the position and are in UI order from top to bottom.

+
+
Type
+

List[StageChannel]

+
+
+
+ +
+
+property me
+

Similar to Client.user except an instance of Member. +This is essentially used to get the member version of yourself.

+
+
Type
+

Member

+
+
+
+ +
+
+property voice_client
+

Returns the VoiceProtocol associated with this guild, if any.

+
+
Type
+

Optional[VoiceProtocol]

+
+
+
+ +
+
+property text_channels
+

A list of text channels that belongs to this guild.

+

This is sorted by the position and are in UI order from top to bottom.

+
+
Type
+

List[TextChannel]

+
+
+
+ +
+
+property categories
+

A list of categories that belongs to this guild.

+

This is sorted by the position and are in UI order from top to bottom.

+
+
Type
+

List[CategoryChannel]

+
+
+
+ +
+
+by_category()
+

Returns every CategoryChannel and their associated channels.

+

These channels and categories are sorted in the official Discord UI order.

+

If the channels do not have a category, then the first element of the tuple is +None.

+
+
Returns
+

The categories and their associated channels.

+
+
Return type
+

List[Tuple[Optional[CategoryChannel], List[abc.GuildChannel]]]

+
+
+
+ +
+
+get_channel_or_thread(channel_id, /)
+

Returns a channel or thread with the given ID.

+
+

New in version 2.0.

+
+
+
Parameters
+

channel_id (int) – The ID to search for.

+
+
Returns
+

The returned channel or thread or None if not found.

+
+
Return type
+

Optional[Union[Thread, abc.GuildChannel]]

+
+
+
+ +
+
+get_channel(channel_id, /)
+

Returns a channel with the given ID.

+
+

Note

+

This does not search for threads.

+
+
+
Parameters
+

channel_id (int) – The ID to search for.

+
+
Returns
+

The returned channel or None if not found.

+
+
Return type
+

Optional[abc.GuildChannel]

+
+
+
+ +
+
+get_thread(thread_id, /)
+

Returns a thread with the given ID.

+
+

New in version 2.0.

+
+
+
Parameters
+

thread_id (int) – The ID to search for.

+
+
Returns
+

The returned thread or None if not found.

+
+
Return type
+

Optional[Thread]

+
+
+
+ +
+
+property system_channel
+

Returns the guild’s channel used for system messages.

+

If no channel is set, then this returns None.

+
+
Type
+

Optional[TextChannel]

+
+
+
+ +
+
+property system_channel_flags
+

Returns the guild’s system channel settings.

+
+
Type
+

SystemChannelFlags

+
+
+
+ +
+
+property rules_channel
+

Return’s the guild’s channel used for the rules. +The guild must be a Community guild.

+

If no channel is set, then this returns None.

+
+

New in version 1.3.

+
+
+
Type
+

Optional[TextChannel]

+
+
+
+ +
+
+property public_updates_channel
+

Return’s the guild’s channel where admins and +moderators of the guilds receive notices from Discord. The guild must be a +Community guild.

+

If no channel is set, then this returns None.

+
+

New in version 1.4.

+
+
+
Type
+

Optional[TextChannel]

+
+
+
+ +
+
+property emoji_limit
+

The maximum number of emoji slots this guild has.

+
+
Type
+

int

+
+
+
+ +
+
+property sticker_limit
+

The maximum number of sticker slots this guild has.

+
+

New in version 2.0.

+
+
+
Type
+

int

+
+
+
+ +
+
+property bitrate_limit
+

The maximum bitrate for voice channels this guild can have.

+
+
Type
+

float

+
+
+
+ +
+
+property filesize_limit
+

The maximum number of bytes files can have when uploaded to this guild.

+
+
Type
+

int

+
+
+
+ +
+
+property members
+

A list of members that belong to this guild.

+
+
Type
+

List[Member]

+
+
+
+ +
+
+property humans
+

A list of human members that belong to this guild.

+
+

New in version 2.0.

+
+
+
Type
+

List[Member]

+
+
+
+ +
+
+property bots
+

A list of bots that belong to this guild.

+
+

New in version 2.0.

+
+
+
Type
+

List[Member]

+
+
+
+ +
+
+get_member(user_id, /)
+

Returns a member with the given ID.

+
+
Parameters
+

user_id (int) – The ID to search for.

+
+
Returns
+

The member or None if not found.

+
+
Return type
+

Optional[Member]

+
+
+
+ +
+
+property premium_subscribers
+

A list of members who have “boosted” this guild.

+
+
Type
+

List[Member]

+
+
+
+ +
+
+property roles
+

Returns a list of the guild’s roles in hierarchy order.

+

The first element of this list will be the lowest role in the +hierarchy.

+
+
Type
+

List[Role]

+
+
+
+ +
+
+get_role(role_id, /)
+

Returns a role with the given ID.

+
+
Parameters
+

role_id (int) – The ID to search for.

+
+
Returns
+

The role or None if not found.

+
+
Return type
+

Optional[Role]

+
+
+
+ +
+
+property default_role
+

Gets the @everyone role that all members have by default.

+
+
Type
+

Role

+
+
+
+ +
+
+property premium_subscriber_role
+

Gets the premium subscriber role, AKA “boost” role, in this guild.

+
+

New in version 1.6.

+
+
+
Type
+

Optional[Role]

+
+
+
+ +
+
+property self_role
+

Gets the role associated with this client’s user, if any.

+
+

New in version 1.6.

+
+
+
Type
+

Optional[Role]

+
+
+
+ +
+
+property stage_instances
+

Returns a list of the guild’s stage instances that +are currently running.

+
+

New in version 2.0.

+
+
+
Type
+

List[StageInstance]

+
+
+
+ +
+
+get_stage_instance(stage_instance_id, /)
+

Returns a stage instance with the given ID.

+
+

New in version 2.0.

+
+
+
Parameters
+

stage_instance_id (int) – The ID to search for.

+
+
Returns
+

The stage instance or None if not found.

+
+
Return type
+

Optional[StageInstance]

+
+
+
+ +
+
+property owner
+

The member that owns the guild.

+
+
Type
+

Optional[Member]

+
+
+
+ +
+
+property icon
+

Returns the guild’s icon asset, if available.

+
+
Type
+

Optional[Asset]

+
+
+
+ +
+
+property banner
+

Returns the guild’s banner asset, if available.

+
+
Type
+

Optional[Asset]

+
+
+
+ +
+
+property splash
+

Returns the guild’s invite splash asset, if available.

+
+
Type
+

Optional[Asset]

+
+
+
+ +
+
+property discovery_splash
+

Returns the guild’s discovery splash asset, if available.

+
+
Type
+

Optional[Asset]

+
+
+
+ +
+
+property member_count
+

Returns the true member count regardless of it being loaded fully or not.

+
+

Warning

+

Due to a Discord limitation, in order for this attribute to remain up-to-date and +accurate, it requires Intents.members to be specified.

+
+
+
Type
+

int

+
+
+
+ +
+
+property chunked
+

Returns a boolean indicating if the guild is “chunked”.

+

A chunked guild means that member_count is equal to the +number of members stored in the internal members cache.

+

If this value returns False, then you should request for +offline members.

+
+
Type
+

bool

+
+
+
+ +
+
+property shard_id
+

Returns the shard ID for this guild if applicable.

+
+
Type
+

int

+
+
+
+ +
+
+property created_at
+

Returns the guild’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+get_member_named(name, /)
+

Returns the first member found that matches the name provided.

+

The name can have an optional discriminator argument, e.g. “Jake#0001” +or “Jake” will both do the lookup. However the former will give a more +precise result. Note that the discriminator must have all 4 digits +for this to work.

+

If a nickname is passed, then it is looked up via the nickname. Note +however, that a nickname + discriminator combo will not lookup the nickname +but rather the username + discriminator combo due to nickname + discriminator +not being unique.

+

If no member is found, None is returned.

+
+
Parameters
+

name (str) – The name of the member to lookup with an optional discriminator.

+
+
Returns
+

The member in this guild with the associated name. If not found +then None is returned.

+
+
Return type
+

Optional[Member]

+
+
+
+ +
+
+await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)
+

This function is a coroutine.

+

Creates a TextChannel for the guild.

+

Note that you need the manage_channels permission +to create the channel.

+

The overwrites parameter can be used to create a ‘secret’ +channel upon creation. This parameter expects a dict of +overwrites with the target (either a Member or a Role) +as the key and a PermissionOverwrite as the value.

+
+

Note

+

Creating a channel of a specified position will not update the position of +other channels to follow suit. A follow-up call to edit() +will be required to update the position of the channel in the channel list.

+
+

Examples

+

Creating a basic channel:

+
channel = await guild.create_text_channel('cool-channel')
+
+
+

Creating a “secret” channel:

+
overwrites = {
+    guild.default_role: discord.PermissionOverwrite(read_messages=False),
+    guild.me: discord.PermissionOverwrite(read_messages=True)
+}
+
+channel = await guild.create_text_channel('secret', overwrites=overwrites)
+
+
+
+
Parameters
+
    +
  • name (str) – The channel’s name.

  • +
  • overwrites (Dict[Union[Role, Member], PermissionOverwrite]) – A dict of target (either a role or a member) to +PermissionOverwrite to apply upon creation of a channel. +Useful for creating secret channels.

  • +
  • category (Optional[CategoryChannel]) – The category to place the newly created channel under. +The permissions will be automatically synced to category if no +overwrites are provided.

  • +
  • position (int) – The position in the channel list. This is a number that starts +at 0. e.g. the top channel is position 0.

  • +
  • topic (str) – The new channel’s topic.

  • +
  • slowmode_delay (int) – Specifies the slowmode rate limit for user in this channel, in seconds. +The maximum value possible is 21600.

  • +
  • nsfw (bool) – To mark the channel as NSFW or not.

  • +
  • reason (Optional[str]) – The reason for creating this channel. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have the proper permissions to create this channel.

  • +
  • HTTPException – Creating the channel failed.

  • +
  • InvalidArgument – The permission overwrite information is not in proper form.

  • +
+
+
Returns
+

The channel that was just created.

+
+
Return type
+

TextChannel

+
+
+
+ +
+
+await create_voice_channel(name, *, reason=None, category=None, position=..., bitrate=..., user_limit=..., rtc_region=..., video_quality_mode=..., overwrites=...)
+

This function is a coroutine.

+

This is similar to create_text_channel() except makes a VoiceChannel instead.

+
+
Parameters
+
    +
  • name (str) – The channel’s name.

  • +
  • overwrites (Dict[Union[Role, Member], PermissionOverwrite]) – A dict of target (either a role or a member) to +PermissionOverwrite to apply upon creation of a channel. +Useful for creating secret channels.

  • +
  • category (Optional[CategoryChannel]) – The category to place the newly created channel under. +The permissions will be automatically synced to category if no +overwrites are provided.

  • +
  • position (int) – The position in the channel list. This is a number that starts +at 0. e.g. the top channel is position 0.

  • +
  • bitrate (int) – The channel’s preferred audio bitrate in bits per second.

  • +
  • user_limit (int) – The channel’s limit for number of members that can be in a voice channel.

  • +
  • rtc_region (Optional[VoiceRegion]) –

    The region for the voice channel’s voice communication. +A value of None indicates automatic voice region detection.

    +
    +

    New in version 1.7.

    +
    +

  • +
  • video_quality_mode (VideoQualityMode) –

    The camera video quality for the voice channel’s participants.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • reason (Optional[str]) – The reason for creating this channel. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have the proper permissions to create this channel.

  • +
  • HTTPException – Creating the channel failed.

  • +
  • InvalidArgument – The permission overwrite information is not in proper form.

  • +
+
+
Returns
+

The channel that was just created.

+
+
Return type
+

VoiceChannel

+
+
+
+ +
+
+await create_stage_channel(name, *, topic, position=..., overwrites=..., category=None, reason=None)
+

This function is a coroutine.

+

This is similar to create_text_channel() except makes a StageChannel instead.

+
+

New in version 1.7.

+
+
+
Parameters
+
    +
  • name (str) – The channel’s name.

  • +
  • topic (str) – The new channel’s topic.

  • +
  • overwrites (Dict[Union[Role, Member], PermissionOverwrite]) – A dict of target (either a role or a member) to +PermissionOverwrite to apply upon creation of a channel. +Useful for creating secret channels.

  • +
  • category (Optional[CategoryChannel]) – The category to place the newly created channel under. +The permissions will be automatically synced to category if no +overwrites are provided.

  • +
  • position (int) – The position in the channel list. This is a number that starts +at 0. e.g. the top channel is position 0.

  • +
  • reason (Optional[str]) – The reason for creating this channel. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have the proper permissions to create this channel.

  • +
  • HTTPException – Creating the channel failed.

  • +
  • InvalidArgument – The permission overwrite information is not in proper form.

  • +
+
+
Returns
+

The channel that was just created.

+
+
Return type
+

StageChannel

+
+
+
+ +
+
+await create_category(name, *, overwrites=..., reason=None, position=...)
+

This function is a coroutine.

+

Same as create_text_channel() except makes a CategoryChannel instead.

+
+

Note

+

The category parameter is not supported in this function since categories +cannot have categories.

+
+
+
Raises
+
    +
  • Forbidden – You do not have the proper permissions to create this channel.

  • +
  • HTTPException – Creating the channel failed.

  • +
  • InvalidArgument – The permission overwrite information is not in proper form.

  • +
+
+
Returns
+

The channel that was just created.

+
+
Return type
+

CategoryChannel

+
+
+
+ +
+
+await create_category_channel(name, *, overwrites=..., reason=None, position=...)
+

This function is a coroutine.

+

Same as create_text_channel() except makes a CategoryChannel instead.

+
+

Note

+

The category parameter is not supported in this function since categories +cannot have categories.

+
+
+
Raises
+
    +
  • Forbidden – You do not have the proper permissions to create this channel.

  • +
  • HTTPException – Creating the channel failed.

  • +
  • InvalidArgument – The permission overwrite information is not in proper form.

  • +
+
+
Returns
+

The channel that was just created.

+
+
Return type
+

CategoryChannel

+
+
+
+ +
+
+await leave()
+

This function is a coroutine.

+

Leaves the guild.

+
+

Note

+

You cannot leave the guild that you own, you must delete it instead +via delete().

+
+
+
Raises
+

HTTPException – Leaving the guild failed.

+
+
+
+ +
+
+await delete()
+

This function is a coroutine.

+

Deletes the guild. You must be the guild owner to delete the +guild.

+
+
Raises
+
    +
  • HTTPException – Deleting the guild failed.

  • +
  • Forbidden – You do not have permissions to delete the guild.

  • +
+
+
+
+ +
+
+await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., region=..., afk_channel=..., owner=..., afk_timeout=..., default_notifications=..., verification_level=..., explicit_content_filter=..., vanity_code=..., system_channel=..., system_channel_flags=..., preferred_locale=..., rules_channel=..., public_updates_channel=...)
+

This function is a coroutine.

+

Edits the guild.

+

You must have the manage_guild permission +to edit the guild.

+
+

Changed in version 1.4: The rules_channel and public_updates_channel keyword-only parameters were added.

+
+
+

Changed in version 2.0: The discovery_splash and community keyword-only parameters were added.

+
+
+

Changed in version 2.0: The newly updated guild is returned.

+
+
+
Parameters
+
    +
  • name (str) – The new name of the guild.

  • +
  • description (Optional[str]) – The new description of the guild. Could be None for no description. +This is only available to guilds that contain PUBLIC in Guild.features.

  • +
  • icon (bytes) – A bytes-like object representing the icon. Only PNG/JPEG is supported. +GIF is only available to guilds that contain ANIMATED_ICON in Guild.features. +Could be None to denote removal of the icon.

  • +
  • banner (bytes) – A bytes-like object representing the banner. +Could be None to denote removal of the banner. This is only available to guilds that contain +BANNER in Guild.features.

  • +
  • splash (bytes) – A bytes-like object representing the invite splash. +Only PNG/JPEG supported. Could be None to denote removing the +splash. This is only available to guilds that contain INVITE_SPLASH +in Guild.features.

  • +
  • discovery_splash (bytes) – A bytes-like object representing the discovery splash. +Only PNG/JPEG supported. Could be None to denote removing the +splash. This is only available to guilds that contain DISCOVERABLE +in Guild.features.

  • +
  • community (bool) – Whether the guild should be a Community guild. If set to True, both rules_channel +and public_updates_channel parameters are required.

  • +
  • region (Union[str, VoiceRegion]) – The new region for the guild’s voice communication.

  • +
  • afk_channel (Optional[VoiceChannel]) – The new channel that is the AFK channel. Could be None for no AFK channel.

  • +
  • afk_timeout (int) – The number of seconds until someone is moved to the AFK channel.

  • +
  • owner (Member) – The new owner of the guild to transfer ownership to. Note that you must +be owner of the guild to do this.

  • +
  • verification_level (VerificationLevel) – The new verification level for the guild.

  • +
  • default_notifications (NotificationLevel) – The new default notification level for the guild.

  • +
  • explicit_content_filter (ContentFilter) – The new explicit content filter for the guild.

  • +
  • vanity_code (str) – The new vanity code for the guild.

  • +
  • system_channel (Optional[TextChannel]) – The new channel that is used for the system channel. Could be None for no system channel.

  • +
  • system_channel_flags (SystemChannelFlags) – The new system channel settings to use with the new system channel.

  • +
  • preferred_locale (str) – The new preferred locale for the guild. Used as the primary language in the guild. +If set, this must be an ISO 639 code, e.g. en-US or ja or zh-CN.

  • +
  • rules_channel (Optional[TextChannel]) – The new channel that is used for rules. This is only available to +guilds that contain PUBLIC in Guild.features. Could be None for no rules +channel.

  • +
  • public_updates_channel (Optional[TextChannel]) – The new channel that is used for public updates from Discord. This is only available to +guilds that contain PUBLIC in Guild.features. Could be None for no +public updates channel.

  • +
  • reason (Optional[str]) – The reason for editing this guild. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to edit the guild.

  • +
  • HTTPException – Editing the guild failed.

  • +
  • InvalidArgument – The image format passed in to icon is invalid. It must be + PNG or JPG. This is also raised if you are not the owner of the + guild and request an ownership transfer.

  • +
+
+
Returns
+

The newly updated guild. Note that this has the same limitations as +mentioned in Client.fetch_guild() and may not have full data.

+
+
Return type
+

Guild

+
+
+
+ +
+
+await fetch_channels()
+

This function is a coroutine.

+

Retrieves all abc.GuildChannel that the guild has.

+
+

Note

+

This method is an API call. For general usage, consider channels instead.

+
+
+

New in version 1.2.

+
+
+
Raises
+
    +
  • InvalidData – An unknown channel type was received from Discord.

  • +
  • HTTPException – Retrieving the channels failed.

  • +
+
+
Returns
+

All channels in the guild.

+
+
Return type
+

Sequence[abc.GuildChannel]

+
+
+
+ +
+
+await active_threads()
+

This function is a coroutine.

+

Returns a list of active Thread that the client can access.

+

This includes both private and public threads.

+
+

New in version 2.0.

+
+
+
Raises
+

HTTPException – The request to get the active threads failed.

+
+
Returns
+

The active threads

+
+
Return type
+

List[Thread]

+
+
+
+ +
+
+await fetch_member(member_id, /)
+

This function is a coroutine.

+

Retrieves a Member from a guild ID, and a member ID.

+
+

Note

+

This method is an API call. If you have Intents.members and member cache enabled, consider get_member() instead.

+
+
+
Parameters
+

member_id (int) – The member’s ID to fetch from.

+
+
Raises
+
    +
  • Forbidden – You do not have access to the guild.

  • +
  • HTTPException – Fetching the member failed.

  • +
  • NotFound – A member with that ID does not exist.

  • +
+
+
Returns
+

The member from the member ID.

+
+
Return type
+

Member

+
+
+
+ +
+
+await try_member(member_id, /)
+

This function is a coroutine.

+

Returns a member with the given ID. This uses the cache first, and if not found, it’ll request using fetch_member().

+
+

Note

+

This method might result in an API call.

+
+
+
Parameters
+

member_id (int) – The ID to search for.

+
+
Returns
+

The member or None if not found.

+
+
Return type
+

Optional[Member]

+
+
+
+ +
+
+await fetch_ban(user)
+

This function is a coroutine.

+

Retrieves the BanEntry for a user.

+

You must have the ban_members permission +to get this information.

+
+
Parameters
+

user (abc.Snowflake) – The user to get ban information from.

+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to get the information.

  • +
  • NotFound – This user is not banned.

  • +
  • HTTPException – An error occurred while fetching the information.

  • +
+
+
Returns
+

The BanEntry object for the specified user.

+
+
Return type
+

BanEntry

+
+
+
+ +
+
+await fetch_channel(channel_id, /)
+

This function is a coroutine.

+

Retrieves a abc.GuildChannel or Thread with the specified ID.

+
+

Note

+

This method is an API call. For general usage, consider get_channel_or_thread() instead.

+
+
+

New in version 2.0.

+
+
+
Raises
+
    +
  • InvalidData – An unknown channel type was received from Discord + or the guild the channel belongs to is not the same + as the one in this object points to.

  • +
  • HTTPException – Retrieving the channel failed.

  • +
  • NotFound – Invalid Channel ID.

  • +
  • Forbidden – You do not have permission to fetch this channel.

  • +
+
+
Returns
+

The channel from the ID.

+
+
Return type
+

Union[abc.GuildChannel, Thread]

+
+
+
+ +
+
+await bans()
+

This function is a coroutine.

+

Retrieves all the users that are banned from the guild as a list of BanEntry.

+

You must have the ban_members permission +to get this information.

+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to get the information.

  • +
  • HTTPException – An error occurred while fetching the information.

  • +
+
+
Returns
+

A list of BanEntry objects.

+
+
Return type
+

List[BanEntry]

+
+
+
+ +
+
+await prune_members(*, days, compute_prune_count=True, roles=..., reason=None)
+

This function is a coroutine.

+

Prunes the guild from its inactive members.

+

The inactive members are denoted if they have not logged on in +days number of days and they have no roles.

+

You must have the kick_members permission +to use this.

+

To check how many members you would prune without actually pruning, +see the estimate_pruned_members() function.

+

To prune members that have specific roles see the roles parameter.

+
+

Changed in version 1.4: The roles keyword-only parameter was added.

+
+
+
Parameters
+
    +
  • days (int) – The number of days before counting as inactive.

  • +
  • reason (Optional[str]) – The reason for doing this action. Shows up on the audit log.

  • +
  • compute_prune_count (bool) – Whether to compute the prune count. This defaults to True +which makes it prone to timeouts in very large guilds. In order +to prevent timeouts, you must set this to False. If this is +set to False, then this function will always return None.

  • +
  • roles (List[abc.Snowflake]) – A list of abc.Snowflake that represent roles to include in the pruning process. If a member +has a role that is not specified, they’ll be excluded.

  • +
+
+
Raises
+
+
+
Returns
+

The number of members pruned. If compute_prune_count is False +then this returns None.

+
+
Return type
+

Optional[int]

+
+
+
+ +
+
+await templates()
+

This function is a coroutine.

+

Gets the list of templates from this guild.

+

Requires manage_guild permissions.

+
+

New in version 1.7.

+
+
+
Raises
+

Forbidden – You don’t have permissions to get the templates.

+
+
Returns
+

The templates for this guild.

+
+
Return type
+

List[Template]

+
+
+
+ +
+
+await webhooks()
+

This function is a coroutine.

+

Gets the list of webhooks from this guild.

+

Requires manage_webhooks permissions.

+
+
Raises
+

Forbidden – You don’t have permissions to get the webhooks.

+
+
Returns
+

The webhooks for this guild.

+
+
Return type
+

List[Webhook]

+
+
+
+ +
+
+await estimate_pruned_members(*, days, roles=...)
+

This function is a coroutine.

+

Similar to prune_members() except instead of actually +pruning members, it returns how many members it would prune +from the guild had it been called.

+
+
Parameters
+
    +
  • days (int) – The number of days before counting as inactive.

  • +
  • roles (List[abc.Snowflake]) –

    A list of abc.Snowflake that represent roles to include in the estimate. If a member +has a role that is not specified, they’ll be excluded.

    +
    +

    New in version 1.7.

    +
    +

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to prune members.

  • +
  • HTTPException – An error occurred while fetching the prune members estimate.

  • +
  • InvalidArgument – An integer was not passed for days.

  • +
+
+
Returns
+

The number of members estimated to be pruned.

+
+
Return type
+

int

+
+
+
+ +
+
+await invites()
+

This function is a coroutine.

+

Returns a list of all active instant invites from the guild.

+

You must have the manage_guild permission to get +this information.

+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to get the information.

  • +
  • HTTPException – An error occurred while fetching the information.

  • +
+
+
Returns
+

The list of invites that are currently active.

+
+
Return type
+

List[Invite]

+
+
+
+ +
+
+await create_template(*, name, description=...)
+

This function is a coroutine.

+

Creates a template for the guild.

+

You must have the manage_guild permission to +do this.

+
+

New in version 1.7.

+
+
+
Parameters
+
    +
  • name (str) – The name of the template.

  • +
  • description (str) – The description of the template.

  • +
+
+
+
+ +
+
+await create_integration(*, type, id)
+

This function is a coroutine.

+

Attaches an integration to the guild.

+

You must have the manage_guild permission to +do this.

+
+

New in version 1.4.

+
+
+
Parameters
+
    +
  • type (str) – The integration type (e.g. Twitch).

  • +
  • id (int) – The integration ID.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permission to create the integration.

  • +
  • HTTPException – The account could not be found.

  • +
+
+
+
+ +
+
+await integrations()
+

This function is a coroutine.

+

Returns a list of all integrations attached to the guild.

+

You must have the manage_guild permission to +do this.

+
+

New in version 1.4.

+
+
+
Raises
+
    +
  • Forbidden – You do not have permission to create the integration.

  • +
  • HTTPException – Fetching the integrations failed.

  • +
+
+
Returns
+

The list of integrations that are attached to the guild.

+
+
Return type
+

List[Integration]

+
+
+
+ +
+
+await fetch_stickers()
+

This function is a coroutine.

+

Retrieves a list of all Stickers for the guild.

+
+

New in version 2.0.

+
+
+

Note

+

This method is an API call. For general usage, consider stickers instead.

+
+
+
Raises
+

HTTPException – An error occurred fetching the stickers.

+
+
Returns
+

The retrieved stickers.

+
+
Return type
+

List[GuildSticker]

+
+
+
+ +
+
+await fetch_sticker(sticker_id, /)
+

This function is a coroutine.

+

Retrieves a custom Sticker from the guild.

+
+

New in version 2.0.

+
+
+

Note

+

This method is an API call. +For general usage, consider iterating over stickers instead.

+
+
+
Parameters
+

sticker_id (int) – The sticker’s ID.

+
+
Raises
+
    +
  • NotFound – The sticker requested could not be found.

  • +
  • HTTPException – An error occurred fetching the sticker.

  • +
+
+
Returns
+

The retrieved sticker.

+
+
Return type
+

GuildSticker

+
+
+
+ +
+
+await create_sticker(*, name, description=None, emoji, file, reason=None)
+

This function is a coroutine.

+

Creates a Sticker for the guild.

+

You must have manage_emojis_and_stickers permission to +do this.

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • name (str) – The sticker name. Must be at least 2 characters.

  • +
  • description (Optional[str]) – The sticker’s description. Can be None.

  • +
  • emoji (str) – The name of a unicode emoji that represents the sticker’s expression.

  • +
  • file (File) – The file of the sticker to upload.

  • +
  • reason (str) – The reason for creating this sticker. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You are not allowed to create stickers.

  • +
  • HTTPException – An error occurred creating a sticker.

  • +
+
+
Returns
+

The created sticker.

+
+
Return type
+

GuildSticker

+
+
+
+ +
+
+await delete_sticker(sticker, *, reason=None)
+

This function is a coroutine.

+

Deletes the custom Sticker from the guild.

+

You must have manage_emojis_and_stickers permission to +do this.

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • sticker (abc.Snowflake) – The sticker you are deleting.

  • +
  • reason (Optional[str]) – The reason for deleting this sticker. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You are not allowed to delete stickers.

  • +
  • HTTPException – An error occurred deleting the sticker.

  • +
+
+
+
+ +
+
+await fetch_emojis()
+

This function is a coroutine.

+

Retrieves all custom Emojis from the guild.

+
+

Note

+

This method is an API call. For general usage, consider emojis instead.

+
+
+
Raises
+

HTTPException – An error occurred fetching the emojis.

+
+
Returns
+

The retrieved emojis.

+
+
Return type
+

List[Emoji]

+
+
+
+ +
+
+await fetch_emoji(emoji_id, /)
+

This function is a coroutine.

+

Retrieves a custom Emoji from the guild.

+
+

Note

+

This method is an API call. +For general usage, consider iterating over emojis instead.

+
+
+
Parameters
+

emoji_id (int) – The emoji’s ID.

+
+
Raises
+
    +
  • NotFound – The emoji requested could not be found.

  • +
  • HTTPException – An error occurred fetching the emoji.

  • +
+
+
Returns
+

The retrieved emoji.

+
+
Return type
+

Emoji

+
+
+
+ +
+
+await create_custom_emoji(*, name, image, roles=..., reason=None)
+

This function is a coroutine.

+

Creates a custom Emoji for the guild.

+

There is currently a limit of 50 static and animated emojis respectively per guild, +unless the guild has the MORE_EMOJI feature which extends the limit to 200.

+

You must have the manage_emojis permission to +do this.

+
+
Parameters
+
    +
  • name (str) – The emoji name. Must be at least 2 characters.

  • +
  • image (bytes) – The bytes-like object representing the image data to use. +Only JPG, PNG and GIF images are supported.

  • +
  • roles (List[Role]) – A list of Roles that can use this emoji. Leave empty to make it available to everyone.

  • +
  • reason (Optional[str]) – The reason for creating this emoji. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You are not allowed to create emojis.

  • +
  • HTTPException – An error occurred creating an emoji.

  • +
+
+
Returns
+

The created emoji.

+
+
Return type
+

Emoji

+
+
+
+ +
+
+await delete_emoji(emoji, *, reason=None)
+

This function is a coroutine.

+

Deletes the custom Emoji from the guild.

+

You must have manage_emojis permission to +do this.

+
+
Parameters
+
    +
  • emoji (abc.Snowflake) – The emoji you are deleting.

  • +
  • reason (Optional[str]) – The reason for deleting this emoji. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You are not allowed to delete emojis.

  • +
  • HTTPException – An error occurred deleting the emoji.

  • +
+
+
+
+ +
+
+await fetch_roles()
+

This function is a coroutine.

+

Retrieves all Role that the guild has.

+
+

Note

+

This method is an API call. For general usage, consider roles instead.

+
+
+

New in version 1.3.

+
+
+
Raises
+

HTTPException – Retrieving the roles failed.

+
+
Returns
+

All roles in the guild.

+
+
Return type
+

List[Role]

+
+
+
+ +
+
+await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., mentionable=..., reason=None)
+

This function is a coroutine.

+

Creates a Role for the guild.

+

All fields are optional.

+

You must have the manage_roles permission to +do this.

+
+

Changed in version 1.6: Can now pass int to colour keyword-only parameter.

+
+
+
Parameters
+
    +
  • name (str) – The role name. Defaults to ‘new role’.

  • +
  • permissions (Permissions) – The permissions to have. Defaults to no permissions.

  • +
  • colour (Union[Colour, int]) – The colour for the role. Defaults to Colour.default(). +This is aliased to color as well.

  • +
  • hoist (bool) – Indicates if the role should be shown separately in the member list. +Defaults to False.

  • +
  • mentionable (bool) – Indicates if the role should be mentionable by others. +Defaults to False.

  • +
  • reason (Optional[str]) – The reason for creating this role. Shows up on the audit log.

  • +
+
+
Raises
+
+
+
Returns
+

The newly created role.

+
+
Return type
+

Role

+
+
+
+ +
+
+await edit_role_positions(positions, *, reason=None)
+

This function is a coroutine.

+

Bulk edits a list of Role in the guild.

+

You must have the manage_roles permission to +do this.

+
+

New in version 1.4.

+
+

Example:

+
positions = {
+    bots_role: 1, # penultimate role
+    tester_role: 2,
+    admin_role: 6
+}
+
+await guild.edit_role_positions(positions=positions)
+
+
+
+
Parameters
+
    +
  • positions – A dict of Role to int to change the positions +of each given role.

  • +
  • reason (Optional[str]) – The reason for editing the role positions. Shows up on the audit log.

  • +
+
+
Raises
+
+
+
Returns
+

A list of all the roles in the guild.

+
+
Return type
+

List[Role]

+
+
+
+ +
+
+await kick(user, *, reason=None)
+

This function is a coroutine.

+

Kicks a user from the guild.

+

The user must meet the abc.Snowflake abc.

+

You must have the kick_members permission to +do this.

+
+
Parameters
+
    +
  • user (abc.Snowflake) – The user to kick from their guild.

  • +
  • reason (Optional[str]) – The reason the user got kicked.

  • +
+
+
Raises
+
+
+
+
+ +
+
+await ban(user, *, reason=None, delete_message_days=1)
+

This function is a coroutine.

+

Bans a user from the guild.

+

The user must meet the abc.Snowflake abc.

+

You must have the ban_members permission to +do this.

+
+
Parameters
+
    +
  • user (abc.Snowflake) – The user to ban from their guild.

  • +
  • delete_message_days (int) – The number of days worth of messages to delete from the user +in the guild. The minimum is 0 and the maximum is 7.

  • +
  • reason (Optional[str]) – The reason the user got banned.

  • +
+
+
Raises
+
+
+
+
+ +
+
+await unban(user, *, reason=None)
+

This function is a coroutine.

+

Unbans a user from the guild.

+

The user must meet the abc.Snowflake abc.

+

You must have the ban_members permission to +do this.

+
+
Parameters
+
    +
  • user (abc.Snowflake) – The user to unban.

  • +
  • reason (Optional[str]) – The reason for doing this action. Shows up on the audit log.

  • +
+
+
Raises
+
+
+
+
+ +
+
+await vanity_invite()
+

This function is a coroutine.

+

Returns the guild’s special vanity invite.

+

The guild must have VANITY_URL in features.

+

You must have the manage_guild permission to use +this as well.

+
+
Raises
+
    +
  • Forbidden – You do not have the proper permissions to get this.

  • +
  • HTTPException – Retrieving the vanity invite failed.

  • +
+
+
Returns
+

The special vanity invite. If None then the guild does not +have a vanity invite set.

+
+
Return type
+

Optional[Invite]

+
+
+
+ +
+
+await widget()
+

This function is a coroutine.

+

Returns the widget of the guild.

+
+

Note

+

The guild must have the widget enabled to get this information.

+
+
+
Raises
+
+
+
Returns
+

The guild’s widget.

+
+
Return type
+

Widget

+
+
+
+ +
+
+await edit_widget(*, enabled=..., channel=...)
+

This function is a coroutine.

+

Edits the widget of the guild.

+

You must have the manage_guild permission to +use this

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • enabled (bool) – Whether to enable the widget for the guild.

  • +
  • channel (Optional[Snowflake]) – The new widget channel. None removes the widget channel.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permission to edit the widget.

  • +
  • HTTPException – Editing the widget failed.

  • +
+
+
+
+ +
+
+await chunk(*, cache=True)
+

This function is a coroutine.

+

Requests all members that belong to this guild. In order to use this, +Intents.members() must be enabled.

+

This is a websocket operation and can be slow.

+
+

New in version 1.5.

+
+
+
Parameters
+

cache (bool) – Whether to cache the members as well.

+
+
Raises
+

ClientException – The members intent is not enabled.

+
+
+
+ +
+
+await query_members(query=None, *, limit=5, user_ids=None, presences=False, cache=True)
+

This function is a coroutine.

+

Request members that belong to this guild whose username starts with +the query given.

+

This is a websocket operation and can be slow.

+
+

New in version 1.3.

+
+
+
Parameters
+
    +
  • query (Optional[str]) – The string that the username’s start with.

  • +
  • limit (int) – The maximum number of members to send back. This must be +a number between 5 and 100.

  • +
  • presences (bool) –

    Whether to request for presences to be provided. This defaults +to False.

    +
    +

    New in version 1.6.

    +
    +

  • +
  • cache (bool) – Whether to cache the members internally. This makes operations +such as get_member() work for those that matched.

  • +
  • user_ids (Optional[List[int]]) –

    List of user IDs to search for. If the user ID is not in the guild then it won’t be returned.

    +
    +

    New in version 1.4.

    +
    +

  • +
+
+
Raises
+
+
+
Returns
+

The list of members that have matched the query.

+
+
Return type
+

List[Member]

+
+
+
+ +
+
+await change_voice_state(*, channel, self_mute=False, self_deaf=False)
+

This function is a coroutine.

+

Changes client’s voice state in the guild.

+
+

New in version 1.4.

+
+
+
Parameters
+
    +
  • channel (Optional[VoiceChannel]) – Channel the client wants to join. Use None to disconnect.

  • +
  • self_mute (bool) – Indicates if the client should be self-muted.

  • +
  • self_deaf (bool) – Indicates if the client should be self-deafened.

  • +
+
+
+
+ +
+ +
+
+class discord.BanEntry
+

A namedtuple which represents a ban returned from bans().

+
+
+reason
+

The reason this user was banned.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+user
+

The User that was banned.

+
+
Type
+

User

+
+
+
+ +
+ +
+
+

Integration

+
+
+class discord.Integration
+

Represents a guild integration.

+
+

New in version 1.4.

+
+
+
+id
+

The integration ID.

+
+
Type
+

int

+
+
+
+ +
+
+name
+

The integration name.

+
+
Type
+

str

+
+
+
+ +
+
+guild
+

The guild of the integration.

+
+
Type
+

Guild

+
+
+
+ +
+
+type
+

The integration type (i.e. Twitch).

+
+
Type
+

str

+
+
+
+ +
+
+enabled
+

Whether the integration is currently enabled.

+
+
Type
+

bool

+
+
+
+ +
+
+account
+

The account linked to this integration.

+
+
Type
+

IntegrationAccount

+
+
+
+ +
+
+user
+

The user that added this integration.

+
+
Type
+

User

+
+
+
+ +
+
+await delete(*, reason=None)
+

This function is a coroutine.

+

Deletes the integration.

+

You must have the manage_guild permission to +do this.

+
+
Parameters
+

reason (str) –

The reason the integration was deleted. Shows up on the audit log.

+
+

New in version 2.0.

+
+

+
+
Raises
+
    +
  • Forbidden – You do not have permission to delete the integration.

  • +
  • HTTPException – Deleting the integration failed.

  • +
+
+
+
+ +
+ +
+
+class discord.IntegrationAccount
+

Represents an integration account.

+
+

New in version 1.4.

+
+
+
+id
+

The account ID.

+
+
Type
+

str

+
+
+
+ +
+
+name
+

The account name.

+
+
Type
+

str

+
+
+
+ +
+ +
+
+class discord.BotIntegration
+

Represents a bot integration on discord.

+
+

New in version 2.0.

+
+
+
+id
+

The integration ID.

+
+
Type
+

int

+
+
+
+ +
+
+name
+

The integration name.

+
+
Type
+

str

+
+
+
+ +
+
+guild
+

The guild of the integration.

+
+
Type
+

Guild

+
+
+
+ +
+
+type
+

The integration type (i.e. Twitch).

+
+
Type
+

str

+
+
+
+ +
+
+enabled
+

Whether the integration is currently enabled.

+
+
Type
+

bool

+
+
+
+ +
+
+user
+

The user that added this integration.

+
+
Type
+

User

+
+
+
+ +
+
+account
+

The integration account information.

+
+
Type
+

IntegrationAccount

+
+
+
+ +
+
+application
+

The application tied to this integration.

+
+
Type
+

IntegrationApplication

+
+
+
+ +
+ +
+
+class discord.IntegrationApplication
+

Represents an application for a bot integration.

+
+

New in version 2.0.

+
+
+
+id
+

The ID for this application.

+
+
Type
+

int

+
+
+
+ +
+
+name
+

The application’s name.

+
+
Type
+

str

+
+
+
+ +
+
+icon
+

The application’s icon hash.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+description
+

The application’s description. Can be an empty string.

+
+
Type
+

str

+
+
+
+ +
+
+summary
+

The summary of the application. Can be an empty string.

+
+
Type
+

str

+
+
+
+ +
+
+user
+

The bot user on this application.

+
+
Type
+

Optional[User]

+
+
+
+ +
+ +
+
+class discord.StreamIntegration
+

Represents a stream integration for Twitch or YouTube.

+
+

New in version 2.0.

+
+
+
+id
+

The integration ID.

+
+
Type
+

int

+
+
+
+ +
+
+name
+

The integration name.

+
+
Type
+

str

+
+
+
+ +
+
+guild
+

The guild of the integration.

+
+
Type
+

Guild

+
+
+
+ +
+
+type
+

The integration type (i.e. Twitch).

+
+
Type
+

str

+
+
+
+ +
+
+enabled
+

Whether the integration is currently enabled.

+
+
Type
+

bool

+
+
+
+ +
+
+syncing
+

Where the integration is currently syncing.

+
+
Type
+

bool

+
+
+
+ +
+
+enable_emoticons
+

Whether emoticons should be synced for this integration (currently twitch only).

+
+
Type
+

Optional[bool]

+
+
+
+ +
+
+expire_behaviour
+

The behaviour of expiring subscribers. Aliased to expire_behavior as well.

+
+
Type
+

ExpireBehaviour

+
+
+
+ +
+
+expire_grace_period
+

The grace period (in days) for expiring subscribers.

+
+
Type
+

int

+
+
+
+ +
+
+user
+

The user for the integration.

+
+
Type
+

User

+
+
+
+ +
+
+account
+

The integration account information.

+
+
Type
+

IntegrationAccount

+
+
+
+ +
+
+synced_at
+

An aware UTC datetime representing when the integration was last synced.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+property expire_behavior
+

An alias for expire_behaviour.

+
+
Type
+

ExpireBehaviour

+
+
+
+ +
+
+property role
+

Optional[Role] The role which the integration uses for subscribers.

+
+ +
+
+await edit(*, expire_behaviour=..., expire_grace_period=..., enable_emoticons=...)
+

This function is a coroutine.

+

Edits the integration.

+

You must have the manage_guild permission to +do this.

+
+
Parameters
+
    +
  • expire_behaviour (ExpireBehaviour) – The behaviour when an integration subscription lapses. Aliased to expire_behavior as well.

  • +
  • expire_grace_period (int) – The period (in days) where the integration will ignore lapsed subscriptions.

  • +
  • enable_emoticons (bool) – Where emoticons should be synced for this integration (currently twitch only).

  • +
+
+
Raises
+
+
+
+
+ +
+
+await sync()
+

This function is a coroutine.

+

Syncs the integration.

+

You must have the manage_guild permission to +do this.

+
+
Raises
+
    +
  • Forbidden – You do not have permission to sync the integration.

  • +
  • HTTPException – Syncing the integration failed.

  • +
+
+
+
+ +
+ +
+
+

Interaction

+
+
+class discord.Interaction
+

Represents a Discord interaction.

+

An interaction happens when a user does an action that needs to +be notified. Current examples are slash commands and components.

+
+

New in version 2.0.

+
+
+
+id
+

The interaction’s ID.

+
+
Type
+

int

+
+
+
+ +
+
+type
+

The interaction type.

+
+
Type
+

InteractionType

+
+
+
+ +
+
+guild_id
+

The guild ID the interaction was sent from.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+channel_id
+

The channel ID the interaction was sent from.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+application_id
+

The application ID that the interaction was for.

+
+
Type
+

int

+
+
+
+ +
+
+user
+

The user or member that sent the interaction.

+
+
Type
+

Optional[Union[User, Member]]

+
+
+
+ +
+
+message
+

The message that sent this interaction.

+
+
Type
+

Optional[Message]

+
+
+
+ +
+
+token
+

The token to continue the interaction. These are valid +for 15 minutes.

+
+
Type
+

str

+
+
+
+ +
+
+data
+

The raw interaction data.

+
+
Type
+

dict

+
+
+
+ +
+
+property guild
+

The guild the interaction was sent from.

+
+
Type
+

Optional[Guild]

+
+
+
+ +
+
+channel
+

The channel the interaction was sent from.

+

Note that due to a Discord limitation, DM channels are not resolved since there is +no data to complete them. These are PartialMessageable instead.

+
+
Type
+

Optional[Union[abc.GuildChannel, PartialMessageable, Thread]]

+
+
+
+ +
+
+property permissions
+

The resolved permissions of the member in the channel, including overwrites.

+

In a non-guild context where this doesn’t apply, an empty permissions object is returned.

+
+
Type
+

Permissions

+
+
+
+ +
+
+response
+

Returns an object responsible for handling responding to the interaction.

+

A response can only be done once. If secondary messages need to be sent, consider using followup +instead.

+
+
Type
+

InteractionResponse

+
+
+
+ +
+
+followup
+

Returns the follow up webhook for follow up interactions.

+
+
Type
+

Webhook

+
+
+
+ +
+
+await original_message()
+

This function is a coroutine.

+

Fetches the original interaction response message associated with the interaction.

+

If the interaction response was InteractionResponse.send_message() then this would +return the message that was sent using that response. Otherwise, this would return +the message that triggered the interaction.

+

Repeated calls to this will return a cached value.

+
+
Raises
+
    +
  • HTTPException – Fetching the original response message failed.

  • +
  • ClientException – The channel for the message could not be resolved.

  • +
+
+
Returns
+

The original interaction response message.

+
+
Return type
+

InteractionMessage

+
+
+
+ +
+
+await edit_original_message(*, content=..., embeds=..., embed=..., file=..., files=..., view=..., allowed_mentions=None)
+

This function is a coroutine.

+

Edits the original interaction response message.

+

This is a lower level interface to InteractionMessage.edit() in case +you do not want to fetch the message and save an HTTP request.

+

This method is also the only way to edit the original message if +the message sent was ephemeral.

+
+
Parameters
+
    +
  • content (Optional[str]) – The content to edit the message with or None to clear it.

  • +
  • embeds (List[Embed]) – A list of embeds to edit the message with.

  • +
  • embed (Optional[Embed]) – The embed to edit the message with. None suppresses the embeds. +This should not be mixed with the embeds parameter.

  • +
  • file (File) – The file to upload. This cannot be mixed with files parameter.

  • +
  • files (List[File]) – A list of files to send with the content. This cannot be mixed with the +file parameter.

  • +
  • allowed_mentions (AllowedMentions) – Controls the mentions being processed in this message. +See abc.Messageable.send() for more information.

  • +
  • view (Optional[View]) – The updated view to update this message with. If None is passed then +the view is removed.

  • +
+
+
Raises
+
    +
  • HTTPException – Editing the message failed.

  • +
  • Forbidden – Edited a message that is not yours.

  • +
  • TypeError – You specified both embed and embeds or file and files

  • +
  • ValueError – The length of embeds was invalid.

  • +
+
+
Returns
+

The newly edited message.

+
+
Return type
+

InteractionMessage

+
+
+
+ +
+
+await delete_original_message()
+

This function is a coroutine.

+

Deletes the original interaction response message.

+

This is a lower level interface to InteractionMessage.delete() in case +you do not want to fetch the message and save an HTTP request.

+
+
Raises
+
+
+
+
+ +
+ +
+
+

InteractionResponse

+
+ +Methods +
+
+class discord.InteractionResponse
+

Represents a Discord interaction response.

+

This type can be accessed through Interaction.response.

+
+

New in version 2.0.

+
+
+
+is_done()
+

bool: Indicates whether an interaction response has been done before.

+

An interaction can only be responded to once.

+
+ +
+
+await defer(*, ephemeral=False)
+

This function is a coroutine.

+

Defers the interaction response.

+

This is typically used when the interaction is acknowledged +and a secondary action will be done later.

+
+
Parameters
+

ephemeral (bool) – Indicates whether the deferred message will eventually be ephemeral. +This only applies for interactions of type InteractionType.application_command.

+
+
Raises
+
+
+
+
+ +
+
+await pong()
+

This function is a coroutine.

+

Pongs the ping interaction.

+

This should rarely be used.

+
+
Raises
+
+
+
+
+ +
+
+await send_message(content=None, *, embed=..., embeds=..., view=..., tts=False, ephemeral=False)
+

This function is a coroutine.

+

Responds to this interaction by sending a message.

+
+
Parameters
+
    +
  • content (Optional[str]) – The content of the message to send.

  • +
  • embeds (List[Embed]) – A list of embeds to send with the content. Maximum of 10. This cannot +be mixed with the embed parameter.

  • +
  • embed (Embed) – The rich embed for the content to send. This cannot be mixed with +embeds parameter.

  • +
  • tts (bool) – Indicates if the message should be sent using text-to-speech.

  • +
  • view (discord.ui.View) – The view to send with the message.

  • +
  • ephemeral (bool) – Indicates if the message should only be visible to the user who started the interaction. +If a view is sent with an ephemeral message and it has no timeout set then the timeout +is set to 15 minutes.

  • +
+
+
Raises
+
+
+
+
+ +
+
+await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=...)
+

This function is a coroutine.

+

Responds to this interaction by editing the original message of +a component interaction.

+
+
Parameters
+
    +
  • content (Optional[str]) – The new content to replace the message with. None removes the content.

  • +
  • embeds (List[Embed]) – A list of embeds to edit the message with.

  • +
  • embed (Optional[Embed]) – The embed to edit the message with. None suppresses the embeds. +This should not be mixed with the embeds parameter.

  • +
  • attachments (List[Attachment]) – A list of attachments to keep in the message. If [] is passed +then all attachments are removed.

  • +
  • view (Optional[View]) – The updated view to update this message with. If None is passed then +the view is removed.

  • +
+
+
Raises
+
+
+
+
+ +
+ +
+
+

InteractionMessage

+
+ +Methods +
+
+class discord.InteractionMessage
+

Represents the original interaction response message.

+

This allows you to edit or delete the message associated with +the interaction response. To retrieve this object see Interaction.original_message().

+

This inherits from discord.Message with changes to +edit() and delete() to work.

+
+

New in version 2.0.

+
+
+
+await edit(content=..., embeds=..., embed=..., file=..., files=..., view=..., allowed_mentions=None)
+

This function is a coroutine.

+

Edits the message.

+
+
Parameters
+
    +
  • content (Optional[str]) – The content to edit the message with or None to clear it.

  • +
  • embeds (List[Embed]) – A list of embeds to edit the message with.

  • +
  • embed (Optional[Embed]) – The embed to edit the message with. None suppresses the embeds. +This should not be mixed with the embeds parameter.

  • +
  • file (File) – The file to upload. This cannot be mixed with files parameter.

  • +
  • files (List[File]) – A list of files to send with the content. This cannot be mixed with the +file parameter.

  • +
  • allowed_mentions (AllowedMentions) – Controls the mentions being processed in this message. +See abc.Messageable.send() for more information.

  • +
  • view (Optional[View]) – The updated view to update this message with. If None is passed then +the view is removed.

  • +
+
+
Raises
+
    +
  • HTTPException – Editing the message failed.

  • +
  • Forbidden – Edited a message that is not yours.

  • +
  • TypeError – You specified both embed and embeds or file and files

  • +
  • ValueError – The length of embeds was invalid.

  • +
+
+
Returns
+

The newly edited message.

+
+
Return type
+

InteractionMessage

+
+
+
+ +
+
+await delete(*, delay=None)
+

This function is a coroutine.

+

Deletes the message.

+
+
Parameters
+

delay (Optional[float]) – If provided, the number of seconds to wait before deleting the message. +The waiting is done in the background and deletion failures are ignored.

+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to delete the message.

  • +
  • NotFound – The message was deleted already.

  • +
  • HTTPException – Deleting the message failed.

  • +
+
+
+
+ +
+ +
+
+

Member

+
+
+class discord.Member
+

Represents a Discord member to a Guild.

+

This implements a lot of the functionality of User.

+
+
+
+x == y
+

Checks if two members are equal. +Note that this works with User instances too.

+
+ +
+
+x != y
+

Checks if two members are not equal. +Note that this works with User instances too.

+
+ +
+
+hash(x)
+

Returns the member’s hash.

+
+ +
+
+str(x)
+

Returns the member’s name with the discriminator.

+
+ +
+
+int(x)
+

Returns the user’s ID.

+
+ +
+
+
+joined_at
+

An aware datetime object that specifies the date and time in UTC that the member joined the guild. +If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.

+
+
Type
+

Optional[datetime.datetime]

+
+
+
+ +
+
+activities
+

The activities that the user is currently doing.

+
+

Note

+

Due to a Discord API limitation, a user’s Spotify activity may not appear +if they are listening to a song with a title longer +than 128 characters. See GH-1738 for more information.

+
+
+
Type
+

Tuple[Union[BaseActivity, Spotify]]

+
+
+
+ +
+
+guild
+

The guild that the member belongs to.

+
+
Type
+

Guild

+
+
+
+ +
+
+nick
+

The guild specific nickname of the user.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+pending
+

Whether the member is pending member verification.

+
+

New in version 1.6.

+
+
+
Type
+

bool

+
+
+
+ +
+
+premium_since
+

An aware datetime object that specifies the date and time in UTC when the member used their +“Nitro boost” on the guild, if available. This could be None.

+
+
Type
+

Optional[datetime.datetime]

+
+
+
+ +
+
+async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
+

Returns an AsyncIterator that enables receiving the destination’s message history.

+

You must have read_message_history permissions to use this.

+

Examples

+

Usage

+
counter = 0
+async for message in channel.history(limit=200):
+    if message.author == client.user:
+        counter += 1
+
+
+

Flattening into a list:

+
messages = await channel.history(limit=123).flatten()
+# messages is now a list of Message...
+
+
+

All parameters are optional.

+
+
Parameters
+
    +
  • limit (Optional[int]) – The number of messages to retrieve. +If None, retrieves every message in the channel. Note, however, +that this would make it a slow operation.

  • +
  • before (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • after (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • around (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time. +When using this argument, the maximum limit is 101. Note that if the limit is an +even number then this will return at most limit + 1 messages.

  • +
  • oldest_first (Optional[bool]) – If set to True, return messages in oldest->newest order. Defaults to True if +after is specified, otherwise False.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to get channel message history.

  • +
  • HTTPException – The request to get message history failed.

  • +
+
+
Yields
+

Message – The message with the message data parsed.

+
+
+
+ +
+
+async with typing()
+

Returns a context manager that allows you to type for an indefinite period of time.

+

This is useful for denoting long computations in your bot.

+
+

Note

+

This is both a regular context manager and an async context manager. +This means that both with and async with work with this.

+
+

Example Usage:

+
async with channel.typing():
+    # simulate something heavy
+    await asyncio.sleep(10)
+
+await channel.send('done!')
+
+
+
+ +
+
+property name
+

Equivalent to User.name

+
+ +
+
+property id
+

Equivalent to User.id

+
+ +
+
+property discriminator
+

Equivalent to User.discriminator

+
+ +
+
+property bot
+

Equivalent to User.bot

+
+ +
+
+property system
+

Equivalent to User.system

+
+ +
+
+property created_at
+

Equivalent to User.created_at

+
+ +
+
+property default_avatar
+

Equivalent to User.default_avatar

+
+ +
+
+property avatar
+

Equivalent to User.avatar

+
+ +
+
+property dm_channel
+

Equivalent to User.dm_channel

+
+ +
+
+await create_dm()
+

This function is a coroutine.

+

Creates a DMChannel with this user.

+

This should be rarely called, as this is done transparently for most +people.

+
+
Returns
+

The channel that was created.

+
+
Return type
+

DMChannel

+
+
+
+ +
+
+property mutual_guilds
+

Equivalent to User.mutual_guilds

+
+ +
+
+property public_flags
+

Equivalent to User.public_flags

+
+ +
+
+property banner
+

Equivalent to User.banner

+
+ +
+
+property accent_color
+

Equivalent to User.accent_color

+
+ +
+
+property accent_colour
+

Equivalent to User.accent_colour

+
+ +
+
+property raw_status
+

The member’s overall status as a string value.

+
+

New in version 1.5.

+
+
+
Type
+

str

+
+
+
+ +
+
+property status
+

The member’s overall status. If the value is unknown, then it will be a str instead.

+
+
Type
+

Status

+
+
+
+ +
+
+property mobile_status
+

The member’s status on a mobile device, if applicable.

+
+
Type
+

Status

+
+
+
+ +
+
+property desktop_status
+

The member’s status on the desktop client, if applicable.

+
+
Type
+

Status

+
+
+
+ +
+
+property web_status
+

The member’s status on the web client, if applicable.

+
+
Type
+

Status

+
+
+
+ +
+
+is_on_mobile()
+

bool: A helper function that determines if a member is active on a mobile device.

+
+ +
+
+property colour
+

A property that returns a colour denoting the rendered colour +for the member. If the default colour is the one rendered then an instance +of Colour.default() is returned.

+

There is an alias for this named color.

+
+
Type
+

Colour

+
+
+
+ +
+
+property color
+

A property that returns a color denoting the rendered color for +the member. If the default color is the one rendered then an instance of Colour.default() +is returned.

+

There is an alias for this named colour.

+
+
Type
+

Colour

+
+
+
+ +
+
+property roles
+

A list of Role that the member belongs to. Note +that the first element of this list is always the default @everyone’ +role.

+

These roles are sorted by their position in the role hierarchy.

+
+
Type
+

List[Role]

+
+
+
+ +
+
+property mention
+

Returns a string that allows you to mention the member.

+
+
Type
+

str

+
+
+
+ +
+
+property display_name
+

Returns the user’s display name.

+

For regular users this is just their username, but +if they have a guild specific nickname then that +is returned instead.

+
+
Type
+

str

+
+
+
+ +
+
+property display_avatar
+

Returns the member’s display avatar.

+

For regular members this is just their avatar, but +if they have a guild specific avatar then that +is returned instead.

+
+

New in version 2.0.

+
+
+
Type
+

Asset

+
+
+
+ +
+
+property guild_avatar
+

Returns an Asset for the guild avatar +the member has. If unavailable, None is returned.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[Asset]

+
+
+
+ +
+
+property activity
+

Returns the primary +activity the user is currently doing. Could be None if no activity is being done.

+
+

Note

+

Due to a Discord API limitation, this may be None if +the user is listening to a song on Spotify with a title longer +than 128 characters. See GH-1738 for more information.

+
+
+

Note

+

A user may have multiple activities, these can be accessed under activities.

+
+
+
Type
+

Optional[Union[BaseActivity, Spotify]]

+
+
+
+ +
+
+mentioned_in(message)
+

Checks if the member is mentioned in the specified message.

+
+
Parameters
+

message (Message) – The message to check if you’re mentioned in.

+
+
Returns
+

Indicates if the member is mentioned in the message.

+
+
Return type
+

bool

+
+
+
+ +
+
+property top_role
+

Returns the member’s highest role.

+

This is useful for figuring where a member stands in the role +hierarchy chain.

+
+
Type
+

Role

+
+
+
+ +
+
+property guild_permissions
+

Returns the member’s guild permissions.

+

This only takes into consideration the guild permissions +and not most of the implied permissions or any of the +channel permission overwrites. For 100% accurate permission +calculation, please use abc.GuildChannel.permissions_for().

+

This does take into consideration guild ownership and the +administrator implication.

+
+
Type
+

Permissions

+
+
+
+ +
+
+property voice
+

Returns the member’s current voice state.

+
+
Type
+

Optional[VoiceState]

+
+
+
+ +
+
+await ban(*, delete_message_days=1, reason=None)
+

This function is a coroutine.

+

Bans this member. Equivalent to Guild.ban().

+
+ +
+
+await unban(*, reason=None)
+

This function is a coroutine.

+

Unbans this member. Equivalent to Guild.unban().

+
+ +
+
+await kick(*, reason=None)
+

This function is a coroutine.

+

Kicks this member. Equivalent to Guild.kick().

+
+ +
+
+await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., reason=None)
+

This function is a coroutine.

+

Edits the member’s data.

+

Depending on the parameter passed, this requires different permissions listed below:

+
++++ + + + + + + + + + + + + + + + + + + + + +

Parameter

Permission

nick

Permissions.manage_nicknames

mute

Permissions.mute_members

deafen

Permissions.deafen_members

roles

Permissions.manage_roles

voice_channel

Permissions.move_members

+

All parameters are optional.

+
+

Changed in version 1.1: Can now pass None to voice_channel to kick a member from voice.

+
+
+

Changed in version 2.0: The newly member is now optionally returned, if applicable.

+
+
+
Parameters
+
    +
  • nick (Optional[str]) – The member’s new nickname. Use None to remove the nickname.

  • +
  • mute (bool) – Indicates if the member should be guild muted or un-muted.

  • +
  • deafen (bool) – Indicates if the member should be guild deafened or un-deafened.

  • +
  • suppress (bool) –

    Indicates if the member should be suppressed in stage channels.

    +
    +

    New in version 1.7.

    +
    +

  • +
  • roles (List[Role]) – The member’s new list of roles. This replaces the roles.

  • +
  • voice_channel (Optional[VoiceChannel]) – The voice channel to move the member to. +Pass None to kick them from voice.

  • +
  • reason (Optional[str]) – The reason for editing this member. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have the proper permissions to the action requested.

  • +
  • HTTPException – The operation failed.

  • +
+
+
Returns
+

The newly updated member, if applicable. This is only returned +when certain fields are updated.

+
+
Return type
+

Optional[Member]

+
+
+
+ +
+
+await request_to_speak()
+

This function is a coroutine.

+

Request to speak in the connected channel.

+

Only applies to stage channels.

+
+

Note

+

Requesting members that are not the client is equivalent +to edit providing suppress as False.

+
+
+

New in version 1.7.

+
+
+
Raises
+
    +
  • Forbidden – You do not have the proper permissions to the action requested.

  • +
  • HTTPException – The operation failed.

  • +
+
+
+
+ +
+
+await move_to(channel, *, reason=None)
+

This function is a coroutine.

+

Moves a member to a new voice channel (they must be connected first).

+

You must have the move_members permission to +use this.

+

This raises the same exceptions as edit().

+
+

Changed in version 1.1: Can now pass None to kick a member from voice.

+
+
+
Parameters
+
    +
  • channel (Optional[VoiceChannel]) – The new voice channel to move the member to. +Pass None to kick them from voice.

  • +
  • reason (Optional[str]) – The reason for doing this action. Shows up on the audit log.

  • +
+
+
+
+ +
+
+await add_roles(*roles, reason=None, atomic=True)
+

This function is a coroutine.

+

Gives the member a number of Roles.

+

You must have the manage_roles permission to +use this, and the added Roles must appear lower in the list +of roles than the highest role of the member.

+
+
Parameters
+
    +
  • *roles (abc.Snowflake) – An argument list of abc.Snowflake representing a Role +to give to the member.

  • +
  • reason (Optional[str]) – The reason for adding these roles. Shows up on the audit log.

  • +
  • atomic (bool) – Whether to atomically add roles. This will ensure that multiple +operations will always be applied regardless of the current +state of the cache.

  • +
+
+
Raises
+
+
+
+
+ +
+
+await fetch_message(id, /)
+

This function is a coroutine.

+

Retrieves a single Message from the destination.

+
+
Parameters
+

id (int) – The message ID to look for.

+
+
Raises
+
    +
  • NotFound – The specified message was not found.

  • +
  • Forbidden – You do not have the permissions required to get a message.

  • +
  • HTTPException – Retrieving the message failed.

  • +
+
+
Returns
+

The message asked for.

+
+
Return type
+

Message

+
+
+
+ +
+
+await pins()
+

This function is a coroutine.

+

Retrieves all messages that are currently pinned in the channel.

+
+

Note

+

Due to a limitation with the Discord API, the Message +objects returned by this method do not contain complete +Message.reactions data.

+
+
+
Raises
+

HTTPException – Retrieving the pinned messages failed.

+
+
Returns
+

The messages that are currently pinned.

+
+
Return type
+

List[Message]

+
+
+
+ +
+
+await remove_roles(*roles, reason=None, atomic=True)
+

This function is a coroutine.

+

Removes Roles from this member.

+

You must have the manage_roles permission to +use this, and the removed Roles must appear lower in the list +of roles than the highest role of the member.

+
+
Parameters
+
    +
  • *roles (abc.Snowflake) – An argument list of abc.Snowflake representing a Role +to remove from the member.

  • +
  • reason (Optional[str]) – The reason for removing these roles. Shows up on the audit log.

  • +
  • atomic (bool) – Whether to atomically remove roles. This will ensure that multiple +operations will always be applied regardless of the current +state of the cache.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to remove these roles.

  • +
  • HTTPException – Removing the roles failed.

  • +
+
+
+
+ +
+
+await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)
+

This function is a coroutine.

+

Sends a message to the destination with the content given.

+

The content must be a type that can convert to a string through str(content). +If the content is set to None (the default), then the embed parameter must +be provided.

+

To upload a single file, the file parameter should be used with a +single File object. To upload multiple files, the files +parameter should be used with a list of File objects. +Specifying both parameters will lead to an exception.

+

To upload a single embed, the embed parameter should be used with a +single Embed object. To upload multiple embeds, the embeds +parameter should be used with a list of Embed objects. +Specifying both parameters will lead to an exception.

+
+
Parameters
+
    +
  • content (Optional[str]) – The content of the message to send.

  • +
  • tts (bool) – Indicates if the message should be sent using text-to-speech.

  • +
  • embed (Embed) – The rich embed for the content.

  • +
  • file (File) – The file to upload.

  • +
  • files (List[File]) – A list of files to upload. Must be a maximum of 10.

  • +
  • nonce (int) – The nonce to use for sending this message. If the message was successfully sent, +then the message will have a nonce with this value.

  • +
  • delete_after (float) – If provided, the number of seconds to wait in the background +before deleting the message we just sent. If the deletion fails, +then it is silently ignored.

  • +
  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is +passed, then the object is merged with allowed_mentions. +The merging behaviour only overrides attributes that have been explicitly passed +to the object, otherwise it uses the attributes set in allowed_mentions. +If no object is passed at all then the defaults given by allowed_mentions +are used instead.

    +
    +

    New in version 1.4.

    +
    +

  • +
  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using +to_reference() or passed directly as a Message. You can control +whether this mentions the author of the referenced message using the replied_user +attribute of allowed_mentions or by setting mention_author.

    +
    +

    New in version 1.6.

    +
    +

  • +
  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    +
    +

    New in version 1.6.

    +
    +

  • +
  • view (discord.ui.View) – A Discord UI View to add to the message.

  • +
  • embeds (List[Embed]) –

    A list of embeds to upload. Must be a maximum of 10.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
+
+
Returns
+

The message that was sent.

+
+
Return type
+

Message

+
+
+
+ +
+
+await trigger_typing()
+

This function is a coroutine.

+

Triggers a typing indicator to the destination.

+

Typing indicator will go away after 10 seconds, or after a message is sent.

+
+ +
+
+get_role(role_id, /)
+

Returns a role with the given ID from roles which the member has.

+
+

New in version 2.0.

+
+
+
Parameters
+

role_id (int) – The ID to search for.

+
+
Returns
+

The role or None if not found in the member’s roles.

+
+
Return type
+

Optional[Role]

+
+
+
+ +
+ +
+
+

Spotify

+
+
+class discord.Spotify
+

Represents a Spotify listening activity from Discord. This is a special case of +Activity that makes it easier to work with the Spotify integration.

+
+
+
+x == y
+

Checks if two activities are equal.

+
+ +
+
+x != y
+

Checks if two activities are not equal.

+
+ +
+
+hash(x)
+

Returns the activity’s hash.

+
+ +
+
+str(x)
+

Returns the string ‘Spotify’.

+
+ +
+
+
+property type
+

Returns the activity’s type. This is for compatibility with Activity.

+

It always returns ActivityType.listening.

+
+
Type
+

ActivityType

+
+
+
+ +
+
+property created_at
+

When the user started listening in UTC.

+
+

New in version 1.3.

+
+
+
Type
+

Optional[datetime.datetime]

+
+
+
+ +
+
+property colour
+

Returns the Spotify integration colour, as a Colour.

+

There is an alias for this named color

+
+
Type
+

Colour

+
+
+
+ +
+
+property color
+

Returns the Spotify integration colour, as a Colour.

+

There is an alias for this named colour

+
+
Type
+

Colour

+
+
+
+ +
+
+property name
+

The activity’s name. This will always return “Spotify”.

+
+
Type
+

str

+
+
+
+ +
+
+property title
+

The title of the song being played.

+
+
Type
+

str

+
+
+
+ +
+
+property artists
+

The artists of the song being played.

+
+
Type
+

List[str]

+
+
+
+ +
+
+property artist
+

The artist of the song being played.

+

This does not attempt to split the artist information into +multiple artists. Useful if there’s only a single artist.

+
+
Type
+

str

+
+
+
+ +
+
+property album
+

The album that the song being played belongs to.

+
+
Type
+

str

+
+
+
+ +
+
+property album_cover_url
+

The album cover image URL from Spotify’s CDN.

+
+
Type
+

str

+
+
+
+ +
+
+property track_id
+

The track ID used by Spotify to identify this song.

+
+
Type
+

str

+
+
+
+ +
+
+property track_url
+

The track URL to listen on Spotify.

+
+

New in version 2.0.

+
+
+
Type
+

str

+
+
+
+ +
+
+property start
+

When the user started playing this song in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+property end
+

When the user will stop playing this song in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+property duration
+

The duration of the song being played.

+
+
Type
+

datetime.timedelta

+
+
+
+ +
+
+property party_id
+

The party ID of the listening party.

+
+
Type
+

str

+
+
+
+ +
+ +
+
+

VoiceState

+
+
+class discord.VoiceState
+

Represents a Discord user’s voice state.

+
+
+deaf
+

Indicates if the user is currently deafened by the guild.

+
+
Type
+

bool

+
+
+
+ +
+
+mute
+

Indicates if the user is currently muted by the guild.

+
+
Type
+

bool

+
+
+
+ +
+
+self_mute
+

Indicates if the user is currently muted by their own accord.

+
+
Type
+

bool

+
+
+
+ +
+
+self_deaf
+

Indicates if the user is currently deafened by their own accord.

+
+
Type
+

bool

+
+
+
+ +
+
+self_stream
+

Indicates if the user is currently streaming via ‘Go Live’ feature.

+
+

New in version 1.3.

+
+
+
Type
+

bool

+
+
+
+ +
+
+self_video
+

Indicates if the user is currently broadcasting video.

+
+
Type
+

bool

+
+
+
+ +
+
+suppress
+

Indicates if the user is suppressed from speaking.

+

Only applies to stage channels.

+
+

New in version 1.7.

+
+
+
Type
+

bool

+
+
+
+ +
+
+requested_to_speak_at
+

An aware datetime object that specifies the date and time in UTC that the member +requested to speak. It will be None if they are not requesting to speak +anymore or have been accepted to speak.

+

Only applicable to stage channels.

+
+

New in version 1.7.

+
+
+
Type
+

Optional[datetime.datetime]

+
+
+
+ +
+
+afk
+

Indicates if the user is currently in the AFK channel in the guild.

+
+
Type
+

bool

+
+
+
+ +
+
+channel
+

The voice channel that the user is currently connected to. None if the user +is not currently in a voice channel.

+
+
Type
+

Optional[Union[VoiceChannel, StageChannel]]

+
+
+
+ +
+ +
+
+

Emoji

+
+ +Methods +
+
+class discord.Emoji
+

Represents a custom emoji.

+

Depending on the way this object was created, some of the attributes can +have a value of None.

+
+
+
+x == y
+

Checks if two emoji are the same.

+
+ +
+
+x != y
+

Checks if two emoji are not the same.

+
+ +
+
+hash(x)
+

Return the emoji’s hash.

+
+ +
+
+iter(x)
+

Returns an iterator of (field, value) pairs. This allows this class +to be used as an iterable in list/dict/etc constructions.

+
+ +
+
+str(x)
+

Returns the emoji rendered for discord.

+
+ +
+
+int(x)
+

Returns the emoji ID.

+
+ +
+
+
+name
+

The name of the emoji.

+
+
Type
+

str

+
+
+
+ +
+
+id
+

The emoji’s ID.

+
+
Type
+

int

+
+
+
+ +
+
+require_colons
+

If colons are required to use this emoji in the client (:PJSalt: vs PJSalt).

+
+
Type
+

bool

+
+
+
+ +
+
+animated
+

Whether an emoji is animated or not.

+
+
Type
+

bool

+
+
+
+ +
+
+managed
+

If this emoji is managed by a Twitch integration.

+
+
Type
+

bool

+
+
+
+ +
+
+guild_id
+

The guild ID the emoji belongs to.

+
+
Type
+

int

+
+
+
+ +
+
+available
+

Whether the emoji is available for use.

+
+
Type
+

bool

+
+
+
+ +
+
+user
+

The user that created the emoji. This can only be retrieved using Guild.fetch_emoji() and +having the manage_emojis permission.

+
+
Type
+

Optional[User]

+
+
+
+ +
+
+property created_at
+

Returns the emoji’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+property url
+

Returns the URL of the emoji.

+
+
Type
+

str

+
+
+
+ +
+
+property roles
+

A list of roles that is allowed to use this emoji.

+

If roles is empty, the emoji is unrestricted.

+
+
Type
+

List[Role]

+
+
+
+ +
+
+property guild
+

The guild this emoji belongs to.

+
+
Type
+

Guild

+
+
+
+ +
+
+is_usable()
+

bool: Whether the bot can use this emoji.

+
+

New in version 1.3.

+
+
+ +
+
+await delete(*, reason=None)
+

This function is a coroutine.

+

Deletes the custom emoji.

+

You must have manage_emojis permission to +do this.

+
+
Parameters
+

reason (Optional[str]) – The reason for deleting this emoji. Shows up on the audit log.

+
+
Raises
+
    +
  • Forbidden – You are not allowed to delete emojis.

  • +
  • HTTPException – An error occurred deleting the emoji.

  • +
+
+
+
+ +
+
+await edit(*, name=..., roles=..., reason=None)
+

This function is a coroutine.

+

Edits the custom emoji.

+

You must have manage_emojis permission to +do this.

+
+

Changed in version 2.0: The newly updated emoji is returned.

+
+
+
Parameters
+
    +
  • name (str) – The new emoji name.

  • +
  • roles (Optional[List[Snowflake]]) – A list of roles that can use this emoji. An empty list can be passed to make it available to everyone.

  • +
  • reason (Optional[str]) – The reason for editing this emoji. Shows up on the audit log.

  • +
+
+
Raises
+
+
+
Returns
+

The newly updated emoji.

+
+
Return type
+

Emoji

+
+
+
+ +
+
+await read()
+

This function is a coroutine.

+

Retrieves the content of this asset as a bytes object.

+
+
Raises
+
+
+
Returns
+

The content of the asset.

+
+
Return type
+

bytes

+
+
+
+ +
+
+await save(fp, *, seek_begin=True)
+

This function is a coroutine.

+

Saves this asset into a file-like object.

+
+
Parameters
+
    +
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this attachment to or the filename +to use. If a filename is passed then a file is created with that +filename and used instead.

  • +
  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is +successfully done.

  • +
+
+
Raises
+
+
+
Returns
+

The number of bytes written.

+
+
Return type
+

int

+
+
+
+ +
+ +
+
+

PartialEmoji

+
+ +Attributes +
+ +Methods +
+
+class discord.PartialEmoji
+

Represents a “partial” emoji.

+

This model will be given in two scenarios:

+ +
+
+
+x == y
+

Checks if two emoji are the same.

+
+ +
+
+x != y
+

Checks if two emoji are not the same.

+
+ +
+
+hash(x)
+

Return the emoji’s hash.

+
+ +
+
+str(x)
+

Returns the emoji rendered for discord.

+
+ +
+
+
+name
+

The custom emoji name, if applicable, or the unicode codepoint +of the non-custom emoji. This can be None if the emoji +got deleted (e.g. removing a reaction with a deleted emoji).

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+animated
+

Whether the emoji is animated or not.

+
+
Type
+

bool

+
+
+
+ +
+
+id
+

The ID of the custom emoji, if applicable.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+classmethod from_str(value)
+

Converts a Discord string representation of an emoji to a PartialEmoji.

+

The formats accepted are:

+
    +
  • a:name:id

  • +
  • <a:name:id>

  • +
  • name:id

  • +
  • <:name:id>

  • +
+

If the format does not match then it is assumed to be a unicode emoji.

+
+

New in version 2.0.

+
+
+
Parameters
+

value (str) – The string representation of an emoji.

+
+
Returns
+

The partial emoji from this string.

+
+
Return type
+

PartialEmoji

+
+
+
+ +
+
+is_custom_emoji()
+

bool: Checks if this is a custom non-Unicode emoji.

+
+ +
+
+is_unicode_emoji()
+

bool: Checks if this is a Unicode emoji.

+
+ +
+
+property created_at
+

Returns the emoji’s creation time in UTC, or None if Unicode emoji.

+
+

New in version 1.6.

+
+
+
Type
+

Optional[datetime.datetime]

+
+
+
+ +
+
+property url
+

Returns the URL of the emoji, if it is custom.

+

If this isn’t a custom emoji then an empty string is returned

+
+
Type
+

str

+
+
+
+ +
+
+await read()
+

This function is a coroutine.

+

Retrieves the content of this asset as a bytes object.

+
+
Raises
+
+
+
Returns
+

The content of the asset.

+
+
Return type
+

bytes

+
+
+
+ +
+
+await save(fp, *, seek_begin=True)
+

This function is a coroutine.

+

Saves this asset into a file-like object.

+
+
Parameters
+
    +
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this attachment to or the filename +to use. If a filename is passed then a file is created with that +filename and used instead.

  • +
  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is +successfully done.

  • +
+
+
Raises
+
+
+
Returns
+

The number of bytes written.

+
+
Return type
+

int

+
+
+
+ +
+ +
+
+

Role

+
+
+class discord.Role
+

Represents a Discord role in a Guild.

+
+
+
+x == y
+

Checks if two roles are equal.

+
+ +
+
+x != y
+

Checks if two roles are not equal.

+
+ +
+
+x > y
+

Checks if a role is higher than another in the hierarchy.

+
+ +
+
+x < y
+

Checks if a role is lower than another in the hierarchy.

+
+ +
+
+x >= y
+

Checks if a role is higher or equal to another in the hierarchy.

+
+ +
+
+x <= y
+

Checks if a role is lower or equal to another in the hierarchy.

+
+ +
+
+hash(x)
+

Return the role’s hash.

+
+ +
+
+str(x)
+

Returns the role’s name.

+
+ +
+
+str(x)
+

Returns the role’s ID.

+
+ +
+
+int(x)
+

Returns the role’s ID.

+
+ +
+
+
+id
+

The ID for the role.

+
+
Type
+

int

+
+
+
+ +
+
+name
+

The name of the role.

+
+
Type
+

str

+
+
+
+ +
+
+guild
+

The guild the role belongs to.

+
+
Type
+

Guild

+
+
+
+ +
+
+hoist
+

Indicates if the role will be displayed separately from other members.

+
+
Type
+

bool

+
+
+
+ +
+
+position
+

The position of the role. This number is usually positive. The bottom +role has a position of 0.

+
+

Warning

+

Multiple roles can have the same position number. As a consequence +of this, comparing via role position is prone to subtle bugs if +checking for role hierarchy. The recommended and correct way to +compare for roles in the hierarchy is using the comparison +operators on the role objects themselves.

+
+
+
Type
+

int

+
+
+
+ +
+
+managed
+

Indicates if the role is managed by the guild through some form of +integrations such as Twitch.

+
+
Type
+

bool

+
+
+
+ +
+
+mentionable
+

Indicates if the role can be mentioned by users.

+
+
Type
+

bool

+
+
+
+ +
+
+tags
+

The role tags associated with this role.

+
+
Type
+

Optional[RoleTags]

+
+
+
+ +
+
+is_default()
+

bool: Checks if the role is the default role.

+
+ +
+
+is_bot_managed()
+

bool: Whether the role is associated with a bot.

+
+

New in version 1.6.

+
+
+ +
+
+is_premium_subscriber()
+

bool: Whether the role is the premium subscriber, AKA “boost”, role for the guild.

+
+

New in version 1.6.

+
+
+ +
+
+is_integration()
+

bool: Whether the role is managed by an integration.

+
+

New in version 1.6.

+
+
+ +
+
+is_assignable()
+

bool: Whether the role is able to be assigned or removed by the bot.

+
+

New in version 2.0.

+
+
+ +
+
+property permissions
+

Returns the role’s permissions.

+
+
Type
+

Permissions

+
+
+
+ +
+
+property colour
+

Returns the role colour. An alias exists under color.

+
+
Type
+

Colour

+
+
+
+ +
+
+property color
+

Returns the role color. An alias exists under colour.

+
+
Type
+

Colour

+
+
+
+ +
+
+property created_at
+

Returns the role’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+property mention
+

Returns a string that allows you to mention a role.

+
+
Type
+

str

+
+
+
+ +
+
+property members
+

Returns all the members with this role.

+
+
Type
+

List[Member]

+
+
+
+ +
+
+await edit(*, name=..., permissions=..., colour=..., color=..., hoist=..., mentionable=..., position=..., reason=...)
+

This function is a coroutine.

+

Edits the role.

+

You must have the manage_roles permission to +use this.

+

All fields are optional.

+
+

Changed in version 1.4: Can now pass int to colour keyword-only parameter.

+
+
+

Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead.

+
+
+
Parameters
+
    +
  • name (str) – The new role name to change to.

  • +
  • permissions (Permissions) – The new permissions to change to.

  • +
  • colour (Union[Colour, int]) – The new colour to change to. (aliased to color as well)

  • +
  • hoist (bool) – Indicates if the role should be shown separately in the member list.

  • +
  • mentionable (bool) – Indicates if the role should be mentionable by others.

  • +
  • position (int) – The new role’s position. This must be below your top role’s +position or it will fail.

  • +
  • reason (Optional[str]) – The reason for editing this role. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to change the role.

  • +
  • HTTPException – Editing the role failed.

  • +
  • InvalidArgument – An invalid position was given or the default + role was asked to be moved.

  • +
+
+
Returns
+

The newly edited role.

+
+
Return type
+

Role

+
+
+
+ +
+
+await delete(*, reason=None)
+

This function is a coroutine.

+

Deletes the role.

+

You must have the manage_roles permission to +use this.

+
+
Parameters
+

reason (Optional[str]) – The reason for deleting this role. Shows up on the audit log.

+
+
Raises
+
    +
  • Forbidden – You do not have permissions to delete the role.

  • +
  • HTTPException – Deleting the role failed.

  • +
+
+
+
+ +
+ +
+
+

RoleTags

+
+ +Attributes +
+ +Methods +
+
+class discord.RoleTags
+

Represents tags on a role.

+

A role tag is a piece of extra information attached to a managed role +that gives it context for the reason the role is managed.

+

While this can be accessed, a useful interface is also provided in the +Role and Guild classes as well.

+
+

New in version 1.6.

+
+
+
+bot_id
+

The bot’s user ID that manages this role.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+integration_id
+

The integration ID that manages the role.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+is_bot_managed()
+

bool: Whether the role is associated with a bot.

+
+ +
+
+is_premium_subscriber()
+

bool: Whether the role is the premium subscriber, AKA “boost”, role for the guild.

+
+ +
+
+is_integration()
+

bool: Whether the role is managed by an integration.

+
+ +
+ +
+
+

PartialMessageable

+
+ +Attributes +
+ +Methods +
+
+class discord.PartialMessageable
+

Represents a partial messageable to aid with working messageable channels when +only a channel ID are present.

+

The only way to construct this class is through Client.get_partial_messageable().

+

Note that this class is trimmed down and has no rich attributes.

+
+

New in version 2.0.

+
+
+
+
+x == y
+

Checks if two partial messageables are equal.

+
+ +
+
+x != y
+

Checks if two partial messageables are not equal.

+
+ +
+
+hash(x)
+

Returns the partial messageable’s hash.

+
+ +
+
+int(x)
+

Returns the messageable’s ID.

+
+ +
+
+
+id
+

The channel ID associated with this partial messageable.

+
+
Type
+

int

+
+
+
+ +
+
+type
+

The channel type associated with this partial messageable, if given.

+
+
Type
+

Optional[ChannelType]

+
+
+
+ +
+
+await fetch_message(id, /)
+

This function is a coroutine.

+

Retrieves a single Message from the destination.

+
+
Parameters
+

id (int) – The message ID to look for.

+
+
Raises
+
    +
  • NotFound – The specified message was not found.

  • +
  • Forbidden – You do not have the permissions required to get a message.

  • +
  • HTTPException – Retrieving the message failed.

  • +
+
+
Returns
+

The message asked for.

+
+
Return type
+

Message

+
+
+
+ +
+
+history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
+

Returns an AsyncIterator that enables receiving the destination’s message history.

+

You must have read_message_history permissions to use this.

+

Examples

+

Usage

+
counter = 0
+async for message in channel.history(limit=200):
+    if message.author == client.user:
+        counter += 1
+
+
+

Flattening into a list:

+
messages = await channel.history(limit=123).flatten()
+# messages is now a list of Message...
+
+
+

All parameters are optional.

+
+
Parameters
+
    +
  • limit (Optional[int]) – The number of messages to retrieve. +If None, retrieves every message in the channel. Note, however, +that this would make it a slow operation.

  • +
  • before (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • after (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • around (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time. +When using this argument, the maximum limit is 101. Note that if the limit is an +even number then this will return at most limit + 1 messages.

  • +
  • oldest_first (Optional[bool]) – If set to True, return messages in oldest->newest order. Defaults to True if +after is specified, otherwise False.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to get channel message history.

  • +
  • HTTPException – The request to get message history failed.

  • +
+
+
Yields
+

Message – The message with the message data parsed.

+
+
+
+ +
+
+await pins()
+

This function is a coroutine.

+

Retrieves all messages that are currently pinned in the channel.

+
+

Note

+

Due to a limitation with the Discord API, the Message +objects returned by this method do not contain complete +Message.reactions data.

+
+
+
Raises
+

HTTPException – Retrieving the pinned messages failed.

+
+
Returns
+

The messages that are currently pinned.

+
+
Return type
+

List[Message]

+
+
+
+ +
+
+await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)
+

This function is a coroutine.

+

Sends a message to the destination with the content given.

+

The content must be a type that can convert to a string through str(content). +If the content is set to None (the default), then the embed parameter must +be provided.

+

To upload a single file, the file parameter should be used with a +single File object. To upload multiple files, the files +parameter should be used with a list of File objects. +Specifying both parameters will lead to an exception.

+

To upload a single embed, the embed parameter should be used with a +single Embed object. To upload multiple embeds, the embeds +parameter should be used with a list of Embed objects. +Specifying both parameters will lead to an exception.

+
+
Parameters
+
    +
  • content (Optional[str]) – The content of the message to send.

  • +
  • tts (bool) – Indicates if the message should be sent using text-to-speech.

  • +
  • embed (Embed) – The rich embed for the content.

  • +
  • file (File) – The file to upload.

  • +
  • files (List[File]) – A list of files to upload. Must be a maximum of 10.

  • +
  • nonce (int) – The nonce to use for sending this message. If the message was successfully sent, +then the message will have a nonce with this value.

  • +
  • delete_after (float) – If provided, the number of seconds to wait in the background +before deleting the message we just sent. If the deletion fails, +then it is silently ignored.

  • +
  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is +passed, then the object is merged with allowed_mentions. +The merging behaviour only overrides attributes that have been explicitly passed +to the object, otherwise it uses the attributes set in allowed_mentions. +If no object is passed at all then the defaults given by allowed_mentions +are used instead.

    +
    +

    New in version 1.4.

    +
    +

  • +
  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using +to_reference() or passed directly as a Message. You can control +whether this mentions the author of the referenced message using the replied_user +attribute of allowed_mentions or by setting mention_author.

    +
    +

    New in version 1.6.

    +
    +

  • +
  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    +
    +

    New in version 1.6.

    +
    +

  • +
  • view (discord.ui.View) – A Discord UI View to add to the message.

  • +
  • embeds (List[Embed]) –

    A list of embeds to upload. Must be a maximum of 10.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
+
+
Returns
+

The message that was sent.

+
+
Return type
+

Message

+
+
+
+ +
+
+await trigger_typing()
+

This function is a coroutine.

+

Triggers a typing indicator to the destination.

+

Typing indicator will go away after 10 seconds, or after a message is sent.

+
+ +
+
+typing()
+

Returns a context manager that allows you to type for an indefinite period of time.

+

This is useful for denoting long computations in your bot.

+
+

Note

+

This is both a regular context manager and an async context manager. +This means that both with and async with work with this.

+
+

Example Usage:

+
async with channel.typing():
+    # simulate something heavy
+    await asyncio.sleep(10)
+
+await channel.send('done!')
+
+
+
+ +
+
+get_partial_message(message_id, /)
+

Creates a PartialMessage from the message ID.

+

This is useful if you want to work with a message and only have its ID without +doing an unnecessary API call.

+
+
Parameters
+

message_id (int) – The message ID to create a partial message for.

+
+
Returns
+

The partial message.

+
+
Return type
+

PartialMessage

+
+
+
+ +
+ +
+
+

TextChannel

+
+
+class discord.TextChannel
+

Represents a Discord guild text channel.

+
+
+
+x == y
+

Checks if two channels are equal.

+
+ +
+
+x != y
+

Checks if two channels are not equal.

+
+ +
+
+hash(x)
+

Returns the channel’s hash.

+
+ +
+
+str(x)
+

Returns the channel’s name.

+
+ +
+
+int(x)
+

Returns the channel’s ID.

+
+ +
+
+
+name
+

The channel name.

+
+
Type
+

str

+
+
+
+ +
+
+guild
+

The guild the channel belongs to.

+
+
Type
+

Guild

+
+
+
+ +
+
+id
+

The channel ID.

+
+
Type
+

int

+
+
+
+ +
+
+category_id
+

The category channel ID this channel belongs to, if applicable.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+topic
+

The channel’s topic. None if it doesn’t exist.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+position
+

The position in the channel list. This is a number that starts at 0. e.g. the +top channel is position 0.

+
+
Type
+

int

+
+
+
+ +
+
+last_message_id
+

The last message ID of the message sent to this channel. It may +not point to an existing or valid message.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+slowmode_delay
+

The number of seconds a member must wait between sending messages +in this channel. A value of 0 denotes that it is disabled. +Bots and users with manage_channels or +manage_messages bypass slowmode.

+
+
Type
+

int

+
+
+
+ +
+
+nsfw
+

If the channel is marked as “not safe for work”.

+
+

Note

+

To check if the channel or the guild of that channel are marked as NSFW, consider is_nsfw() instead.

+
+
+
Type
+

bool

+
+
+
+ +
+
+default_auto_archive_duration
+

The default auto archive duration in minutes for threads created in this channel.

+
+

New in version 2.0.

+
+
+
Type
+

int

+
+
+
+ +
+
+async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
+

Returns an AsyncIterator that enables receiving the destination’s message history.

+

You must have read_message_history permissions to use this.

+

Examples

+

Usage

+
counter = 0
+async for message in channel.history(limit=200):
+    if message.author == client.user:
+        counter += 1
+
+
+

Flattening into a list:

+
messages = await channel.history(limit=123).flatten()
+# messages is now a list of Message...
+
+
+

All parameters are optional.

+
+
Parameters
+
    +
  • limit (Optional[int]) – The number of messages to retrieve. +If None, retrieves every message in the channel. Note, however, +that this would make it a slow operation.

  • +
  • before (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • after (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • around (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time. +When using this argument, the maximum limit is 101. Note that if the limit is an +even number then this will return at most limit + 1 messages.

  • +
  • oldest_first (Optional[bool]) – If set to True, return messages in oldest->newest order. Defaults to True if +after is specified, otherwise False.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to get channel message history.

  • +
  • HTTPException – The request to get message history failed.

  • +
+
+
Yields
+

Message – The message with the message data parsed.

+
+
+
+ +
+
+async with typing()
+

Returns a context manager that allows you to type for an indefinite period of time.

+

This is useful for denoting long computations in your bot.

+
+

Note

+

This is both a regular context manager and an async context manager. +This means that both with and async with work with this.

+
+

Example Usage:

+
async with channel.typing():
+    # simulate something heavy
+    await asyncio.sleep(10)
+
+await channel.send('done!')
+
+
+
+ +
+
+property type
+

The channel’s Discord type.

+
+
Type
+

ChannelType

+
+
+
+ +
+
+permissions_for(obj, /)
+

Handles permission resolution for the Member +or Role.

+

This function takes into consideration the following cases:

+
    +
  • Guild owner

  • +
  • Guild roles

  • +
  • Channel overrides

  • +
  • Member overrides

  • +
+

If a Role is passed, then it checks the permissions +someone with that role would have, which is essentially:

+
    +
  • The default role permissions

  • +
  • The permissions of the role used as a parameter

  • +
  • The default role permission overwrites

  • +
  • The permission overwrites of the role used as a parameter

  • +
+
+

Changed in version 2.0: The object passed in can now be a role object.

+
+
+
Parameters
+

obj (Union[Member, Role]) – The object to resolve permissions for. This could be either +a member or a role. If it’s a role then member overwrites +are not computed.

+
+
Returns
+

The resolved permissions for the member or role.

+
+
Return type
+

Permissions

+
+
+
+ +
+
+property members
+

Returns all members that can see this channel.

+
+
Type
+

List[Member]

+
+
+
+ +
+
+property bots
+

Returns all bots that can see this channel.

+
+
Type
+

List[Member]

+
+
+
+ +
+
+property humans
+

Returns all human members that can see this channel.

+
+
Type
+

List[Member]

+
+
+
+ +
+
+property threads
+

Returns all the threads that you can see.

+
+

New in version 2.0.

+
+
+
Type
+

List[Thread]

+
+
+
+ +
+
+is_nsfw()
+

bool: Checks if the channel is NSFW.

+
+ +
+
+is_news()
+

bool: Checks if the channel is a news channel.

+
+ +
+
+property last_message
+

Fetches the last message from this channel in cache.

+

The message might not be valid or point to an existing message.

+
+

Reliable Fetching

+

For a slightly more reliable method of fetching the +last message, consider using either history() +or fetch_message() with the last_message_id +attribute.

+
+
+
Returns
+

The last message in this channel or None if not found.

+
+
Return type
+

Optional[Message]

+
+
+
+ +
+
+await edit(*, reason=None, **options)
+

This function is a coroutine.

+

Edits the channel.

+

You must have the manage_channels permission to +use this.

+
+

Changed in version 1.3: The overwrites keyword-only parameter was added.

+
+
+

Changed in version 1.4: The type keyword-only parameter was added.

+
+
+

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.

+
+
+
Parameters
+
    +
  • name (str) – The new channel name.

  • +
  • topic (str) – The new channel’s topic.

  • +
  • position (int) – The new channel’s position.

  • +
  • nsfw (bool) – To mark the channel as NSFW or not.

  • +
  • sync_permissions (bool) – Whether to sync permissions with the channel’s new or pre-existing +category. Defaults to False.

  • +
  • category (Optional[CategoryChannel]) – The new category for this channel. Can be None to remove the +category.

  • +
  • slowmode_delay (int) – Specifies the slowmode rate limit for user in this channel, in seconds. +A value of 0 disables slowmode. The maximum value possible is 21600.

  • +
  • type (ChannelType) – Change the type of this text channel. Currently, only conversion between +ChannelType.text and ChannelType.news is supported. This +is only available to guilds that contain NEWS in Guild.features.

  • +
  • reason (Optional[str]) – The reason for editing this channel. Shows up on the audit log.

  • +
  • overwrites (Mapping) – A Mapping of target (either a role or a member) to +PermissionOverwrite to apply to the channel.

  • +
  • default_auto_archive_duration (int) – The new default auto archive duration in minutes for threads created in this channel. +Must be one of 60, 1440, 4320, or 10080.

  • +
+
+
Raises
+
    +
  • InvalidArgument – If position is less than 0 or greater than the number of channels, or if + the permission overwrite information is not in proper form.

  • +
  • Forbidden – You do not have permissions to edit the channel.

  • +
  • HTTPException – Editing the channel failed.

  • +
+
+
Returns
+

The newly edited text channel. If the edit was only positional +then None is returned instead.

+
+
Return type
+

Optional[TextChannel]

+
+
+
+ +
+
+await clone(*, name=None, reason=None)
+

This function is a coroutine.

+

Clones this channel. This creates a channel with the same properties +as this channel.

+

You must have the manage_channels permission to +do this.

+
+

New in version 1.1.

+
+
+
Parameters
+
    +
  • name (Optional[str]) – The name of the new channel. If not provided, defaults to this +channel name.

  • +
  • reason (Optional[str]) – The reason for cloning this channel. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have the proper permissions to create this channel.

  • +
  • HTTPException – Creating the channel failed.

  • +
+
+
Returns
+

The channel that was created.

+
+
Return type
+

abc.GuildChannel

+
+
+
+ +
+
+await delete_messages(messages)
+

This function is a coroutine.

+

Deletes a list of messages. This is similar to Message.delete() +except it bulk deletes multiple messages.

+

As a special case, if the number of messages is 0, then nothing +is done. If the number of messages is 1 then single message +delete is done. If it’s more than two, then bulk delete is used.

+

You cannot bulk delete more than 100 messages or messages that +are older than 14 days old.

+

You must have the manage_messages permission to +use this.

+
+
Parameters
+

messages (Iterable[abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.

+
+
Raises
+
    +
  • ClientException – The number of messages to delete was more than 100.

  • +
  • Forbidden – You do not have proper permissions to delete the messages.

  • +
  • NotFound – If single delete, then the message was already deleted.

  • +
  • HTTPException – Deleting the messages failed.

  • +
+
+
+
+ +
+
+await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)
+

This function is a coroutine.

+

Purges a list of messages that meet the criteria given by the predicate +check. If a check is not provided then all messages are deleted +without discrimination.

+

You must have the manage_messages permission to +delete messages even if they are your own. +The read_message_history permission is +also needed to retrieve message history.

+

Examples

+

Deleting bot’s messages

+
def is_me(m):
+    return m.author == client.user
+
+deleted = await channel.purge(limit=100, check=is_me)
+await channel.send(f'Deleted {len(deleted)} message(s)')
+
+
+
+
Parameters
+
+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to do the actions required.

  • +
  • HTTPException – Purging the messages failed.

  • +
+
+
Returns
+

The list of messages that were deleted.

+
+
Return type
+

List[Message]

+
+
+
+ +
+
+await webhooks()
+

This function is a coroutine.

+

Gets the list of webhooks from this channel.

+

Requires manage_webhooks permissions.

+
+
Raises
+

Forbidden – You don’t have permissions to get the webhooks.

+
+
Returns
+

The webhooks for this channel.

+
+
Return type
+

List[Webhook]

+
+
+
+ +
+
+await create_webhook(*, name, avatar=None, reason=None)
+

This function is a coroutine.

+

Creates a webhook for this channel.

+

Requires manage_webhooks permissions.

+
+

Changed in version 1.1: Added the reason keyword-only parameter.

+
+
+
Parameters
+
    +
  • name (str) – The webhook’s name.

  • +
  • avatar (Optional[bytes]) – A bytes-like object representing the webhook’s default avatar. +This operates similarly to edit().

  • +
  • reason (Optional[str]) – The reason for creating this webhook. Shows up in the audit logs.

  • +
+
+
Raises
+
    +
  • HTTPException – Creating the webhook failed.

  • +
  • Forbidden – You do not have permissions to create a webhook.

  • +
+
+
Returns
+

The created webhook.

+
+
Return type
+

Webhook

+
+
+
+ +
+
+await follow(*, destination, reason=None)
+

Follows a channel using a webhook.

+

Only news channels can be followed.

+
+

Note

+

The webhook returned will not provide a token to do webhook +actions, as Discord does not provide it.

+
+
+

New in version 1.3.

+
+
+
Parameters
+
    +
  • destination (TextChannel) – The channel you would like to follow from.

  • +
  • reason (Optional[str]) –

    The reason for following the channel. Shows up on the destination guild’s audit log.

    +
    +

    New in version 1.4.

    +
    +

  • +
+
+
Raises
+
    +
  • HTTPException – Following the channel failed.

  • +
  • Forbidden – You do not have the permissions to create a webhook.

  • +
+
+
Returns
+

The created webhook.

+
+
Return type
+

Webhook

+
+
+
+ +
+
+get_partial_message(message_id, /)
+

Creates a PartialMessage from the message ID.

+

This is useful if you want to work with a message and only have its ID without +doing an unnecessary API call.

+
+

New in version 1.6.

+
+
+
Parameters
+

message_id (int) – The message ID to create a partial message for.

+
+
Returns
+

The partial message.

+
+
Return type
+

PartialMessage

+
+
+
+ +
+
+get_thread(thread_id, /)
+

Returns a thread with the given ID.

+
+

New in version 2.0.

+
+
+
Parameters
+

thread_id (int) – The ID to search for.

+
+
Returns
+

The returned thread or None if not found.

+
+
Return type
+

Optional[Thread]

+
+
+
+ +
+
+await create_thread(*, name, message=None, auto_archive_duration=..., type=None, reason=None)
+

This function is a coroutine.

+

Creates a thread in this text channel.

+

To create a public thread, you must have create_public_threads. +For a private thread, create_private_threads is needed instead.

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • name (str) – The name of the thread.

  • +
  • message (Optional[abc.Snowflake]) – A snowflake representing the message to create the thread with. +If None is passed then a private thread is created. +Defaults to None.

  • +
  • auto_archive_duration (int) – The duration in minutes before a thread is automatically archived for inactivity. +If not provided, the channel’s default auto archive duration is used.

  • +
  • type (Optional[ChannelType]) – The type of thread to create. If a message is passed then this parameter +is ignored, as a thread created with a message is always a public thread. +By default this creates a private thread if this is None.

  • +
  • reason (str) – The reason for creating a new thread. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to create a thread.

  • +
  • HTTPException – Starting the thread failed.

  • +
+
+
Returns
+

The created thread

+
+
Return type
+

Thread

+
+
+
+ +
+
+archived_threads(*, private=False, joined=False, limit=50, before=None)
+

Returns an AsyncIterator that iterates over all archived threads in the guild.

+

You must have read_message_history to use this. If iterating over private threads +then manage_threads is also required.

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • limit (Optional[bool]) – The number of threads to retrieve. +If None, retrieves every archived thread in the channel. Note, however, +that this would make it a slow operation.

  • +
  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve archived channels before the given date or ID.

  • +
  • private (bool) – Whether to retrieve private archived threads.

  • +
  • joined (bool) – Whether to retrieve private archived threads that you’ve joined. +You cannot set joined to True and private to False.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to get archived threads.

  • +
  • HTTPException – The request to get the archived threads failed.

  • +
+
+
Yields
+

Thread – The archived threads.

+
+
+
+ +
+
+property category
+

The category this channel belongs to.

+

If there is no category then this is None.

+
+
Type
+

Optional[CategoryChannel]

+
+
+
+ +
+
+property changed_roles
+

Returns a list of roles that have been overridden from +their default values in the roles attribute.

+
+
Type
+

List[Role]

+
+
+
+ +
+
+await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)
+

This function is a coroutine.

+

Creates an instant invite from a text or voice channel.

+

You must have the create_instant_invite permission to +do this.

+
+
Parameters
+
    +
  • max_age (int) – How long the invite should last in seconds. If it’s 0 then the invite +doesn’t expire. Defaults to 0.

  • +
  • max_uses (int) – How many uses the invite could be used for. If it’s 0 then there +are unlimited uses. Defaults to 0.

  • +
  • temporary (bool) – Denotes that the invite grants temporary membership +(i.e. they get kicked after they disconnect). Defaults to False.

  • +
  • unique (bool) – Indicates if a unique invite URL should be created. Defaults to True. +If this is set to False then it will return a previously created +invite.

  • +
  • reason (Optional[str]) – The reason for creating this invite. Shows up on the audit log.

  • +
  • target_type (Optional[InviteTarget]) –

    The type of target for the voice channel invite, if any.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • target_user (Optional[User]) –

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • target_application_id:

    Optional[int]: The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
    +
  • HTTPException – Invite creation failed.

  • +
  • NotFound – The channel that was passed is a category or an invalid channel.

  • +
+
+
Returns
+

The invite that was created.

+
+
Return type
+

Invite

+
+
+
+ +
+
+property created_at
+

Returns the channel’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+await delete(*, reason=None)
+

This function is a coroutine.

+

Deletes the channel.

+

You must have manage_channels permission to use this.

+
+
Parameters
+

reason (Optional[str]) – The reason for deleting this channel. +Shows up on the audit log.

+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to delete the channel.

  • +
  • NotFound – The channel was not found or was already deleted.

  • +
  • HTTPException – Deleting the channel failed.

  • +
+
+
+
+ +
+
+await fetch_message(id, /)
+

This function is a coroutine.

+

Retrieves a single Message from the destination.

+
+
Parameters
+

id (int) – The message ID to look for.

+
+
Raises
+
    +
  • NotFound – The specified message was not found.

  • +
  • Forbidden – You do not have the permissions required to get a message.

  • +
  • HTTPException – Retrieving the message failed.

  • +
+
+
Returns
+

The message asked for.

+
+
Return type
+

Message

+
+
+
+ +
+
+await invites()
+

This function is a coroutine.

+

Returns a list of all active instant invites from this channel.

+

You must have manage_channels to get this information.

+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to get the information.

  • +
  • HTTPException – An error occurred while fetching the information.

  • +
+
+
Returns
+

The list of invites that are currently active.

+
+
Return type
+

List[Invite]

+
+
+
+ +
+
+property mention
+

The string that allows you to mention the channel.

+
+
Type
+

str

+
+
+
+ +
+
+await move(**kwargs)
+

This function is a coroutine.

+

A rich interface to help move a channel relative to other channels.

+

If exact position movement is required, edit should be used instead.

+

You must have the manage_channels permission to +do this.

+
+

Note

+

Voice channels will always be sorted below text channels. +This is a Discord limitation.

+
+
+

New in version 1.7.

+
+
+
Parameters
+
    +
  • beginning (bool) – Whether to move the channel to the beginning of the +channel list (or category if given). +This is mutually exclusive with end, before, and after.

  • +
  • end (bool) – Whether to move the channel to the end of the +channel list (or category if given). +This is mutually exclusive with beginning, before, and after.

  • +
  • before (Snowflake) – The channel that should be before our current channel. +This is mutually exclusive with beginning, end, and after.

  • +
  • after (Snowflake) – The channel that should be after our current channel. +This is mutually exclusive with beginning, end, and before.

  • +
  • offset (int) – The number of channels to offset the move by. For example, +an offset of 2 with beginning=True would move +it 2 after the beginning. A positive number moves it below +while a negative number moves it above. Note that this +number is relative and computed after the beginning, +end, before, and after parameters.

  • +
  • category (Optional[Snowflake]) – The category to move this channel under. +If None is given then it moves it out of the category. +This parameter is ignored if moving a category channel.

  • +
  • sync_permissions (bool) – Whether to sync the permissions with the category (if given).

  • +
  • reason (str) – The reason for the move.

  • +
+
+
Raises
+
    +
  • InvalidArgument – An invalid position was given or a bad mix of arguments were passed.

  • +
  • Forbidden – You do not have permissions to move the channel.

  • +
  • HTTPException – Moving the channel failed.

  • +
+
+
+
+ +
+
+property overwrites
+

Returns all of the channel’s overwrites.

+

This is returned as a dictionary where the key contains the target which +can be either a Role or a Member and the value is the +overwrite as a PermissionOverwrite.

+
+
Returns
+

The channel’s permission overwrites.

+
+
Return type
+

Dict[Union[Role, Member], PermissionOverwrite]

+
+
+
+ +
+
+overwrites_for(obj)
+

Returns the channel-specific overwrites for a member or a role.

+
+
Parameters
+

obj (Union[Role, User]) – The role or user denoting +whose overwrite to get.

+
+
Returns
+

The permission overwrites for this object.

+
+
Return type
+

PermissionOverwrite

+
+
+
+ +
+
+property permissions_synced
+

Whether or not the permissions for this channel are synced with the +category it belongs to.

+

If there is no category then this is False.

+
+

New in version 1.3.

+
+
+
Type
+

bool

+
+
+
+ +
+
+await pins()
+

This function is a coroutine.

+

Retrieves all messages that are currently pinned in the channel.

+
+

Note

+

Due to a limitation with the Discord API, the Message +objects returned by this method do not contain complete +Message.reactions data.

+
+
+
Raises
+

HTTPException – Retrieving the pinned messages failed.

+
+
Returns
+

The messages that are currently pinned.

+
+
Return type
+

List[Message]

+
+
+
+ +
+
+await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)
+

This function is a coroutine.

+

Sends a message to the destination with the content given.

+

The content must be a type that can convert to a string through str(content). +If the content is set to None (the default), then the embed parameter must +be provided.

+

To upload a single file, the file parameter should be used with a +single File object. To upload multiple files, the files +parameter should be used with a list of File objects. +Specifying both parameters will lead to an exception.

+

To upload a single embed, the embed parameter should be used with a +single Embed object. To upload multiple embeds, the embeds +parameter should be used with a list of Embed objects. +Specifying both parameters will lead to an exception.

+
+
Parameters
+
    +
  • content (Optional[str]) – The content of the message to send.

  • +
  • tts (bool) – Indicates if the message should be sent using text-to-speech.

  • +
  • embed (Embed) – The rich embed for the content.

  • +
  • file (File) – The file to upload.

  • +
  • files (List[File]) – A list of files to upload. Must be a maximum of 10.

  • +
  • nonce (int) – The nonce to use for sending this message. If the message was successfully sent, +then the message will have a nonce with this value.

  • +
  • delete_after (float) – If provided, the number of seconds to wait in the background +before deleting the message we just sent. If the deletion fails, +then it is silently ignored.

  • +
  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is +passed, then the object is merged with allowed_mentions. +The merging behaviour only overrides attributes that have been explicitly passed +to the object, otherwise it uses the attributes set in allowed_mentions. +If no object is passed at all then the defaults given by allowed_mentions +are used instead.

    +
    +

    New in version 1.4.

    +
    +

  • +
  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using +to_reference() or passed directly as a Message. You can control +whether this mentions the author of the referenced message using the replied_user +attribute of allowed_mentions or by setting mention_author.

    +
    +

    New in version 1.6.

    +
    +

  • +
  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    +
    +

    New in version 1.6.

    +
    +

  • +
  • view (discord.ui.View) – A Discord UI View to add to the message.

  • +
  • embeds (List[Embed]) –

    A list of embeds to upload. Must be a maximum of 10.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
+
+
Returns
+

The message that was sent.

+
+
Return type
+

Message

+
+
+
+ +
+
+await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)
+

This function is a coroutine.

+

Sets the channel specific permission overwrites for a target in the +channel.

+

The target parameter should either be a Member or a +Role that belongs to guild.

+

The overwrite parameter, if given, must either be None or +PermissionOverwrite. For convenience, you can pass in +keyword arguments denoting Permissions attributes. If this is +done, then you cannot mix the keyword arguments with the overwrite +parameter.

+

If the overwrite parameter is None, then the permission +overwrites are deleted.

+

You must have the manage_roles permission to use this.

+
+

Note

+

This method replaces the old overwrites with the ones given.

+
+

Examples

+

Setting allow and deny:

+
await message.channel.set_permissions(message.author, read_messages=True,
+                                                      send_messages=False)
+
+
+

Deleting overwrites

+
await channel.set_permissions(member, overwrite=None)
+
+
+

Using PermissionOverwrite

+
overwrite = discord.PermissionOverwrite()
+overwrite.send_messages = False
+overwrite.read_messages = True
+await channel.set_permissions(member, overwrite=overwrite)
+
+
+
+
Parameters
+
    +
  • target (Union[Member, Role]) – The member or role to overwrite permissions for.

  • +
  • overwrite (Optional[PermissionOverwrite]) – The permissions to allow and deny to the target, or None to +delete the overwrite.

  • +
  • **permissions – A keyword argument list of permissions to set for ease of use. +Cannot be mixed with overwrite.

  • +
  • reason (Optional[str]) – The reason for doing this action. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to edit channel specific permissions.

  • +
  • HTTPException – Editing channel specific permissions failed.

  • +
  • NotFound – The role or member being edited is not part of the guild.

  • +
  • InvalidArgument – The overwrite parameter invalid or the target type was not + Role or Member.

  • +
+
+
+
+ +
+
+await trigger_typing()
+

This function is a coroutine.

+

Triggers a typing indicator to the destination.

+

Typing indicator will go away after 10 seconds, or after a message is sent.

+
+ +
+ +
+
+

Thread

+
+
+class discord.Thread
+

Represents a Discord thread.

+
+
+
+x == y
+

Checks if two threads are equal.

+
+ +
+
+x != y
+

Checks if two threads are not equal.

+
+ +
+
+hash(x)
+

Returns the thread’s hash.

+
+ +
+
+int(x)
+

Returns the thread’s ID.

+
+ +
+
+str(x)
+

Returns the thread’s name.

+
+ +
+
+

New in version 2.0.

+
+
+
+name
+

The thread name.

+
+
Type
+

str

+
+
+
+ +
+
+guild
+

The guild the thread belongs to.

+
+
Type
+

Guild

+
+
+
+ +
+
+id
+

The thread ID.

+
+
Type
+

int

+
+
+
+ +
+
+parent_id
+

The parent TextChannel ID this thread belongs to.

+
+
Type
+

int

+
+
+
+ +
+
+owner_id
+

The user’s ID that created this thread.

+
+
Type
+

int

+
+
+
+ +
+
+last_message_id
+

The last message ID of the message sent to this thread. It may +not point to an existing or valid message.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+slowmode_delay
+

The number of seconds a member must wait between sending messages +in this thread. A value of 0 denotes that it is disabled. +Bots and users with manage_channels or +manage_messages bypass slowmode.

+
+
Type
+

int

+
+
+
+ +
+
+message_count
+

An approximate number of messages in this thread. This caps at 50.

+
+
Type
+

int

+
+
+
+ +
+
+member_count
+

An approximate number of members in this thread. This caps at 50.

+
+
Type
+

int

+
+
+
+ +
+
+me
+

A thread member representing yourself, if you’ve joined the thread. +This could not be available.

+
+
Type
+

Optional[ThreadMember]

+
+
+
+ +
+
+archived
+

Whether the thread is archived.

+
+
Type
+

bool

+
+
+
+ +
+
+locked
+

Whether the thread is locked.

+
+
Type
+

bool

+
+
+
+ +
+
+invitable
+

Whether non-moderators can add other non-moderators to this thread. +This is always True for public threads.

+
+
Type
+

bool

+
+
+
+ +
+
+archiver_id
+

The user’s ID that archived this thread.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+auto_archive_duration
+

The duration in minutes until the thread is automatically archived due to inactivity. +Usually a value of 60, 1440, 4320 and 10080.

+
+
Type
+

int

+
+
+
+ +
+
+archive_timestamp
+

An aware timestamp of when the thread’s archived status was last updated in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
+

Returns an AsyncIterator that enables receiving the destination’s message history.

+

You must have read_message_history permissions to use this.

+

Examples

+

Usage

+
counter = 0
+async for message in channel.history(limit=200):
+    if message.author == client.user:
+        counter += 1
+
+
+

Flattening into a list:

+
messages = await channel.history(limit=123).flatten()
+# messages is now a list of Message...
+
+
+

All parameters are optional.

+
+
Parameters
+
    +
  • limit (Optional[int]) – The number of messages to retrieve. +If None, retrieves every message in the channel. Note, however, +that this would make it a slow operation.

  • +
  • before (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • after (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • around (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time. +When using this argument, the maximum limit is 101. Note that if the limit is an +even number then this will return at most limit + 1 messages.

  • +
  • oldest_first (Optional[bool]) – If set to True, return messages in oldest->newest order. Defaults to True if +after is specified, otherwise False.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to get channel message history.

  • +
  • HTTPException – The request to get message history failed.

  • +
+
+
Yields
+

Message – The message with the message data parsed.

+
+
+
+ +
+
+async with typing()
+

Returns a context manager that allows you to type for an indefinite period of time.

+

This is useful for denoting long computations in your bot.

+
+

Note

+

This is both a regular context manager and an async context manager. +This means that both with and async with work with this.

+
+

Example Usage:

+
async with channel.typing():
+    # simulate something heavy
+    await asyncio.sleep(10)
+
+await channel.send('done!')
+
+
+
+ +
+
+property type
+

The channel’s Discord type.

+
+
Type
+

ChannelType

+
+
+
+ +
+
+property parent
+

The parent channel this thread belongs to.

+
+
Type
+

Optional[TextChannel]

+
+
+
+ +
+
+property owner
+

The member this thread belongs to.

+
+
Type
+

Optional[Member]

+
+
+
+ +
+
+property mention
+

The string that allows you to mention the thread.

+
+
Type
+

str

+
+
+
+ +
+
+property members
+

A list of thread members in this thread.

+

This requires Intents.members to be properly filled. Most of the time however, +this data is not provided by the gateway and a call to fetch_members() is +needed.

+
+
Type
+

List[ThreadMember]

+
+
+
+ +
+
+property last_message
+

Fetches the last message from this channel in cache.

+

The message might not be valid or point to an existing message.

+
+

Reliable Fetching

+

For a slightly more reliable method of fetching the +last message, consider using either history() +or fetch_message() with the last_message_id +attribute.

+
+
+
Returns
+

The last message in this channel or None if not found.

+
+
Return type
+

Optional[Message]

+
+
+
+ +
+
+property category
+

The category channel the parent channel belongs to, if applicable.

+
+
Raises
+

ClientException – The parent channel was not cached and returned None.

+
+
Returns
+

The parent channel’s category.

+
+
Return type
+

Optional[CategoryChannel]

+
+
+
+ +
+
+property category_id
+

The category channel ID the parent channel belongs to, if applicable.

+
+
Raises
+

ClientException – The parent channel was not cached and returned None.

+
+
Returns
+

The parent channel’s category ID.

+
+
Return type
+

Optional[int]

+
+
+
+ +
+
+is_private()
+

bool: Whether the thread is a private thread.

+

A private thread is only viewable by those that have been explicitly +invited or have manage_threads.

+
+ +
+
+is_news()
+

bool: Whether the thread is a news thread.

+

A news thread is a thread that has a parent that is a news channel, +i.e. TextChannel.is_news() is True.

+
+ +
+
+is_nsfw()
+

bool: Whether the thread is NSFW or not.

+

An NSFW thread is a thread that has a parent that is an NSFW channel, +i.e. TextChannel.is_nsfw() is True.

+
+ +
+
+permissions_for(obj, /)
+

Handles permission resolution for the Member +or Role.

+

Since threads do not have their own permissions, they inherit them +from the parent channel. This is a convenience method for +calling permissions_for() on the +parent channel.

+
+
Parameters
+

obj (Union[Member, Role]) – The object to resolve permissions for. This could be either +a member or a role. If it’s a role then member overwrites +are not computed.

+
+
Raises
+

ClientException – The parent channel was not cached and returned None

+
+
Returns
+

The resolved permissions for the member or role.

+
+
Return type
+

Permissions

+
+
+
+ +
+
+await delete_messages(messages)
+

This function is a coroutine.

+

Deletes a list of messages. This is similar to Message.delete() +except it bulk deletes multiple messages.

+

As a special case, if the number of messages is 0, then nothing +is done. If the number of messages is 1 then single message +delete is done. If it’s more than two, then bulk delete is used.

+

You cannot bulk delete more than 100 messages or messages that +are older than 14 days old.

+

You must have the manage_messages permission to +use this.

+

Usable only by bot accounts.

+
+
Parameters
+

messages (Iterable[abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.

+
+
Raises
+
    +
  • ClientException – The number of messages to delete was more than 100.

  • +
  • Forbidden – You do not have proper permissions to delete the messages or + you’re not using a bot account.

  • +
  • NotFound – If single delete, then the message was already deleted.

  • +
  • HTTPException – Deleting the messages failed.

  • +
+
+
+
+ +
+
+await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)
+

This function is a coroutine.

+

Purges a list of messages that meet the criteria given by the predicate +check. If a check is not provided then all messages are deleted +without discrimination.

+

You must have the manage_messages permission to +delete messages even if they are your own (unless you are a user +account). The read_message_history permission is +also needed to retrieve message history.

+

Examples

+

Deleting bot’s messages

+
def is_me(m):
+    return m.author == client.user
+
+deleted = await thread.purge(limit=100, check=is_me)
+await thread.send(f'Deleted {len(deleted)} message(s)')
+
+
+
+
Parameters
+
+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to do the actions required.

  • +
  • HTTPException – Purging the messages failed.

  • +
+
+
Returns
+

The list of messages that were deleted.

+
+
Return type
+

List[Message]

+
+
+
+ +
+
+await edit(*, name=..., archived=..., locked=..., invitable=..., slowmode_delay=..., auto_archive_duration=...)
+

This function is a coroutine.

+

Edits the thread.

+

Editing the thread requires Permissions.manage_threads. The thread +creator can also edit name, archived or auto_archive_duration. +Note that if the thread is locked then only those with Permissions.manage_threads +can unarchive a thread.

+

The thread must be unarchived to be edited.

+
+
Parameters
+
    +
  • name (str) – The new name of the thread.

  • +
  • archived (bool) – Whether to archive the thread or not.

  • +
  • locked (bool) – Whether to lock the thread or not.

  • +
  • invitable (bool) – Whether non-moderators can add other non-moderators to this thread. +Only available for private threads.

  • +
  • auto_archive_duration (int) – The new duration in minutes before a thread is automatically archived for inactivity. +Must be one of 60, 1440, 4320, or 10080.

  • +
  • slowmode_delay (int) – Specifies the slowmode rate limit for user in this thread, in seconds. +A value of 0 disables slowmode. The maximum value possible is 21600.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to edit the thread.

  • +
  • HTTPException – Editing the thread failed.

  • +
+
+
Returns
+

The newly edited thread.

+
+
Return type
+

Thread

+
+
+
+ +
+
+await join()
+

This function is a coroutine.

+

Joins this thread.

+

You must have send_messages_in_threads to join a thread. +If the thread is private, manage_threads is also needed.

+
+
Raises
+
    +
  • Forbidden – You do not have permissions to join the thread.

  • +
  • HTTPException – Joining the thread failed.

  • +
+
+
+
+ +
+
+await leave()
+

This function is a coroutine.

+

Leaves this thread.

+
+
Raises
+

HTTPException – Leaving the thread failed.

+
+
+
+ +
+
+await add_user(user)
+

This function is a coroutine.

+

Adds a user to this thread.

+

You must have send_messages and use_threads +to add a user to a public thread. If the thread is private then send_messages +and either use_private_threads or manage_messages +is required to add a user to the thread.

+
+
Parameters
+

user (abc.Snowflake) – The user to add to the thread.

+
+
Raises
+
    +
  • Forbidden – You do not have permissions to add the user to the thread.

  • +
  • HTTPException – Adding the user to the thread failed.

  • +
+
+
+
+ +
+
+await remove_user(user)
+

This function is a coroutine.

+

Removes a user from this thread.

+

You must have manage_threads or be the creator of the thread to remove a user.

+
+
Parameters
+

user (abc.Snowflake) – The user to add to the thread.

+
+
Raises
+
    +
  • Forbidden – You do not have permissions to remove the user from the thread.

  • +
  • HTTPException – Removing the user from the thread failed.

  • +
+
+
+
+ +
+
+await fetch_members()
+

This function is a coroutine.

+

Retrieves all ThreadMember that are in this thread.

+

This requires Intents.members to get information about members +other than yourself.

+
+
Raises
+

HTTPException – Retrieving the members failed.

+
+
Returns
+

All thread members in the thread.

+
+
Return type
+

List[ThreadMember]

+
+
+
+ +
+
+await delete()
+

This function is a coroutine.

+

Deletes this thread.

+

You must have manage_threads to delete threads.

+
+
Raises
+
    +
  • Forbidden – You do not have permissions to delete this thread.

  • +
  • HTTPException – Deleting the thread failed.

  • +
+
+
+
+ +
+
+get_partial_message(message_id, /)
+

Creates a PartialMessage from the message ID.

+

This is useful if you want to work with a message and only have its ID without +doing an unnecessary API call.

+
+

New in version 2.0.

+
+
+
Parameters
+

message_id (int) – The message ID to create a partial message for.

+
+
Returns
+

The partial message.

+
+
Return type
+

PartialMessage

+
+
+
+ +
+
+await fetch_message(id, /)
+

This function is a coroutine.

+

Retrieves a single Message from the destination.

+
+
Parameters
+

id (int) – The message ID to look for.

+
+
Raises
+
    +
  • NotFound – The specified message was not found.

  • +
  • Forbidden – You do not have the permissions required to get a message.

  • +
  • HTTPException – Retrieving the message failed.

  • +
+
+
Returns
+

The message asked for.

+
+
Return type
+

Message

+
+
+
+ +
+
+await pins()
+

This function is a coroutine.

+

Retrieves all messages that are currently pinned in the channel.

+
+

Note

+

Due to a limitation with the Discord API, the Message +objects returned by this method do not contain complete +Message.reactions data.

+
+
+
Raises
+

HTTPException – Retrieving the pinned messages failed.

+
+
Returns
+

The messages that are currently pinned.

+
+
Return type
+

List[Message]

+
+
+
+ +
+
+await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)
+

This function is a coroutine.

+

Sends a message to the destination with the content given.

+

The content must be a type that can convert to a string through str(content). +If the content is set to None (the default), then the embed parameter must +be provided.

+

To upload a single file, the file parameter should be used with a +single File object. To upload multiple files, the files +parameter should be used with a list of File objects. +Specifying both parameters will lead to an exception.

+

To upload a single embed, the embed parameter should be used with a +single Embed object. To upload multiple embeds, the embeds +parameter should be used with a list of Embed objects. +Specifying both parameters will lead to an exception.

+
+
Parameters
+
    +
  • content (Optional[str]) – The content of the message to send.

  • +
  • tts (bool) – Indicates if the message should be sent using text-to-speech.

  • +
  • embed (Embed) – The rich embed for the content.

  • +
  • file (File) – The file to upload.

  • +
  • files (List[File]) – A list of files to upload. Must be a maximum of 10.

  • +
  • nonce (int) – The nonce to use for sending this message. If the message was successfully sent, +then the message will have a nonce with this value.

  • +
  • delete_after (float) – If provided, the number of seconds to wait in the background +before deleting the message we just sent. If the deletion fails, +then it is silently ignored.

  • +
  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is +passed, then the object is merged with allowed_mentions. +The merging behaviour only overrides attributes that have been explicitly passed +to the object, otherwise it uses the attributes set in allowed_mentions. +If no object is passed at all then the defaults given by allowed_mentions +are used instead.

    +
    +

    New in version 1.4.

    +
    +

  • +
  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using +to_reference() or passed directly as a Message. You can control +whether this mentions the author of the referenced message using the replied_user +attribute of allowed_mentions or by setting mention_author.

    +
    +

    New in version 1.6.

    +
    +

  • +
  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    +
    +

    New in version 1.6.

    +
    +

  • +
  • view (discord.ui.View) – A Discord UI View to add to the message.

  • +
  • embeds (List[Embed]) –

    A list of embeds to upload. Must be a maximum of 10.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
+
+
Returns
+

The message that was sent.

+
+
Return type
+

Message

+
+
+
+ +
+
+await trigger_typing()
+

This function is a coroutine.

+

Triggers a typing indicator to the destination.

+

Typing indicator will go away after 10 seconds, or after a message is sent.

+
+ +
+ +
+
+

ThreadMember

+
+ +Attributes +
+ +Methods +
+
+class discord.ThreadMember
+

Represents a Discord thread member.

+
+
+
+x == y
+

Checks if two thread members are equal.

+
+ +
+
+x != y
+

Checks if two thread members are not equal.

+
+ +
+
+hash(x)
+

Returns the thread member’s hash.

+
+ +
+
+int(x)
+

Returns the thread member’s ID.

+
+ +
+
+str(x)
+

Returns the thread member’s name.

+
+ +
+
+

New in version 2.0.

+
+
+
+id
+

The thread member’s ID.

+
+
Type
+

int

+
+
+
+ +
+
+thread_id
+

The thread’s ID.

+
+
Type
+

int

+
+
+
+ +
+
+joined_at
+

The time the member joined the thread in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+property thread
+

The thread this member belongs to.

+
+
Type
+

Thread

+
+
+
+ +
+
+await fetch_member()
+

This function is a coroutine.

+

Retrieves a Member from the ThreadMember object.

+
+

Note

+

This method is an API call. If you have Intents.members and member cache enabled, consider get_member() instead.

+
+
+
Raises
+
+
+
Returns
+

The member.

+
+
Return type
+

Member

+
+
+
+ +
+
+get_member()
+

Get the Member from cache for the ThreadMember object.

+
+
Returns
+

The member or None if not found.

+
+
Return type
+

Optional[Member]

+
+
+
+ +
+ +
+
+

StoreChannel

+
+ +Methods +
+
+class discord.StoreChannel
+

Represents a Discord guild store channel.

+
+
+
+x == y
+

Checks if two channels are equal.

+
+ +
+
+x != y
+

Checks if two channels are not equal.

+
+ +
+
+hash(x)
+

Returns the channel’s hash.

+
+ +
+
+str(x)
+

Returns the channel’s name.

+
+ +
+
+int(x)
+

Returns the channel’s ID.

+
+ +
+
+
+name
+

The channel name.

+
+
Type
+

str

+
+
+
+ +
+
+guild
+

The guild the channel belongs to.

+
+
Type
+

Guild

+
+
+
+ +
+
+id
+

The channel ID.

+
+
Type
+

int

+
+
+
+ +
+
+category_id
+

The category channel ID this channel belongs to.

+
+
Type
+

int

+
+
+
+ +
+
+position
+

The position in the channel list. This is a number that starts at 0. e.g. the +top channel is position 0.

+
+
Type
+

int

+
+
+
+ +
+
+nsfw
+

If the channel is marked as “not safe for work”.

+
+

Note

+

To check if the channel or the guild of that channel are marked as NSFW, consider is_nsfw() instead.

+
+
+
Type
+

bool

+
+
+
+ +
+
+property type
+

The channel’s Discord type.

+
+
Type
+

ChannelType

+
+
+
+ +
+
+permissions_for(obj, /)
+

Handles permission resolution for the Member +or Role.

+

This function takes into consideration the following cases:

+
    +
  • Guild owner

  • +
  • Guild roles

  • +
  • Channel overrides

  • +
  • Member overrides

  • +
+

If a Role is passed, then it checks the permissions +someone with that role would have, which is essentially:

+
    +
  • The default role permissions

  • +
  • The permissions of the role used as a parameter

  • +
  • The default role permission overwrites

  • +
  • The permission overwrites of the role used as a parameter

  • +
+
+

Changed in version 2.0: The object passed in can now be a role object.

+
+
+
Parameters
+

obj (Union[Member, Role]) – The object to resolve permissions for. This could be either +a member or a role. If it’s a role then member overwrites +are not computed.

+
+
Returns
+

The resolved permissions for the member or role.

+
+
Return type
+

Permissions

+
+
+
+ +
+
+is_nsfw()
+

bool: Checks if the channel is NSFW.

+
+ +
+
+await clone(*, name=None, reason=None)
+

This function is a coroutine.

+

Clones this channel. This creates a channel with the same properties +as this channel.

+

You must have the manage_channels permission to +do this.

+
+

New in version 1.1.

+
+
+
Parameters
+
    +
  • name (Optional[str]) – The name of the new channel. If not provided, defaults to this +channel name.

  • +
  • reason (Optional[str]) – The reason for cloning this channel. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have the proper permissions to create this channel.

  • +
  • HTTPException – Creating the channel failed.

  • +
+
+
Returns
+

The channel that was created.

+
+
Return type
+

abc.GuildChannel

+
+
+
+ +
+
+await edit(*, reason=None, **options)
+

This function is a coroutine.

+

Edits the channel.

+

You must have the manage_channels permission to +use this.

+
+

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.

+
+
+
Parameters
+
    +
  • name (str) – The new channel name.

  • +
  • position (int) – The new channel’s position.

  • +
  • nsfw (bool) – To mark the channel as NSFW or not.

  • +
  • sync_permissions (bool) – Whether to sync permissions with the channel’s new or pre-existing +category. Defaults to False.

  • +
  • category (Optional[CategoryChannel]) – The new category for this channel. Can be None to remove the +category.

  • +
  • reason (Optional[str]) – The reason for editing this channel. Shows up on the audit log.

  • +
  • overwrites (Mapping) –

    A Mapping of target (either a role or a member) to +PermissionOverwrite to apply to the channel.

    +
    +

    New in version 1.3.

    +
    +

  • +
+
+
Raises
+
    +
  • InvalidArgument – If position is less than 0 or greater than the number of channels, or if + the permission overwrite information is not in proper form.

  • +
  • Forbidden – You do not have permissions to edit the channel.

  • +
  • HTTPException – Editing the channel failed.

  • +
+
+
Returns
+

The newly edited store channel. If the edit was only positional +then None is returned instead.

+
+
Return type
+

Optional[StoreChannel]

+
+
+
+ +
+
+property category
+

The category this channel belongs to.

+

If there is no category then this is None.

+
+
Type
+

Optional[CategoryChannel]

+
+
+
+ +
+
+property changed_roles
+

Returns a list of roles that have been overridden from +their default values in the roles attribute.

+
+
Type
+

List[Role]

+
+
+
+ +
+
+await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)
+

This function is a coroutine.

+

Creates an instant invite from a text or voice channel.

+

You must have the create_instant_invite permission to +do this.

+
+
Parameters
+
    +
  • max_age (int) – How long the invite should last in seconds. If it’s 0 then the invite +doesn’t expire. Defaults to 0.

  • +
  • max_uses (int) – How many uses the invite could be used for. If it’s 0 then there +are unlimited uses. Defaults to 0.

  • +
  • temporary (bool) – Denotes that the invite grants temporary membership +(i.e. they get kicked after they disconnect). Defaults to False.

  • +
  • unique (bool) – Indicates if a unique invite URL should be created. Defaults to True. +If this is set to False then it will return a previously created +invite.

  • +
  • reason (Optional[str]) – The reason for creating this invite. Shows up on the audit log.

  • +
  • target_type (Optional[InviteTarget]) –

    The type of target for the voice channel invite, if any.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • target_user (Optional[User]) –

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • target_application_id:

    Optional[int]: The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
    +
  • HTTPException – Invite creation failed.

  • +
  • NotFound – The channel that was passed is a category or an invalid channel.

  • +
+
+
Returns
+

The invite that was created.

+
+
Return type
+

Invite

+
+
+
+ +
+
+property created_at
+

Returns the channel’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+await delete(*, reason=None)
+

This function is a coroutine.

+

Deletes the channel.

+

You must have manage_channels permission to use this.

+
+
Parameters
+

reason (Optional[str]) – The reason for deleting this channel. +Shows up on the audit log.

+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to delete the channel.

  • +
  • NotFound – The channel was not found or was already deleted.

  • +
  • HTTPException – Deleting the channel failed.

  • +
+
+
+
+ +
+
+await invites()
+

This function is a coroutine.

+

Returns a list of all active instant invites from this channel.

+

You must have manage_channels to get this information.

+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to get the information.

  • +
  • HTTPException – An error occurred while fetching the information.

  • +
+
+
Returns
+

The list of invites that are currently active.

+
+
Return type
+

List[Invite]

+
+
+
+ +
+
+property mention
+

The string that allows you to mention the channel.

+
+
Type
+

str

+
+
+
+ +
+
+await move(**kwargs)
+

This function is a coroutine.

+

A rich interface to help move a channel relative to other channels.

+

If exact position movement is required, edit should be used instead.

+

You must have the manage_channels permission to +do this.

+
+

Note

+

Voice channels will always be sorted below text channels. +This is a Discord limitation.

+
+
+

New in version 1.7.

+
+
+
Parameters
+
    +
  • beginning (bool) – Whether to move the channel to the beginning of the +channel list (or category if given). +This is mutually exclusive with end, before, and after.

  • +
  • end (bool) – Whether to move the channel to the end of the +channel list (or category if given). +This is mutually exclusive with beginning, before, and after.

  • +
  • before (Snowflake) – The channel that should be before our current channel. +This is mutually exclusive with beginning, end, and after.

  • +
  • after (Snowflake) – The channel that should be after our current channel. +This is mutually exclusive with beginning, end, and before.

  • +
  • offset (int) – The number of channels to offset the move by. For example, +an offset of 2 with beginning=True would move +it 2 after the beginning. A positive number moves it below +while a negative number moves it above. Note that this +number is relative and computed after the beginning, +end, before, and after parameters.

  • +
  • category (Optional[Snowflake]) – The category to move this channel under. +If None is given then it moves it out of the category. +This parameter is ignored if moving a category channel.

  • +
  • sync_permissions (bool) – Whether to sync the permissions with the category (if given).

  • +
  • reason (str) – The reason for the move.

  • +
+
+
Raises
+
    +
  • InvalidArgument – An invalid position was given or a bad mix of arguments were passed.

  • +
  • Forbidden – You do not have permissions to move the channel.

  • +
  • HTTPException – Moving the channel failed.

  • +
+
+
+
+ +
+
+property overwrites
+

Returns all of the channel’s overwrites.

+

This is returned as a dictionary where the key contains the target which +can be either a Role or a Member and the value is the +overwrite as a PermissionOverwrite.

+
+
Returns
+

The channel’s permission overwrites.

+
+
Return type
+

Dict[Union[Role, Member], PermissionOverwrite]

+
+
+
+ +
+
+overwrites_for(obj)
+

Returns the channel-specific overwrites for a member or a role.

+
+
Parameters
+

obj (Union[Role, User]) – The role or user denoting +whose overwrite to get.

+
+
Returns
+

The permission overwrites for this object.

+
+
Return type
+

PermissionOverwrite

+
+
+
+ +
+
+property permissions_synced
+

Whether or not the permissions for this channel are synced with the +category it belongs to.

+

If there is no category then this is False.

+
+

New in version 1.3.

+
+
+
Type
+

bool

+
+
+
+ +
+
+await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)
+

This function is a coroutine.

+

Sets the channel specific permission overwrites for a target in the +channel.

+

The target parameter should either be a Member or a +Role that belongs to guild.

+

The overwrite parameter, if given, must either be None or +PermissionOverwrite. For convenience, you can pass in +keyword arguments denoting Permissions attributes. If this is +done, then you cannot mix the keyword arguments with the overwrite +parameter.

+

If the overwrite parameter is None, then the permission +overwrites are deleted.

+

You must have the manage_roles permission to use this.

+
+

Note

+

This method replaces the old overwrites with the ones given.

+
+

Examples

+

Setting allow and deny:

+
await message.channel.set_permissions(message.author, read_messages=True,
+                                                      send_messages=False)
+
+
+

Deleting overwrites

+
await channel.set_permissions(member, overwrite=None)
+
+
+

Using PermissionOverwrite

+
overwrite = discord.PermissionOverwrite()
+overwrite.send_messages = False
+overwrite.read_messages = True
+await channel.set_permissions(member, overwrite=overwrite)
+
+
+
+
Parameters
+
    +
  • target (Union[Member, Role]) – The member or role to overwrite permissions for.

  • +
  • overwrite (Optional[PermissionOverwrite]) – The permissions to allow and deny to the target, or None to +delete the overwrite.

  • +
  • **permissions – A keyword argument list of permissions to set for ease of use. +Cannot be mixed with overwrite.

  • +
  • reason (Optional[str]) – The reason for doing this action. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to edit channel specific permissions.

  • +
  • HTTPException – Editing channel specific permissions failed.

  • +
  • NotFound – The role or member being edited is not part of the guild.

  • +
  • InvalidArgument – The overwrite parameter invalid or the target type was not + Role or Member.

  • +
+
+
+
+ +
+ +
+
+

VoiceChannel

+
+
+class discord.VoiceChannel
+

Represents a Discord guild voice channel.

+
+
+
+x == y
+

Checks if two channels are equal.

+
+ +
+
+x != y
+

Checks if two channels are not equal.

+
+ +
+
+hash(x)
+

Returns the channel’s hash.

+
+ +
+
+str(x)
+

Returns the channel’s name.

+
+ +
+
+
+name
+

The channel name.

+
+
Type
+

str

+
+
+
+ +
+
+guild
+

The guild the channel belongs to.

+
+
Type
+

Guild

+
+
+
+ +
+
+id
+

The channel ID.

+
+
Type
+

int

+
+
+
+ +
+
+category_id
+

The category channel ID this channel belongs to, if applicable.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+position
+

The position in the channel list. This is a number that starts at 0. e.g. the +top channel is position 0.

+
+
Type
+

int

+
+
+
+ +
+
+bitrate
+

The channel’s preferred audio bitrate in bits per second.

+
+
Type
+

int

+
+
+
+ +
+
+user_limit
+

The channel’s limit for number of members that can be in a voice channel.

+
+
Type
+

int

+
+
+
+ +
+
+rtc_region
+

The region for the voice channel’s voice communication. +A value of None indicates automatic voice region detection.

+
+

New in version 1.7.

+
+
+
Type
+

Optional[VoiceRegion]

+
+
+
+ +
+
+video_quality_mode
+

The camera video quality for the voice channel’s participants.

+
+

New in version 2.0.

+
+
+
Type
+

VideoQualityMode

+
+
+
+ +
+
+property type
+

The channel’s Discord type.

+
+
Type
+

ChannelType

+
+
+
+ +
+
+await clone(*, name=None, reason=None)
+

This function is a coroutine.

+

Clones this channel. This creates a channel with the same properties +as this channel.

+

You must have the manage_channels permission to +do this.

+
+

New in version 1.1.

+
+
+
Parameters
+
    +
  • name (Optional[str]) – The name of the new channel. If not provided, defaults to this +channel name.

  • +
  • reason (Optional[str]) – The reason for cloning this channel. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have the proper permissions to create this channel.

  • +
  • HTTPException – Creating the channel failed.

  • +
+
+
Returns
+

The channel that was created.

+
+
Return type
+

abc.GuildChannel

+
+
+
+ +
+
+await edit(*, reason=None, **options)
+

This function is a coroutine.

+

Edits the channel.

+

You must have the manage_channels permission to +use this.

+
+

Changed in version 1.3: The overwrites keyword-only parameter was added.

+
+
+

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.

+
+
+
Parameters
+
    +
  • name (str) – The new channel’s name.

  • +
  • bitrate (int) – The new channel’s bitrate.

  • +
  • user_limit (int) – The new channel’s user limit.

  • +
  • position (int) – The new channel’s position.

  • +
  • sync_permissions (bool) – Whether to sync permissions with the channel’s new or pre-existing +category. Defaults to False.

  • +
  • category (Optional[CategoryChannel]) – The new category for this channel. Can be None to remove the +category.

  • +
  • reason (Optional[str]) – The reason for editing this channel. Shows up on the audit log.

  • +
  • overwrites (Mapping) – A Mapping of target (either a role or a member) to +PermissionOverwrite to apply to the channel.

  • +
  • rtc_region (Optional[VoiceRegion]) –

    The new region for the voice channel’s voice communication. +A value of None indicates automatic voice region detection.

    +
    +

    New in version 1.7.

    +
    +

  • +
  • video_quality_mode (VideoQualityMode) –

    The camera video quality for the voice channel’s participants.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
    +
  • InvalidArgument – If the permission overwrite information is not in proper form.

  • +
  • Forbidden – You do not have permissions to edit the channel.

  • +
  • HTTPException – Editing the channel failed.

  • +
+
+
Returns
+

The newly edited voice channel. If the edit was only positional +then None is returned instead.

+
+
Return type
+

Optional[VoiceChannel]

+
+
+
+ +
+
+property category
+

The category this channel belongs to.

+

If there is no category then this is None.

+
+
Type
+

Optional[CategoryChannel]

+
+
+
+ +
+
+property changed_roles
+

Returns a list of roles that have been overridden from +their default values in the roles attribute.

+
+
Type
+

List[Role]

+
+
+
+ +
+
+await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)
+

This function is a coroutine.

+

Connects to voice and creates a VoiceClient to establish +your connection to the voice server.

+

This requires Intents.voice_states.

+
+
Parameters
+
    +
  • timeout (float) – The timeout in seconds to wait for the voice endpoint.

  • +
  • reconnect (bool) – Whether the bot should automatically attempt +a reconnect if a part of the handshake fails +or the gateway goes down.

  • +
  • cls (Type[VoiceProtocol]) – A type that subclasses VoiceProtocol to connect with. +Defaults to VoiceClient.

  • +
+
+
Raises
+
+
+
Returns
+

A voice client that is fully connected to the voice server.

+
+
Return type
+

VoiceProtocol

+
+
+
+ +
+
+await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)
+

This function is a coroutine.

+

Creates an instant invite from a text or voice channel.

+

You must have the create_instant_invite permission to +do this.

+
+
Parameters
+
    +
  • max_age (int) – How long the invite should last in seconds. If it’s 0 then the invite +doesn’t expire. Defaults to 0.

  • +
  • max_uses (int) – How many uses the invite could be used for. If it’s 0 then there +are unlimited uses. Defaults to 0.

  • +
  • temporary (bool) – Denotes that the invite grants temporary membership +(i.e. they get kicked after they disconnect). Defaults to False.

  • +
  • unique (bool) – Indicates if a unique invite URL should be created. Defaults to True. +If this is set to False then it will return a previously created +invite.

  • +
  • reason (Optional[str]) – The reason for creating this invite. Shows up on the audit log.

  • +
  • target_type (Optional[InviteTarget]) –

    The type of target for the voice channel invite, if any.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • target_user (Optional[User]) –

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • target_application_id:

    Optional[int]: The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
    +
  • HTTPException – Invite creation failed.

  • +
  • NotFound – The channel that was passed is a category or an invalid channel.

  • +
+
+
Returns
+

The invite that was created.

+
+
Return type
+

Invite

+
+
+
+ +
+
+property created_at
+

Returns the channel’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+await delete(*, reason=None)
+

This function is a coroutine.

+

Deletes the channel.

+

You must have manage_channels permission to use this.

+
+
Parameters
+

reason (Optional[str]) – The reason for deleting this channel. +Shows up on the audit log.

+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to delete the channel.

  • +
  • NotFound – The channel was not found or was already deleted.

  • +
  • HTTPException – Deleting the channel failed.

  • +
+
+
+
+ +
+
+await invites()
+

This function is a coroutine.

+

Returns a list of all active instant invites from this channel.

+

You must have manage_channels to get this information.

+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to get the information.

  • +
  • HTTPException – An error occurred while fetching the information.

  • +
+
+
Returns
+

The list of invites that are currently active.

+
+
Return type
+

List[Invite]

+
+
+
+ +
+
+property members
+

Returns all members that are currently inside this voice channel.

+
+
Type
+

List[Member]

+
+
+
+ +
+
+property mention
+

The string that allows you to mention the channel.

+
+
Type
+

str

+
+
+
+ +
+
+await move(**kwargs)
+

This function is a coroutine.

+

A rich interface to help move a channel relative to other channels.

+

If exact position movement is required, edit should be used instead.

+

You must have the manage_channels permission to +do this.

+
+

Note

+

Voice channels will always be sorted below text channels. +This is a Discord limitation.

+
+
+

New in version 1.7.

+
+
+
Parameters
+
    +
  • beginning (bool) – Whether to move the channel to the beginning of the +channel list (or category if given). +This is mutually exclusive with end, before, and after.

  • +
  • end (bool) – Whether to move the channel to the end of the +channel list (or category if given). +This is mutually exclusive with beginning, before, and after.

  • +
  • before (Snowflake) – The channel that should be before our current channel. +This is mutually exclusive with beginning, end, and after.

  • +
  • after (Snowflake) – The channel that should be after our current channel. +This is mutually exclusive with beginning, end, and before.

  • +
  • offset (int) – The number of channels to offset the move by. For example, +an offset of 2 with beginning=True would move +it 2 after the beginning. A positive number moves it below +while a negative number moves it above. Note that this +number is relative and computed after the beginning, +end, before, and after parameters.

  • +
  • category (Optional[Snowflake]) – The category to move this channel under. +If None is given then it moves it out of the category. +This parameter is ignored if moving a category channel.

  • +
  • sync_permissions (bool) – Whether to sync the permissions with the category (if given).

  • +
  • reason (str) – The reason for the move.

  • +
+
+
Raises
+
    +
  • InvalidArgument – An invalid position was given or a bad mix of arguments were passed.

  • +
  • Forbidden – You do not have permissions to move the channel.

  • +
  • HTTPException – Moving the channel failed.

  • +
+
+
+
+ +
+
+property overwrites
+

Returns all of the channel’s overwrites.

+

This is returned as a dictionary where the key contains the target which +can be either a Role or a Member and the value is the +overwrite as a PermissionOverwrite.

+
+
Returns
+

The channel’s permission overwrites.

+
+
Return type
+

Dict[Union[Role, Member], PermissionOverwrite]

+
+
+
+ +
+
+overwrites_for(obj)
+

Returns the channel-specific overwrites for a member or a role.

+
+
Parameters
+

obj (Union[Role, User]) – The role or user denoting +whose overwrite to get.

+
+
Returns
+

The permission overwrites for this object.

+
+
Return type
+

PermissionOverwrite

+
+
+
+ +
+
+permissions_for(obj, /)
+

Handles permission resolution for the Member +or Role.

+

This function takes into consideration the following cases:

+
    +
  • Guild owner

  • +
  • Guild roles

  • +
  • Channel overrides

  • +
  • Member overrides

  • +
+

If a Role is passed, then it checks the permissions +someone with that role would have, which is essentially:

+
    +
  • The default role permissions

  • +
  • The permissions of the role used as a parameter

  • +
  • The default role permission overwrites

  • +
  • The permission overwrites of the role used as a parameter

  • +
+
+

Changed in version 2.0: The object passed in can now be a role object.

+
+
+
Parameters
+

obj (Union[Member, Role]) – The object to resolve permissions for. This could be either +a member or a role. If it’s a role then member overwrites +are not computed.

+
+
Returns
+

The resolved permissions for the member or role.

+
+
Return type
+

Permissions

+
+
+
+ +
+
+property permissions_synced
+

Whether or not the permissions for this channel are synced with the +category it belongs to.

+

If there is no category then this is False.

+
+

New in version 1.3.

+
+
+
Type
+

bool

+
+
+
+ +
+
+await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)
+

This function is a coroutine.

+

Sets the channel specific permission overwrites for a target in the +channel.

+

The target parameter should either be a Member or a +Role that belongs to guild.

+

The overwrite parameter, if given, must either be None or +PermissionOverwrite. For convenience, you can pass in +keyword arguments denoting Permissions attributes. If this is +done, then you cannot mix the keyword arguments with the overwrite +parameter.

+

If the overwrite parameter is None, then the permission +overwrites are deleted.

+

You must have the manage_roles permission to use this.

+
+

Note

+

This method replaces the old overwrites with the ones given.

+
+

Examples

+

Setting allow and deny:

+
await message.channel.set_permissions(message.author, read_messages=True,
+                                                      send_messages=False)
+
+
+

Deleting overwrites

+
await channel.set_permissions(member, overwrite=None)
+
+
+

Using PermissionOverwrite

+
overwrite = discord.PermissionOverwrite()
+overwrite.send_messages = False
+overwrite.read_messages = True
+await channel.set_permissions(member, overwrite=overwrite)
+
+
+
+
Parameters
+
    +
  • target (Union[Member, Role]) – The member or role to overwrite permissions for.

  • +
  • overwrite (Optional[PermissionOverwrite]) – The permissions to allow and deny to the target, or None to +delete the overwrite.

  • +
  • **permissions – A keyword argument list of permissions to set for ease of use. +Cannot be mixed with overwrite.

  • +
  • reason (Optional[str]) – The reason for doing this action. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to edit channel specific permissions.

  • +
  • HTTPException – Editing channel specific permissions failed.

  • +
  • NotFound – The role or member being edited is not part of the guild.

  • +
  • InvalidArgument – The overwrite parameter invalid or the target type was not + Role or Member.

  • +
+
+
+
+ +
+
+property voice_states
+

Returns a mapping of member IDs who have voice states in this channel.

+
+

New in version 1.3.

+
+
+

Note

+

This function is intentionally low level to replace members +when the member cache is unavailable.

+
+
+
Returns
+

The mapping of member ID to a voice state.

+
+
Return type
+

Mapping[int, VoiceState]

+
+
+
+ +
+ +
+
+

StageChannel

+
+
+class discord.StageChannel
+

Represents a Discord guild stage channel.

+
+

New in version 1.7.

+
+
+
+
+x == y
+

Checks if two channels are equal.

+
+ +
+
+x != y
+

Checks if two channels are not equal.

+
+ +
+
+hash(x)
+

Returns the channel’s hash.

+
+ +
+
+str(x)
+

Returns the channel’s name.

+
+ +
+
+
+name
+

The channel name.

+
+
Type
+

str

+
+
+
+ +
+
+guild
+

The guild the channel belongs to.

+
+
Type
+

Guild

+
+
+
+ +
+
+id
+

The channel ID.

+
+
Type
+

int

+
+
+
+ +
+
+topic
+

The channel’s topic. None if it isn’t set.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+category_id
+

The category channel ID this channel belongs to, if applicable.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+position
+

The position in the channel list. This is a number that starts at 0. e.g. the +top channel is position 0.

+
+
Type
+

int

+
+
+
+ +
+
+bitrate
+

The channel’s preferred audio bitrate in bits per second.

+
+
Type
+

int

+
+
+
+ +
+
+user_limit
+

The channel’s limit for number of members that can be in a stage channel.

+
+
Type
+

int

+
+
+
+ +
+
+rtc_region
+

The region for the stage channel’s voice communication. +A value of None indicates automatic voice region detection.

+
+
Type
+

Optional[VoiceRegion]

+
+
+
+ +
+
+video_quality_mode
+

The camera video quality for the stage channel’s participants.

+
+

New in version 2.0.

+
+
+
Type
+

VideoQualityMode

+
+
+
+ +
+
+property requesting_to_speak
+

A list of members who are requesting to speak in the stage channel.

+
+
Type
+

List[Member]

+
+
+
+ +
+
+property speakers
+

A list of members who have been permitted to speak in the stage channel.

+
+

New in version 2.0.

+
+
+
Type
+

List[Member]

+
+
+
+ +
+
+property listeners
+

A list of members who are listening in the stage channel.

+
+

New in version 2.0.

+
+
+
Type
+

List[Member]

+
+
+
+ +
+
+property moderators
+

A list of members who are moderating the stage channel.

+
+

New in version 2.0.

+
+
+
Type
+

List[Member]

+
+
+
+ +
+
+property type
+

The channel’s Discord type.

+
+
Type
+

ChannelType

+
+
+
+ +
+
+await clone(*, name=None, reason=None)
+

This function is a coroutine.

+

Clones this channel. This creates a channel with the same properties +as this channel.

+

You must have the manage_channels permission to +do this.

+
+

New in version 1.1.

+
+
+
Parameters
+
    +
  • name (Optional[str]) – The name of the new channel. If not provided, defaults to this +channel name.

  • +
  • reason (Optional[str]) – The reason for cloning this channel. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have the proper permissions to create this channel.

  • +
  • HTTPException – Creating the channel failed.

  • +
+
+
Returns
+

The channel that was created.

+
+
Return type
+

abc.GuildChannel

+
+
+
+ +
+
+property instance
+

The running stage instance of the stage channel.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[StageInstance]

+
+
+
+ +
+
+await create_instance(*, topic, privacy_level=..., reason=None)
+

This function is a coroutine.

+

Create a stage instance.

+

You must have the manage_channels permission to +use this.

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • topic (str) – The stage instance’s topic.

  • +
  • privacy_level (StagePrivacyLevel) – The stage instance’s privacy level. Defaults to StagePrivacyLevel.guild_only.

  • +
  • reason (str) – The reason the stage instance was created. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • InvalidArgument – If the privacy_level parameter is not the proper type.

  • +
  • Forbidden – You do not have permissions to create a stage instance.

  • +
  • HTTPException – Creating a stage instance failed.

  • +
+
+
Returns
+

The newly created stage instance.

+
+
Return type
+

StageInstance

+
+
+
+ +
+
+await fetch_instance()
+

This function is a coroutine.

+

Gets the running StageInstance.

+
+

New in version 2.0.

+
+
+
Raises
+
    +
  • NotFound – The stage instance or channel could not be found.

  • +
  • HTTPException – Getting the stage instance failed.

  • +
+
+
Returns
+

The stage instance.

+
+
Return type
+

StageInstance

+
+
+
+ +
+
+await edit(*, reason=None, **options)
+

This function is a coroutine.

+

Edits the channel.

+

You must have the manage_channels permission to +use this.

+
+

Changed in version 2.0: The topic parameter must now be set via create_instance.

+
+
+

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.

+
+
+
Parameters
+
    +
  • name (str) – The new channel’s name.

  • +
  • position (int) – The new channel’s position.

  • +
  • sync_permissions (bool) – Whether to sync permissions with the channel’s new or pre-existing +category. Defaults to False.

  • +
  • category (Optional[CategoryChannel]) – The new category for this channel. Can be None to remove the +category.

  • +
  • reason (Optional[str]) – The reason for editing this channel. Shows up on the audit log.

  • +
  • overwrites (Mapping) – A Mapping of target (either a role or a member) to +PermissionOverwrite to apply to the channel.

  • +
  • rtc_region (Optional[VoiceRegion]) – The new region for the stage channel’s voice communication. +A value of None indicates automatic voice region detection.

  • +
  • video_quality_mode (VideoQualityMode) –

    The camera video quality for the stage channel’s participants.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
    +
  • InvalidArgument – If the permission overwrite information is not in proper form.

  • +
  • Forbidden – You do not have permissions to edit the channel.

  • +
  • HTTPException – Editing the channel failed.

  • +
+
+
Returns
+

The newly edited stage channel. If the edit was only positional +then None is returned instead.

+
+
Return type
+

Optional[StageChannel]

+
+
+
+ +
+
+property category
+

The category this channel belongs to.

+

If there is no category then this is None.

+
+
Type
+

Optional[CategoryChannel]

+
+
+
+ +
+
+property changed_roles
+

Returns a list of roles that have been overridden from +their default values in the roles attribute.

+
+
Type
+

List[Role]

+
+
+
+ +
+
+await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)
+

This function is a coroutine.

+

Connects to voice and creates a VoiceClient to establish +your connection to the voice server.

+

This requires Intents.voice_states.

+
+
Parameters
+
    +
  • timeout (float) – The timeout in seconds to wait for the voice endpoint.

  • +
  • reconnect (bool) – Whether the bot should automatically attempt +a reconnect if a part of the handshake fails +or the gateway goes down.

  • +
  • cls (Type[VoiceProtocol]) – A type that subclasses VoiceProtocol to connect with. +Defaults to VoiceClient.

  • +
+
+
Raises
+
+
+
Returns
+

A voice client that is fully connected to the voice server.

+
+
Return type
+

VoiceProtocol

+
+
+
+ +
+
+await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)
+

This function is a coroutine.

+

Creates an instant invite from a text or voice channel.

+

You must have the create_instant_invite permission to +do this.

+
+
Parameters
+
    +
  • max_age (int) – How long the invite should last in seconds. If it’s 0 then the invite +doesn’t expire. Defaults to 0.

  • +
  • max_uses (int) – How many uses the invite could be used for. If it’s 0 then there +are unlimited uses. Defaults to 0.

  • +
  • temporary (bool) – Denotes that the invite grants temporary membership +(i.e. they get kicked after they disconnect). Defaults to False.

  • +
  • unique (bool) – Indicates if a unique invite URL should be created. Defaults to True. +If this is set to False then it will return a previously created +invite.

  • +
  • reason (Optional[str]) – The reason for creating this invite. Shows up on the audit log.

  • +
  • target_type (Optional[InviteTarget]) –

    The type of target for the voice channel invite, if any.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • target_user (Optional[User]) –

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • target_application_id:

    Optional[int]: The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
    +
  • HTTPException – Invite creation failed.

  • +
  • NotFound – The channel that was passed is a category or an invalid channel.

  • +
+
+
Returns
+

The invite that was created.

+
+
Return type
+

Invite

+
+
+
+ +
+
+property created_at
+

Returns the channel’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+await delete(*, reason=None)
+

This function is a coroutine.

+

Deletes the channel.

+

You must have manage_channels permission to use this.

+
+
Parameters
+

reason (Optional[str]) – The reason for deleting this channel. +Shows up on the audit log.

+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to delete the channel.

  • +
  • NotFound – The channel was not found or was already deleted.

  • +
  • HTTPException – Deleting the channel failed.

  • +
+
+
+
+ +
+
+await invites()
+

This function is a coroutine.

+

Returns a list of all active instant invites from this channel.

+

You must have manage_channels to get this information.

+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to get the information.

  • +
  • HTTPException – An error occurred while fetching the information.

  • +
+
+
Returns
+

The list of invites that are currently active.

+
+
Return type
+

List[Invite]

+
+
+
+ +
+
+property members
+

Returns all members that are currently inside this voice channel.

+
+
Type
+

List[Member]

+
+
+
+ +
+
+property mention
+

The string that allows you to mention the channel.

+
+
Type
+

str

+
+
+
+ +
+
+await move(**kwargs)
+

This function is a coroutine.

+

A rich interface to help move a channel relative to other channels.

+

If exact position movement is required, edit should be used instead.

+

You must have the manage_channels permission to +do this.

+
+

Note

+

Voice channels will always be sorted below text channels. +This is a Discord limitation.

+
+
+

New in version 1.7.

+
+
+
Parameters
+
    +
  • beginning (bool) – Whether to move the channel to the beginning of the +channel list (or category if given). +This is mutually exclusive with end, before, and after.

  • +
  • end (bool) – Whether to move the channel to the end of the +channel list (or category if given). +This is mutually exclusive with beginning, before, and after.

  • +
  • before (Snowflake) – The channel that should be before our current channel. +This is mutually exclusive with beginning, end, and after.

  • +
  • after (Snowflake) – The channel that should be after our current channel. +This is mutually exclusive with beginning, end, and before.

  • +
  • offset (int) – The number of channels to offset the move by. For example, +an offset of 2 with beginning=True would move +it 2 after the beginning. A positive number moves it below +while a negative number moves it above. Note that this +number is relative and computed after the beginning, +end, before, and after parameters.

  • +
  • category (Optional[Snowflake]) – The category to move this channel under. +If None is given then it moves it out of the category. +This parameter is ignored if moving a category channel.

  • +
  • sync_permissions (bool) – Whether to sync the permissions with the category (if given).

  • +
  • reason (str) – The reason for the move.

  • +
+
+
Raises
+
    +
  • InvalidArgument – An invalid position was given or a bad mix of arguments were passed.

  • +
  • Forbidden – You do not have permissions to move the channel.

  • +
  • HTTPException – Moving the channel failed.

  • +
+
+
+
+ +
+
+property overwrites
+

Returns all of the channel’s overwrites.

+

This is returned as a dictionary where the key contains the target which +can be either a Role or a Member and the value is the +overwrite as a PermissionOverwrite.

+
+
Returns
+

The channel’s permission overwrites.

+
+
Return type
+

Dict[Union[Role, Member], PermissionOverwrite]

+
+
+
+ +
+
+overwrites_for(obj)
+

Returns the channel-specific overwrites for a member or a role.

+
+
Parameters
+

obj (Union[Role, User]) – The role or user denoting +whose overwrite to get.

+
+
Returns
+

The permission overwrites for this object.

+
+
Return type
+

PermissionOverwrite

+
+
+
+ +
+
+permissions_for(obj, /)
+

Handles permission resolution for the Member +or Role.

+

This function takes into consideration the following cases:

+
    +
  • Guild owner

  • +
  • Guild roles

  • +
  • Channel overrides

  • +
  • Member overrides

  • +
+

If a Role is passed, then it checks the permissions +someone with that role would have, which is essentially:

+
    +
  • The default role permissions

  • +
  • The permissions of the role used as a parameter

  • +
  • The default role permission overwrites

  • +
  • The permission overwrites of the role used as a parameter

  • +
+
+

Changed in version 2.0: The object passed in can now be a role object.

+
+
+
Parameters
+

obj (Union[Member, Role]) – The object to resolve permissions for. This could be either +a member or a role. If it’s a role then member overwrites +are not computed.

+
+
Returns
+

The resolved permissions for the member or role.

+
+
Return type
+

Permissions

+
+
+
+ +
+
+property permissions_synced
+

Whether or not the permissions for this channel are synced with the +category it belongs to.

+

If there is no category then this is False.

+
+

New in version 1.3.

+
+
+
Type
+

bool

+
+
+
+ +
+
+await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)
+

This function is a coroutine.

+

Sets the channel specific permission overwrites for a target in the +channel.

+

The target parameter should either be a Member or a +Role that belongs to guild.

+

The overwrite parameter, if given, must either be None or +PermissionOverwrite. For convenience, you can pass in +keyword arguments denoting Permissions attributes. If this is +done, then you cannot mix the keyword arguments with the overwrite +parameter.

+

If the overwrite parameter is None, then the permission +overwrites are deleted.

+

You must have the manage_roles permission to use this.

+
+

Note

+

This method replaces the old overwrites with the ones given.

+
+

Examples

+

Setting allow and deny:

+
await message.channel.set_permissions(message.author, read_messages=True,
+                                                      send_messages=False)
+
+
+

Deleting overwrites

+
await channel.set_permissions(member, overwrite=None)
+
+
+

Using PermissionOverwrite

+
overwrite = discord.PermissionOverwrite()
+overwrite.send_messages = False
+overwrite.read_messages = True
+await channel.set_permissions(member, overwrite=overwrite)
+
+
+
+
Parameters
+
    +
  • target (Union[Member, Role]) – The member or role to overwrite permissions for.

  • +
  • overwrite (Optional[PermissionOverwrite]) – The permissions to allow and deny to the target, or None to +delete the overwrite.

  • +
  • **permissions – A keyword argument list of permissions to set for ease of use. +Cannot be mixed with overwrite.

  • +
  • reason (Optional[str]) – The reason for doing this action. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to edit channel specific permissions.

  • +
  • HTTPException – Editing channel specific permissions failed.

  • +
  • NotFound – The role or member being edited is not part of the guild.

  • +
  • InvalidArgument – The overwrite parameter invalid or the target type was not + Role or Member.

  • +
+
+
+
+ +
+
+property voice_states
+

Returns a mapping of member IDs who have voice states in this channel.

+
+

New in version 1.3.

+
+
+

Note

+

This function is intentionally low level to replace members +when the member cache is unavailable.

+
+
+
Returns
+

The mapping of member ID to a voice state.

+
+
Return type
+

Mapping[int, VoiceState]

+
+
+
+ +
+ +
+
+

StageInstance

+
+ +Methods +
+
+class discord.StageInstance
+

Represents a stage instance of a stage channel in a guild.

+
+

New in version 2.0.

+
+
+
+
+x == y
+

Checks if two stage instances are equal.

+
+ +
+
+x != y
+

Checks if two stage instances are not equal.

+
+ +
+
+hash(x)
+

Returns the stage instance’s hash.

+
+ +
+
+int(x)
+

Returns the stage instance’s ID.

+
+ +
+
+
+id
+

The stage instance’s ID.

+
+
Type
+

int

+
+
+
+ +
+
+guild
+

The guild that the stage instance is running in.

+
+
Type
+

Guild

+
+
+
+ +
+
+channel_id
+

The ID of the channel that the stage instance is running in.

+
+
Type
+

int

+
+
+
+ +
+
+topic
+

The topic of the stage instance.

+
+
Type
+

str

+
+
+
+ +
+
+privacy_level
+

The privacy level of the stage instance.

+
+
Type
+

StagePrivacyLevel

+
+
+
+ +
+
+discoverable_disabled
+

Whether discoverability for the stage instance is disabled.

+
+
Type
+

bool

+
+
+
+ +
+
+channel
+

The channel that stage instance is running in.

+
+
Type
+

Optional[StageChannel]

+
+
+
+ +
+
+await edit(*, topic=..., privacy_level=..., reason=None)
+

This function is a coroutine.

+

Edits the stage instance.

+

You must have the manage_channels permission to +use this.

+
+
Parameters
+
    +
  • topic (str) – The stage instance’s new topic.

  • +
  • privacy_level (StagePrivacyLevel) – The stage instance’s new privacy level.

  • +
  • reason (str) – The reason the stage instance was edited. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • InvalidArgument – If the privacy_level parameter is not the proper type.

  • +
  • Forbidden – You do not have permissions to edit the stage instance.

  • +
  • HTTPException – Editing a stage instance failed.

  • +
+
+
+
+ +
+
+await delete(*, reason=None)
+

This function is a coroutine.

+

Deletes the stage instance.

+

You must have the manage_channels permission to +use this.

+
+
Parameters
+

reason (str) – The reason the stage instance was deleted. Shows up on the audit log.

+
+
Raises
+
    +
  • Forbidden – You do not have permissions to delete the stage instance.

  • +
  • HTTPException – Deleting the stage instance failed.

  • +
+
+
+
+ +
+ +
+
+

CategoryChannel

+
+
+class discord.CategoryChannel
+

Represents a Discord channel category.

+

These are useful to group channels to logical compartments.

+
+
+
+x == y
+

Checks if two channels are equal.

+
+ +
+
+x != y
+

Checks if two channels are not equal.

+
+ +
+
+hash(x)
+

Returns the category’s hash.

+
+ +
+
+str(x)
+

Returns the category’s name.

+
+ +
+
+int(x)
+

Returns the category’s ID.

+
+ +
+
+
+name
+

The category name.

+
+
Type
+

str

+
+
+
+ +
+
+guild
+

The guild the category belongs to.

+
+
Type
+

Guild

+
+
+
+ +
+
+id
+

The category channel ID.

+
+
Type
+

int

+
+
+
+ +
+
+position
+

The position in the category list. This is a number that starts at 0. e.g. the +top category is position 0.

+
+
Type
+

int

+
+
+
+ +
+
+nsfw
+

If the channel is marked as “not safe for work”.

+
+

Note

+

To check if the channel or the guild of that channel are marked as NSFW, consider is_nsfw() instead.

+
+
+
Type
+

bool

+
+
+
+ +
+
+property type
+

The channel’s Discord type.

+
+
Type
+

ChannelType

+
+
+
+ +
+
+is_nsfw()
+

bool: Checks if the category is NSFW.

+
+ +
+
+await clone(*, name=None, reason=None)
+

This function is a coroutine.

+

Clones this channel. This creates a channel with the same properties +as this channel.

+

You must have the manage_channels permission to +do this.

+
+

New in version 1.1.

+
+
+
Parameters
+
    +
  • name (Optional[str]) – The name of the new channel. If not provided, defaults to this +channel name.

  • +
  • reason (Optional[str]) – The reason for cloning this channel. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have the proper permissions to create this channel.

  • +
  • HTTPException – Creating the channel failed.

  • +
+
+
Returns
+

The channel that was created.

+
+
Return type
+

abc.GuildChannel

+
+
+
+ +
+
+await edit(*, reason=None, **options)
+

This function is a coroutine.

+

Edits the channel.

+

You must have the manage_channels permission to +use this.

+
+

Changed in version 1.3: The overwrites keyword-only parameter was added.

+
+
+

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.

+
+
+
Parameters
+
    +
  • name (str) – The new category’s name.

  • +
  • position (int) – The new category’s position.

  • +
  • nsfw (bool) – To mark the category as NSFW or not.

  • +
  • reason (Optional[str]) – The reason for editing this category. Shows up on the audit log.

  • +
  • overwrites (Mapping) – A Mapping of target (either a role or a member) to +PermissionOverwrite to apply to the channel.

  • +
+
+
Raises
+
    +
  • InvalidArgument – If position is less than 0 or greater than the number of categories.

  • +
  • Forbidden – You do not have permissions to edit the category.

  • +
  • HTTPException – Editing the category failed.

  • +
+
+
Returns
+

The newly edited category channel. If the edit was only positional +then None is returned instead.

+
+
Return type
+

Optional[CategoryChannel]

+
+
+
+ +
+
+await move(**kwargs)
+

This function is a coroutine.

+

A rich interface to help move a channel relative to other channels.

+

If exact position movement is required, edit should be used instead.

+

You must have the manage_channels permission to +do this.

+
+

Note

+

Voice channels will always be sorted below text channels. +This is a Discord limitation.

+
+
+

New in version 1.7.

+
+
+
Parameters
+
    +
  • beginning (bool) – Whether to move the channel to the beginning of the +channel list (or category if given). +This is mutually exclusive with end, before, and after.

  • +
  • end (bool) – Whether to move the channel to the end of the +channel list (or category if given). +This is mutually exclusive with beginning, before, and after.

  • +
  • before (Snowflake) – The channel that should be before our current channel. +This is mutually exclusive with beginning, end, and after.

  • +
  • after (Snowflake) – The channel that should be after our current channel. +This is mutually exclusive with beginning, end, and before.

  • +
  • offset (int) – The number of channels to offset the move by. For example, +an offset of 2 with beginning=True would move +it 2 after the beginning. A positive number moves it below +while a negative number moves it above. Note that this +number is relative and computed after the beginning, +end, before, and after parameters.

  • +
  • category (Optional[Snowflake]) – The category to move this channel under. +If None is given then it moves it out of the category. +This parameter is ignored if moving a category channel.

  • +
  • sync_permissions (bool) – Whether to sync the permissions with the category (if given).

  • +
  • reason (str) – The reason for the move.

  • +
+
+
Raises
+
    +
  • InvalidArgument – An invalid position was given or a bad mix of arguments were passed.

  • +
  • Forbidden – You do not have permissions to move the channel.

  • +
  • HTTPException – Moving the channel failed.

  • +
+
+
+
+ +
+
+property channels
+

Returns the channels that are under this category.

+

These are sorted by the official Discord UI, which places voice channels below the text channels.

+
+
Type
+

List[abc.GuildChannel]

+
+
+
+ +
+
+property text_channels
+

Returns the text channels that are under this category.

+
+
Type
+

List[TextChannel]

+
+
+
+ +
+
+property voice_channels
+

Returns the voice channels that are under this category.

+
+
Type
+

List[VoiceChannel]

+
+
+
+ +
+
+property stage_channels
+

Returns the stage channels that are under this category.

+
+

New in version 1.7.

+
+
+
Type
+

List[StageChannel]

+
+
+
+ +
+
+await create_text_channel(name, **options)
+

This function is a coroutine.

+

A shortcut method to Guild.create_text_channel() to create a TextChannel in the category.

+
+
Returns
+

The channel that was just created.

+
+
Return type
+

TextChannel

+
+
+
+ +
+
+await create_voice_channel(name, **options)
+

This function is a coroutine.

+

A shortcut method to Guild.create_voice_channel() to create a VoiceChannel in the category.

+
+
Returns
+

The channel that was just created.

+
+
Return type
+

VoiceChannel

+
+
+
+ +
+
+await create_stage_channel(name, **options)
+

This function is a coroutine.

+

A shortcut method to Guild.create_stage_channel() to create a StageChannel in the category.

+
+

New in version 1.7.

+
+
+
Returns
+

The channel that was just created.

+
+
Return type
+

StageChannel

+
+
+
+ +
+
+property category
+

The category this channel belongs to.

+

If there is no category then this is None.

+
+
Type
+

Optional[CategoryChannel]

+
+
+
+ +
+
+property changed_roles
+

Returns a list of roles that have been overridden from +their default values in the roles attribute.

+
+
Type
+

List[Role]

+
+
+
+ +
+
+await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)
+

This function is a coroutine.

+

Creates an instant invite from a text or voice channel.

+

You must have the create_instant_invite permission to +do this.

+
+
Parameters
+
    +
  • max_age (int) – How long the invite should last in seconds. If it’s 0 then the invite +doesn’t expire. Defaults to 0.

  • +
  • max_uses (int) – How many uses the invite could be used for. If it’s 0 then there +are unlimited uses. Defaults to 0.

  • +
  • temporary (bool) – Denotes that the invite grants temporary membership +(i.e. they get kicked after they disconnect). Defaults to False.

  • +
  • unique (bool) – Indicates if a unique invite URL should be created. Defaults to True. +If this is set to False then it will return a previously created +invite.

  • +
  • reason (Optional[str]) – The reason for creating this invite. Shows up on the audit log.

  • +
  • target_type (Optional[InviteTarget]) –

    The type of target for the voice channel invite, if any.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • target_user (Optional[User]) –

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • target_application_id:

    Optional[int]: The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
    +
  • HTTPException – Invite creation failed.

  • +
  • NotFound – The channel that was passed is a category or an invalid channel.

  • +
+
+
Returns
+

The invite that was created.

+
+
Return type
+

Invite

+
+
+
+ +
+
+property created_at
+

Returns the channel’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+await delete(*, reason=None)
+

This function is a coroutine.

+

Deletes the channel.

+

You must have manage_channels permission to use this.

+
+
Parameters
+

reason (Optional[str]) – The reason for deleting this channel. +Shows up on the audit log.

+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to delete the channel.

  • +
  • NotFound – The channel was not found or was already deleted.

  • +
  • HTTPException – Deleting the channel failed.

  • +
+
+
+
+ +
+
+await invites()
+

This function is a coroutine.

+

Returns a list of all active instant invites from this channel.

+

You must have manage_channels to get this information.

+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to get the information.

  • +
  • HTTPException – An error occurred while fetching the information.

  • +
+
+
Returns
+

The list of invites that are currently active.

+
+
Return type
+

List[Invite]

+
+
+
+ +
+
+property mention
+

The string that allows you to mention the channel.

+
+
Type
+

str

+
+
+
+ +
+
+property overwrites
+

Returns all of the channel’s overwrites.

+

This is returned as a dictionary where the key contains the target which +can be either a Role or a Member and the value is the +overwrite as a PermissionOverwrite.

+
+
Returns
+

The channel’s permission overwrites.

+
+
Return type
+

Dict[Union[Role, Member], PermissionOverwrite]

+
+
+
+ +
+
+overwrites_for(obj)
+

Returns the channel-specific overwrites for a member or a role.

+
+
Parameters
+

obj (Union[Role, User]) – The role or user denoting +whose overwrite to get.

+
+
Returns
+

The permission overwrites for this object.

+
+
Return type
+

PermissionOverwrite

+
+
+
+ +
+
+permissions_for(obj, /)
+

Handles permission resolution for the Member +or Role.

+

This function takes into consideration the following cases:

+
    +
  • Guild owner

  • +
  • Guild roles

  • +
  • Channel overrides

  • +
  • Member overrides

  • +
+

If a Role is passed, then it checks the permissions +someone with that role would have, which is essentially:

+
    +
  • The default role permissions

  • +
  • The permissions of the role used as a parameter

  • +
  • The default role permission overwrites

  • +
  • The permission overwrites of the role used as a parameter

  • +
+
+

Changed in version 2.0: The object passed in can now be a role object.

+
+
+
Parameters
+

obj (Union[Member, Role]) – The object to resolve permissions for. This could be either +a member or a role. If it’s a role then member overwrites +are not computed.

+
+
Returns
+

The resolved permissions for the member or role.

+
+
Return type
+

Permissions

+
+
+
+ +
+
+property permissions_synced
+

Whether or not the permissions for this channel are synced with the +category it belongs to.

+

If there is no category then this is False.

+
+

New in version 1.3.

+
+
+
Type
+

bool

+
+
+
+ +
+
+await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)
+

This function is a coroutine.

+

Sets the channel specific permission overwrites for a target in the +channel.

+

The target parameter should either be a Member or a +Role that belongs to guild.

+

The overwrite parameter, if given, must either be None or +PermissionOverwrite. For convenience, you can pass in +keyword arguments denoting Permissions attributes. If this is +done, then you cannot mix the keyword arguments with the overwrite +parameter.

+

If the overwrite parameter is None, then the permission +overwrites are deleted.

+

You must have the manage_roles permission to use this.

+
+

Note

+

This method replaces the old overwrites with the ones given.

+
+

Examples

+

Setting allow and deny:

+
await message.channel.set_permissions(message.author, read_messages=True,
+                                                      send_messages=False)
+
+
+

Deleting overwrites

+
await channel.set_permissions(member, overwrite=None)
+
+
+

Using PermissionOverwrite

+
overwrite = discord.PermissionOverwrite()
+overwrite.send_messages = False
+overwrite.read_messages = True
+await channel.set_permissions(member, overwrite=overwrite)
+
+
+
+
Parameters
+
    +
  • target (Union[Member, Role]) – The member or role to overwrite permissions for.

  • +
  • overwrite (Optional[PermissionOverwrite]) – The permissions to allow and deny to the target, or None to +delete the overwrite.

  • +
  • **permissions – A keyword argument list of permissions to set for ease of use. +Cannot be mixed with overwrite.

  • +
  • reason (Optional[str]) – The reason for doing this action. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to edit channel specific permissions.

  • +
  • HTTPException – Editing channel specific permissions failed.

  • +
  • NotFound – The role or member being edited is not part of the guild.

  • +
  • InvalidArgument – The overwrite parameter invalid or the target type was not + Role or Member.

  • +
+
+
+
+ +
+ +
+
+

DMChannel

+
+ +Attributes +
+ +Methods +
+
+class discord.DMChannel
+

Represents a Discord direct message channel.

+
+
+
+x == y
+

Checks if two channels are equal.

+
+ +
+
+x != y
+

Checks if two channels are not equal.

+
+ +
+
+hash(x)
+

Returns the channel’s hash.

+
+ +
+
+str(x)
+

Returns a string representation of the channel

+
+ +
+
+int(x)
+

Returns the channel’s ID.

+
+ +
+
+
+recipient
+

The user you are participating with in the direct message channel. +If this channel is received through the gateway, the recipient information +may not be always available.

+
+
Type
+

Optional[User]

+
+
+
+ +
+
+me
+

The user presenting yourself.

+
+
Type
+

ClientUser

+
+
+
+ +
+
+id
+

The direct message channel ID.

+
+
Type
+

int

+
+
+
+ +
+
+async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
+

Returns an AsyncIterator that enables receiving the destination’s message history.

+

You must have read_message_history permissions to use this.

+

Examples

+

Usage

+
counter = 0
+async for message in channel.history(limit=200):
+    if message.author == client.user:
+        counter += 1
+
+
+

Flattening into a list:

+
messages = await channel.history(limit=123).flatten()
+# messages is now a list of Message...
+
+
+

All parameters are optional.

+
+
Parameters
+
    +
  • limit (Optional[int]) – The number of messages to retrieve. +If None, retrieves every message in the channel. Note, however, +that this would make it a slow operation.

  • +
  • before (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • after (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • around (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time. +When using this argument, the maximum limit is 101. Note that if the limit is an +even number then this will return at most limit + 1 messages.

  • +
  • oldest_first (Optional[bool]) – If set to True, return messages in oldest->newest order. Defaults to True if +after is specified, otherwise False.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to get channel message history.

  • +
  • HTTPException – The request to get message history failed.

  • +
+
+
Yields
+

Message – The message with the message data parsed.

+
+
+
+ +
+
+async with typing()
+

Returns a context manager that allows you to type for an indefinite period of time.

+

This is useful for denoting long computations in your bot.

+
+

Note

+

This is both a regular context manager and an async context manager. +This means that both with and async with work with this.

+
+

Example Usage:

+
async with channel.typing():
+    # simulate something heavy
+    await asyncio.sleep(10)
+
+await channel.send('done!')
+
+
+
+ +
+
+property type
+

The channel’s Discord type.

+
+
Type
+

ChannelType

+
+
+
+ +
+
+property created_at
+

Returns the direct message channel’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+permissions_for(obj=None, /)
+

Handles permission resolution for a User.

+

This function is there for compatibility with other channel types.

+

Actual direct messages do not really have the concept of permissions.

+

This returns all the Text related permissions set to True except:

+ +
+
Parameters
+

obj (User) – The user to check permissions for. This parameter is ignored +but kept for compatibility with other permissions_for methods.

+
+
Returns
+

The resolved permissions.

+
+
Return type
+

Permissions

+
+
+
+ +
+
+get_partial_message(message_id, /)
+

Creates a PartialMessage from the message ID.

+

This is useful if you want to work with a message and only have its ID without +doing an unnecessary API call.

+
+

New in version 1.6.

+
+
+
Parameters
+

message_id (int) – The message ID to create a partial message for.

+
+
Returns
+

The partial message.

+
+
Return type
+

PartialMessage

+
+
+
+ +
+
+await fetch_message(id, /)
+

This function is a coroutine.

+

Retrieves a single Message from the destination.

+
+
Parameters
+

id (int) – The message ID to look for.

+
+
Raises
+
    +
  • NotFound – The specified message was not found.

  • +
  • Forbidden – You do not have the permissions required to get a message.

  • +
  • HTTPException – Retrieving the message failed.

  • +
+
+
Returns
+

The message asked for.

+
+
Return type
+

Message

+
+
+
+ +
+
+await pins()
+

This function is a coroutine.

+

Retrieves all messages that are currently pinned in the channel.

+
+

Note

+

Due to a limitation with the Discord API, the Message +objects returned by this method do not contain complete +Message.reactions data.

+
+
+
Raises
+

HTTPException – Retrieving the pinned messages failed.

+
+
Returns
+

The messages that are currently pinned.

+
+
Return type
+

List[Message]

+
+
+
+ +
+
+await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)
+

This function is a coroutine.

+

Sends a message to the destination with the content given.

+

The content must be a type that can convert to a string through str(content). +If the content is set to None (the default), then the embed parameter must +be provided.

+

To upload a single file, the file parameter should be used with a +single File object. To upload multiple files, the files +parameter should be used with a list of File objects. +Specifying both parameters will lead to an exception.

+

To upload a single embed, the embed parameter should be used with a +single Embed object. To upload multiple embeds, the embeds +parameter should be used with a list of Embed objects. +Specifying both parameters will lead to an exception.

+
+
Parameters
+
    +
  • content (Optional[str]) – The content of the message to send.

  • +
  • tts (bool) – Indicates if the message should be sent using text-to-speech.

  • +
  • embed (Embed) – The rich embed for the content.

  • +
  • file (File) – The file to upload.

  • +
  • files (List[File]) – A list of files to upload. Must be a maximum of 10.

  • +
  • nonce (int) – The nonce to use for sending this message. If the message was successfully sent, +then the message will have a nonce with this value.

  • +
  • delete_after (float) – If provided, the number of seconds to wait in the background +before deleting the message we just sent. If the deletion fails, +then it is silently ignored.

  • +
  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is +passed, then the object is merged with allowed_mentions. +The merging behaviour only overrides attributes that have been explicitly passed +to the object, otherwise it uses the attributes set in allowed_mentions. +If no object is passed at all then the defaults given by allowed_mentions +are used instead.

    +
    +

    New in version 1.4.

    +
    +

  • +
  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using +to_reference() or passed directly as a Message. You can control +whether this mentions the author of the referenced message using the replied_user +attribute of allowed_mentions or by setting mention_author.

    +
    +

    New in version 1.6.

    +
    +

  • +
  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    +
    +

    New in version 1.6.

    +
    +

  • +
  • view (discord.ui.View) – A Discord UI View to add to the message.

  • +
  • embeds (List[Embed]) –

    A list of embeds to upload. Must be a maximum of 10.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
+
+
Returns
+

The message that was sent.

+
+
Return type
+

Message

+
+
+
+ +
+
+await trigger_typing()
+

This function is a coroutine.

+

Triggers a typing indicator to the destination.

+

Typing indicator will go away after 10 seconds, or after a message is sent.

+
+ +
+ +
+
+

GroupChannel

+
+ +Attributes +
+ +Methods +
+
+class discord.GroupChannel
+

Represents a Discord group channel.

+
+
+
+x == y
+

Checks if two channels are equal.

+
+ +
+
+x != y
+

Checks if two channels are not equal.

+
+ +
+
+hash(x)
+

Returns the channel’s hash.

+
+ +
+
+str(x)
+

Returns a string representation of the channel

+
+ +
+
+int(x)
+

Returns the channel’s ID.

+
+ +
+
+
+recipients
+

The users you are participating with in the group channel.

+
+
Type
+

List[User]

+
+
+
+ +
+
+me
+

The user presenting yourself.

+
+
Type
+

ClientUser

+
+
+
+ +
+
+id
+

The group channel ID.

+
+
Type
+

int

+
+
+
+ +
+
+owner
+

The user that owns the group channel.

+
+
Type
+

Optional[User]

+
+
+
+ +
+
+owner_id
+

The owner ID that owns the group channel.

+
+

New in version 2.0.

+
+
+
Type
+

int

+
+
+
+ +
+
+name
+

The group channel’s name if provided.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
+

Returns an AsyncIterator that enables receiving the destination’s message history.

+

You must have read_message_history permissions to use this.

+

Examples

+

Usage

+
counter = 0
+async for message in channel.history(limit=200):
+    if message.author == client.user:
+        counter += 1
+
+
+

Flattening into a list:

+
messages = await channel.history(limit=123).flatten()
+# messages is now a list of Message...
+
+
+

All parameters are optional.

+
+
Parameters
+
    +
  • limit (Optional[int]) – The number of messages to retrieve. +If None, retrieves every message in the channel. Note, however, +that this would make it a slow operation.

  • +
  • before (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • after (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • around (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time. +When using this argument, the maximum limit is 101. Note that if the limit is an +even number then this will return at most limit + 1 messages.

  • +
  • oldest_first (Optional[bool]) – If set to True, return messages in oldest->newest order. Defaults to True if +after is specified, otherwise False.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to get channel message history.

  • +
  • HTTPException – The request to get message history failed.

  • +
+
+
Yields
+

Message – The message with the message data parsed.

+
+
+
+ +
+
+async with typing()
+

Returns a context manager that allows you to type for an indefinite period of time.

+

This is useful for denoting long computations in your bot.

+
+

Note

+

This is both a regular context manager and an async context manager. +This means that both with and async with work with this.

+
+

Example Usage:

+
async with channel.typing():
+    # simulate something heavy
+    await asyncio.sleep(10)
+
+await channel.send('done!')
+
+
+
+ +
+
+property type
+

The channel’s Discord type.

+
+
Type
+

ChannelType

+
+
+
+ +
+
+property icon
+

Returns the channel’s icon asset if available.

+
+
Type
+

Optional[Asset]

+
+
+
+ +
+
+property created_at
+

Returns the channel’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+permissions_for(obj, /)
+

Handles permission resolution for a User.

+

This function is there for compatibility with other channel types.

+

Actual direct messages do not really have the concept of permissions.

+

This returns all the Text related permissions set to True except:

+ +

This also checks the kick_members permission if the user is the owner.

+
+
Parameters
+

obj (Snowflake) – The user to check permissions for.

+
+
Returns
+

The resolved permissions for the user.

+
+
Return type
+

Permissions

+
+
+
+ +
+
+await leave()
+

This function is a coroutine.

+

Leave the group.

+

If you are the only one in the group, this deletes it as well.

+
+
Raises
+

HTTPException – Leaving the group failed.

+
+
+
+ +
+
+await fetch_message(id, /)
+

This function is a coroutine.

+

Retrieves a single Message from the destination.

+
+
Parameters
+

id (int) – The message ID to look for.

+
+
Raises
+
    +
  • NotFound – The specified message was not found.

  • +
  • Forbidden – You do not have the permissions required to get a message.

  • +
  • HTTPException – Retrieving the message failed.

  • +
+
+
Returns
+

The message asked for.

+
+
Return type
+

Message

+
+
+
+ +
+
+await pins()
+

This function is a coroutine.

+

Retrieves all messages that are currently pinned in the channel.

+
+

Note

+

Due to a limitation with the Discord API, the Message +objects returned by this method do not contain complete +Message.reactions data.

+
+
+
Raises
+

HTTPException – Retrieving the pinned messages failed.

+
+
Returns
+

The messages that are currently pinned.

+
+
Return type
+

List[Message]

+
+
+
+ +
+
+await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)
+

This function is a coroutine.

+

Sends a message to the destination with the content given.

+

The content must be a type that can convert to a string through str(content). +If the content is set to None (the default), then the embed parameter must +be provided.

+

To upload a single file, the file parameter should be used with a +single File object. To upload multiple files, the files +parameter should be used with a list of File objects. +Specifying both parameters will lead to an exception.

+

To upload a single embed, the embed parameter should be used with a +single Embed object. To upload multiple embeds, the embeds +parameter should be used with a list of Embed objects. +Specifying both parameters will lead to an exception.

+
+
Parameters
+
    +
  • content (Optional[str]) – The content of the message to send.

  • +
  • tts (bool) – Indicates if the message should be sent using text-to-speech.

  • +
  • embed (Embed) – The rich embed for the content.

  • +
  • file (File) – The file to upload.

  • +
  • files (List[File]) – A list of files to upload. Must be a maximum of 10.

  • +
  • nonce (int) – The nonce to use for sending this message. If the message was successfully sent, +then the message will have a nonce with this value.

  • +
  • delete_after (float) – If provided, the number of seconds to wait in the background +before deleting the message we just sent. If the deletion fails, +then it is silently ignored.

  • +
  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is +passed, then the object is merged with allowed_mentions. +The merging behaviour only overrides attributes that have been explicitly passed +to the object, otherwise it uses the attributes set in allowed_mentions. +If no object is passed at all then the defaults given by allowed_mentions +are used instead.

    +
    +

    New in version 1.4.

    +
    +

  • +
  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using +to_reference() or passed directly as a Message. You can control +whether this mentions the author of the referenced message using the replied_user +attribute of allowed_mentions or by setting mention_author.

    +
    +

    New in version 1.6.

    +
    +

  • +
  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    +
    +

    New in version 1.6.

    +
    +

  • +
  • view (discord.ui.View) – A Discord UI View to add to the message.

  • +
  • embeds (List[Embed]) –

    A list of embeds to upload. Must be a maximum of 10.

    +
    +

    New in version 2.0.

    +
    +

  • +
  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
+
+
Returns
+

The message that was sent.

+
+
Return type
+

Message

+
+
+
+ +
+
+await trigger_typing()
+

This function is a coroutine.

+

Triggers a typing indicator to the destination.

+

Typing indicator will go away after 10 seconds, or after a message is sent.

+
+ +
+ +
+
+

PartialInviteGuild

+
+
+class discord.PartialInviteGuild
+

Represents a “partial” invite guild.

+

This model will be given when the user is not part of the +guild the Invite resolves to.

+
+
+
+x == y
+

Checks if two partial guilds are the same.

+
+ +
+
+x != y
+

Checks if two partial guilds are not the same.

+
+ +
+
+hash(x)
+

Return the partial guild’s hash.

+
+ +
+
+str(x)
+

Returns the partial guild’s name.

+
+ +
+
+
+name
+

The partial guild’s name.

+
+
Type
+

str

+
+
+
+ +
+
+id
+

The partial guild’s ID.

+
+
Type
+

int

+
+
+
+ +
+
+verification_level
+

The partial guild’s verification level.

+
+
Type
+

VerificationLevel

+
+
+
+ +
+
+features
+

A list of features the guild has. See Guild.features for more information.

+
+
Type
+

List[str]

+
+
+
+ +
+
+description
+

The partial guild’s description.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+property created_at
+

Returns the guild’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+property icon
+

Returns the guild’s icon asset, if available.

+
+
Type
+

Optional[Asset]

+
+
+
+ +
+
+property banner
+

Returns the guild’s banner asset, if available.

+
+
Type
+

Optional[Asset]

+
+
+
+ +
+
+property splash
+

Returns the guild’s invite splash asset, if available.

+
+
Type
+

Optional[Asset]

+
+
+
+ +
+ +
+
+

PartialInviteChannel

+
+ +Attributes +
+
+class discord.PartialInviteChannel
+

Represents a “partial” invite channel.

+

This model will be given when the user is not part of the +guild the Invite resolves to.

+
+
+
+x == y
+

Checks if two partial channels are the same.

+
+ +
+
+x != y
+

Checks if two partial channels are not the same.

+
+ +
+
+hash(x)
+

Return the partial channel’s hash.

+
+ +
+
+str(x)
+

Returns the partial channel’s name.

+
+ +
+
+
+name
+

The partial channel’s name.

+
+
Type
+

str

+
+
+
+ +
+
+id
+

The partial channel’s ID.

+
+
Type
+

int

+
+
+
+ +
+
+type
+

The partial channel’s type.

+
+
Type
+

ChannelType

+
+
+
+ +
+
+property mention
+

The string that allows you to mention the channel.

+
+
Type
+

str

+
+
+
+ +
+
+property created_at
+

Returns the channel’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+ +
+
+

Invite

+
+
+class discord.Invite
+

Represents a Discord Guild or abc.GuildChannel invite.

+

Depending on the way this object was created, some of the attributes can +have a value of None.

+
+
+
+x == y
+

Checks if two invites are equal.

+
+ +
+
+x != y
+

Checks if two invites are not equal.

+
+ +
+
+hash(x)
+

Returns the invite hash.

+
+ +
+
+str(x)
+

Returns the invite URL.

+
+ +
+

The following table illustrates what methods will obtain the attributes:

+

If it’s not in the table above then it is available by all methods.

+
+
+max_age
+

How long before the invite expires in seconds. +A value of 0 indicates that it doesn’t expire.

+
+
Type
+

int

+
+
+
+ +
+
+code
+

The URL fragment used for the invite.

+
+
Type
+

str

+
+
+
+ +
+
+guild
+

The guild the invite is for. Can be None if it’s from a group direct message.

+
+
Type
+

Optional[Union[Guild, Object, PartialInviteGuild]]

+
+
+
+ +
+
+revoked
+

Indicates if the invite has been revoked.

+
+
Type
+

bool

+
+
+
+ +
+
+created_at
+

An aware UTC datetime object denoting the time the invite was created.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+temporary
+

Indicates that the invite grants temporary membership. +If True, members who joined via this invite will be kicked upon disconnect.

+
+
Type
+

bool

+
+
+
+ +
+
+uses
+

How many times the invite has been used.

+
+
Type
+

int

+
+
+
+ +
+
+max_uses
+

How many times the invite can be used. +A value of 0 indicates that it has unlimited uses.

+
+
Type
+

int

+
+
+
+ +
+
+inviter
+

The user who created the invite.

+
+
Type
+

Optional[User]

+
+
+
+ +
+
+approximate_member_count
+

The approximate number of members in the guild.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+approximate_presence_count
+

The approximate number of members currently active in the guild. +This includes idle, dnd, online, and invisible members. Offline members are excluded.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+expires_at
+

The expiration date of the invite. If the value is None when received through +Client.fetch_invite with with_expiration enabled, the invite will never expire.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[datetime.datetime]

+
+
+
+ +
+
+channel
+

The channel the invite is for.

+
+
Type
+

Union[abc.GuildChannel, Object, PartialInviteChannel]

+
+
+
+ +
+
+target_type
+

The type of target for the voice channel invite.

+
+

New in version 2.0.

+
+
+
Type
+

InviteTarget

+
+
+
+ +
+
+target_user
+

The user whose stream to display for this invite, if any.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[User]

+
+
+
+ +
+
+target_application
+

The embedded application the invite targets, if any.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[PartialAppInfo]

+
+
+
+ +
+
+property id
+

Returns the proper code portion of the invite.

+
+
Type
+

str

+
+
+
+ +
+
+property url
+

A property that retrieves the invite URL.

+
+
Type
+

str

+
+
+
+ +
+
+await delete(*, reason=None)
+

This function is a coroutine.

+

Revokes the instant invite.

+

You must have the manage_channels permission to do this.

+
+
Parameters
+

reason (Optional[str]) – The reason for deleting this invite. Shows up on the audit log.

+
+
Raises
+
    +
  • Forbidden – You do not have permissions to revoke invites.

  • +
  • NotFound – The invite is invalid or expired.

  • +
  • HTTPException – Revoking the invite failed.

  • +
+
+
+
+ +
+ +
+
+

Template

+
+ +Methods +
+
+class discord.Template
+

Represents a Discord template.

+
+

New in version 1.4.

+
+
+
+code
+

The template code.

+
+
Type
+

str

+
+
+
+ +
+
+uses
+

How many times the template has been used.

+
+
Type
+

int

+
+
+
+ +
+
+name
+

The name of the template.

+
+
Type
+

str

+
+
+
+ +
+
+description
+

The description of the template.

+
+
Type
+

str

+
+
+
+ +
+
+creator
+

The creator of the template.

+
+
Type
+

User

+
+
+
+ +
+
+created_at
+

An aware datetime in UTC representing when the template was created.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+updated_at
+

An aware datetime in UTC representing when the template was last updated. +This is referred to as “last synced” in the official Discord client.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+source_guild
+

The source guild.

+
+
Type
+

Guild

+
+
+
+ +
+
+is_dirty
+

Whether the template has unsynced changes.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[bool]

+
+
+
+ +
+
+await create_guild(name, region=None, icon=None)
+

This function is a coroutine.

+

Creates a Guild using the template.

+

Bot accounts in more than 10 guilds are not allowed to create guilds.

+
+
Parameters
+
+
+
Raises
+
+
+
Returns
+

The guild created. This is not the same guild that is +added to cache.

+
+
Return type
+

Guild

+
+
+
+ +
+
+await sync()
+

This function is a coroutine.

+

Sync the template to the guild’s current state.

+

You must have the manage_guild permission in the +source guild to do this.

+
+

New in version 1.7.

+
+
+

Changed in version 2.0: The template is no longer edited in-place, instead it is returned.

+
+
+
Raises
+
    +
  • HTTPException – Editing the template failed.

  • +
  • Forbidden – You don’t have permissions to edit the template.

  • +
  • NotFound – This template does not exist.

  • +
+
+
Returns
+

The newly edited template.

+
+
Return type
+

Template

+
+
+
+ +
+
+await edit(*, name=..., description=...)
+

This function is a coroutine.

+

Edit the template metadata.

+

You must have the manage_guild permission in the +source guild to do this.

+
+

New in version 1.7.

+
+
+

Changed in version 2.0: The template is no longer edited in-place, instead it is returned.

+
+
+
Parameters
+
    +
  • name (str) – The template’s new name.

  • +
  • description (Optional[str]) – The template’s new description.

  • +
+
+
Raises
+
    +
  • HTTPException – Editing the template failed.

  • +
  • Forbidden – You don’t have permissions to edit the template.

  • +
  • NotFound – This template does not exist.

  • +
+
+
Returns
+

The newly edited template.

+
+
Return type
+

Template

+
+
+
+ +
+
+await delete()
+

This function is a coroutine.

+

Delete the template.

+

You must have the manage_guild permission in the +source guild to do this.

+
+

New in version 1.7.

+
+
+
Raises
+
    +
  • HTTPException – Editing the template failed.

  • +
  • Forbidden – You don’t have permissions to edit the template.

  • +
  • NotFound – This template does not exist.

  • +
+
+
+
+ +
+
+property url
+

The template url.

+
+

New in version 2.0.

+
+
+
Type
+

str

+
+
+
+ +
+ +
+
+

WidgetChannel

+
+ +Attributes +
+
+class discord.WidgetChannel
+

Represents a “partial” widget channel.

+
+
+
+x == y
+

Checks if two partial channels are the same.

+
+ +
+
+x != y
+

Checks if two partial channels are not the same.

+
+ +
+
+hash(x)
+

Return the partial channel’s hash.

+
+ +
+
+str(x)
+

Returns the partial channel’s name.

+
+ +
+
+
+id
+

The channel’s ID.

+
+
Type
+

int

+
+
+
+ +
+
+name
+

The channel’s name.

+
+
Type
+

str

+
+
+
+ +
+
+position
+

The channel’s position

+
+
Type
+

int

+
+
+
+ +
+
+property mention
+

The string that allows you to mention the channel.

+
+
Type
+

str

+
+
+
+ +
+
+property created_at
+

Returns the channel’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+ +
+
+

WidgetMember

+
+
+class discord.WidgetMember
+

Represents a “partial” member of the widget’s guild.

+
+
+
+x == y
+

Checks if two widget members are the same.

+
+ +
+
+x != y
+

Checks if two widget members are not the same.

+
+ +
+
+hash(x)
+

Return the widget member’s hash.

+
+ +
+
+str(x)
+

Returns the widget member’s name#discriminator.

+
+ +
+
+
+id
+

The member’s ID.

+
+
Type
+

int

+
+
+
+ +
+
+name
+

The member’s username.

+
+
Type
+

str

+
+
+
+ +
+
+discriminator
+

The member’s discriminator.

+
+
Type
+

str

+
+
+
+ +
+
+bot
+

Whether the member is a bot.

+
+
Type
+

bool

+
+
+
+ +
+
+status
+

The member’s status.

+
+
Type
+

Status

+
+
+
+ +
+
+nick
+

The member’s nickname.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+avatar
+

The member’s avatar hash.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+activity
+

The member’s activity.

+
+
Type
+

Optional[Union[BaseActivity, Spotify]]

+
+
+
+ +
+
+deafened
+

Whether the member is currently deafened.

+
+
Type
+

Optional[bool]

+
+
+
+ +
+
+muted
+

Whether the member is currently muted.

+
+
Type
+

Optional[bool]

+
+
+
+ +
+
+suppress
+

Whether the member is currently being suppressed.

+
+
Type
+

Optional[bool]

+
+
+
+ +
+
+connected_channel
+

Which channel the member is connected to.

+
+
Type
+

Optional[WidgetChannel]

+
+
+
+ +
+
+property display_name
+

Returns the member’s display name.

+
+
Type
+

str

+
+
+
+ +
+
+property accent_color
+

Returns the user’s accent color, if applicable.

+

There is an alias for this named accent_colour.

+
+

New in version 2.0.

+
+
+

Note

+

This information is only available via Client.fetch_user().

+
+
+
Type
+

Optional[Colour]

+
+
+
+ +
+
+property accent_colour
+

Returns the user’s accent colour, if applicable.

+

There is an alias for this named accent_color.

+
+

New in version 2.0.

+
+
+

Note

+

This information is only available via Client.fetch_user().

+
+
+
Type
+

Optional[Colour]

+
+
+
+ +
+
+property banner
+

Returns the user’s banner asset, if available.

+
+

New in version 2.0.

+
+
+

Note

+

This information is only available via Client.fetch_user().

+
+
+
Type
+

Optional[Asset]

+
+
+
+ +
+
+property color
+

A property that returns a color denoting the rendered color +for the user. This always returns Colour.default().

+

There is an alias for this named colour.

+
+
Type
+

Colour

+
+
+
+ +
+
+property colour
+

A property that returns a colour denoting the rendered colour +for the user. This always returns Colour.default().

+

There is an alias for this named color.

+
+
Type
+

Colour

+
+
+
+ +
+
+property created_at
+

Returns the user’s creation time in UTC.

+

This is when the user’s Discord account was created.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+property default_avatar
+

Returns the default avatar for a given user. This is calculated by the user’s discriminator.

+
+
Type
+

Asset

+
+
+
+ +
+
+property display_avatar
+

Returns the user’s display avatar.

+

For regular users this is just their default avatar or uploaded avatar.

+
+

New in version 2.0.

+
+
+
Type
+

Asset

+
+
+
+ +
+
+property mention
+

Returns a string that allows you to mention the given user.

+
+
Type
+

str

+
+
+
+ +
+
+mentioned_in(message)
+

Checks if the user is mentioned in the specified message.

+
+
Parameters
+

message (Message) – The message to check if you’re mentioned in.

+
+
Returns
+

Indicates if the user is mentioned in the message.

+
+
Return type
+

bool

+
+
+
+ +
+
+property public_flags
+

The publicly available flags the user has.

+
+
Type
+

PublicUserFlags

+
+
+
+ +
+ +
+
+

Widget

+
+ +Methods +
+
+class discord.Widget
+

Represents a Guild widget.

+
+
+
+x == y
+

Checks if two widgets are the same.

+
+ +
+
+x != y
+

Checks if two widgets are not the same.

+
+ +
+
+str(x)
+

Returns the widget’s JSON URL.

+
+ +
+
+
+id
+

The guild’s ID.

+
+
Type
+

int

+
+
+
+ +
+
+name
+

The guild’s name.

+
+
Type
+

str

+
+
+
+ +
+
+channels
+

The accessible voice channels in the guild.

+
+
Type
+

List[WidgetChannel]

+
+
+
+ +
+
+members
+

The online members in the server. Offline members +do not appear in the widget.

+
+

Note

+

Due to a Discord limitation, if this data is available +the users will be “anonymized” with linear IDs and discriminator +information being incorrect. Likewise, the number of members +retrieved is capped.

+
+
+
Type
+

List[Member]

+
+
+
+ +
+
+property created_at
+

Returns the member’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+property json_url
+

The JSON URL of the widget.

+
+
Type
+

str

+
+
+
+ +
+
+property invite_url
+

The invite URL for the guild, if available.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+await fetch_invite(*, with_counts=True)
+

This function is a coroutine.

+

Retrieves an Invite from the widget’s invite URL. +This is the same as Client.fetch_invite(); the invite +code is abstracted away.

+
+
Parameters
+

with_counts (bool) – Whether to include count information in the invite. This fills the +Invite.approximate_member_count and Invite.approximate_presence_count +fields.

+
+
Returns
+

The invite from the widget’s invite URL.

+
+
Return type
+

Invite

+
+
+
+ +
+ +
+
+

StickerPack

+
+
+class discord.StickerPack
+

Represents a sticker pack.

+
+

New in version 2.0.

+
+
+
+
+str(x)
+

Returns the name of the sticker pack.

+
+ +
+
+hash(x)
+

Returns the hash of the sticker pack.

+
+ +
+
+int(x)
+

Returns the ID of the sticker pack.

+
+ +
+
+x == y
+

Checks if the sticker pack is equal to another sticker pack.

+
+ +
+
+x != y
+

Checks if the sticker pack is not equal to another sticker pack.

+
+ +
+
+
+name
+

The name of the sticker pack.

+
+
Type
+

str

+
+
+
+ +
+
+description
+

The description of the sticker pack.

+
+
Type
+

str

+
+
+
+ +
+
+id
+

The id of the sticker pack.

+
+
Type
+

int

+
+
+
+ +
+
+stickers
+

The stickers of this sticker pack.

+
+
Type
+

List[StandardSticker]

+
+
+
+ +
+
+sku_id
+

The SKU ID of the sticker pack.

+
+
Type
+

int

+
+
+
+ +
+
+cover_sticker_id
+

The ID of the sticker used for the cover of the sticker pack.

+
+
Type
+

int

+
+
+
+ +
+
+cover_sticker
+

The sticker used for the cover of the sticker pack.

+
+
Type
+

StandardSticker

+
+
+
+ +
+
+property banner
+

The banner asset of the sticker pack.

+
+
Type
+

Asset

+
+
+
+ +
+ +
+
+

StickerItem

+
+ +Attributes +
+ +Methods +
+
+class discord.StickerItem
+

Represents a sticker item.

+
+

New in version 2.0.

+
+
+
+
+str(x)
+

Returns the name of the sticker item.

+
+ +
+
+x == y
+

Checks if the sticker item is equal to another sticker item.

+
+ +
+
+x != y
+

Checks if the sticker item is not equal to another sticker item.

+
+ +
+
+
+name
+

The sticker’s name.

+
+
Type
+

str

+
+
+
+ +
+
+id
+

The id of the sticker.

+
+
Type
+

int

+
+
+
+ +
+
+format
+

The format for the sticker’s image.

+
+
Type
+

StickerFormatType

+
+
+
+ +
+
+url
+

The URL for the sticker’s image.

+
+
Type
+

str

+
+
+
+ +
+
+await fetch()
+

This function is a coroutine.

+

Attempts to retrieve the full sticker data of the sticker item.

+
+
Raises
+

HTTPException – Retrieving the sticker failed.

+
+
Returns
+

The retrieved sticker.

+
+
Return type
+

Union[StandardSticker, GuildSticker]

+
+
+
+ +
+ +
+
+

Sticker

+
+ +Attributes +
+
+class discord.Sticker
+

Represents a sticker.

+
+

New in version 1.6.

+
+
+
+
+str(x)
+

Returns the name of the sticker.

+
+ +
+
+x == y
+

Checks if the sticker is equal to another sticker.

+
+ +
+
+x != y
+

Checks if the sticker is not equal to another sticker.

+
+ +
+
+
+name
+

The sticker’s name.

+
+
Type
+

str

+
+
+
+ +
+
+id
+

The id of the sticker.

+
+
Type
+

int

+
+
+
+ +
+
+description
+

The description of the sticker.

+
+
Type
+

str

+
+
+
+ +
+
+pack_id
+

The id of the sticker’s pack.

+
+
Type
+

int

+
+
+
+ +
+
+format
+

The format for the sticker’s image.

+
+
Type
+

StickerFormatType

+
+
+
+ +
+
+url
+

The URL for the sticker’s image.

+
+
Type
+

str

+
+
+
+ +
+
+property created_at
+

Returns the sticker’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+ +
+
+

StandardSticker

+
+ +Attributes +
+ +Methods +
+
+class discord.StandardSticker
+

Represents a sticker that is found in a standard sticker pack.

+
+

New in version 2.0.

+
+
+
+
+str(x)
+

Returns the name of the sticker.

+
+ +
+
+x == y
+

Checks if the sticker is equal to another sticker.

+
+ +
+
+x != y
+

Checks if the sticker is not equal to another sticker.

+
+ +
+
+
+name
+

The sticker’s name.

+
+
Type
+

str

+
+
+
+ +
+
+id
+

The id of the sticker.

+
+
Type
+

int

+
+
+
+ +
+
+description
+

The description of the sticker.

+
+
Type
+

str

+
+
+
+ +
+
+pack_id
+

The id of the sticker’s pack.

+
+
Type
+

int

+
+
+
+ +
+
+format
+

The format for the sticker’s image.

+
+
Type
+

StickerFormatType

+
+
+
+ +
+
+tags
+

A list of tags for the sticker.

+
+
Type
+

List[str]

+
+
+
+ +
+
+sort_value
+

The sticker’s sort order within its pack.

+
+
Type
+

int

+
+
+
+ +
+
+await pack()
+

This function is a coroutine.

+

Retrieves the sticker pack that this sticker belongs to.

+
+
Raises
+
    +
  • InvalidData – The corresponding sticker pack was not found.

  • +
  • HTTPException – Retrieving the sticker pack failed.

  • +
+
+
Returns
+

The retrieved sticker pack.

+
+
Return type
+

StickerPack

+
+
+
+ +
+ +
+
+

GuildSticker

+
+ +Attributes +
+ +Methods +
+
+class discord.GuildSticker
+

Represents a sticker that belongs to a guild.

+
+

New in version 2.0.

+
+
+
+
+str(x)
+

Returns the name of the sticker.

+
+ +
+
+x == y
+

Checks if the sticker is equal to another sticker.

+
+ +
+
+x != y
+

Checks if the sticker is not equal to another sticker.

+
+ +
+
+
+name
+

The sticker’s name.

+
+
Type
+

str

+
+
+
+ +
+
+id
+

The id of the sticker.

+
+
Type
+

int

+
+
+
+ +
+
+description
+

The description of the sticker.

+
+
Type
+

str

+
+
+
+ +
+
+format
+

The format for the sticker’s image.

+
+
Type
+

StickerFormatType

+
+
+
+ +
+
+available
+

Whether this sticker is available for use.

+
+
Type
+

bool

+
+
+
+ +
+
+guild_id
+

The ID of the guild that this sticker is from.

+
+
Type
+

int

+
+
+
+ +
+
+user
+

The user that created this sticker. This can only be retrieved using Guild.fetch_sticker() and +having the manage_emojis_and_stickers permission.

+
+
Type
+

Optional[User]

+
+
+
+ +
+
+emoji
+

The name of a unicode emoji that represents this sticker.

+
+
Type
+

str

+
+
+
+ +
+
+guild
+

The guild that this sticker is from. +Could be None if the bot is not in the guild.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[Guild]

+
+
+
+ +
+
+await edit(*, name=..., description=..., emoji=..., reason=None)
+

This function is a coroutine.

+

Edits a GuildSticker for the guild.

+
+
Parameters
+
    +
  • name (str) – The sticker’s new name. Must be at least 2 characters.

  • +
  • description (Optional[str]) – The sticker’s new description. Can be None.

  • +
  • emoji (str) – The name of a unicode emoji that represents the sticker’s expression.

  • +
  • reason (str) – The reason for editing this sticker. Shows up on the audit log.

  • +
+
+
Raises
+
    +
  • Forbidden – You are not allowed to edit stickers.

  • +
  • HTTPException – An error occurred editing the sticker.

  • +
+
+
Returns
+

The newly modified sticker.

+
+
Return type
+

GuildSticker

+
+
+
+ +
+
+await delete(*, reason=None)
+

This function is a coroutine.

+

Deletes the custom Sticker from the guild.

+

You must have manage_emojis_and_stickers permission to +do this.

+
+
Parameters
+

reason (Optional[str]) – The reason for deleting this sticker. Shows up on the audit log.

+
+
Raises
+
    +
  • Forbidden – You are not allowed to delete stickers.

  • +
  • HTTPException – An error occurred deleting the sticker.

  • +
+
+
+
+ +
+ +
+
+

RawTypingEvent

+
+ +Attributes +
+
+class discord.RawTypingEvent
+

Represents the payload for a on_raw_typing() event.

+
+

New in version 2.0.

+
+
+
+channel_id
+

The channel ID where the typing originated from.

+
+
Type
+

int

+
+
+
+ +
+
+user_id
+

The ID of the user that started typing.

+
+
Type
+

int

+
+
+
+ +
+
+when
+

When the typing started as an aware datetime in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+guild_id
+

The guild ID where the typing originated from, if applicable.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+member
+

The member who started typing. Only available if the member started typing in a guild.

+
+
Type
+

Optional[Member]

+
+
+
+ +
+ +
+
+

RawMessageDeleteEvent

+
+
+class discord.RawMessageDeleteEvent
+

Represents the event payload for a on_raw_message_delete() event.

+
+
+channel_id
+

The channel ID where the deletion took place.

+
+
Type
+

int

+
+
+
+ +
+
+guild_id
+

The guild ID where the deletion took place, if applicable.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+message_id
+

The message ID that got deleted.

+
+
Type
+

int

+
+
+
+ +
+
+cached_message
+

The cached message, if found in the internal message cache.

+
+
Type
+

Optional[Message]

+
+
+
+ +
+ +
+
+

RawBulkMessageDeleteEvent

+
+
+class discord.RawBulkMessageDeleteEvent
+

Represents the event payload for a on_raw_bulk_message_delete() event.

+
+
+message_ids
+

A set of the message IDs that were deleted.

+
+
Type
+

Set[int]

+
+
+
+ +
+
+channel_id
+

The channel ID where the message got deleted.

+
+
Type
+

int

+
+
+
+ +
+
+guild_id
+

The guild ID where the message got deleted, if applicable.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+cached_messages
+

The cached messages, if found in the internal message cache.

+
+
Type
+

List[Message]

+
+
+
+ +
+ +
+
+

RawMessageUpdateEvent

+
+
+class discord.RawMessageUpdateEvent
+

Represents the payload for a on_raw_message_edit() event.

+
+
+message_id
+

The message ID that got updated.

+
+
Type
+

int

+
+
+
+ +
+
+channel_id
+

The channel ID where the update took place.

+
+

New in version 1.3.

+
+
+
Type
+

int

+
+
+
+ +
+
+guild_id
+

The guild ID where the message got updated, if applicable.

+
+

New in version 1.7.

+
+
+
Type
+

Optional[int]

+
+
+
+ +
+
+data
+

The raw data given by the gateway

+
+
Type
+

dict

+
+
+
+ +
+
+cached_message
+

The cached message, if found in the internal message cache. Represents the message before +it is modified by the data in RawMessageUpdateEvent.data.

+
+
Type
+

Optional[Message]

+
+
+
+ +
+ +
+
+

RawReactionActionEvent

+
+
+class discord.RawReactionActionEvent
+

Represents the payload for a on_raw_reaction_add() or +on_raw_reaction_remove() event.

+
+
+message_id
+

The message ID that got or lost a reaction.

+
+
Type
+

int

+
+
+
+ +
+
+user_id
+

The user ID who added the reaction or whose reaction was removed.

+
+
Type
+

int

+
+
+
+ +
+
+channel_id
+

The channel ID where the reaction got added or removed.

+
+
Type
+

int

+
+
+
+ +
+
+guild_id
+

The guild ID where the reaction got added or removed, if applicable.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+emoji
+

The custom or unicode emoji being used.

+
+
Type
+

PartialEmoji

+
+
+
+ +
+
+member
+

The member who added the reaction. Only available if event_type is REACTION_ADD and the reaction is inside a guild.

+
+

New in version 1.3.

+
+
+
Type
+

Optional[Member]

+
+
+
+ +
+
+event_type
+

The event type that triggered this action. Can be +REACTION_ADD for reaction addition or +REACTION_REMOVE for reaction removal.

+
+

New in version 1.3.

+
+
+
Type
+

str

+
+
+
+ +
+ +
+
+

RawReactionClearEvent

+
+ +Attributes +
+
+class discord.RawReactionClearEvent
+

Represents the payload for a on_raw_reaction_clear() event.

+
+
+message_id
+

The message ID that got its reactions cleared.

+
+
Type
+

int

+
+
+
+ +
+
+channel_id
+

The channel ID where the reactions got cleared.

+
+
Type
+

int

+
+
+
+ +
+
+guild_id
+

The guild ID where the reactions got cleared.

+
+
Type
+

Optional[int]

+
+
+
+ +
+ +
+
+

RawReactionClearEmojiEvent

+
+ +Attributes +
+
+class discord.RawReactionClearEmojiEvent
+

Represents the payload for a on_raw_reaction_clear_emoji() event.

+
+

New in version 1.3.

+
+
+
+message_id
+

The message ID that got its reactions cleared.

+
+
Type
+

int

+
+
+
+ +
+
+channel_id
+

The channel ID where the reactions got cleared.

+
+
Type
+

int

+
+
+
+ +
+
+guild_id
+

The guild ID where the reactions got cleared.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+emoji
+

The custom or unicode emoji being removed.

+
+
Type
+

PartialEmoji

+
+
+
+ +
+ +
+
+

RawIntegrationDeleteEvent

+
+ +Attributes +
+
+class discord.RawIntegrationDeleteEvent
+

Represents the payload for a on_raw_integration_delete() event.

+
+

New in version 2.0.

+
+
+
+integration_id
+

The ID of the integration that got deleted.

+
+
Type
+

int

+
+
+
+ +
+
+application_id
+

The ID of the bot/OAuth2 application for this deleted integration.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+guild_id
+

The guild ID where the integration got deleted.

+
+
Type
+

int

+
+
+
+ +
+ +
+
+

PartialWebhookGuild

+
+ +Attributes +
+
+class discord.PartialWebhookGuild
+

Represents a partial guild for webhooks.

+

These are typically given for channel follower webhooks.

+
+

New in version 2.0.

+
+
+
+id
+

The partial guild’s ID.

+
+
Type
+

int

+
+
+
+ +
+
+name
+

The partial guild’s name.

+
+
Type
+

str

+
+
+
+ +
+
+property icon
+

Returns the guild’s icon asset, if available.

+
+
Type
+

Optional[Asset]

+
+
+
+ +
+ +
+
+

PartialWebhookChannel

+
+ +Attributes +
+
+class discord.PartialWebhookChannel
+

Represents a partial channel for webhooks.

+

These are typically given for channel follower webhooks.

+
+

New in version 2.0.

+
+
+
+id
+

The partial channel’s ID.

+
+
Type
+

int

+
+
+
+ +
+
+name
+

The partial channel’s name.

+
+
Type
+

str

+
+
+
+ +
+ +
+
+
+

Data Classes

+

Some classes are just there to be data containers, this lists them.

+

Unlike models you are allowed to create +most of these yourself, even if they can also be used to hold attributes.

+

Nearly all classes here have __slots__ defined which means that it is +impossible to have dynamic attributes to the data classes.

+

The only exception to this rule is Object, which is made with +dynamic attributes in mind.

+
+

Object

+
+ +Attributes +
+
+class discord.Object(id)
+

Represents a generic Discord object.

+

The purpose of this class is to allow you to create ‘miniature’ +versions of data classes if you want to pass in just an ID. Most functions +that take in a specific data class with an ID can also take in this class +as a substitute instead. Note that even though this is the case, not all +objects (if any) actually inherit from this class.

+

There are also some cases where some websocket events are received +in strange order and when such events happened you would +receive this class rather than the actual data class. These cases are +extremely rare.

+
+
+
+x == y
+

Checks if two objects are equal.

+
+ +
+
+x != y
+

Checks if two objects are not equal.

+
+ +
+
+hash(x)
+

Returns the object’s hash.

+
+ +
+
+int(x)
+

Returns the object’s ID.

+
+ +
+
+
+id
+

The ID of the object.

+
+
Type
+

int

+
+
+
+ +
+
+property created_at
+

Returns the snowflake’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+ +
+
+

Embed

+
+
+class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)
+

Represents a Discord embed.

+
+
+
+len(x)
+

Returns the total size of the embed. +Useful for checking if it’s within the 6000 character limit.

+
+ +
+
+bool(b)
+

Returns whether the embed has any data set.

+
+

New in version 2.0.

+
+
+ +
+

Certain properties return an EmbedProxy, a type +that acts similar to a regular dict except using dotted access, +e.g. embed.author.icon_url. If the attribute +is invalid or empty, then a special sentinel value is returned, +Embed.Empty.

+

For ease of use, all parameters that expect a str are implicitly +casted to str for you.

+
+
+title
+

The title of the embed. +This can be set during initialisation.

+
+
Type
+

str

+
+
+
+ +
+
+type
+

The type of embed. Usually “rich”. +This can be set during initialisation. +Possible strings for embed types can be found on discord’s +api docs

+
+
Type
+

str

+
+
+
+ +
+
+description
+

The description of the embed. +This can be set during initialisation.

+
+
Type
+

str

+
+
+
+ +
+
+url
+

The URL of the embed. +This can be set during initialisation.

+
+
Type
+

str

+
+
+
+ +
+
+timestamp
+

The timestamp of the embed content. This is an aware datetime. +If a naive datetime is passed, it is converted to an aware +datetime with the local timezone.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+colour
+

The colour code of the embed. Aliased to color as well. +This can be set during initialisation.

+
+
Type
+

Union[Colour, int]

+
+
+
+ +
+
+Empty
+

A special sentinel value used by EmbedProxy and this class +to denote that the value or attribute is empty.

+
+
Type
+

Final

+
+
+
+ +
+
+classmethod from_dict(data)
+

Converts a dict to a Embed provided it is in the +format that Discord expects it to be in.

+

You can find out about this format in the official Discord documentation.

+
+
Parameters
+

data (dict) – The dictionary to convert into an embed.

+
+
+
+ +
+
+copy()
+

Returns a shallow copy of the embed.

+
+ +
+
+property footer
+

Returns an EmbedProxy denoting the footer contents.

+

See set_footer() for possible values you can access.

+

If the attribute has no value then Empty is returned.

+
+ +
+ +

Sets the footer for the embed content.

+

This function returns the class instance to allow for fluent-style +chaining.

+
+
Parameters
+
    +
  • text (str) – The footer text.

  • +
  • icon_url (str) – The URL of the footer icon. Only HTTP(S) is supported.

  • +
+
+
+
+ +
+ +

Clears embed’s footer information.

+

This function returns the class instance to allow for fluent-style +chaining.

+
+

New in version 2.0.

+
+
+ +
+
+property image
+

Returns an EmbedProxy denoting the image contents.

+

Possible attributes you can access are:

+
    +
  • url

  • +
  • proxy_url

  • +
  • width

  • +
  • height

  • +
+

If the attribute has no value then Empty is returned.

+
+ +
+
+set_image(*, url)
+

Sets the image for the embed content.

+

This function returns the class instance to allow for fluent-style +chaining.

+
+

Changed in version 1.4: Passing Empty removes the image.

+
+
+
Parameters
+

url (str) – The source URL for the image. Only HTTP(S) is supported.

+
+
+
+ +
+
+property thumbnail
+

Returns an EmbedProxy denoting the thumbnail contents.

+

Possible attributes you can access are:

+
    +
  • url

  • +
  • proxy_url

  • +
  • width

  • +
  • height

  • +
+

If the attribute has no value then Empty is returned.

+
+ +
+
+set_thumbnail(*, url)
+

Sets the thumbnail for the embed content.

+

This function returns the class instance to allow for fluent-style +chaining.

+
+

Changed in version 1.4: Passing Empty removes the thumbnail.

+
+
+
Parameters
+

url (str) – The source URL for the thumbnail. Only HTTP(S) is supported.

+
+
+
+ +
+
+property video
+

Returns an EmbedProxy denoting the video contents.

+

Possible attributes include:

+
    +
  • url for the video URL.

  • +
  • height for the video height.

  • +
  • width for the video width.

  • +
+

If the attribute has no value then Empty is returned.

+
+ +
+
+property provider
+

Returns an EmbedProxy denoting the provider contents.

+

The only attributes that might be accessed are name and url.

+

If the attribute has no value then Empty is returned.

+
+ +
+
+property author
+

Returns an EmbedProxy denoting the author contents.

+

See set_author() for possible values you can access.

+

If the attribute has no value then Empty is returned.

+
+ +
+
+set_author(*, name, url=Embed.Empty, icon_url=Embed.Empty)
+

Sets the author for the embed content.

+

This function returns the class instance to allow for fluent-style +chaining.

+
+
Parameters
+
    +
  • name (str) – The name of the author.

  • +
  • url (str) – The URL for the author.

  • +
  • icon_url (str) – The URL of the author icon. Only HTTP(S) is supported.

  • +
+
+
+
+ +
+
+remove_author()
+

Clears embed’s author information.

+

This function returns the class instance to allow for fluent-style +chaining.

+
+

New in version 1.4.

+
+
+ +
+
+property fields
+

Returns a list of EmbedProxy denoting the field contents.

+

See add_field() for possible values you can access.

+

If the attribute has no value then Empty is returned.

+
+
Type
+

List[Union[EmbedProxy, Empty]]

+
+
+
+ +
+
+add_field(*, name, value, inline=True)
+

Adds a field to the embed object.

+

This function returns the class instance to allow for fluent-style +chaining.

+
+
Parameters
+
    +
  • name (str) – The name of the field.

  • +
  • value (str) – The value of the field.

  • +
  • inline (bool) – Whether the field should be displayed inline.

  • +
+
+
+
+ +
+
+insert_field_at(index, *, name, value, inline=True)
+

Inserts a field before a specified index to the embed.

+

This function returns the class instance to allow for fluent-style +chaining.

+
+

New in version 1.2.

+
+
+
Parameters
+
    +
  • index (int) – The index of where to insert the field.

  • +
  • name (str) – The name of the field.

  • +
  • value (str) – The value of the field.

  • +
  • inline (bool) – Whether the field should be displayed inline.

  • +
+
+
+
+ +
+
+clear_fields()
+

Removes all fields from this embed.

+
+ +
+
+remove_field(index)
+

Removes a field at a specified index.

+

If the index is invalid or out of bounds then the error is +silently swallowed.

+
+

Note

+

When deleting a field by index, the index of the other fields +shift to fill the gap just like a regular list.

+
+
+
Parameters
+

index (int) – The index of the field to remove.

+
+
+
+ +
+
+set_field_at(index, *, name, value, inline=True)
+

Modifies a field to the embed object.

+

The index must point to a valid pre-existing field.

+

This function returns the class instance to allow for fluent-style +chaining.

+
+
Parameters
+
    +
  • index (int) – The index of the field to modify.

  • +
  • name (str) – The name of the field.

  • +
  • value (str) – The value of the field.

  • +
  • inline (bool) – Whether the field should be displayed inline.

  • +
+
+
Raises
+

IndexError – An invalid index was provided.

+
+
+
+ +
+
+to_dict()
+

Converts this embed object into a dict.

+
+ +
+ +
+
+

AllowedMentions

+
+ +Attributes +
+ +Methods +
+
+class discord.AllowedMentions(*, everyone=True, users=True, roles=True, replied_user=True)
+

A class that represents what mentions are allowed in a message.

+

This class can be set during Client initialisation to apply +to every message sent. It can also be applied on a per message basis +via abc.Messageable.send() for more fine-grained control.

+
+
+everyone
+

Whether to allow everyone and here mentions. Defaults to True.

+
+
Type
+

bool

+
+
+
+ +
+
+users
+

Controls the users being mentioned. If True (the default) then +users are mentioned based on the message content. If False then +users are not mentioned at all. If a list of abc.Snowflake +is given then only the users provided will be mentioned, provided those +users are in the message content.

+
+
Type
+

Union[bool, List[abc.Snowflake]]

+
+
+
+ +
+
+roles
+

Controls the roles being mentioned. If True (the default) then +roles are mentioned based on the message content. If False then +roles are not mentioned at all. If a list of abc.Snowflake +is given then only the roles provided will be mentioned, provided those +roles are in the message content.

+
+
Type
+

Union[bool, List[abc.Snowflake]]

+
+
+
+ +
+
+replied_user
+

Whether to mention the author of the message being replied to. Defaults +to True.

+
+

New in version 1.6.

+
+
+
Type
+

bool

+
+
+
+ +
+
+classmethod all()
+

A factory method that returns a AllowedMentions with all fields explicitly set to True

+
+

New in version 1.5.

+
+
+ +
+
+classmethod none()
+

A factory method that returns a AllowedMentions with all fields set to False

+
+

New in version 1.5.

+
+
+ +
+ +
+
+

MessageReference

+
+
+class discord.MessageReference(*, message_id, channel_id, guild_id=None, fail_if_not_exists=True)
+

Represents a reference to a Message.

+
+

New in version 1.5.

+
+
+

Changed in version 1.6: This class can now be constructed by users.

+
+
+
+message_id
+

The id of the message referenced.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+channel_id
+

The channel id of the message referenced.

+
+
Type
+

int

+
+
+
+ +
+
+guild_id
+

The guild id of the message referenced.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+fail_if_not_exists
+

Whether replying to the referenced message should raise HTTPException +if the message no longer exists or Discord could not fetch the message.

+
+

New in version 1.7.

+
+
+
Type
+

bool

+
+
+
+ +
+
+resolved
+

The message that this reference resolved to. If this is None +then the original message was not fetched either due to the Discord API +not attempting to resolve it or it not being available at the time of creation. +If the message was resolved at a prior point but has since been deleted then +this will be of type DeletedReferencedMessage.

+

Currently, this is mainly the replied to message when a user replies to a message.

+
+

New in version 1.6.

+
+
+
Type
+

Optional[Union[Message, DeletedReferencedMessage]]

+
+
+
+ +
+
+classmethod from_message(message, *, fail_if_not_exists=True)
+

Creates a MessageReference from an existing Message.

+
+

New in version 1.6.

+
+
+
Parameters
+
    +
  • message (Message) – The message to be converted into a reference.

  • +
  • fail_if_not_exists (bool) –

    Whether replying to the referenced message should raise HTTPException +if the message no longer exists or Discord could not fetch the message.

    +
    +

    New in version 1.7.

    +
    +

  • +
+
+
Returns
+

A reference to the message.

+
+
Return type
+

MessageReference

+
+
+
+ +
+
+property cached_message
+

The cached message, if found in the internal message cache.

+
+
Type
+

Optional[Message]

+
+
+
+ +
+
+property jump_url
+

Returns a URL that allows the client to jump to the referenced message.

+
+

New in version 1.7.

+
+
+
Type
+

str

+
+
+
+ +
+ +
+
+

PartialMessage

+
+ +Attributes +
+ +Methods +
+
+class discord.PartialMessage(*, channel, id)
+

Represents a partial message to aid with working messages when only +a message and channel ID are present.

+

There are two ways to construct this class. The first one is through +the constructor itself, and the second is via the following:

+ +

Note that this class is trimmed down and has no rich attributes.

+
+

New in version 1.6.

+
+
+
+
+x == y
+

Checks if two partial messages are equal.

+
+ +
+
+x != y
+

Checks if two partial messages are not equal.

+
+ +
+
+hash(x)
+

Returns the partial message’s hash.

+
+ +
+
+int(x)
+

Returns the partial message’s ID.

+
+ +
+
+
+channel
+

The channel associated with this partial message.

+
+
Type
+

Union[TextChannel, Thread, DMChannel]

+
+
+
+ +
+
+id
+

The message ID.

+
+
Type
+

int

+
+
+
+ +
+
+property jump_url
+

Returns a URL that allows the client to jump to this message.

+
+
Type
+

str

+
+
+
+ +
+
+await delete(*, delay=None, silent=False)
+

This function is a coroutine.

+

Deletes the message.

+

Your own messages could be deleted without any proper permissions. However to +delete other people’s messages, you need the manage_messages +permission.

+
+

Changed in version 1.1: Added the new delay keyword-only parameter.

+
+
+

Changed in version 2.0: Added the new silent keyword-only parameter.

+
+
+
Parameters
+
    +
  • delay (Optional[float]) – If provided, the number of seconds to wait in the background +before deleting the message. If the deletion fails then it is silently ignored.

  • +
  • silent (bool) – If silent is set to True, the error will not be raised, it will be ignored. +This defaults to False

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have proper permissions to delete the message.

  • +
  • NotFound – The message was deleted already

  • +
  • HTTPException – Deleting the message failed.

  • +
+
+
+
+ +
+
+await publish()
+

This function is a coroutine.

+

Publishes this message to your announcement channel.

+

You must have the send_messages permission to do this.

+

If the message is not your own then the manage_messages +permission is also needed.

+
+
Raises
+
    +
  • Forbidden – You do not have the proper permissions to publish this message.

  • +
  • HTTPException – Publishing the message failed.

  • +
+
+
+
+ +
+
+await pin(*, reason=None)
+

This function is a coroutine.

+

Pins the message.

+

You must have the manage_messages permission to do +this in a non-private channel context.

+
+
Parameters
+

reason (Optional[str]) –

The reason for pinning the message. Shows up on the audit log.

+
+

New in version 1.4.

+
+

+
+
Raises
+
    +
  • Forbidden – You do not have permissions to pin the message.

  • +
  • NotFound – The message or channel was not found or deleted.

  • +
  • HTTPException – Pinning the message failed, probably due to the channel + having more than 50 pinned messages.

  • +
+
+
+
+ +
+
+await unpin(*, reason=None)
+

This function is a coroutine.

+

Unpins the message.

+

You must have the manage_messages permission to do +this in a non-private channel context.

+
+
Parameters
+

reason (Optional[str]) –

The reason for unpinning the message. Shows up on the audit log.

+
+

New in version 1.4.

+
+

+
+
Raises
+
    +
  • Forbidden – You do not have permissions to unpin the message.

  • +
  • NotFound – The message or channel was not found or deleted.

  • +
  • HTTPException – Unpinning the message failed.

  • +
+
+
+
+ +
+
+await add_reaction(emoji)
+

This function is a coroutine.

+

Add a reaction to the message.

+

The emoji may be a unicode emoji or a custom guild Emoji.

+

You must have the read_message_history permission +to use this. If nobody else has reacted to the message using this +emoji, the add_reactions permission is required.

+
+
Parameters
+

emoji (Union[Emoji, Reaction, PartialEmoji, str]) – The emoji to react with.

+
+
Raises
+
    +
  • HTTPException – Adding the reaction failed.

  • +
  • Forbidden – You do not have the proper permissions to react to the message.

  • +
  • NotFound – The emoji you specified was not found.

  • +
  • InvalidArgument – The emoji parameter is invalid.

  • +
+
+
+
+ +
+
+await remove_reaction(emoji, member)
+

This function is a coroutine.

+

Remove a reaction by the member from the message.

+

The emoji may be a unicode emoji or a custom guild Emoji.

+

If the reaction is not your own (i.e. member parameter is not you) then +the manage_messages permission is needed.

+

The member parameter must represent a member and meet +the abc.Snowflake abc.

+
+
Parameters
+
+
+
Raises
+
    +
  • HTTPException – Removing the reaction failed.

  • +
  • Forbidden – You do not have the proper permissions to remove the reaction.

  • +
  • NotFound – The member or emoji you specified was not found.

  • +
  • InvalidArgument – The emoji parameter is invalid.

  • +
+
+
+
+ +
+
+await clear_reaction(emoji)
+

This function is a coroutine.

+

Clears a specific reaction from the message.

+

The emoji may be a unicode emoji or a custom guild Emoji.

+

You need the manage_messages permission to use this.

+
+

New in version 1.3.

+
+
+
Parameters
+

emoji (Union[Emoji, Reaction, PartialEmoji, str]) – The emoji to clear.

+
+
Raises
+
    +
  • HTTPException – Clearing the reaction failed.

  • +
  • Forbidden – You do not have the proper permissions to clear the reaction.

  • +
  • NotFound – The emoji you specified was not found.

  • +
  • InvalidArgument – The emoji parameter is invalid.

  • +
+
+
+
+ +
+
+await clear_reactions()
+

This function is a coroutine.

+

Removes all the reactions from the message.

+

You need the manage_messages permission to use this.

+
+
Raises
+
    +
  • HTTPException – Removing the reactions failed.

  • +
  • Forbidden – You do not have the proper permissions to remove all the reactions.

  • +
+
+
+
+ +
+
+await reply(content=None, **kwargs)
+

This function is a coroutine.

+

A shortcut method to abc.Messageable.send() to reply to the +Message.

+
+

New in version 1.6.

+
+
+
Raises
+
    +
  • HTTPException – Sending the message failed.

  • +
  • Forbidden – You do not have the proper permissions to send the message.

  • +
  • InvalidArgument – The files list is not of the appropriate size or + you specified both file and files.

  • +
+
+
Returns
+

The message that was sent.

+
+
Return type
+

Message

+
+
+
+ +
+
+to_reference(*, fail_if_not_exists=True)
+

Creates a MessageReference from the current message.

+
+

New in version 1.6.

+
+
+
Parameters
+

fail_if_not_exists (bool) –

Whether replying using the message reference should raise HTTPException +if the message no longer exists or Discord could not fetch the message.

+
+

New in version 1.7.

+
+

+
+
Returns
+

The reference to this message.

+
+
Return type
+

MessageReference

+
+
+
+ +
+
+property created_at
+

The partial message’s creation time in UTC.

+
+
Type
+

datetime.datetime

+
+
+
+ +
+
+guild
+

The guild that the partial message belongs to, if applicable.

+
+
Type
+

Optional[Guild]

+
+
+
+ +
+
+await fetch()
+

This function is a coroutine.

+

Fetches the partial message to a full Message.

+
+
Raises
+
    +
  • NotFound – The message was not found.

  • +
  • Forbidden – You do not have the permissions required to get a message.

  • +
  • HTTPException – Retrieving the message failed.

  • +
+
+
Returns
+

The full message.

+
+
Return type
+

Message

+
+
+
+ +
+
+await edit(**fields)
+

This function is a coroutine.

+

Edits the message.

+

The content must be able to be transformed into a string via str(content).

+
+

Changed in version 1.7: discord.Message is returned instead of None if an edit took place.

+
+
+
Parameters
+
    +
  • content (Optional[str]) – The new content to replace the message with. +Could be None to remove the content.

  • +
  • embed (Optional[Embed]) – The new embed to replace the original with. +Could be None to remove the embed.

  • +
  • suppress (bool) – Whether to suppress embeds for the message. This removes +all the embeds if set to True. If set to False +this brings the embeds back if they were suppressed. +Using this parameter requires manage_messages.

  • +
  • delete_after (Optional[float]) – If provided, the number of seconds to wait in the background +before deleting the message we just edited. If the deletion fails, +then it is silently ignored.

  • +
  • allowed_mentions (Optional[AllowedMentions]) – Controls the mentions being processed in this message. If this is +passed, then the object is merged with allowed_mentions. +The merging behaviour only overrides attributes that have been explicitly passed +to the object, otherwise it uses the attributes set in allowed_mentions. +If no object is passed at all then the defaults given by allowed_mentions +are used instead.

  • +
  • view (Optional[View]) –

    The updated view to update this message with. If None is passed then +the view is removed.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
    +
  • NotFound – The message was not found.

  • +
  • HTTPException – Editing the message failed.

  • +
  • Forbidden – Tried to suppress a message without permissions or + edited a message’s content or embed that isn’t yours.

  • +
+
+
Returns
+

The message that was edited.

+
+
Return type
+

Optional[Message]

+
+
+
+ +
+ +
+
+

SelectOption

+
+ +Attributes +
+
+class discord.SelectOption(*, label, value=..., description=None, emoji=None, default=False)
+

Represents a select menu’s option.

+

These can be created by users.

+
+

New in version 2.0.

+
+
+
+label
+

The label of the option. This is displayed to users. +Can only be up to 100 characters.

+
+
Type
+

str

+
+
+
+ +
+
+value
+

The value of the option. This is not displayed to users. +If not provided when constructed then it defaults to the +label. Can only be up to 100 characters.

+
+
Type
+

str

+
+
+
+ +
+
+description
+

An additional description of the option, if any. +Can only be up to 100 characters.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+emoji
+

The emoji of the option, if available.

+
+
Type
+

Optional[Union[str, Emoji, PartialEmoji]]

+
+
+
+ +
+
+default
+

Whether this option is selected by default.

+
+
Type
+

bool

+
+
+
+ +
+ +
+
+

Intents

+
+
+class discord.Intents(**kwargs)
+

Wraps up a Discord gateway intent flag.

+

Similar to Permissions, the properties provided are two way. +You can set and retrieve individual bits using the properties as if they +were regular bools.

+

To construct an object you can pass keyword arguments denoting the flags +to enable or disable.

+

This is used to disable certain gateway features that are unnecessary to +run your bot. To make use of this, it is passed to the intents keyword +argument of Client.

+
+

New in version 1.5.

+
+
+
+
+x == y
+

Checks if two flags are equal.

+
+ +
+
+x != y
+

Checks if two flags are not equal.

+
+ +
+
+hash(x)
+

Return the flag’s hash.

+
+ +
+
+iter(x)
+

Returns an iterator of (name, value) pairs. This allows it +to be, for example, constructed as a dict or a list of pairs.

+
+ +
+
+
+value
+

The raw value. You should query flags via the properties +rather than using this raw value.

+
+
Type
+

int

+
+
+
+ +
+
+classmethod all()
+

A factory method that creates a Intents with everything enabled.

+
+ +
+
+classmethod none()
+

A factory method that creates a Intents with everything disabled.

+
+ +
+
+guilds
+

Whether guild related events are enabled.

+

This corresponds to the following events:

+ +

This also corresponds to the following attributes and classes in terms of cache:

+ +

It is highly advisable to leave this intent enabled for your bot to function.

+
+
Type
+

bool

+
+
+
+ +
+
+members
+

Whether guild member related events are enabled.

+

This corresponds to the following events:

+ +

This also corresponds to the following attributes and classes in terms of cache:

+ +

For more information go to the member intent documentation.

+
+

Note

+

Currently, this requires opting in explicitly via the developer portal as well. +Bots in over 100 guilds will need to apply to Discord for verification.

+
+
+
Type
+

bool

+
+
+
+ +
+
+bans
+

Whether guild ban related events are enabled.

+

This corresponds to the following events:

+ +

This does not correspond to any attributes or classes in the library in terms of cache.

+
+
Type
+

bool

+
+
+
+ +
+
+emojis
+

Alias of emojis_and_stickers.

+
+

Changed in version 2.0: Changed to an alias.

+
+
+
Type
+

bool

+
+
+
+ +
+
+emojis_and_stickers
+

Whether guild emoji and sticker related events are enabled.

+
+

New in version 2.0.

+
+

This corresponds to the following events:

+ +

This also corresponds to the following attributes and classes in terms of cache:

+ +
+
Type
+

bool

+
+
+
+ +
+
+integrations
+

Whether guild integration related events are enabled.

+

This corresponds to the following events:

+ +

This does not correspond to any attributes or classes in the library in terms of cache.

+
+
Type
+

bool

+
+
+
+ +
+
+webhooks
+

Whether guild webhook related events are enabled.

+

This corresponds to the following events:

+ +

This does not correspond to any attributes or classes in the library in terms of cache.

+
+
Type
+

bool

+
+
+
+ +
+
+invites
+

Whether guild invite related events are enabled.

+

This corresponds to the following events:

+ +

This does not correspond to any attributes or classes in the library in terms of cache.

+
+
Type
+

bool

+
+
+
+ +
+
+voice_states
+

Whether guild voice state related events are enabled.

+

This corresponds to the following events:

+ +

This also corresponds to the following attributes and classes in terms of cache:

+ +
+

Note

+

This intent is required to connect to voice.

+
+
+
Type
+

bool

+
+
+
+ +
+
+presences
+

Whether guild presence related events are enabled.

+

This corresponds to the following events:

+ +

This also corresponds to the following attributes and classes in terms of cache:

+ +

For more information go to the presence intent documentation.

+
+

Note

+

Currently, this requires opting in explicitly via the developer portal as well. +Bots in over 100 guilds will need to apply to Discord for verification.

+
+
+
Type
+

bool

+
+
+
+ +
+
+messages
+

Whether guild and direct message related events are enabled.

+

This is a shortcut to set or get both guild_messages and dm_messages.

+

This corresponds to the following events:

+ +

This also corresponds to the following attributes and classes in terms of cache:

+ +

Note that due to an implicit relationship this also corresponds to the following events:

+ +
+
Type
+

bool

+
+
+
+ +
+
+guild_messages
+

Whether guild message related events are enabled.

+

See also dm_messages for DMs or messages for both.

+

This corresponds to the following events:

+ +

This also corresponds to the following attributes and classes in terms of cache:

+ +

Note that due to an implicit relationship this also corresponds to the following events:

+ +
+
Type
+

bool

+
+
+
+ +
+
+dm_messages
+

Whether direct message related events are enabled.

+

See also guild_messages for guilds or messages for both.

+

This corresponds to the following events:

+ +

This also corresponds to the following attributes and classes in terms of cache:

+ +

Note that due to an implicit relationship this also corresponds to the following events:

+ +
+
Type
+

bool

+
+
+
+ +
+
+reactions
+

Whether guild and direct message reaction related events are enabled.

+

This is a shortcut to set or get both guild_reactions and dm_reactions.

+

This corresponds to the following events:

+ +

This also corresponds to the following attributes and classes in terms of cache:

+ +
+
Type
+

bool

+
+
+
+ +
+
+guild_reactions
+

Whether guild message reaction related events are enabled.

+

See also dm_reactions for DMs or reactions for both.

+

This corresponds to the following events:

+ +

This also corresponds to the following attributes and classes in terms of cache:

+ +
+
Type
+

bool

+
+
+
+ +
+
+dm_reactions
+

Whether direct message reaction related events are enabled.

+

See also guild_reactions for guilds or reactions for both.

+

This corresponds to the following events:

+ +

This also corresponds to the following attributes and classes in terms of cache:

+ +
+
Type
+

bool

+
+
+
+ +
+
+typing
+

Whether guild and direct message typing related events are enabled.

+

This is a shortcut to set or get both guild_typing and dm_typing.

+

This corresponds to the following events:

+ +

This does not correspond to any attributes or classes in the library in terms of cache.

+
+
Type
+

bool

+
+
+
+ +
+
+guild_typing
+

Whether guild and direct message typing related events are enabled.

+

See also dm_typing for DMs or typing for both.

+

This corresponds to the following events:

+ +

This does not correspond to any attributes or classes in the library in terms of cache.

+
+
Type
+

bool

+
+
+
+ +
+
+dm_typing
+

Whether guild and direct message typing related events are enabled.

+

See also guild_typing for guilds or typing for both.

+

This corresponds to the following events:

+ +

This does not correspond to any attributes or classes in the library in terms of cache.

+
+
Type
+

bool

+
+
+
+ +
+ +
+
+

MemberCacheFlags

+
+ +Attributes +
+
+class discord.MemberCacheFlags(**kwargs)
+

Controls the library’s cache policy when it comes to members.

+

This allows for finer grained control over what members are cached. +Note that the bot’s own member is always cached. This class is passed +to the member_cache_flags parameter in Client.

+

Due to a quirk in how Discord works, in order to ensure proper cleanup +of cache resources it is recommended to have Intents.members +enabled. Otherwise the library cannot know when a member leaves a guild and +is thus unable to cleanup after itself.

+

To construct an object you can pass keyword arguments denoting the flags +to enable or disable.

+

The default value is all flags enabled.

+
+

New in version 1.5.

+
+
+
+
+x == y
+

Checks if two flags are equal.

+
+ +
+
+x != y
+

Checks if two flags are not equal.

+
+ +
+
+hash(x)
+

Return the flag’s hash.

+
+ +
+
+iter(x)
+

Returns an iterator of (name, value) pairs. This allows it +to be, for example, constructed as a dict or a list of pairs.

+
+ +
+
+
+value
+

The raw value. You should query flags via the properties +rather than using this raw value.

+
+
Type
+

int

+
+
+
+ +
+
+classmethod all()
+

A factory method that creates a MemberCacheFlags with everything enabled.

+
+ +
+
+classmethod none()
+

A factory method that creates a MemberCacheFlags with everything disabled.

+
+ +
+
+voice
+

Whether to cache members that are in voice.

+

This requires Intents.voice_states.

+

Members that leave voice are no longer cached.

+
+
Type
+

bool

+
+
+
+ +
+
+joined
+

Whether to cache members that joined the guild +or are chunked as part of the initial log in flow.

+

This requires Intents.members.

+

Members that leave the guild are no longer cached.

+
+
Type
+

bool

+
+
+
+ +
+
+classmethod from_intents(intents)
+

A factory method that creates a MemberCacheFlags based on +the currently selected Intents.

+
+
Parameters
+

intents (Intents) – The intents to select from.

+
+
Returns
+

The resulting member cache flags.

+
+
Return type
+

MemberCacheFlags

+
+
+
+ +
+ +
+
+

ApplicationFlags

+
+
+class discord.ApplicationFlags(**kwargs)
+

Wraps up the Discord Application flags.

+
+
+
+x == y
+

Checks if two ApplicationFlags are equal.

+
+ +
+
+x != y
+

Checks if two ApplicationFlags are not equal.

+
+ +
+
+hash(x)
+

Return the flag’s hash.

+
+ +
+
+iter(x)
+

Returns an iterator of (name, value) pairs. This allows it +to be, for example, constructed as a dict or a list of pairs. +Note that aliases are not shown.

+
+ +
+
+

New in version 2.0.

+
+
+
+value
+

The raw value. You should query flags via the properties +rather than using this raw value.

+
+
Type
+

int

+
+
+
+ +
+
+gateway_presence
+

Returns True if the application is verified and is allowed to +receive presence information over the gateway.

+
+
Type
+

bool

+
+
+
+ +
+
+gateway_presence_limited
+

Returns True if the application is allowed to receive limited +presence information over the gateway.

+
+
Type
+

bool

+
+
+
+ +
+
+gateway_guild_members
+

Returns True if the application is verified and is allowed to +receive guild members information over the gateway.

+
+
Type
+

bool

+
+
+
+ +
+
+gateway_guild_members_limited
+

Returns True if the application is allowed to receive limited +guild members information over the gateway.

+
+
Type
+

bool

+
+
+
+ +
+
+verification_pending_guild_limit
+

Returns True if the application is currently pending verification +and has hit the guild limit.

+
+
Type
+

bool

+
+
+
+ +
+
+embedded
+

Returns True if the application is embedded within the Discord client.

+
+
Type
+

bool

+
+
+
+ +
+ +
+
+

File

+
+ +Attributes +
+
+class discord.File(fp, filename=None, *, spoiler=False)
+

A parameter object used for abc.Messageable.send() +for sending file objects.

+
+

Note

+

File objects are single use and are not meant to be reused in +multiple abc.Messageable.send()s.

+
+
+
+fp
+

A file-like object opened in binary mode and read mode +or a filename representing a file in the hard drive to +open.

+
+

Note

+

If the file-like object passed is opened via open then the +modes ‘rb’ should be used.

+

To pass binary data, consider usage of io.BytesIO.

+
+
+
Type
+

Union[os.PathLike, io.BufferedIOBase]

+
+
+
+ +
+
+filename
+

The filename to display when uploading to Discord. +If this is not given then it defaults to fp.name or if fp is +a string then the filename will default to the string given.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+spoiler
+

Whether the attachment is a spoiler.

+
+
Type
+

bool

+
+
+
+ +
+ +
+
+

Colour

+
+
+class discord.Colour(value)
+

Represents a Discord role colour. This class is similar +to a (red, green, blue) tuple.

+

There is an alias for this called Color.

+
+
+
+x == y
+

Checks if two colours are equal.

+
+ +
+
+x != y
+

Checks if two colours are not equal.

+
+ +
+
+hash(x)
+

Return the colour’s hash.

+
+ +
+
+str(x)
+

Returns the hex format for the colour.

+
+ +
+
+int(x)
+

Returns the raw colour value.

+
+ +
+
+
+value
+

The raw integer colour value.

+
+
Type
+

int

+
+
+
+ +
+
+property r
+

Returns the red component of the colour.

+
+
Type
+

int

+
+
+
+ +
+
+property g
+

Returns the green component of the colour.

+
+
Type
+

int

+
+
+
+ +
+
+property b
+

Returns the blue component of the colour.

+
+
Type
+

int

+
+
+
+ +
+
+to_rgb()
+

Tuple[int, int, int]: Returns an (r, g, b) tuple representing the colour.

+
+ +
+
+classmethod from_rgb(r, g, b)
+

Constructs a Colour from an RGB tuple.

+
+ +
+
+classmethod from_hsv(h, s, v)
+

Constructs a Colour from an HSV tuple.

+
+ +
+
+classmethod default()
+

A factory method that returns a Colour with a value of 0.

+
+ +
+
+classmethod random(*, seed=None)
+

A factory method that returns a Colour with a random hue.

+
+

Note

+

The random algorithm works by choosing a colour with a random hue but +with maxed out saturation and value.

+
+
+

New in version 1.6.

+
+
+
Parameters
+

seed (Optional[Union[int, str, float, bytes, bytearray]]) –

The seed to initialize the RNG with. If None is passed the default RNG is used.

+
+

New in version 1.7.

+
+

+
+
+
+ +
+
+classmethod teal()
+

A factory method that returns a Colour with a value of 0x1abc9c.

+
+ +
+
+classmethod dark_teal()
+

A factory method that returns a Colour with a value of 0x11806a.

+
+ +
+
+classmethod brand_green()
+

A factory method that returns a Colour with a value of 0x57F287.

+
+

New in version 2.0.

+
+
+ +
+
+classmethod green()
+

A factory method that returns a Colour with a value of 0x2ecc71.

+
+ +
+
+classmethod dark_green()
+

A factory method that returns a Colour with a value of 0x1f8b4c.

+
+ +
+
+classmethod blue()
+

A factory method that returns a Colour with a value of 0x3498db.

+
+ +
+
+classmethod dark_blue()
+

A factory method that returns a Colour with a value of 0x206694.

+
+ +
+
+classmethod purple()
+

A factory method that returns a Colour with a value of 0x9b59b6.

+
+ +
+
+classmethod dark_purple()
+

A factory method that returns a Colour with a value of 0x71368a.

+
+ +
+
+classmethod magenta()
+

A factory method that returns a Colour with a value of 0xe91e63.

+
+ +
+
+classmethod dark_magenta()
+

A factory method that returns a Colour with a value of 0xad1457.

+
+ +
+
+classmethod gold()
+

A factory method that returns a Colour with a value of 0xf1c40f.

+
+ +
+
+classmethod dark_gold()
+

A factory method that returns a Colour with a value of 0xc27c0e.

+
+ +
+
+classmethod orange()
+

A factory method that returns a Colour with a value of 0xe67e22.

+
+ +
+
+classmethod dark_orange()
+

A factory method that returns a Colour with a value of 0xa84300.

+
+ +
+
+classmethod brand_red()
+

A factory method that returns a Colour with a value of 0xED4245.

+
+

New in version 2.0.

+
+
+ +
+
+classmethod red()
+

A factory method that returns a Colour with a value of 0xe74c3c.

+
+ +
+
+classmethod nitro_booster()
+

A factory method that returns a Colour with a value of 0xf47fff.

+
+

New in version 2.0.

+
+
+ +
+
+classmethod dark_red()
+

A factory method that returns a Colour with a value of 0x992d22.

+
+ +
+
+classmethod lighter_grey()
+

A factory method that returns a Colour with a value of 0x95a5a6.

+
+ +
+
+classmethod lighter_gray()
+

A factory method that returns a Colour with a value of 0x95a5a6.

+
+ +
+
+classmethod dark_grey()
+

A factory method that returns a Colour with a value of 0x607d8b.

+
+ +
+
+classmethod dark_gray()
+

A factory method that returns a Colour with a value of 0x607d8b.

+
+ +
+
+classmethod light_grey()
+

A factory method that returns a Colour with a value of 0x979c9f.

+
+ +
+
+classmethod light_gray()
+

A factory method that returns a Colour with a value of 0x979c9f.

+
+ +
+
+classmethod darker_grey()
+

A factory method that returns a Colour with a value of 0x546e7a.

+
+ +
+
+classmethod darker_gray()
+

A factory method that returns a Colour with a value of 0x546e7a.

+
+ +
+
+classmethod og_blurple()
+

A factory method that returns a Colour with a value of 0x7289da.

+
+ +
+
+classmethod blurple()
+

A factory method that returns a Colour with a value of 0x5865F2.

+
+ +
+
+classmethod greyple()
+

A factory method that returns a Colour with a value of 0x99aab5.

+
+ +
+
+classmethod dark_theme()
+

A factory method that returns a Colour with a value of 0x36393F. +This will appear transparent on Discord’s dark theme.

+
+

New in version 1.5.

+
+
+ +
+
+classmethod fuchsia()
+

A factory method that returns a Colour with a value of 0xEB459E.

+
+

New in version 2.0.

+
+
+ +
+
+classmethod yellow()
+

A factory method that returns a Colour with a value of 0xFEE75C.

+
+

New in version 2.0.

+
+
+ +
+
+classmethod dark_blurple()
+

A factory method that returns a Colour with a value of 0x4E5D94. +This is the original Dark Blurple branding.

+
+

New in version 2.0.

+
+
+ +
+ +
+
+

BaseActivity

+
+ +Attributes +
+
+class discord.BaseActivity(**kwargs)
+

The base activity that all user-settable activities inherit from. +A user-settable activity is one that can be used in Client.change_presence().

+

The following types currently count as user-settable:

+ +

Note that although these types are considered user-settable by the library, +Discord typically ignores certain combinations of activity depending on +what is currently set. This behaviour may change in the future so there are +no guarantees on whether Discord will actually let you set these types.

+
+

New in version 1.3.

+
+
+
+property created_at
+

When the user started doing this activity in UTC.

+
+

New in version 1.3.

+
+
+
Type
+

Optional[datetime.datetime]

+
+
+
+ +
+ +
+
+

Activity

+
+
+class discord.Activity(**kwargs)
+

Represents an activity in Discord.

+

This could be an activity such as streaming, playing, listening +or watching.

+

For memory optimisation purposes, some activities are offered in slimmed +down versions:

+ +
+
+application_id
+

The application ID of the game.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+name
+

The name of the activity.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+url
+

A stream URL that the activity could be doing.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+type
+

The type of activity currently being done.

+
+
Type
+

ActivityType

+
+
+
+ +
+
+state
+

The user’s current state. For example, “In Game”.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+details
+

The detail of the user’s current activity.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+timestamps
+

A dictionary of timestamps. It contains the following optional keys:

+
    +
  • start: Corresponds to when the user started doing the +activity in milliseconds since Unix epoch.

  • +
  • end: Corresponds to when the user will finish doing the +activity in milliseconds since Unix epoch.

  • +
+
+
Type
+

dict

+
+
+
+ +
+
+assets
+

A dictionary representing the images and their hover text of an activity. +It contains the following optional keys:

+
    +
  • large_image: A string representing the ID for the large image asset.

  • +
  • large_text: A string representing the text when hovering over the large image asset.

  • +
  • small_image: A string representing the ID for the small image asset.

  • +
  • small_text: A string representing the text when hovering over the small image asset.

  • +
+
+
Type
+

dict

+
+
+
+ +
+
+party
+

A dictionary representing the activity party. It contains the following optional keys:

+
    +
  • id: A string representing the party ID.

  • +
  • size: A list of up to two integer elements denoting (current_size, maximum_size).

  • +
+
+
Type
+

dict

+
+
+
+ +
+
+buttons
+

An list of dictionaries representing custom buttons shown in a rich presence. +Each dictionary contains the following keys:

+
    +
  • label: A string representing the text shown on the button.

  • +
  • url: A string representing the URL opened upon clicking the button.

  • +
+
+

New in version 2.0.

+
+
+
Type
+

List[dict]

+
+
+
+ +
+
+emoji
+

The emoji that belongs to this activity.

+
+
Type
+

Optional[PartialEmoji]

+
+
+
+ +
+
+property start
+

When the user started doing this activity in UTC, if applicable.

+
+
Type
+

Optional[datetime.datetime]

+
+
+
+ +
+
+property end
+

When the user will stop doing this activity in UTC, if applicable.

+
+
Type
+

Optional[datetime.datetime]

+
+
+
+ +
+
+property large_image_url
+

Returns a URL pointing to the large image asset of this activity if applicable.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+property small_image_url
+

Returns a URL pointing to the small image asset of this activity if applicable.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+property large_image_text
+

Returns the large image asset hover text of this activity if applicable.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+property small_image_text
+

Returns the small image asset hover text of this activity if applicable.

+
+
Type
+

Optional[str]

+
+
+
+ +
+ +
+
+

Game

+
+ +Attributes +
+
+class discord.Game(name, **extra)
+

A slimmed down version of Activity that represents a Discord game.

+

This is typically displayed via Playing on the official Discord client.

+
+
+
+x == y
+

Checks if two games are equal.

+
+ +
+
+x != y
+

Checks if two games are not equal.

+
+ +
+
+hash(x)
+

Returns the game’s hash.

+
+ +
+
+str(x)
+

Returns the game’s name.

+
+ +
+
+
Parameters
+

name (str) – The game’s name.

+
+
+
+
+name
+

The game’s name.

+
+
Type
+

str

+
+
+
+ +
+
+property type
+

Returns the game’s type. This is for compatibility with Activity.

+

It always returns ActivityType.playing.

+
+
Type
+

ActivityType

+
+
+
+ +
+
+property start
+

When the user started playing this game in UTC, if applicable.

+
+
Type
+

Optional[datetime.datetime]

+
+
+
+ +
+
+property end
+

When the user will stop playing this game in UTC, if applicable.

+
+
Type
+

Optional[datetime.datetime]

+
+
+
+ +
+ +
+
+

Streaming

+
+ +Attributes +
+
+class discord.Streaming(*, name, url, **extra)
+

A slimmed down version of Activity that represents a Discord streaming status.

+

This is typically displayed via Streaming on the official Discord client.

+
+
+
+x == y
+

Checks if two streams are equal.

+
+ +
+
+x != y
+

Checks if two streams are not equal.

+
+ +
+
+hash(x)
+

Returns the stream’s hash.

+
+ +
+
+str(x)
+

Returns the stream’s name.

+
+ +
+
+
+platform
+

Where the user is streaming from (ie. YouTube, Twitch).

+
+

New in version 1.3.

+
+
+
Type
+

Optional[str]

+
+
+
+ +
+
+name
+

The stream’s name.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+details
+

An alias for name

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+game
+

The game being streamed.

+
+

New in version 1.3.

+
+
+
Type
+

Optional[str]

+
+
+
+ +
+
+url
+

The stream’s URL.

+
+
Type
+

str

+
+
+
+ +
+
+assets
+

A dictionary comprising of similar keys than those in Activity.assets.

+
+
Type
+

dict

+
+
+
+ +
+
+property type
+

Returns the game’s type. This is for compatibility with Activity.

+

It always returns ActivityType.streaming.

+
+
Type
+

ActivityType

+
+
+
+ +
+
+property twitch_name
+

If provided, the twitch name of the user streaming.

+

This corresponds to the large_image key of the Streaming.assets +dictionary if it starts with twitch:. Typically set by the Discord client.

+
+
Type
+

Optional[str]

+
+
+
+ +
+ +
+
+

CustomActivity

+
+ +Attributes +
+
+class discord.CustomActivity(name, *, emoji=None, **extra)
+

Represents a Custom activity from Discord.

+
+
+
+x == y
+

Checks if two activities are equal.

+
+ +
+
+x != y
+

Checks if two activities are not equal.

+
+ +
+
+hash(x)
+

Returns the activity’s hash.

+
+ +
+
+str(x)
+

Returns the custom status text.

+
+ +
+
+

New in version 1.3.

+
+
+
+name
+

The custom activity’s name.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+emoji
+

The emoji to pass to the activity, if any.

+
+
Type
+

Optional[PartialEmoji]

+
+
+
+ +
+
+property type
+

Returns the activity’s type. This is for compatibility with Activity.

+

It always returns ActivityType.custom.

+
+
Type
+

ActivityType

+
+
+
+ +
+ +
+
+

Permissions

+
+
+class discord.Permissions(permissions=0, **kwargs)
+

Wraps up the Discord permission value.

+

The properties provided are two way. You can set and retrieve individual +bits using the properties as if they were regular bools. This allows +you to edit permissions.

+
+

Changed in version 1.3: You can now use keyword arguments to initialize Permissions +similar to update().

+
+
+
+
+x == y
+

Checks if two permissions are equal.

+
+ +
+
+x != y
+

Checks if two permissions are not equal.

+
+ +
+
+x <= y
+

Checks if a permission is a subset of another permission.

+
+ +
+
+x >= y
+

Checks if a permission is a superset of another permission.

+
+ +
+
+x < y
+

Checks if a permission is a strict subset of another permission.

+
+ +
+
+x > y
+

Checks if a permission is a strict superset of another permission.

+
+ +
+
+hash(x)
+

Return the permission’s hash.

+
+ +
+
+iter(x)
+

Returns an iterator of (perm, value) pairs. This allows it +to be, for example, constructed as a dict or a list of pairs. +Note that aliases are not shown.

+
+ +
+
+
+value
+

The raw value. This value is a bit array field of a 53-bit integer +representing the currently available permissions. You should query +permissions via the properties rather than using this raw value.

+
+
Type
+

int

+
+
+
+ +
+
+is_subset(other)
+

Returns True if self has the same or fewer permissions as other.

+
+ +
+
+is_superset(other)
+

Returns True if self has the same or more permissions as other.

+
+ +
+
+is_strict_subset(other)
+

Returns True if the permissions on other are a strict subset of those on self.

+
+ +
+
+is_strict_superset(other)
+

Returns True if the permissions on other are a strict superset of those on self.

+
+ +
+
+classmethod none()
+

A factory method that creates a Permissions with all +permissions set to False.

+
+ +
+
+classmethod all()
+

A factory method that creates a Permissions with all +permissions set to True.

+
+ +
+
+classmethod all_channel()
+

A Permissions with all channel-specific permissions set to +True and the guild-specific ones set to False. The guild-specific +permissions are currently:

+ +
+

Changed in version 1.7: Added stream, priority_speaker and use_slash_commands permissions.

+
+ +
+ +
+
+classmethod general()
+

A factory method that creates a Permissions with all +“General” permissions from the official Discord UI set to True.

+
+

Changed in version 1.7: Permission read_messages is now included in the general permissions, but +permissions administrator, create_instant_invite, kick_members, +ban_members, change_nickname and manage_nicknames are +no longer part of the general permissions.

+
+
+ +
+
+classmethod membership()
+

A factory method that creates a Permissions with all +“Membership” permissions from the official Discord UI set to True.

+
+

New in version 1.7.

+
+
+ +
+
+classmethod text()
+

A factory method that creates a Permissions with all +“Text” permissions from the official Discord UI set to True.

+
+

Changed in version 1.7: Permission read_messages is no longer part of the text permissions. +Added use_slash_commands permission.

+
+ +
+ +
+
+classmethod voice()
+

A factory method that creates a Permissions with all +“Voice” permissions from the official Discord UI set to True.

+
+ +
+
+classmethod stage()
+

A factory method that creates a Permissions with all +“Stage Channel” permissions from the official Discord UI set to True.

+
+

New in version 1.7.

+
+
+ +
+
+classmethod stage_moderator()
+

A factory method that creates a Permissions with all +“Stage Moderator” permissions from the official Discord UI set to True.

+
+

New in version 1.7.

+
+
+ +
+
+classmethod advanced()
+

A factory method that creates a Permissions with all +“Advanced” permissions from the official Discord UI set to True.

+
+

New in version 1.7.

+
+
+ +
+
+update(**kwargs)
+

Bulk updates this permission object.

+

Allows you to set multiple attributes by using keyword +arguments. The names must be equivalent to the properties +listed. Extraneous key/value pairs will be silently ignored.

+
+
Parameters
+

**kwargs – A list of key/value pairs to bulk update permissions with.

+
+
+
+ +
+
+create_instant_invite
+

Returns True if the user can create instant invites.

+
+
Type
+

bool

+
+
+
+ +
+
+kick_members
+

Returns True if the user can kick users from the guild.

+
+
Type
+

bool

+
+
+
+ +
+
+ban_members
+

Returns True if a user can ban users from the guild.

+
+
Type
+

bool

+
+
+
+ +
+
+administrator
+

Returns True if a user is an administrator. This role overrides all other permissions.

+

This also bypasses all channel-specific overrides.

+
+
Type
+

bool

+
+
+
+ +
+
+admin
+

An alias for administrator. +.. versionadded:: 2.0

+
+
Type
+

bool

+
+
+
+ +
+
+manage_channels
+

Returns True if a user can edit, delete, or create channels in the guild.

+

This also corresponds to the “Manage Channel” channel-specific override.

+
+
Type
+

bool

+
+
+
+ +
+
+manage_guild
+

Returns True if a user can edit guild properties.

+
+
Type
+

bool

+
+
+
+ +
+
+add_reactions
+

Returns True if a user can add reactions to messages.

+
+
Type
+

bool

+
+
+
+ +
+
+view_audit_log
+

Returns True if a user can view the guild’s audit log.

+
+
Type
+

bool

+
+
+
+ +
+
+priority_speaker
+

Returns True if a user can be more easily heard while talking.

+
+
Type
+

bool

+
+
+
+ +
+
+stream
+

Returns True if a user can stream in a voice channel.

+
+
Type
+

bool

+
+
+
+ +
+
+read_messages
+

Returns True if a user can read messages from all or specific text channels.

+
+
Type
+

bool

+
+
+
+ +
+
+view_channel
+

An alias for read_messages.

+
+

New in version 1.3.

+
+
+
Type
+

bool

+
+
+
+ +
+
+send_messages
+

Returns True if a user can send messages from all or specific text channels.

+
+
Type
+

bool

+
+
+
+ +
+
+send_tts_messages
+

Returns True if a user can send TTS messages from all or specific text channels.

+
+
Type
+

bool

+
+
+
+ +
+
+manage_messages
+

Returns True if a user can delete or pin messages in a text channel.

+
+

Note

+

Note that there are currently no ways to edit other people’s messages.

+
+
+
Type
+

bool

+
+
+
+ +
+ +

Returns True if a user’s messages will automatically be embedded by Discord.

+
+
Type
+

bool

+
+
+
+ +
+
+attach_files
+

Returns True if a user can send files in their messages.

+
+
Type
+

bool

+
+
+
+ +
+
+read_message_history
+

Returns True if a user can read a text channel’s previous messages.

+
+
Type
+

bool

+
+
+
+ +
+
+mention_everyone
+

Returns True if a user’s @everyone or @here will mention everyone in the text channel.

+
+
Type
+

bool

+
+
+
+ +
+
+external_emojis
+

Returns True if a user can use emojis from other guilds.

+
+
Type
+

bool

+
+
+
+ +
+
+use_external_emojis
+

An alias for external_emojis.

+
+

New in version 1.3.

+
+
+
Type
+

bool

+
+
+
+ +
+
+view_guild_insights
+

Returns True if a user can view the guild’s insights.

+
+

New in version 1.3.

+
+
+
Type
+

bool

+
+
+
+ +
+
+connect
+

Returns True if a user can connect to a voice channel.

+
+
Type
+

bool

+
+
+
+ +
+
+speak
+

Returns True if a user can speak in a voice channel.

+
+
Type
+

bool

+
+
+
+ +
+
+mute_members
+

Returns True if a user can mute other users.

+
+
Type
+

bool

+
+
+
+ +
+
+deafen_members
+

Returns True if a user can deafen other users.

+
+
Type
+

bool

+
+
+
+ +
+
+move_members
+

Returns True if a user can move users between other voice channels.

+
+
Type
+

bool

+
+
+
+ +
+
+use_voice_activation
+

Returns True if a user can use voice activation in voice channels.

+
+
Type
+

bool

+
+
+
+ +
+
+change_nickname
+

Returns True if a user can change their nickname in the guild.

+
+
Type
+

bool

+
+
+
+ +
+
+manage_nicknames
+

Returns True if a user can change other user’s nickname in the guild.

+
+
Type
+

bool

+
+
+
+ +
+
+manage_roles
+

Returns True if a user can create or edit roles less than their role’s position.

+

This also corresponds to the “Manage Permissions” channel-specific override.

+
+
Type
+

bool

+
+
+
+ +
+
+manage_permissions
+

An alias for manage_roles.

+
+

New in version 1.3.

+
+
+
Type
+

bool

+
+
+
+ +
+
+manage_webhooks
+

Returns True if a user can create, edit, or delete webhooks.

+
+
Type
+

bool

+
+
+
+ +
+
+manage_emojis
+

Returns True if a user can create, edit, or delete emojis.

+
+
Type
+

bool

+
+
+
+ +
+
+manage_emojis_and_stickers
+

An alias for manage_emojis.

+
+

New in version 2.0.

+
+
+
Type
+

bool

+
+
+
+ +
+
+use_slash_commands
+

Returns True if a user can use slash commands.

+
+

New in version 1.7.

+
+
+
Type
+

bool

+
+
+
+ +
+
+request_to_speak
+

Returns True if a user can request to speak in a stage channel.

+
+

New in version 1.7.

+
+
+
Type
+

bool

+
+
+
+ +
+
+manage_events
+

Returns True if a user can manage guild events.

+
+

New in version 2.0.

+
+
+
Type
+

bool

+
+
+
+ +
+
+manage_threads
+

Returns True if a user can manage threads.

+
+

New in version 2.0.

+
+
+
Type
+

bool

+
+
+
+ +
+
+create_public_threads
+

Returns True if a user can create public threads.

+
+

New in version 2.0.

+
+
+
Type
+

bool

+
+
+
+ +
+
+create_private_threads
+

Returns True if a user can create private threads.

+
+

New in version 2.0.

+
+
+
Type
+

bool

+
+
+
+ +
+
+external_stickers
+

Returns True if a user can use stickers from other guilds.

+
+

New in version 2.0.

+
+
+
Type
+

bool

+
+
+
+ +
+
+use_external_stickers
+

An alias for external_stickers.

+
+

New in version 2.0.

+
+
+
Type
+

bool

+
+
+
+ +
+
+send_messages_in_threads
+

Returns True if a user can send messages in threads.

+
+

New in version 2.0.

+
+
+
Type
+

bool

+
+
+
+ +
+ +
+
+

PermissionOverwrite

+
+ +Methods +
+
+class discord.PermissionOverwrite(**kwargs)
+

A type that is used to represent a channel specific permission.

+

Unlike a regular Permissions, the default value of a +permission is equivalent to None and not False. Setting +a value to False is explicitly denying that permission, +while setting a value to True is explicitly allowing +that permission.

+

The values supported by this are the same as Permissions +with the added possibility of it being set to None.

+
+
+
+x == y
+

Checks if two overwrites are equal.

+
+ +
+
+x != y
+

Checks if two overwrites are not equal.

+
+ +
+
+iter(x)
+

Returns an iterator of (perm, value) pairs. This allows it +to be, for example, constructed as a dict or a list of pairs. +Note that aliases are not shown.

+
+ +
+
+
Parameters
+

**kwargs – Set the value of permissions by their name.

+
+
+
+
+pair()
+

Tuple[Permissions, Permissions]: Returns the (allow, deny) pair from this overwrite.

+
+ +
+
+classmethod from_pair(allow, deny)
+

Creates an overwrite from an allow/deny pair of Permissions.

+
+ +
+
+is_empty()
+

Checks if the permission overwrite is currently empty.

+

An empty permission overwrite is one that has no overwrites set +to True or False.

+
+
Returns
+

Indicates if the overwrite is empty.

+
+
Return type
+

bool

+
+
+
+ +
+
+update(**kwargs)
+

Bulk updates this permission overwrite object.

+

Allows you to set multiple attributes by using keyword +arguments. The names must be equivalent to the properties +listed. Extraneous key/value pairs will be silently ignored.

+
+
Parameters
+

**kwargs – A list of key/value pairs to bulk update with.

+
+
+
+ +
+ +
+
+

ShardInfo

+
+ +Attributes +
+ +Methods +
+
+class discord.ShardInfo
+

A class that gives information and control over a specific shard.

+

You can retrieve this object via AutoShardedClient.get_shard() +or AutoShardedClient.shards.

+
+

New in version 1.4.

+
+
+
+id
+

The shard ID for this shard.

+
+
Type
+

int

+
+
+
+ +
+
+shard_count
+

The shard count for this cluster. If this is None then the bot has not started yet.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+is_closed()
+

bool: Whether the shard connection is currently closed.

+
+ +
+
+await disconnect()
+

This function is a coroutine.

+

Disconnects a shard. When this is called, the shard connection will no +longer be open.

+

If the shard is already disconnected this does nothing.

+
+ +
+
+await reconnect()
+

This function is a coroutine.

+

Disconnects and then connects the shard again.

+
+ +
+
+await connect()
+

This function is a coroutine.

+

Connects a shard. If the shard is already connected this does nothing.

+
+ +
+
+property latency
+

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds for this shard.

+
+
Type
+

float

+
+
+
+ +
+
+is_ws_ratelimited()
+

bool: Whether the websocket is currently rate limited.

+

This can be useful to know when deciding whether you should query members +using HTTP or via the gateway.

+
+

New in version 1.6.

+
+
+ +
+ +
+
+

SystemChannelFlags

+
+
+class discord.SystemChannelFlags
+

Wraps up a Discord system channel flag value.

+

Similar to Permissions, the properties provided are two way. +You can set and retrieve individual bits using the properties as if they +were regular bools. This allows you to edit the system flags easily.

+

To construct an object you can pass keyword arguments denoting the flags +to enable or disable.

+
+
+
+x == y
+

Checks if two flags are equal.

+
+ +
+
+x != y
+

Checks if two flags are not equal.

+
+ +
+
+hash(x)
+

Return the flag’s hash.

+
+ +
+
+iter(x)
+

Returns an iterator of (name, value) pairs. This allows it +to be, for example, constructed as a dict or a list of pairs.

+
+ +
+
+
+value
+

The raw value. This value is a bit array field of a 53-bit integer +representing the currently available flags. You should query +flags via the properties rather than using this raw value.

+
+
Type
+

int

+
+
+
+ +
+
+join_notifications
+

Returns True if the system channel is used for member join notifications.

+
+
Type
+

bool

+
+
+
+ +
+
+premium_subscriptions
+

Returns True if the system channel is used for “Nitro boosting” notifications.

+
+
Type
+

bool

+
+
+
+ +
+
+guild_reminder_notifications
+

Returns True if the system channel is used for server setup helpful tips notifications.

+
+

New in version 2.0.

+
+
+
Type
+

bool

+
+
+
+ +
+ +
+
+

MessageFlags

+
+
+class discord.MessageFlags
+

Wraps up a Discord Message flag value.

+

See SystemChannelFlags.

+
+
+
+x == y
+

Checks if two flags are equal.

+
+ +
+
+x != y
+

Checks if two flags are not equal.

+
+ +
+
+hash(x)
+

Return the flag’s hash.

+
+ +
+
+iter(x)
+

Returns an iterator of (name, value) pairs. This allows it +to be, for example, constructed as a dict or a list of pairs.

+
+ +
+
+

New in version 1.3.

+
+
+
+value
+

The raw value. This value is a bit array field of a 53-bit integer +representing the currently available flags. You should query +flags via the properties rather than using this raw value.

+
+
Type
+

int

+
+
+
+ +
+
+crossposted
+

Returns True if the message is the original crossposted message.

+
+
Type
+

bool

+
+
+
+ +
+
+is_crossposted
+

Returns True if the message was crossposted from another channel.

+
+
Type
+

bool

+
+
+
+ +
+
+suppress_embeds
+

Returns True if the message’s embeds have been suppressed.

+
+
Type
+

bool

+
+
+
+ +
+
+source_message_deleted
+

Returns True if the source message for this crosspost has been deleted.

+
+
Type
+

bool

+
+
+
+ +
+
+urgent
+

Returns True if the source message is an urgent message.

+

An urgent message is one sent by Discord Trust and Safety.

+
+
Type
+

bool

+
+
+
+ +
+
+has_thread
+

Returns True if the source message is associated with a thread.

+
+

New in version 2.0.

+
+
+
Type
+

bool

+
+
+
+ +
+
+ephemeral
+

Returns True if the source message is ephemeral.

+
+

New in version 2.0.

+
+
+
Type
+

bool

+
+
+
+ +
+ +
+
+

PublicUserFlags

+
+
+class discord.PublicUserFlags
+

Wraps up the Discord User Public flags.

+
+
+
+x == y
+

Checks if two PublicUserFlags are equal.

+
+ +
+
+x != y
+

Checks if two PublicUserFlags are not equal.

+
+ +
+
+hash(x)
+

Return the flag’s hash.

+
+ +
+
+iter(x)
+

Returns an iterator of (name, value) pairs. This allows it +to be, for example, constructed as a dict or a list of pairs. +Note that aliases are not shown.

+
+ +
+
+

New in version 1.4.

+
+
+
+value
+

The raw value. This value is a bit array field of a 53-bit integer +representing the currently available flags. You should query +flags via the properties rather than using this raw value.

+
+
Type
+

int

+
+
+
+ +
+
+staff
+

Returns True if the user is a Discord Employee.

+
+
Type
+

bool

+
+
+
+ +
+
+partner
+

Returns True if the user is a Discord Partner.

+
+
Type
+

bool

+
+
+
+ +
+
+hypesquad
+

Returns True if the user is a HypeSquad Events member.

+
+
Type
+

bool

+
+
+
+ +
+
+bug_hunter
+

Returns True if the user is a Bug Hunter

+
+
Type
+

bool

+
+
+
+ +
+
+hypesquad_bravery
+

Returns True if the user is a HypeSquad Bravery member.

+
+
Type
+

bool

+
+
+
+ +
+
+hypesquad_brilliance
+

Returns True if the user is a HypeSquad Brilliance member.

+
+
Type
+

bool

+
+
+
+ +
+
+hypesquad_balance
+

Returns True if the user is a HypeSquad Balance member.

+
+
Type
+

bool

+
+
+
+ +
+
+early_supporter
+

Returns True if the user is an Early Supporter.

+
+
Type
+

bool

+
+
+
+ +
+
+team_user
+

Returns True if the user is a Team User.

+
+
Type
+

bool

+
+
+
+ +
+
+system
+

Returns True if the user is a system user (i.e. represents Discord officially).

+
+
Type
+

bool

+
+
+
+ +
+
+bug_hunter_level_2
+

Returns True if the user is a Bug Hunter Level 2

+
+
Type
+

bool

+
+
+
+ +
+
+verified_bot
+

Returns True if the user is a Verified Bot.

+
+
Type
+

bool

+
+
+
+ +
+
+verified_bot_developer
+

Returns True if the user is an Early Verified Bot Developer.

+
+
Type
+

bool

+
+
+
+ +
+
+early_verified_bot_developer
+

An alias for verified_bot_developer.

+
+

New in version 1.5.

+
+
+
Type
+

bool

+
+
+
+ +
+
+discord_certified_moderator
+

Returns True if the user is a Discord Certified Moderator.

+
+

New in version 2.0.

+
+
+
Type
+

bool

+
+
+
+ +
+
+all()
+

List[UserFlags]: Returns all public flags the user has.

+
+ +
+ +
+
+
+

Bot UI Kit

+

The library has helpers to help create component-based UIs.

+
+

View

+
+ +Attributes +
+ +Methods +
+
+class discord.ui.View(*, timeout=180.0)
+

Represents a UI view.

+

This object must be inherited to create a UI within Discord.

+
+

New in version 2.0.

+
+
+
Parameters
+

timeout (Optional[float]) – Timeout in seconds from last interaction with the UI before no longer accepting input. +If None then there is no timeout.

+
+
+
+
+timeout
+

Timeout from last interaction with the UI before no longer accepting input. +If None then there is no timeout.

+
+
Type
+

Optional[float]

+
+
+
+ +
+
+children
+

The list of children attached to this view.

+
+
Type
+

List[Item]

+
+
+
+ +
+
+classmethod from_message(message, /, *, timeout=180.0)
+

Converts a message’s components into a View.

+

The Message.components of a message are read-only +and separate types from those in the discord.ui namespace. +In order to modify and edit message components they must be +converted into a View first.

+
+
Parameters
+
    +
  • message (discord.Message) – The message with components to convert into a view.

  • +
  • timeout (Optional[float]) – The timeout of the converted view.

  • +
+
+
Returns
+

The converted view. This always returns a View and not +one of its subclasses.

+
+
Return type
+

View

+
+
+
+ +
+
+add_item(item)
+

Adds an item to the view.

+
+
Parameters
+

item (Item) – The item to add to the view.

+
+
Raises
+
    +
  • TypeError – An Item was not passed.

  • +
  • ValueError – Maximum number of children has been exceeded (25) + or the row the item is trying to be added to is full.

  • +
+
+
+
+ +
+
+remove_item(item)
+

Removes an item from the view.

+
+
Parameters
+

item (Item) – The item to remove from the view.

+
+
+
+ +
+
+clear_items()
+

Removes all items from the view.

+
+ +
+
+await interaction_check(interaction)
+

This function is a coroutine.

+

A callback that is called when an interaction happens within the view +that checks whether the view should process item callbacks for the interaction.

+

This is useful to override if, for example, you want to ensure that the +interaction author is a given user.

+

The default implementation of this returns True.

+
+

Note

+

If an exception occurs within the body then the check +is considered a failure and on_error() is called.

+
+
+
Parameters
+

interaction (Interaction) – The interaction that occurred.

+
+
Returns
+

Whether the view children’s callbacks should be called.

+
+
Return type
+

bool

+
+
+
+ +
+
+await on_timeout()
+

This function is a coroutine.

+

A callback that is called when a view’s timeout elapses without being explicitly stopped.

+
+ +
+
+await on_error(error, item, interaction)
+

This function is a coroutine.

+

A callback that is called when an item’s callback or interaction_check() +fails with an error.

+

The default implementation prints the traceback to stderr.

+
+
Parameters
+
    +
  • error (Exception) – The exception that was raised.

  • +
  • item (Item) – The item that failed the dispatch.

  • +
  • interaction (Interaction) – The interaction that led to the failure.

  • +
+
+
+
+ +
+
+stop()
+

Stops listening to interaction events from this view.

+

This operation cannot be undone.

+
+ +
+
+is_finished()
+

bool: Whether the view has finished interacting.

+
+ +
+
+is_dispatching()
+

bool: Whether the view has been added for dispatching purposes.

+
+ +
+
+is_persistent()
+

bool: Whether the view is set up as persistent.

+

A persistent view has all their components with a set custom_id and +a timeout set to None.

+
+ +
+
+await wait()
+

Waits until the view has finished interacting.

+

A view is considered finished when stop() is called +or it times out.

+
+
Returns
+

If True, then the view timed out. If False then +the view finished normally.

+
+
Return type
+

bool

+
+
+
+ +
+ +
+
+

Item

+
+ +Attributes +
+ +Methods +
+
+class discord.ui.Item
+

Represents the base UI item that all UI components inherit from.

+

The current UI items supported are:

+ +
+

New in version 2.0.

+
+
+
+property view
+

The underlying view for this item.

+
+
Type
+

Optional[View]

+
+
+
+ +
+
+await callback(interaction)
+

This function is a coroutine.

+

The callback associated with this UI item.

+

This can be overriden by subclasses.

+
+
Parameters
+

interaction (Interaction) – The interaction that triggered this UI item.

+
+
+
+ +
+ +
+
+

Button

+
+ +Attributes +
+ +Methods +
+
+class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)
+

Represents a UI button.

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • style (discord.ButtonStyle) – The style of the button.

  • +
  • custom_id (Optional[str]) – The ID of the button that gets received during an interaction. +If this button is for a URL, it does not have a custom ID.

  • +
  • url (Optional[str]) – The URL this button sends you to.

  • +
  • disabled (bool) – Whether the button is disabled or not.

  • +
  • label (Optional[str]) – The label of the button, if any.

  • +
  • emoji (Optional[Union[PartialEmoji, Emoji, str]]) – The emoji of the button, if available.

  • +
  • row (Optional[int]) – The relative row this button belongs to. A Discord component can only have 5 +rows. By default, items are arranged automatically into those 5 rows. If you’d +like to control the relative positioning of the row then passing an index is advised. +For example, row=1 will show up before row=2. Defaults to None, which is automatic +ordering. The row number must be between 0 and 4 (i.e. zero indexed).

  • +
+
+
+
+
+property style
+

The style of the button.

+
+
Type
+

discord.ButtonStyle

+
+
+
+ +
+
+property custom_id
+

The ID of the button that gets received during an interaction.

+

If this button is for a URL, it does not have a custom ID.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+property url
+

The URL this button sends you to.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+property disabled
+

Whether the button is disabled or not.

+
+
Type
+

bool

+
+
+
+ +
+
+property label
+

The label of the button, if available.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+property emoji
+

The emoji of the button, if available.

+
+
Type
+

Optional[PartialEmoji]

+
+
+
+ +
+
+await callback(interaction)
+

This function is a coroutine.

+

The callback associated with this UI item.

+

This can be overriden by subclasses.

+
+
Parameters
+

interaction (Interaction) – The interaction that triggered this UI item.

+
+
+
+ +
+
+property view
+

The underlying view for this item.

+
+
Type
+

Optional[View]

+
+
+
+ +
+ +
+
+discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)
+

A decorator that attaches a button to a component.

+

The function being decorated should have three parameters, self representing +the discord.ui.View, the discord.ui.Button being pressed and +the discord.Interaction you receive.

+
+

Note

+

Buttons with a URL cannot be created with this function. +Consider creating a Button manually instead. +This is because buttons with a URL do not have a callback +associated with them since Discord does not do any processing +with it.

+
+
+
Parameters
+
    +
  • label (Optional[str]) – The label of the button, if any.

  • +
  • custom_id (Optional[str]) – The ID of the button that gets received during an interaction. +It is recommended not to set this parameter to prevent conflicts.

  • +
  • style (ButtonStyle) – The style of the button. Defaults to ButtonStyle.grey.

  • +
  • disabled (bool) – Whether the button is disabled or not. Defaults to False.

  • +
  • emoji (Optional[Union[str, Emoji, PartialEmoji]]) – The emoji of the button. This can be in string form or a PartialEmoji +or a full Emoji.

  • +
  • row (Optional[int]) – The relative row this button belongs to. A Discord component can only have 5 +rows. By default, items are arranged automatically into those 5 rows. If you’d +like to control the relative positioning of the row then passing an index is advised. +For example, row=1 will show up before row=2. Defaults to None, which is automatic +ordering. The row number must be between 0 and 4 (i.e. zero indexed).

  • +
+
+
+
+ +
+
+

Select

+
+ +Methods +
+
+class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)
+

Represents a UI select menu.

+

This is usually represented as a drop down menu.

+

In order to get the selected items that the user has chosen, use Select.values.

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • custom_id (str) – The ID of the select menu that gets received during an interaction. +If not given then one is generated for you.

  • +
  • placeholder (Optional[str]) – The placeholder text that is shown if nothing is selected, if any.

  • +
  • min_values (int) – The minimum number of items that must be chosen for this select menu. +Defaults to 1 and must be between 1 and 25.

  • +
  • max_values (int) – The maximum number of items that must be chosen for this select menu. +Defaults to 1 and must be between 1 and 25.

  • +
  • options (List[discord.SelectOption]) – A list of options that can be selected in this menu.

  • +
  • disabled (bool) – Whether the select is disabled or not.

  • +
  • row (Optional[int]) – The relative row this select menu belongs to. A Discord component can only have 5 +rows. By default, items are arranged automatically into those 5 rows. If you’d +like to control the relative positioning of the row then passing an index is advised. +For example, row=1 will show up before row=2. Defaults to None, which is automatic +ordering. The row number must be between 0 and 4 (i.e. zero indexed).

  • +
+
+
+
+
+property custom_id
+

The ID of the select menu that gets received during an interaction.

+
+
Type
+

str

+
+
+
+ +
+
+property placeholder
+

The placeholder text that is shown if nothing is selected, if any.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+property min_values
+

The minimum number of items that must be chosen for this select menu.

+
+
Type
+

int

+
+
+
+ +
+
+property max_values
+

The maximum number of items that must be chosen for this select menu.

+
+
Type
+

int

+
+
+
+ +
+
+property options
+

A list of options that can be selected in this menu.

+
+
Type
+

List[discord.SelectOption]

+
+
+
+ +
+
+add_option(*, label, value=..., description=None, emoji=None, default=False)
+

Adds an option to the select menu.

+

To append a pre-existing discord.SelectOption use the +append_option() method instead.

+
+
Parameters
+
    +
  • label (str) – The label of the option. This is displayed to users. +Can only be up to 100 characters.

  • +
  • value (str) – The value of the option. This is not displayed to users. +If not given, defaults to the label. Can only be up to 100 characters.

  • +
  • description (Optional[str]) – An additional description of the option, if any. +Can only be up to 100 characters.

  • +
  • emoji (Optional[Union[str, Emoji, PartialEmoji]]) – The emoji of the option, if available. This can either be a string representing +the custom or unicode emoji or an instance of PartialEmoji or Emoji.

  • +
  • default (bool) – Whether this option is selected by default.

  • +
+
+
Raises
+

ValueError – The number of options exceeds 25.

+
+
+
+ +
+
+append_option(option)
+

Appends an option to the select menu.

+
+
Parameters
+

option (discord.SelectOption) – The option to append to the select menu.

+
+
Raises
+

ValueError – The number of options exceeds 25.

+
+
+
+ +
+
+property disabled
+

Whether the select is disabled or not.

+
+
Type
+

bool

+
+
+
+ +
+
+property values
+

A list of values that have been selected by the user.

+
+
Type
+

List[str]

+
+
+
+ +
+
+await callback(interaction)
+

This function is a coroutine.

+

The callback associated with this UI item.

+

This can be overriden by subclasses.

+
+
Parameters
+

interaction (Interaction) – The interaction that triggered this UI item.

+
+
+
+ +
+
+property view
+

The underlying view for this item.

+
+
Type
+

Optional[View]

+
+
+
+ +
+ +
+
+discord.ui.select(*, placeholder=None, custom_id=..., min_values=1, max_values=1, options=..., disabled=False, row=None)
+

A decorator that attaches a select menu to a component.

+

The function being decorated should have three parameters, self representing +the discord.ui.View, the discord.ui.Select being pressed and +the discord.Interaction you receive.

+

In order to get the selected items that the user has chosen within the callback +use Select.values.

+
+
Parameters
+
    +
  • placeholder (Optional[str]) – The placeholder text that is shown if nothing is selected, if any.

  • +
  • custom_id (str) – The ID of the select menu that gets received during an interaction. +It is recommended not to set this parameter to prevent conflicts.

  • +
  • row (Optional[int]) – The relative row this select menu belongs to. A Discord component can only have 5 +rows. By default, items are arranged automatically into those 5 rows. If you’d +like to control the relative positioning of the row then passing an index is advised. +For example, row=1 will show up before row=2. Defaults to None, which is automatic +ordering. The row number must be between 0 and 4 (i.e. zero indexed).

  • +
  • min_values (int) – The minimum number of items that must be chosen for this select menu. +Defaults to 1 and must be between 1 and 25.

  • +
  • max_values (int) – The maximum number of items that must be chosen for this select menu. +Defaults to 1 and must be between 1 and 25.

  • +
  • options (List[discord.SelectOption]) – A list of options that can be selected in this menu.

  • +
  • disabled (bool) – Whether the select is disabled or not. Defaults to False.

  • +
+
+
+
+ +
+
+
+

Exceptions

+

The following exceptions are thrown by the library.

+
+
+exception discord.DiscordException
+

Base exception class for discord.py

+

Ideally speaking, this could be caught to handle any exceptions raised from this library.

+
+ +
+
+exception discord.ClientException
+

Exception that’s raised when an operation in the Client fails.

+

These are usually for exceptions that happened due to user input.

+
+ +
+
+exception discord.LoginFailure
+

Exception that’s raised when the Client.login() function +fails to log you in from improper credentials or some other misc. +failure.

+
+ +
+
+exception discord.NoMoreItems
+

Exception that is raised when an async iteration operation has no more items.

+
+ +
+
+exception discord.HTTPException(response, message)
+

Exception that’s raised when an HTTP request operation fails.

+
+
+response
+

The response of the failed HTTP request. This is an +instance of aiohttp.ClientResponse. In some cases +this could also be a requests.Response.

+
+
Type
+

aiohttp.ClientResponse

+
+
+
+ +
+
+text
+

The text of the error. Could be an empty string.

+
+
Type
+

str

+
+
+
+ +
+
+status
+

The status code of the HTTP request.

+
+
Type
+

int

+
+
+
+ +
+
+code
+

The Discord specific error code for the failure.

+
+
Type
+

int

+
+
+
+ +
+ +
+
+exception discord.Forbidden(response, message)
+

Exception that’s raised for when status code 403 occurs.

+

Subclass of HTTPException

+
+ +
+
+exception discord.NotFound(response, message)
+

Exception that’s raised for when status code 404 occurs.

+

Subclass of HTTPException

+
+ +
+
+exception discord.DiscordServerError(response, message)
+

Exception that’s raised for when a 500 range status code occurs.

+

Subclass of HTTPException.

+
+

New in version 1.5.

+
+
+ +
+
+exception discord.InvalidData
+

Exception that’s raised when the library encounters unknown +or invalid data from Discord.

+
+ +
+
+exception discord.InvalidArgument
+

Exception that’s raised when an argument to a function +is invalid some way (e.g. wrong value or wrong type).

+

This could be considered the analogous of ValueError and +TypeError except inherited from ClientException and thus +DiscordException.

+
+ +
+
+exception discord.GatewayNotFound
+

An exception that is raised when the gateway for Discord could not be found

+
+ +
+
+exception discord.ConnectionClosed(socket, *, shard_id, code=None)
+

Exception that’s raised when the gateway connection is +closed for reasons that could not be handled internally.

+
+
+code
+

The close code of the websocket.

+
+
Type
+

int

+
+
+
+ +
+
+reason
+

The reason provided for the closure.

+
+
Type
+

str

+
+
+
+ +
+
+shard_id
+

The shard ID that got closed if applicable.

+
+
Type
+

Optional[int]

+
+
+
+ +
+ +
+
+exception discord.PrivilegedIntentsRequired(shard_id)
+

Exception that’s raised when the gateway is requesting privileged intents +but they’re not ticked in the developer page yet.

+

Go to https://discord.com/developers/applications/ and enable the intents +that are required. Currently these are as follows:

+ +
+
+shard_id
+

The shard ID that got closed if applicable.

+
+
Type
+

Optional[int]

+
+
+
+ +
+ +
+
+exception discord.InteractionResponded(interaction)
+

Exception that’s raised when sending another interaction response using +InteractionResponse when one has already been done before.

+

An interaction can only respond once.

+
+

New in version 2.0.

+
+
+
+interaction
+

The interaction that’s already been responded to.

+
+
Type
+

Interaction

+
+
+
+ +
+ +
+
+exception discord.opus.OpusError(code)
+

An exception that is thrown for libopus related errors.

+
+
+code
+

The error code returned.

+
+
Type
+

int

+
+
+
+ +
+ +
+
+exception discord.opus.OpusNotLoaded
+

An exception that is thrown for when libopus is not loaded.

+
+ +
+

Exception Hierarchy

+ +
+
+
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/discord.html b/docs/Python/html/discord.html new file mode 100644 index 00000000..8c3f99a3 --- /dev/null +++ b/docs/Python/html/discord.html @@ -0,0 +1,234 @@ + + + + + + Creating a Bot Account + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

Creating a Bot Account

+

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

+

Creating a Bot account is a pretty straightforward process.

+
    +
  1. Make sure you’re logged on to the Discord website.

  2. +
  3. Navigate to the application page

  4. +
  5. Click on the “New Application” button.

    +
    +
    The new application button. +
    +
  6. +
  7. Give the application a name and click “Create”.

    +
    +
    The new application form filled in. +
    +
  8. +
  9. Create a Bot User by navigating to the “Bot” tab and clicking “Add Bot”.

    +
    +
      +
    • Click “Yes, do it!” to continue.

    • +
    +The Add Bot button. +
    +
  10. +
  11. Make sure that Public Bot is ticked if you want others to invite your bot.

    +
    +
      +
    • You should also make sure that Require OAuth2 Code Grant is unchecked unless you +are developing a service that needs it. If you’re unsure, then leave it unchecked.

    • +
    +How the Bot User options should look like for most people. +
    +
  12. +
  13. Copy the token using the “Copy” button.

    +
    +
      +
    • This is not the Client Secret at the General Information page.

    • +
    +
    +

    Warning

    +

    It should be worth noting that this token is essentially your bot’s +password. You should never share this with someone else. In doing so, +someone can log in to your bot and do malicious things, such as leaving +servers, ban all members inside a server, or pinging everyone maliciously.

    +

    The possibilities are endless, so do not share this token.

    +

    If you accidentally leaked your token, click the “Regenerate” button as soon +as possible. This revokes your old token and re-generates a new one. +Now you need to use the new token to login.

    +
    +
    +
  14. +
+

And that’s it. You now have a bot account and you can login with that token.

+
+

Inviting Your Bot

+

So you’ve made a Bot User but it’s not actually in any server.

+

If you want to invite your bot you must create an invite URL for it.

+
    +
  1. Make sure you’re logged on to the Discord website.

  2. +
  3. Navigate to the application page

  4. +
  5. Click on your bot’s page.

  6. +
  7. Go to the “OAuth2” tab.

    +
    +
    How the OAuth2 page should look like. +
    +
  8. +
  9. Tick the “bot” checkbox under “scopes”.

    +
    +
    The scopes checkbox with "bot" ticked. +
    +
  10. +
  11. Tick the permissions required for your bot to function under “Bot Permissions”.

    +
    +
      +
    • Please be aware of the consequences of requiring your bot to have the “Administrator” permission.

    • +
    • Bot owners must have 2FA enabled for certain actions and permissions when added in servers that have Server-Wide 2FA enabled. Check the 2FA support page for more information.

    • +
    +The permission checkboxes with some permissions checked. +
    +
  12. +
  13. Now the resulting URL can be used to add your bot to a server. Copy and paste the URL into your browser, choose a server to invite the bot to, and click “Authorize”.

  14. +
+
+

Note

+

The person adding the bot needs “Manage Server” permissions to do so.

+
+

If you want to generate this URL dynamically at run-time inside your bot and using the +discord.Permissions interface, you can use discord.utils.oauth_url().

+
+
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/ext/commands/api.html b/docs/Python/html/ext/commands/api.html new file mode 100644 index 00000000..81e599bf --- /dev/null +++ b/docs/Python/html/ext/commands/api.html @@ -0,0 +1,8921 @@ + + + + + + API Reference + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

API Reference

+

The following section outlines the API of discord.py’s command extension module.

+
+

Bots

+
+

Bot

+
+ +Methods +
+
+class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, *, intents, message_commands=True, slash_commands=False, **options)
+

Represents a discord bot.

+

This class is a subclass of discord.Client and as a result +anything that you can do with a discord.Client you can do with +this bot.

+

This class also subclasses GroupMixin to provide the functionality +to manage commands.

+
+
+command_prefix
+

The command prefix is what the message content must contain initially +to have a command invoked. This prefix could either be a string to +indicate what the prefix should be, or a callable that takes in the bot +as its first parameter and discord.Message as its second +parameter and returns the prefix. This is to facilitate “dynamic” +command prefixes. This callable can be either a regular function or +a coroutine.

+

An empty string as the prefix always matches, enabling prefix-less +command invocation. While this may be useful in DMs it should be avoided +in servers, as it’s likely to cause performance issues and unintended +command invocations.

+

The command prefix could also be an iterable of strings indicating that +multiple checks for the prefix should be used and the first one to +match will be the invocation prefix. You can get this prefix via +Context.prefix. To avoid confusion empty iterables are not +allowed.

+
+

Note

+

When passing multiple prefixes be careful to not pass a prefix +that matches a longer prefix occurring later in the sequence. For +example, if the command prefix is ('!', '!?') the '!?' +prefix will never be matched to any message as the previous one +matches messages starting with !?. This is especially important +when passing an empty string, it should always be last as no prefix +after it will be matched.

+
+
+ +
+
+case_insensitive
+

Whether the commands should be case insensitive. Defaults to True. This +attribute does not carry over to groups. You must set it to every group if +you require group commands to be case insensitive as well.

+
+
Type
+

bool

+
+
+
+ +
+
+description
+

The content prefixed into the default help message.

+
+
Type
+

str

+
+
+
+ +
+
+help_command
+

The help command implementation to use. This can be dynamically +set at runtime. To remove the help command pass None. For more +information on implementing a help command, see Help Commands.

+
+
Type
+

Optional[HelpCommand]

+
+
+
+ +
+
+owner_id
+

The user ID that owns the bot. If this is not set and is then queried via +is_owner() then it is fetched automatically using +application_info().

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+owner_ids
+

The user IDs that owns the bot. This is similar to owner_id. +If this is not set and the application is team based, then it is +fetched automatically using application_info(). +For performance reasons it is recommended to use a set +for the collection. You cannot set both owner_id and owner_ids.

+
+

New in version 1.3.

+
+
+
Type
+

Optional[Collection[int]]

+
+
+
+ +
+
+strip_after_prefix
+

Whether to strip whitespace characters after encountering the command +prefix. This allows for !   hello and !hello to both work if +the command_prefix is set to !. Defaults to False.

+
+

New in version 1.7.

+
+
+
Type
+

bool

+
+
+
+ +
+
+message_commands
+

Whether to process commands based on messages.

+

Can be overwritten per command in the command decorators or when making +a Command object via the message_command parameter

+
+

New in version 2.0.

+
+
+
Type
+

Optional[bool]

+
+
+
+ +
+
+slash_commands
+

Whether to upload and process slash commands.

+

Can be overwritten per command in the command decorators or when making +a Command object via the slash_command parameter

+
+

New in version 2.0.

+
+
+
Type
+

Optional[bool]

+
+
+
+ +
+
+slash_command_guilds
+

If this is set, only upload slash commands to these guild IDs.

+

Can be overwritten per command in the command decorators or when making +a Command object via the slash_command_guilds parameter

+
+

New in version 2.0.

+
+
+
Type
+

Optional[List[int]]

+
+
+
+ +
+
+@after_invoke
+

A decorator that registers a coroutine as a post-invoke hook.

+

A post-invoke hook is called directly after the command is +called. This makes it a useful function to clean-up database +connections or any type of clean up required.

+

This post-invoke hook takes a sole parameter, a Context.

+
+

Note

+

Similar to before_invoke(), this is not called unless +checks and argument parsing procedures succeed. This hook is, +however, always called regardless of the internal command +callback raising an error (i.e. CommandInvokeError). +This makes it ideal for clean-up scenarios.

+
+
+
Parameters
+

coro (coroutine) – The coroutine to register as the post-invoke hook.

+
+
Raises
+

TypeError – The coroutine passed is not actually a coroutine.

+
+
+
+ +
+
+@before_invoke
+

A decorator that registers a coroutine as a pre-invoke hook.

+

A pre-invoke hook is called directly before the command is +called. This makes it a useful function to set up database +connections or any type of set up required.

+

This pre-invoke hook takes a sole parameter, a Context.

+
+

Note

+

The before_invoke() and after_invoke() hooks are +only called if all checks and argument parsing procedures pass +without error. If any check or argument parsing procedures fail +then the hooks are not called.

+
+
+
Parameters
+

coro (coroutine) – The coroutine to register as the pre-invoke hook.

+
+
Raises
+

TypeError – The coroutine passed is not actually a coroutine.

+
+
+
+ +
+
+@check
+

A decorator that adds a global check to the bot.

+

A global check is similar to a check() that is applied +on a per command basis except it is run before any command checks +have been verified and applies to every command the bot has.

+
+

Note

+

This function can either be a regular function or a coroutine.

+
+

Similar to a command check(), this takes a single parameter +of type Context and can only raise exceptions inherited from +CommandError.

+

Example

+
@bot.check
+def check_commands(ctx):
+    return ctx.command.qualified_name in allowed_commands
+
+
+
+ +
+
+@check_once
+

A decorator that adds a “call once” global check to the bot.

+

Unlike regular global checks, this one is called only once +per invoke() call.

+

Regular global checks are called whenever a command is called +or Command.can_run() is called. This type of check +bypasses that and ensures that it’s called only once, even inside +the default help command.

+
+

Note

+

When using this function the Context sent to a group subcommand +may only parse the parent command and not the subcommands due to it +being invoked once per Bot.invoke() call.

+
+
+

Note

+

This function can either be a regular function or a coroutine.

+
+

Similar to a command check(), this takes a single parameter +of type Context and can only raise exceptions inherited from +CommandError.

+

Example

+
@bot.check_once
+def whitelist(ctx):
+    return ctx.message.author.id in my_whitelist
+
+
+
+ +
+
+@command(*args, **kwargs)
+

A shortcut decorator that invokes command() and adds it to +the internal command list via add_command().

+
+
Returns
+

A decorator that converts the provided method into a Command, adds it to the bot, then returns it.

+
+
Return type
+

Callable[…, Command]

+
+
+
+ +
+
+@event
+

A decorator that registers an event to listen to.

+

You can find more info about the events on the documentation below.

+

The events must be a coroutine, if not, TypeError is raised.

+

Example

+
@client.event
+async def on_ready():
+    print('Ready!')
+
+
+
+
Raises
+

TypeError – The coroutine passed is not actually a coroutine.

+
+
+
+ +
+
+@group(*args, **kwargs)
+

A shortcut decorator that invokes group() and adds it to +the internal command list via add_command().

+
+
Returns
+

A decorator that converts the provided method into a Group, adds it to the bot, then returns it.

+
+
Return type
+

Callable[…, Group]

+
+
+
+ +
+
+@listen(name=None)
+

A decorator that registers another function as an external +event listener. Basically this allows you to listen to multiple +events from different places e.g. such as on_ready()

+

The functions being listened to must be a coroutine.

+

Example

+
@bot.listen()
+async def on_message(message):
+    print('one')
+
+# in some other file...
+
+@bot.listen('on_message')
+async def my_message(message):
+    print('two')
+
+
+

Would print one and two in an unspecified order.

+
+
Raises
+

TypeError – The function being listened to is not a coroutine.

+
+
+
+ +
+
+property activity
+

The activity being used upon +logging in.

+
+
Type
+

Optional[BaseActivity]

+
+
+
+ +
+
+add_check(func, *, call_once=False)
+

Adds a global check to the bot.

+

This is the non-decorator interface to check() +and check_once().

+
+
Parameters
+
    +
  • func – The function that was used as a global check.

  • +
  • call_once (bool) – If the function should only be called once per +invoke() call.

  • +
+
+
+
+ +
+
+add_cog(cog, *, override=False)
+

Adds a “cog” to the bot.

+

A cog is a class that has its own event listeners and commands.

+
+

Changed in version 2.0: ClientException is raised when a cog with the same name +is already loaded.

+
+
+
Parameters
+
    +
  • cog (Cog) – The cog to register to the bot.

  • +
  • override (bool) –

    If a previously loaded cog with the same name should be ejected +instead of raising an error.

    +
    +

    New in version 2.0.

    +
    +

  • +
+
+
Raises
+
+
+
+
+ +
+
+add_command(command)
+

Adds a Command into the internal list of commands.

+

This is usually not called, instead the command() or +group() shortcut decorators are used instead.

+
+

Changed in version 1.4: Raise CommandRegistrationError instead of generic ClientException

+
+
+
Parameters
+

command (Command) – The command to add.

+
+
Raises
+
+
+
+
+ +
+
+add_listener(func, name=...)
+

The non decorator alternative to listen().

+
+
Parameters
+
    +
  • func (coroutine) – The function to call.

  • +
  • name (str) – The name of the event to listen for. Defaults to func.__name__.

  • +
+
+
+

Example

+
async def on_ready(): pass
+async def my_message(message): pass
+
+bot.add_listener(on_ready)
+bot.add_listener(my_message, 'on_message')
+
+
+
+ +
+
+add_view(view, *, message_id=None)
+

Registers a View for persistent listening.

+

This method should be used for when a view is comprised of components +that last longer than the lifecycle of the program.

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • view (discord.ui.View) – The view to register for dispatching.

  • +
  • message_id (Optional[int]) – The message ID that the view is attached to. This is currently used to +refresh the view’s state during message update events. If not given +then message update events are not propagated for the view.

  • +
+
+
Raises
+
    +
  • TypeError – A view was not passed.

  • +
  • ValueError – The view is not persistent. A persistent view has no timeout + and all their components have an explicitly provided custom_id.

  • +
+
+
+
+ +
+
+property allowed_mentions
+

The allowed mention configuration.

+
+

New in version 1.4.

+
+
+
Type
+

Optional[AllowedMentions]

+
+
+
+ +
+
+property application_flags
+

The client’s application flags.

+
+

New in version 2.0.

+
+
+
Type
+

ApplicationFlags

+
+
+
+ +
+
+property application_id
+

The client’s application ID.

+

If this is not passed via __init__ then this is retrieved +through the gateway when an event contains the data. Usually +after on_connect() is called.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[int]

+
+
+
+ +
+
+await application_info()
+

This function is a coroutine.

+

Retrieves the bot’s application information.

+
+
Raises
+

HTTPException – Retrieving the information failed somehow.

+
+
Returns
+

The bot’s application information.

+
+
Return type
+

AppInfo

+
+
+
+ +
+
+await before_identify_hook(shard_id, *, initial=False)
+

This function is a coroutine.

+

A hook that is called before IDENTIFYing a session. This is useful +if you wish to have more control over the synchronization of multiple +IDENTIFYing clients.

+

The default implementation sleeps for 5 seconds.

+
+

New in version 1.4.

+
+
+
Parameters
+
    +
  • shard_id (int) – The shard ID that requested being IDENTIFY’d

  • +
  • initial (bool) – Whether this IDENTIFY is the first initial IDENTIFY.

  • +
+
+
+
+ +
+
+property cached_messages
+

Read-only list of messages the connected client has cached.

+
+

New in version 1.1.

+
+
+
Type
+

Sequence[Message]

+
+
+
+ +
+
+await change_presence(*, activity=None, status=None)
+

This function is a coroutine.

+

Changes the client’s presence.

+

Example

+
game = discord.Game("with the API")
+await client.change_presence(status=discord.Status.idle, activity=game)
+
+
+
+

Changed in version 2.0: Removed the afk keyword-only parameter.

+
+
+
Parameters
+
    +
  • activity (Optional[BaseActivity]) – The activity being done. None if no currently active activity is done.

  • +
  • status (Optional[Status]) – Indicates what status to change to. If None, then +Status.online is used.

  • +
+
+
Raises
+

InvalidArgument – If the activity parameter is not the proper type.

+
+
+
+ +
+
+clear()
+

Clears the internal state of the bot.

+

After this, the bot can be considered “re-opened”, i.e. is_closed() +and is_ready() both return False along with the bot’s internal +cache cleared.

+
+ +
+
+await close()
+

This function is a coroutine.

+

Closes the connection to Discord.

+
+ +
+
+property cogs
+

A read-only mapping of cog name to cog.

+
+
Type
+

Mapping[str, Cog]

+
+
+
+ +
+
+property commands
+

A unique set of commands without aliases that are registered.

+
+
Type
+

Set[Command]

+
+
+
+ +
+
+await connect(*, reconnect=True)
+

This function is a coroutine.

+

Creates a websocket connection and lets the websocket listen +to messages from Discord. This is a loop that runs the entire +event system and miscellaneous aspects of the library. Control +is not resumed until the WebSocket connection is terminated.

+
+
Parameters
+

reconnect (bool) – If we should attempt reconnecting, either due to internet +failure or a specific failure on Discord’s part. Certain +disconnects that lead to bad state will not be handled (such as +invalid sharding payloads or bad tokens).

+
+
Raises
+
    +
  • GatewayNotFound – If the gateway to connect to Discord is not found. Usually if this + is thrown then there is a Discord API outage.

  • +
  • ConnectionClosed – The websocket connection has been terminated.

  • +
+
+
+
+ +
+
+await create_dm(user)
+

This function is a coroutine.

+

Creates a DMChannel with this user.

+

This should be rarely called, as this is done transparently for most +people.

+
+

New in version 2.0.

+
+
+
Parameters
+

user (Snowflake) – The user to create a DM with.

+
+
Returns
+

The channel that was created.

+
+
Return type
+

DMChannel

+
+
+
+ +
+
+await create_guild(*, name, region=<VoiceRegion.us_west: 'us-west'>, icon=..., code=...)
+

This function is a coroutine.

+

Creates a Guild.

+

Bot accounts in more than 10 guilds are not allowed to create guilds.

+
+
Parameters
+
    +
  • name (str) – The name of the guild.

  • +
  • region (VoiceRegion) – The region for the voice communication server. +Defaults to VoiceRegion.us_west.

  • +
  • icon (Optional[bytes]) – The bytes-like object representing the icon. See ClientUser.edit() +for more details on what is expected.

  • +
  • code (str) –

    The code for a template to create the guild with.

    +
    +

    New in version 1.4.

    +
    +

  • +
+
+
Raises
+
+
+
Returns
+

The guild created. This is not the same guild that is +added to cache.

+
+
Return type
+

Guild

+
+
+
+ +
+
+await delete_invite(invite)
+

This function is a coroutine.

+

Revokes an Invite, URL, or ID to an invite.

+

You must have the manage_channels permission in +the associated guild to do this.

+
+
Parameters
+

invite (Union[Invite, str]) – The invite to revoke.

+
+
Raises
+
    +
  • Forbidden – You do not have permissions to revoke invites.

  • +
  • NotFound – The invite is invalid or expired.

  • +
  • HTTPException – Revoking the invite failed.

  • +
+
+
+
+ +
+
+property emojis
+

The emojis that the connected client has.

+
+
Type
+

List[Emoji]

+
+
+
+ +
+
+property extensions
+

A read-only mapping of extension name to extension.

+
+
Type
+

Mapping[str, types.ModuleType]

+
+
+
+ +
+
+await fetch_channel(channel_id, /)
+

This function is a coroutine.

+

Retrieves a abc.GuildChannel, abc.PrivateChannel, or Thread with the specified ID.

+
+

Note

+

This method is an API call. For general usage, consider get_channel() instead.

+
+
+

New in version 1.2.

+
+
+
Raises
+
    +
  • InvalidData – An unknown channel type was received from Discord.

  • +
  • HTTPException – Retrieving the channel failed.

  • +
  • NotFound – Invalid Channel ID.

  • +
  • Forbidden – You do not have permission to fetch this channel.

  • +
+
+
Returns
+

The channel from the ID.

+
+
Return type
+

Union[abc.GuildChannel, abc.PrivateChannel, Thread]

+
+
+
+ +
+
+await fetch_guild(guild_id, /)
+

This function is a coroutine.

+

Retrieves a Guild from an ID.

+
+

Note

+

Using this, you will not receive Guild.channels, Guild.members, +Member.activity and Member.voice per Member.

+
+
+

Note

+

This method is an API call. For general usage, consider get_guild() instead.

+
+
+
Parameters
+

guild_id (int) – The guild’s ID to fetch from.

+
+
Raises
+
+
+
Returns
+

The guild from the ID.

+
+
Return type
+

Guild

+
+
+
+ +
+
+fetch_guilds(*, limit=100, before=None, after=None)
+

Retrieves an AsyncIterator that enables receiving your guilds.

+
+

Note

+

Using this, you will only receive Guild.owner, Guild.icon, +Guild.id, and Guild.name per Guild.

+
+
+

Note

+

This method is an API call. For general usage, consider guilds instead.

+
+

Examples

+

Usage

+
async for guild in client.fetch_guilds(limit=150):
+    print(guild.name)
+
+
+

Flattening into a list

+
guilds = await client.fetch_guilds(limit=150).flatten()
+# guilds is now a list of Guild...
+
+
+

All parameters are optional.

+
+
Parameters
+
    +
  • limit (Optional[int]) – The number of guilds to retrieve. +If None, it retrieves every guild you have access to. Note, however, +that this would make it a slow operation. +Defaults to 100.

  • +
  • before (Union[abc.Snowflake, datetime.datetime]) – Retrieves guilds before this date or object. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • after (Union[abc.Snowflake, datetime.datetime]) – Retrieve guilds after this date or object. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
+
+
Raises
+

HTTPException – Getting the guilds failed.

+
+
Yields
+

Guild – The guild with the guild data parsed.

+
+
+
+ +
+
+await fetch_invite(url, *, with_counts=True, with_expiration=True)
+

This function is a coroutine.

+

Gets an Invite from a discord.gg URL or ID.

+
+

Note

+

If the invite is for a guild you have not joined, the guild and channel +attributes of the returned Invite will be PartialInviteGuild and +PartialInviteChannel respectively.

+
+
+
Parameters
+
+
+
Raises
+
+
+
Returns
+

The invite from the URL/ID.

+
+
Return type
+

Invite

+
+
+
+ +
+
+await fetch_premium_sticker_packs()
+

This function is a coroutine.

+

Retrieves all available premium sticker packs.

+
+

New in version 2.0.

+
+
+
Raises
+

HTTPException – Retrieving the sticker packs failed.

+
+
Returns
+

All available premium sticker packs.

+
+
Return type
+

List[StickerPack]

+
+
+
+ +
+
+await fetch_stage_instance(channel_id, /)
+

This function is a coroutine.

+

Gets a StageInstance for a stage channel id.

+
+

New in version 2.0.

+
+
+
Parameters
+

channel_id (int) – The stage channel ID.

+
+
Raises
+
    +
  • NotFound – The stage instance or channel could not be found.

  • +
  • HTTPException – Getting the stage instance failed.

  • +
+
+
Returns
+

The stage instance from the stage channel ID.

+
+
Return type
+

StageInstance

+
+
+
+ +
+
+await fetch_sticker(sticker_id, /)
+

This function is a coroutine.

+

Retrieves a Sticker with the specified ID.

+
+

New in version 2.0.

+
+
+
Raises
+
+
+
Returns
+

The sticker you requested.

+
+
Return type
+

Union[StandardSticker, GuildSticker]

+
+
+
+ +
+
+await fetch_template(code)
+

This function is a coroutine.

+

Gets a Template from a discord.new URL or code.

+
+
Parameters
+

code (Union[Template, str]) – The Discord Template Code or URL (must be a discord.new URL).

+
+
Raises
+
+
+
Returns
+

The template from the URL/code.

+
+
Return type
+

Template

+
+
+
+ +
+
+await fetch_user(user_id, /)
+

This function is a coroutine.

+

Retrieves a User based on their ID. +You do not have to share any guilds with the user to get this information, +however many operations do require that you do.

+
+

Note

+

This method is an API call. If you have discord.Intents.members and member cache enabled, consider get_user() instead.

+
+
+
Parameters
+

user_id (int) – The user’s ID to fetch from.

+
+
Raises
+
+
+
Returns
+

The user you requested.

+
+
Return type
+

User

+
+
+
+ +
+
+await fetch_webhook(webhook_id, /)
+

This function is a coroutine.

+

Retrieves a Webhook with the specified ID.

+
+
Raises
+
    +
  • HTTPException – Retrieving the webhook failed.

  • +
  • NotFound – Invalid webhook ID.

  • +
  • Forbidden – You do not have permission to fetch this webhook.

  • +
+
+
Returns
+

The webhook you requested.

+
+
Return type
+

Webhook

+
+
+
+ +
+
+await fetch_widget(guild_id, /)
+

This function is a coroutine.

+

Gets a Widget from a guild ID.

+
+

Note

+

The guild must have the widget enabled to get this information.

+
+
+
Parameters
+

guild_id (int) – The ID of the guild.

+
+
Raises
+
+
+
Returns
+

The guild’s widget.

+
+
Return type
+

Widget

+
+
+
+ +
+
+for ... in get_all_channels()
+

A generator that retrieves every abc.GuildChannel the client can ‘access’.

+

This is equivalent to:

+
for guild in client.guilds:
+    for channel in guild.channels:
+        yield channel
+
+
+
+

Note

+

Just because you receive a abc.GuildChannel does not mean that +you can communicate in said channel. abc.GuildChannel.permissions_for() should +be used for that.

+
+
+
Yields
+

abc.GuildChannel – A channel the client can ‘access’.

+
+
+
+ +
+
+for ... in get_all_members()
+

Returns a generator with every Member the client can see.

+

This is equivalent to:

+
for guild in client.guilds:
+    for member in guild.members:
+        yield member
+
+
+
+
Yields
+

Member – A member the client can see.

+
+
+
+ +
+
+get_channel(id, /)
+

Returns a channel or thread with the given ID.

+
+
Parameters
+

id (int) – The ID to search for.

+
+
Returns
+

The returned channel or None if not found.

+
+
Return type
+

Optional[Union[abc.GuildChannel, Thread, abc.PrivateChannel]]

+
+
+
+ +
+
+get_cog(name)
+

Gets the cog instance requested.

+

If the cog is not found, None is returned instead.

+
+
Parameters
+

name (str) – The name of the cog you are requesting. +This is equivalent to the name passed via keyword +argument in class creation or the class name if unspecified.

+
+
Returns
+

The cog that was requested. If not found, returns None.

+
+
Return type
+

Optional[Cog]

+
+
+
+ +
+
+get_command(name)
+

Get a Command from the internal list +of commands.

+

This could also be used as a way to get aliases.

+

The name could be fully qualified (e.g. 'foo bar') will get +the subcommand bar of the group command foo. If a +subcommand is not found then None is returned just as usual.

+
+
Parameters
+

name (str) – The name of the command to get.

+
+
Returns
+

The command that was requested. If not found, returns None.

+
+
Return type
+

Optional[Command]

+
+
+
+ +
+
+await get_context(message, *, cls=<class 'discord.ext.commands.context.Context'>)
+

This function is a coroutine.

+

Returns the invocation context from the message.

+

This is a more low-level counter-part for process_commands() +to allow users more fine grained control over the processing.

+

The returned context is not guaranteed to be a valid invocation +context, Context.valid must be checked to make sure it is. +If the context is not valid then it is not a valid candidate to be +invoked under invoke().

+
+
Parameters
+
    +
  • message (discord.Message) – The message to get the invocation context from.

  • +
  • cls – The factory class that will be used to create the context. +By default, this is Context. Should a custom +class be provided, it must be similar enough to Context's +interface.

  • +
+
+
Returns
+

The invocation context. The type of this can change via the +cls parameter.

+
+
Return type
+

Context

+
+
+
+ +
+
+get_emoji(id, /)
+

Returns an emoji with the given ID.

+
+
Parameters
+

id (int) – The ID to search for.

+
+
Returns
+

The custom emoji or None if not found.

+
+
Return type
+

Optional[Emoji]

+
+
+
+ +
+
+get_guild(id, /)
+

Returns a guild with the given ID.

+
+
Parameters
+

id (int) – The ID to search for.

+
+
Returns
+

The guild or None if not found.

+
+
Return type
+

Optional[Guild]

+
+
+
+ +
+
+get_partial_messageable(id, *, type=None)
+

Returns a partial messageable with the given channel ID.

+

This is useful if you have a channel_id but don’t want to do an API call +to send messages to it.

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • id (int) – The channel ID to create a partial messageable for.

  • +
  • type (Optional[ChannelType]) – The underlying channel type for the partial messageable.

  • +
+
+
Returns
+

The partial messageable

+
+
Return type
+

PartialMessageable

+
+
+
+ +
+
+await get_prefix(message)
+

This function is a coroutine.

+

Retrieves the prefix the bot is listening to +with the message as a context.

+
+
Parameters
+

message (discord.Message) – The message context to get the prefix of.

+
+
Returns
+

A list of prefixes or a single prefix that the bot is +listening for.

+
+
Return type
+

Union[List[str], str]

+
+
+
+ +
+
+get_stage_instance(id, /)
+

Returns a stage instance with the given stage channel ID.

+
+

New in version 2.0.

+
+
+
Parameters
+

id (int) – The ID to search for.

+
+
Returns
+

The returns stage instance of None if not found.

+
+
Return type
+

Optional[StageInstance]

+
+
+
+ +
+
+get_sticker(id, /)
+

Returns a guild sticker with the given ID.

+
+

New in version 2.0.

+
+
+

Note

+

To retrieve standard stickers, use fetch_sticker(). +or fetch_premium_sticker_packs().

+
+
+
Returns
+

The sticker or None if not found.

+
+
Return type
+

Optional[GuildSticker]

+
+
+
+ +
+
+get_user(id, /)
+

Returns a user with the given ID.

+
+
Parameters
+

id (int) – The ID to search for.

+
+
Returns
+

The user or None if not found.

+
+
Return type
+

Optional[User]

+
+
+
+ +
+
+property guilds
+

The guilds that the connected client is a member of.

+
+
Type
+

List[Guild]

+
+
+
+ +
+
+property intents
+

The intents configured for this connection.

+
+

New in version 1.5.

+
+
+
Type
+

Intents

+
+
+
+ +
+
+await invoke(ctx)
+

This function is a coroutine.

+

Invokes the command given under the invocation context and +handles all the internal event dispatch mechanisms.

+
+
Parameters
+

ctx (Context) – The invocation context to invoke.

+
+
+
+ +
+
+is_closed()
+

bool: Indicates if the websocket connection is closed.

+
+ +
+
+await is_owner(user)
+

This function is a coroutine.

+

Checks if a User or Member is the owner of +this bot.

+

If an owner_id is not set, it is fetched automatically +through the use of application_info().

+
+

Changed in version 1.3: The function also checks if the application is team-owned if +owner_ids is not set.

+
+
+
Parameters
+

user (abc.User) – The user to check for.

+
+
Returns
+

Whether the user is the owner.

+
+
Return type
+

bool

+
+
+
+ +
+
+is_ready()
+

bool: Specifies if the client’s internal cache is ready for use.

+
+ +
+
+is_ws_ratelimited()
+

bool: Whether the websocket is currently rate limited.

+

This can be useful to know when deciding whether you should query members +using HTTP or via the gateway.

+
+

New in version 1.6.

+
+
+ +
+
+property latency
+

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

+

This could be referred to as the Discord WebSocket protocol latency.

+
+
Type
+

float

+
+
+
+ +
+
+load_extension(name, *, package=None)
+

Loads an extension.

+

An extension is a python module that contains commands, cogs, or +listeners.

+

An extension must have a global function, setup defined as +the entry point on what to do when the extension is loaded. This entry +point must have a single argument, the bot.

+
+
Parameters
+
    +
  • name (str) – The extension name to load. It must be dot separated like +regular Python imports if accessing a sub-module. e.g. +foo.test if you want to import foo/test.py.

  • +
  • package (Optional[str]) –

    The package name to resolve relative imports with. +This is required when loading an extension using a relative path, e.g .foo.test. +Defaults to None.

    +
    +

    New in version 1.7.

    +
    +

  • +
+
+
Raises
+
    +
  • ExtensionNotFound – The extension could not be imported. + This is also raised if the name of the extension could not + be resolved using the provided package parameter.

  • +
  • ExtensionAlreadyLoaded – The extension is already loaded.

  • +
  • NoEntryPointError – The extension does not have a setup function.

  • +
  • ExtensionFailed – The extension or its setup function had an execution error.

  • +
+
+
+
+ +
+
+await login(token)
+

This function is a coroutine.

+

Logs in the client with the specified credentials.

+
+
Parameters
+

token (str) – The authentication token. Do not prefix this token with +anything as the library will do it for you.

+
+
Raises
+
    +
  • LoginFailure – The wrong credentials are passed.

  • +
  • HTTPException – An unknown HTTP related error occurred, + usually when it isn’t 200 or the known incorrect credentials + passing status code.

  • +
+
+
+
+ +
+
+await on_command_error(context, exception)
+

This function is a coroutine.

+

The default command error handler provided by the bot.

+

By default this prints to sys.stderr however it could be +overridden to have a different implementation.

+

This only fires if you do not specify any listeners for command error.

+
+ +
+
+await on_error(event_method, *args, **kwargs)
+

This function is a coroutine.

+

The default error handler provided by the client.

+

By default this prints to sys.stderr however it could be +overridden to have a different implementation. +Check on_error() for more details.

+
+ +
+
+property persistent_views
+

A sequence of persistent views added to the client.

+
+

New in version 2.0.

+
+
+
Type
+

Sequence[View]

+
+
+
+ +
+
+await populate_owners()
+

This function is a coroutine.

+

Populate the owner_id and owner_ids through the use of application_info().

+
+

New in version 2.0.

+
+
+ +
+
+property private_channels
+

The private channels that the connected client is participating on.

+
+

Note

+

This returns only up to 128 most recent private channels due to an internal working +on how Discord deals with private channels.

+
+
+
Type
+

List[abc.PrivateChannel]

+
+
+
+ +
+
+await process_commands(message)
+

This function is a coroutine.

+

This function processes the commands that have been registered +to the bot and other groups. Without this coroutine, none of the +commands will be triggered.

+

By default, this coroutine is called inside the on_message() +event. If you choose to override the on_message() event, then +you should invoke this coroutine as well.

+

This is built using other low level tools, and is equivalent to a +call to get_context() followed by a call to invoke().

+

This also checks if the message’s author is a bot and doesn’t +call get_context() or invoke() if so.

+
+
Parameters
+

message (discord.Message) – The message to process commands for.

+
+
+
+ +
+
+await process_slash_commands(interaction)
+

This function is a coroutine.

+

This function processes a slash command interaction into a usable +message and calls process_commands() based on it. Without this +coroutine slash commands will not be triggered.

+

By default, this coroutine is called inside the on_interaction() +event. If you choose to override the on_interaction() event, +then you should invoke this coroutine as well.

+
+

New in version 2.0.

+
+
+
Parameters
+

interaction (discord.Interaction) – The interaction to process slash commands for.

+
+
+
+ +
+
+reload_extension(name, *, package=None)
+

Atomically reloads an extension.

+

This replaces the extension with the same extension, only refreshed. This is +equivalent to a unload_extension() followed by a load_extension() +except done in an atomic way. That is, if an operation fails mid-reload then +the bot will roll-back to the prior working state.

+
+
Parameters
+
    +
  • name (str) – The extension name to reload. It must be dot separated like +regular Python imports if accessing a sub-module. e.g. +foo.test if you want to import foo/test.py.

  • +
  • package (Optional[str]) –

    The package name to resolve relative imports with. +This is required when reloading an extension using a relative path, e.g .foo.test. +Defaults to None.

    +
    +

    New in version 1.7.

    +
    +

  • +
+
+
Raises
+
    +
  • ExtensionNotLoaded – The extension was not loaded.

  • +
  • ExtensionNotFound – The extension could not be imported. + This is also raised if the name of the extension could not + be resolved using the provided package parameter.

  • +
  • NoEntryPointError – The extension does not have a setup function.

  • +
  • ExtensionFailed – The extension setup function had an execution error.

  • +
+
+
+
+ +
+
+remove_check(func, *, call_once=False)
+

Removes a global check from the bot.

+

This function is idempotent and will not raise an exception +if the function is not in the global checks.

+
+
Parameters
+
    +
  • func – The function to remove from the global checks.

  • +
  • call_once (bool) – If the function was added with call_once=True in +the Bot.add_check() call or using check_once().

  • +
+
+
+
+ +
+
+remove_cog(name)
+

Removes a cog from the bot and returns it.

+

All registered commands and event listeners that the +cog has registered will be removed as well.

+

If no cog is found then this method has no effect.

+
+
Parameters
+

name (str) – The name of the cog to remove.

+
+
Returns
+

The cog that was removed. None if not found.

+
+
Return type
+

Optional[Cog]

+
+
+
+ +
+
+remove_command(name)
+

Remove a Command from the internal list +of commands.

+

This could also be used as a way to remove aliases.

+
+
Parameters
+

name (str) – The name of the command to remove.

+
+
Returns
+

The command that was removed. If the name is not valid then +None is returned instead.

+
+
Return type
+

Optional[Command]

+
+
+
+ +
+
+remove_listener(func, name=...)
+

Removes a listener from the pool of listeners.

+
+
Parameters
+
    +
  • func – The function that was used as a listener to remove.

  • +
  • name (str) – The name of the event we want to remove. Defaults to +func.__name__.

  • +
+
+
+
+ +
+
+run(*args, **kwargs)
+

A blocking call that abstracts away the event loop +initialisation from you.

+

If you want more control over the event loop then this +function should not be used. Use start() coroutine +or connect() + login().

+

Roughly Equivalent to:

+
try:
+    loop.run_until_complete(start(*args, **kwargs))
+except KeyboardInterrupt:
+    loop.run_until_complete(close())
+    # cancel all tasks lingering
+finally:
+    loop.close()
+
+
+
+

Warning

+

This function must be the last function to call due to the fact that it +is blocking. That means that registration of events or anything being +called after this function call will not execute until it returns.

+
+
+ +
+
+await setup()
+

This function is a coroutine.

+

A coroutine to be called to setup the bot, by default this is blank.

+

To perform asynchronous setup after the bot is logged in but before +it has connected to the Websocket, overwrite this coroutine.

+
+

New in version 2.0.

+
+
+ +
+
+await start(token, *, reconnect=True)
+

This function is a coroutine.

+

A shorthand coroutine for login() + setup() + connect().

+
+
Raises
+

TypeError – An unexpected keyword argument was received.

+
+
+
+ +
+
+property status
+

Status: +The status being used upon logging on to Discord.

+
+

New in version 2.0.

+
+
+ +
+
+property stickers
+

The stickers that the connected client has.

+
+

New in version 2.0.

+
+
+
Type
+

List[GuildSticker]

+
+
+
+ +
+
+await try_owners()
+

This function is a coroutine.

+

Returns a list of User representing the owners of the bot. +It uses the owner_id and owner_ids, if set.

+
+

New in version 2.0: The function also checks if the application is team-owned if +owner_ids is not set.

+
+
+
Returns
+

List of owners of the bot.

+
+
Return type
+

List[User]

+
+
+
+ +
+
+await try_user(id, /)
+

This function is a coroutine. +Returns a user with the given ID. If not from cache, the user will be requested from the API.

+

You do not have to share any guilds with the user to get this information from the API, +however many operations do require that you do.

+
+

Note

+

This method is an API call. If you have discord.Intents.members and member cache enabled, consider get_user() instead.

+
+
+

New in version 2.0.

+
+
+
Parameters
+

id (int) – The ID to search for.

+
+
Returns
+

The user or None if not found.

+
+
Return type
+

Optional[User]

+
+
+
+ +
+
+unload_extension(name, *, package=None)
+

Unloads an extension.

+

When the extension is unloaded, all commands, listeners, and cogs are +removed from the bot and the module is un-imported.

+

The extension can provide an optional global function, teardown, +to do miscellaneous clean-up if necessary. This function takes a single +parameter, the bot, similar to setup from +load_extension().

+
+
Parameters
+
    +
  • name (str) – The extension name to unload. It must be dot separated like +regular Python imports if accessing a sub-module. e.g. +foo.test if you want to import foo/test.py.

  • +
  • package (Optional[str]) –

    The package name to resolve relative imports with. +This is required when unloading an extension using a relative path, e.g .foo.test. +Defaults to None.

    +
    +

    New in version 1.7.

    +
    +

  • +
+
+
Raises
+
+
+
+
+ +
+
+property user
+

Represents the connected client. None if not logged in.

+
+
Type
+

Optional[ClientUser]

+
+
+
+ +
+
+property users
+

Returns a list of all the users the bot can see.

+
+
Type
+

List[User]

+
+
+
+ +
+
+property voice_clients
+

Represents a list of voice connections.

+

These are usually VoiceClient instances.

+
+
Type
+

List[VoiceProtocol]

+
+
+
+ +
+
+wait_for(event, *, check=None, timeout=None)
+

This function is a coroutine.

+

Waits for a WebSocket event to be dispatched.

+

This could be used to wait for a user to reply to a message, +or to react to a message, or to edit a message in a self-contained +way.

+

The timeout parameter is passed onto asyncio.wait_for(). By default, +it does not timeout. Note that this does propagate the +asyncio.TimeoutError for you in case of timeout and is provided for +ease of use.

+

In case the event returns multiple arguments, a tuple containing those +arguments is returned instead. Please check the +documentation for a list of events and their +parameters.

+

This function returns the first event that meets the requirements.

+

Examples

+

Waiting for a user reply:

+
@client.event
+async def on_message(message):
+    if message.content.startswith('$greet'):
+        channel = message.channel
+        await channel.send('Say hello!')
+
+        def check(m):
+            return m.content == 'hello' and m.channel == channel
+
+        msg = await client.wait_for('message', check=check)
+        await channel.send(f'Hello {msg.author}!')
+
+
+

Waiting for a thumbs up reaction from the message author:

+
@client.event
+async def on_message(message):
+    if message.content.startswith('$thumb'):
+        channel = message.channel
+        await channel.send('Send me that 👍 reaction, mate')
+
+        def check(reaction, user):
+            return user == message.author and str(reaction.emoji) == '👍'
+
+        try:
+            reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
+        except asyncio.TimeoutError:
+            await channel.send('👎')
+        else:
+            await channel.send('👍')
+
+
+
+
Parameters
+
    +
  • event (str) – The event name, similar to the event reference, +but without the on_ prefix, to wait for.

  • +
  • check (Optional[Callable[…, bool]]) – A predicate to check what to wait for. The arguments must meet the +parameters of the event being waited for.

  • +
  • timeout (Optional[float]) – The number of seconds to wait before timing out and raising +asyncio.TimeoutError.

  • +
+
+
Raises
+

asyncio.TimeoutError – If a timeout is provided and it was reached.

+
+
Returns
+

Returns no arguments, a single argument, or a tuple of multiple +arguments that mirrors the parameters passed in the +event reference.

+
+
Return type
+

Any

+
+
+
+ +
+
+await wait_until_ready()
+

This function is a coroutine.

+

Waits until the client’s internal cache is all ready.

+
+ +
+
+for ... in walk_commands()
+

An iterator that recursively walks through all commands and subcommands.

+
+

Changed in version 1.4: Duplicates due to aliases are no longer returned

+
+
+
Yields
+

Union[Command, Group] – A command or group from the internal list of commands.

+
+
+
+ +
+ +
+
+

AutoShardedBot

+
+
+class discord.ext.commands.AutoShardedBot(command_prefix, help_command=<default-help-command>, description=None, *, intents, message_commands=True, slash_commands=False, **options)
+

This is similar to Bot except that it is inherited from +discord.AutoShardedClient instead.

+
+ +
+
+
+

Prefix Helpers

+
+
+discord.ext.commands.when_mentioned(bot, msg)
+

A callable that implements a command prefix equivalent to being mentioned.

+

These are meant to be passed into the Bot.command_prefix attribute.

+
+ +
+
+discord.ext.commands.when_mentioned_or(*prefixes)
+

A callable that implements when mentioned or other prefixes provided.

+

These are meant to be passed into the Bot.command_prefix attribute.

+

Example

+
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
+
+
+
+

Note

+

This callable returns another callable, so if this is done inside a custom +callable, you must call the returned callable, for example:

+
async def get_prefix(bot, message):
+    extras = await prefixes_for(message.guild) # returns a list
+    return commands.when_mentioned_or(*extras)(bot, message)
+
+
+
+
+

See also

+

when_mentioned()

+
+
+ +
+
+

Event Reference

+

These events function similar to the regular events, except they +are custom to the command extension module.

+
+
+discord.ext.commands.on_command_error(ctx, error)
+

An error handler that is called when an error is raised +inside a command either through user input error, check +failure, or an error in your own code.

+

A default one is provided (Bot.on_command_error()).

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context.

  • +
  • error (CommandError derived) – The error that was raised.

  • +
+
+
+
+ +
+
+discord.ext.commands.on_command(ctx)
+

An event that is called when a command is found and is about to be invoked.

+

This event is called regardless of whether the command itself succeeds via +error or completes.

+
+
Parameters
+

ctx (Context) – The invocation context.

+
+
+
+ +
+
+discord.ext.commands.on_command_completion(ctx)
+

An event that is called when a command has completed its invocation.

+

This event is called only if the command succeeded, i.e. all checks have +passed and the user input it correctly.

+
+
Parameters
+

ctx (Context) – The invocation context.

+
+
+
+ +
+
+

Commands

+
+

Decorators

+
+
+@discord.ext.commands.command(name=..., cls=..., **attrs)
+

A decorator that transforms a function into a Command +or if called with group(), Group.

+

By default the help attribute is received automatically from the +docstring of the function and is cleaned up with the use of +inspect.cleandoc. If the docstring is bytes, then it is decoded +into str using utf-8 encoding.

+

All checks added using the check() & co. decorators are added into +the function. There is no way to supply your own checks through this +decorator.

+
+
Parameters
+
    +
  • name (str) – The name to create the command with. By default this uses the +function name unchanged.

  • +
  • cls – The class to construct with. By default this is Command. +You usually do not change this.

  • +
  • attrs – Keyword arguments to pass into the construction of the class denoted +by cls.

  • +
+
+
Raises
+

TypeError – If the function is not a coroutine or is already a command.

+
+
+
+ +
+
+@discord.ext.commands.group(name=..., cls=..., **attrs)
+

A decorator that transforms a function into a Group.

+

This is similar to the command() decorator but the cls +parameter is set to Group by default.

+
+

Changed in version 1.1: The cls parameter can now be passed.

+
+
+ +
+
+

Command

+
+
+class discord.ext.commands.Command(*args, **kwargs)
+

A class that implements the protocol for a bot text command.

+

These are not created manually, instead they are created via the +decorator or functional interface.

+
+
+name
+

The name of the command.

+
+
Type
+

str

+
+
+
+ +
+
+callback
+

The coroutine that is executed when the command is called.

+
+
Type
+

coroutine

+
+
+
+ +
+
+help
+

The long help text for the command.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+brief
+

The short help text for the command.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+usage
+

A replacement for arguments in the default help text.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+aliases
+

The list of aliases the command can be invoked under.

+
+
Type
+

Union[List[str], Tuple[str]]

+
+
+
+ +
+
+enabled
+

A boolean that indicates if the command is currently enabled. +If the command is invoked while it is disabled, then +DisabledCommand is raised to the on_command_error() +event. Defaults to True.

+
+
Type
+

bool

+
+
+
+ +
+
+parent
+

The parent group that this command belongs to. None if there +isn’t one.

+
+
Type
+

Optional[Group]

+
+
+
+ +
+
+cog
+

The cog that this command belongs to. None if there isn’t one.

+
+
Type
+

Optional[Cog]

+
+
+
+ +
+
+checks
+

A list of predicates that verifies if the command could be executed +with the given Context as the sole parameter. If an exception +is necessary to be thrown to signal failure, then one inherited from +CommandError should be used. Note that if the checks fail then +CheckFailure exception is raised to the on_command_error() +event.

+
+
Type
+

List[Callable[[Context], bool]]

+
+
+
+ +
+
+description
+

The message prefixed into the default help command.

+
+
Type
+

str

+
+
+
+ +
+
+hidden
+

If True, the default help command does not show this in the +help output.

+
+
Type
+

bool

+
+
+
+ +
+
+rest_is_raw
+

If False and a keyword-only argument is provided then the keyword +only argument is stripped and handled as if it was a regular argument +that handles MissingRequiredArgument and default values in a +regular matter rather than passing the rest completely raw. If True +then the keyword-only argument will pass in the rest of the arguments +in a completely raw matter. Defaults to False.

+
+
Type
+

bool

+
+
+
+ +
+
+invoked_subcommand
+

The subcommand that was invoked, if any.

+
+
Type
+

Optional[Command]

+
+
+
+ +
+
+require_var_positional
+

If True and a variadic positional argument is specified, requires +the user to specify at least one argument. Defaults to False.

+
+

New in version 1.5.

+
+
+
Type
+

bool

+
+
+
+ +
+
+ignore_extra
+

If True, ignores extraneous strings passed to a command if all its +requirements are met (e.g. ?foo a b c when only expecting a +and b). Otherwise on_command_error() and local error handlers +are called with TooManyArguments. Defaults to True.

+
+
Type
+

bool

+
+
+
+ +
+
+cooldown_after_parsing
+

If True, cooldown processing is done after argument parsing, +which calls converters. If False then cooldown processing is done +first and then the converters are called second. Defaults to False.

+
+
Type
+

bool

+
+
+
+ +
+
+extras
+

A dict of user provided extras to attach to the Command.

+
+

New in version 2.0.

+
+
+

Note

+

This object may be copied by the library.

+
+
+
Type
+

dict

+
+
+
+ +
+
+message_command
+

Whether to process this command based on messages.

+

This overwrites the global message_commands parameter of Bot.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[bool]

+
+
+
+ +
+
+slash_command
+

Whether to upload and process this command as a slash command.

+

This overwrites the global slash_commands parameter of Bot.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[bool]

+
+
+
+ +
+
+slash_command_guilds
+

If this is set, only upload this slash command to these guild IDs.

+

This overwrites the global slash_command_guilds parameter of Bot.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[List[int]]

+
+
+
+ +
+
+option_descriptions
+

The unpacked option descriptions from Option.

+
+

New in version 2.0.

+
+
+
Type
+

Dict[str, str]

+
+
+
+ +
+
+@after_invoke
+

A decorator that registers a coroutine as a post-invoke hook.

+

A post-invoke hook is called directly after the command is +called. This makes it a useful function to clean-up database +connections or any type of clean up required.

+

This post-invoke hook takes a sole parameter, a Context.

+

See Bot.after_invoke() for more info.

+
+
Parameters
+

coro (coroutine) – The coroutine to register as the post-invoke hook.

+
+
Raises
+

TypeError – The coroutine passed is not actually a coroutine.

+
+
+
+ +
+
+@before_invoke
+

A decorator that registers a coroutine as a pre-invoke hook.

+

A pre-invoke hook is called directly before the command is +called. This makes it a useful function to set up database +connections or any type of set up required.

+

This pre-invoke hook takes a sole parameter, a Context.

+

See Bot.before_invoke() for more info.

+
+
Parameters
+

coro (coroutine) – The coroutine to register as the pre-invoke hook.

+
+
Raises
+

TypeError – The coroutine passed is not actually a coroutine.

+
+
+
+ +
+
+@error
+

A decorator that registers a coroutine as a local error handler.

+

A local error handler is an on_command_error() event limited to +a single command. However, the on_command_error() is still +invoked afterwards as the catch-all.

+
+
Parameters
+

coro (coroutine) – The coroutine to register as the local error handler.

+
+
Raises
+

TypeError – The coroutine passed is not actually a coroutine.

+
+
+
+ +
+
+add_check(func)
+

Adds a check to the command.

+

This is the non-decorator interface to check().

+
+

New in version 1.3.

+
+
+
Parameters
+

func – The function that will be used as a check.

+
+
+
+ +
+
+remove_check(func)
+

Removes a check from the command.

+

This function is idempotent and will not raise an exception +if the function is not in the command’s checks.

+
+

New in version 1.3.

+
+
+
Parameters
+

func – The function to remove from the checks.

+
+
+
+ +
+
+update(**kwargs)
+

Updates Command instance with updated attribute.

+

This works similarly to the command() decorator in terms +of parameters in that they are passed to the Command or +subclass constructors, sans the name and callback.

+
+ +
+
+await __call__(context, *args, **kwargs)
+

This function is a coroutine.

+

Calls the internal callback that the command holds.

+
+

Note

+

This bypasses all mechanisms – including checks, converters, +invoke hooks, cooldowns, etc. You must take care to pass +the proper arguments and types to this function.

+
+
+

New in version 1.3.

+
+
+ +
+
+copy()
+

Creates a copy of this command.

+
+
Returns
+

A new instance of this command.

+
+
Return type
+

Command

+
+
+
+ +
+
+property clean_params
+

Dict[str, inspect.Parameter]: +Retrieves the parameter dictionary without the context or self parameters.

+

Useful for inspecting signature.

+
+ +
+
+property full_parent_name
+

Retrieves the fully qualified parent command name.

+

This the base command name required to execute it. For example, +in ?one two three the parent name would be one two.

+
+
Type
+

str

+
+
+
+ +
+
+property parents
+

Retrieves the parents of this command.

+

If the command has no parents then it returns an empty list.

+

For example in commands ?a b c test, the parents are [c, b, a].

+
+

New in version 1.1.

+
+
+
Type
+

List[Group]

+
+
+
+ +
+
+property root_parent
+

Retrieves the root parent of this command.

+

If the command has no parents then it returns None.

+

For example in commands ?a b c test, the root parent is a.

+
+
Type
+

Optional[Group]

+
+
+
+ +
+
+property qualified_name
+

Retrieves the fully qualified command name.

+

This is the full parent name with the command name as well. +For example, in ?one two three the qualified name would be +one two three.

+
+
Type
+

str

+
+
+
+ +
+
+is_on_cooldown(ctx)
+

Checks whether the command is currently on cooldown.

+
+
Parameters
+

ctx (Context) – The invocation context to use when checking the commands cooldown status.

+
+
Returns
+

A boolean indicating if the command is on cooldown.

+
+
Return type
+

bool

+
+
+
+ +
+
+reset_cooldown(ctx)
+

Resets the cooldown on this command.

+
+
Parameters
+

ctx (Context) – The invocation context to reset the cooldown under.

+
+
+
+ +
+
+get_cooldown_retry_after(ctx)
+

Retrieves the amount of seconds before this command can be tried again.

+
+

New in version 1.4.

+
+
+
Parameters
+

ctx (Context) – The invocation context to retrieve the cooldown from.

+
+
Returns
+

The amount of time left on this command’s cooldown in seconds. +If this is 0.0 then the command isn’t on cooldown.

+
+
Return type
+

float

+
+
+
+ +
+
+has_error_handler()
+

bool: Checks whether the command has an error handler registered.

+
+

New in version 1.7.

+
+
+ +
+
+property cog_name
+

The name of the cog this command belongs to, if any.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+property short_doc
+

Gets the “short” documentation of a command.

+

By default, this is the brief attribute. +If that lookup leads to an empty string then the first line of the +help attribute is used instead.

+
+
Type
+

str

+
+
+
+ +
+
+property signature
+

Returns a POSIX-like signature useful for help command output.

+
+
Type
+

str

+
+
+
+ +
+
+await can_run(ctx)
+

This function is a coroutine.

+

Checks if the command can be executed by checking all the predicates +inside the checks attribute. This also checks whether the +command is disabled.

+
+

Changed in version 1.3: Checks whether the command is disabled or not

+
+
+
Parameters
+

ctx (Context) – The ctx of the command currently being invoked.

+
+
Raises
+

CommandError – Any command error that was raised during a check call will be propagated + by this function.

+
+
Returns
+

A boolean indicating if the command can be invoked.

+
+
Return type
+

bool

+
+
+
+ +
+ +
+
+

Group

+
+
+class discord.ext.commands.Group(*args, **kwargs)
+

A class that implements a grouping protocol for commands to be +executed as subcommands.

+

This class is a subclass of Command and thus all options +valid in Command are valid in here as well.

+
+
+invoke_without_command
+

Indicates if the group callback should begin parsing and +invocation only if no subcommand was found. Useful for +making it an error handling function to tell the user that +no subcommand was found or to have different functionality +in case no subcommand was found. If this is False, then +the group callback will always be invoked first. This means +that the checks and the parsing dictated by its parameters +will be executed. Defaults to False.

+
+
Type
+

bool

+
+
+
+ +
+
+case_insensitive
+

Indicates if the group’s commands should be case insensitive. +Defaults to False.

+
+
Type
+

bool

+
+
+
+ +
+
+@after_invoke
+

A decorator that registers a coroutine as a post-invoke hook.

+

A post-invoke hook is called directly after the command is +called. This makes it a useful function to clean-up database +connections or any type of clean up required.

+

This post-invoke hook takes a sole parameter, a Context.

+

See Bot.after_invoke() for more info.

+
+
Parameters
+

coro (coroutine) – The coroutine to register as the post-invoke hook.

+
+
Raises
+

TypeError – The coroutine passed is not actually a coroutine.

+
+
+
+ +
+
+@before_invoke
+

A decorator that registers a coroutine as a pre-invoke hook.

+

A pre-invoke hook is called directly before the command is +called. This makes it a useful function to set up database +connections or any type of set up required.

+

This pre-invoke hook takes a sole parameter, a Context.

+

See Bot.before_invoke() for more info.

+
+
Parameters
+

coro (coroutine) – The coroutine to register as the pre-invoke hook.

+
+
Raises
+

TypeError – The coroutine passed is not actually a coroutine.

+
+
+
+ +
+
+@command(*args, **kwargs)
+

A shortcut decorator that invokes command() and adds it to +the internal command list via add_command().

+
+
Returns
+

A decorator that converts the provided method into a Command, adds it to the bot, then returns it.

+
+
Return type
+

Callable[…, Command]

+
+
+
+ +
+
+@error
+

A decorator that registers a coroutine as a local error handler.

+

A local error handler is an on_command_error() event limited to +a single command. However, the on_command_error() is still +invoked afterwards as the catch-all.

+
+
Parameters
+

coro (coroutine) – The coroutine to register as the local error handler.

+
+
Raises
+

TypeError – The coroutine passed is not actually a coroutine.

+
+
+
+ +
+
+@group(*args, **kwargs)
+

A shortcut decorator that invokes group() and adds it to +the internal command list via add_command().

+
+
Returns
+

A decorator that converts the provided method into a Group, adds it to the bot, then returns it.

+
+
Return type
+

Callable[…, Group]

+
+
+
+ +
+
+copy()
+

Creates a copy of this Group.

+
+
Returns
+

A new instance of this group.

+
+
Return type
+

Group

+
+
+
+ +
+
+add_check(func)
+

Adds a check to the command.

+

This is the non-decorator interface to check().

+
+

New in version 1.3.

+
+
+
Parameters
+

func – The function that will be used as a check.

+
+
+
+ +
+
+add_command(command)
+

Adds a Command into the internal list of commands.

+

This is usually not called, instead the command() or +group() shortcut decorators are used instead.

+
+

Changed in version 1.4: Raise CommandRegistrationError instead of generic ClientException

+
+
+
Parameters
+

command (Command) – The command to add.

+
+
Raises
+
+
+
+
+ +
+
+await can_run(ctx)
+

This function is a coroutine.

+

Checks if the command can be executed by checking all the predicates +inside the checks attribute. This also checks whether the +command is disabled.

+
+

Changed in version 1.3: Checks whether the command is disabled or not

+
+
+
Parameters
+

ctx (Context) – The ctx of the command currently being invoked.

+
+
Raises
+

CommandError – Any command error that was raised during a check call will be propagated + by this function.

+
+
Returns
+

A boolean indicating if the command can be invoked.

+
+
Return type
+

bool

+
+
+
+ +
+
+property clean_params
+

Dict[str, inspect.Parameter]: +Retrieves the parameter dictionary without the context or self parameters.

+

Useful for inspecting signature.

+
+ +
+
+property cog_name
+

The name of the cog this command belongs to, if any.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+property commands
+

A unique set of commands without aliases that are registered.

+
+
Type
+

Set[Command]

+
+
+
+ +
+
+property full_parent_name
+

Retrieves the fully qualified parent command name.

+

This the base command name required to execute it. For example, +in ?one two three the parent name would be one two.

+
+
Type
+

str

+
+
+
+ +
+
+get_command(name)
+

Get a Command from the internal list +of commands.

+

This could also be used as a way to get aliases.

+

The name could be fully qualified (e.g. 'foo bar') will get +the subcommand bar of the group command foo. If a +subcommand is not found then None is returned just as usual.

+
+
Parameters
+

name (str) – The name of the command to get.

+
+
Returns
+

The command that was requested. If not found, returns None.

+
+
Return type
+

Optional[Command]

+
+
+
+ +
+
+get_cooldown_retry_after(ctx)
+

Retrieves the amount of seconds before this command can be tried again.

+
+

New in version 1.4.

+
+
+
Parameters
+

ctx (Context) – The invocation context to retrieve the cooldown from.

+
+
Returns
+

The amount of time left on this command’s cooldown in seconds. +If this is 0.0 then the command isn’t on cooldown.

+
+
Return type
+

float

+
+
+
+ +
+
+has_error_handler()
+

bool: Checks whether the command has an error handler registered.

+
+

New in version 1.7.

+
+
+ +
+
+is_on_cooldown(ctx)
+

Checks whether the command is currently on cooldown.

+
+
Parameters
+

ctx (Context) – The invocation context to use when checking the commands cooldown status.

+
+
Returns
+

A boolean indicating if the command is on cooldown.

+
+
Return type
+

bool

+
+
+
+ +
+
+property parents
+

Retrieves the parents of this command.

+

If the command has no parents then it returns an empty list.

+

For example in commands ?a b c test, the parents are [c, b, a].

+
+

New in version 1.1.

+
+
+
Type
+

List[Group]

+
+
+
+ +
+
+property qualified_name
+

Retrieves the fully qualified command name.

+

This is the full parent name with the command name as well. +For example, in ?one two three the qualified name would be +one two three.

+
+
Type
+

str

+
+
+
+ +
+
+remove_check(func)
+

Removes a check from the command.

+

This function is idempotent and will not raise an exception +if the function is not in the command’s checks.

+
+

New in version 1.3.

+
+
+
Parameters
+

func – The function to remove from the checks.

+
+
+
+ +
+
+remove_command(name)
+

Remove a Command from the internal list +of commands.

+

This could also be used as a way to remove aliases.

+
+
Parameters
+

name (str) – The name of the command to remove.

+
+
Returns
+

The command that was removed. If the name is not valid then +None is returned instead.

+
+
Return type
+

Optional[Command]

+
+
+
+ +
+
+reset_cooldown(ctx)
+

Resets the cooldown on this command.

+
+
Parameters
+

ctx (Context) – The invocation context to reset the cooldown under.

+
+
+
+ +
+
+property root_parent
+

Retrieves the root parent of this command.

+

If the command has no parents then it returns None.

+

For example in commands ?a b c test, the root parent is a.

+
+
Type
+

Optional[Group]

+
+
+
+ +
+
+property short_doc
+

Gets the “short” documentation of a command.

+

By default, this is the brief attribute. +If that lookup leads to an empty string then the first line of the +help attribute is used instead.

+
+
Type
+

str

+
+
+
+ +
+
+property signature
+

Returns a POSIX-like signature useful for help command output.

+
+
Type
+

str

+
+
+
+ +
+
+update(**kwargs)
+

Updates Command instance with updated attribute.

+

This works similarly to the command() decorator in terms +of parameters in that they are passed to the Command or +subclass constructors, sans the name and callback.

+
+ +
+
+for ... in walk_commands()
+

An iterator that recursively walks through all commands and subcommands.

+
+

Changed in version 1.4: Duplicates due to aliases are no longer returned

+
+
+
Yields
+

Union[Command, Group] – A command or group from the internal list of commands.

+
+
+
+ +
+ +
+
+

GroupMixin

+
+ +Attributes +
+ +Methods +
+
+class discord.ext.commands.GroupMixin(*args, **kwargs)
+

A mixin that implements common functionality for classes that behave +similar to Group and are allowed to register commands.

+
+
+all_commands
+

A mapping of command name to Command +objects.

+
+
Type
+

dict

+
+
+
+ +
+
+case_insensitive
+

Whether the commands should be case insensitive. Defaults to True.

+
+
Type
+

bool

+
+
+
+ +
+
+@command(*args, **kwargs)
+

A shortcut decorator that invokes command() and adds it to +the internal command list via add_command().

+
+
Returns
+

A decorator that converts the provided method into a Command, adds it to the bot, then returns it.

+
+
Return type
+

Callable[…, Command]

+
+
+
+ +
+
+@group(*args, **kwargs)
+

A shortcut decorator that invokes group() and adds it to +the internal command list via add_command().

+
+
Returns
+

A decorator that converts the provided method into a Group, adds it to the bot, then returns it.

+
+
Return type
+

Callable[…, Group]

+
+
+
+ +
+
+property commands
+

A unique set of commands without aliases that are registered.

+
+
Type
+

Set[Command]

+
+
+
+ +
+
+add_command(command)
+

Adds a Command into the internal list of commands.

+

This is usually not called, instead the command() or +group() shortcut decorators are used instead.

+
+

Changed in version 1.4: Raise CommandRegistrationError instead of generic ClientException

+
+
+
Parameters
+

command (Command) – The command to add.

+
+
Raises
+
+
+
+
+ +
+
+remove_command(name)
+

Remove a Command from the internal list +of commands.

+

This could also be used as a way to remove aliases.

+
+
Parameters
+

name (str) – The name of the command to remove.

+
+
Returns
+

The command that was removed. If the name is not valid then +None is returned instead.

+
+
Return type
+

Optional[Command]

+
+
+
+ +
+
+for ... in walk_commands()
+

An iterator that recursively walks through all commands and subcommands.

+
+

Changed in version 1.4: Duplicates due to aliases are no longer returned

+
+
+
Yields
+

Union[Command, Group] – A command or group from the internal list of commands.

+
+
+
+ +
+
+get_command(name)
+

Get a Command from the internal list +of commands.

+

This could also be used as a way to get aliases.

+

The name could be fully qualified (e.g. 'foo bar') will get +the subcommand bar of the group command foo. If a +subcommand is not found then None is returned just as usual.

+
+
Parameters
+

name (str) – The name of the command to get.

+
+
Returns
+

The command that was requested. If not found, returns None.

+
+
Return type
+

Optional[Command]

+
+
+
+ +
+ +
+
+
+

Cogs

+
+

Cog

+
+ +Attributes +
+
+class discord.ext.commands.Cog(*args, **kwargs)
+

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 Cogs page.

+

When inheriting from this class, the options shown in CogMeta +are equally valid here.

+
+
+get_commands()
+
+
Returns
+

A list of Commands that are +defined inside this cog.

+
+

Note

+

This does not include subcommands.

+
+

+
+
Return type
+

List[Command]

+
+
+
+ +
+
+property qualified_name
+

Returns the cog’s specified name, not the class name.

+
+
Type
+

str

+
+
+
+ +
+
+property description
+

Returns the cog’s description, typically the cleaned docstring.

+
+
Type
+

str

+
+
+
+ +
+
+for ... in walk_commands()
+

An iterator that recursively walks through this cog’s commands and subcommands.

+
+
Yields
+

Union[Command, Group] – A command or group from the cog.

+
+
+
+ +
+
+get_listeners()
+

Returns a list of (name, function) listener pairs that are defined in this cog.

+
+
Returns
+

The listeners defined in this cog.

+
+
Return type
+

List[Tuple[str, coroutine]]

+
+
+
+ +
+
+classmethod listener(name=...)
+

A decorator that marks a function as a listener.

+

This is the cog equivalent of Bot.listen().

+
+
Parameters
+

name (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 or a string was not passed as + the name.

+
+
+
+ +
+
+has_error_handler()
+

bool: Checks whether the cog has an error handler.

+
+

New in version 1.7.

+
+
+ +
+
+cog_unload()
+

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.

+
+ +
+
+bot_check_once(ctx)
+

A special method that registers as a Bot.check_once() +check.

+

This function can be a coroutine and must take a sole parameter, +ctx, to represent the Context.

+
+ +
+
+bot_check(ctx)
+

A special method that registers as a Bot.check() +check.

+

This function can be a coroutine and must take a sole parameter, +ctx, to represent the Context.

+
+ +
+
+cog_check(ctx)
+

A special method that registers as a 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 Context.

+
+ +
+
+await cog_command_error(ctx, error)
+

A special method that is called whenever an error +is dispatched inside this cog.

+

This is similar to on_command_error() except only applying +to the commands inside this cog.

+

This must be a coroutine.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context where the error happened.

  • +
  • error (CommandError) – The error that happened.

  • +
+
+
+
+ +
+
+await cog_before_invoke(ctx)
+

A special method that acts as a cog local pre-invoke hook.

+

This is similar to Command.before_invoke().

+

This must be a coroutine.

+
+
Parameters
+

ctx (Context) – The invocation context.

+
+
+
+ +
+
+await cog_after_invoke(ctx)
+

A special method that acts as a cog local post-invoke hook.

+

This is similar to Command.after_invoke().

+

This must be a coroutine.

+
+
Parameters
+

ctx (Context) – The invocation context.

+
+
+
+ +
+ +
+
+

CogMeta

+
+ +Attributes +
+
+class discord.ext.commands.CogMeta(*args, **kwargs)
+

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 abc.ABCMeta metaclass.

+

For example, to create an abstract cog mixin class, the following would be done.

+
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:

+
class MyCog(commands.Cog, name='My Cog'):
+    pass
+
+
+
+
+
+name
+

The cog name. By default, it is the name of the class with no modification.

+
+
Type
+

str

+
+
+
+ +
+
+description
+

The cog description. By default, it is the cleaned docstring of the class.

+
+

New in version 1.6.

+
+
+
Type
+

str

+
+
+
+ +
+
+command_attrs
+

A list of attributes to apply to every command inside this cog. The dictionary +is passed into the Command 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:

+
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
+
+
+
+
Type
+

dict

+
+
+
+ +
+ +
+
+
+

Help Commands

+
+

HelpCommand

+
+
+class discord.ext.commands.HelpCommand(*args, **kwargs)
+

The base implementation for help command formatting.

+
+

Note

+

Internally instances of this class are deep copied every time +the command itself is invoked to prevent a race condition +mentioned in GH-2123.

+

This means that relying on the state of this class to be +the same between command invocations would not work as expected.

+
+
+
+context
+

The context that invoked this help formatter. This is generally set after +the help command assigned, command_callback(), has been called.

+
+
Type
+

Optional[Context]

+
+
+
+ +
+
+show_hidden
+

Specifies if hidden commands should be shown in the output. +Defaults to False.

+
+
Type
+

bool

+
+
+
+ +
+
+verify_checks
+

Specifies if commands should have their Command.checks called +and verified. If True, always calls Command.checks. +If None, only calls Command.checks in a guild setting. +If False, never calls Command.checks. Defaults to True.

+
+

Changed in version 1.7.

+
+
+
Type
+

Optional[bool]

+
+
+
+ +
+
+command_attrs
+

A dictionary of options to pass in for the construction of the help command. +This allows you to change the command behaviour without actually changing +the implementation of the command. The attributes will be the same as the +ones passed in the Command constructor.

+
+
Type
+

dict

+
+
+
+ +
+
+add_check(func)
+

Adds a check to the help command.

+
+

New in version 1.4.

+
+
+
Parameters
+

func – The function that will be used as a check.

+
+
+
+ +
+
+remove_check(func)
+

Removes a check from the help command.

+

This function is idempotent and will not raise an exception if +the function is not in the command’s checks.

+
+

New in version 1.4.

+
+
+
Parameters
+

func – The function to remove from the checks.

+
+
+
+ +
+
+get_bot_mapping()
+

Retrieves the bot mapping passed to send_bot_help().

+
+ +
+
+property invoked_with
+

Similar to Context.invoked_with except properly handles +the case where Context.send_help() is used.

+

If the help command was used regularly then this returns +the Context.invoked_with attribute. Otherwise, if +it the help command was called using Context.send_help() +then it returns the internal command name of the help command.

+
+
Returns
+

The command name that triggered this invocation.

+
+
Return type
+

str

+
+
+
+ +
+
+get_command_signature(command)
+

Retrieves the signature portion of the help page.

+
+
Parameters
+

command (Command) – The command to get the signature of.

+
+
Returns
+

The signature for the command.

+
+
Return type
+

str

+
+
+
+ +
+
+remove_mentions(string)
+

Removes mentions from the string to prevent abuse.

+

This includes @everyone, @here, member mentions and role mentions.

+
+
Returns
+

The string with mentions removed.

+
+
Return type
+

str

+
+
+
+ +
+
+property cog
+

A property for retrieving or setting the cog for the help command.

+

When a cog is set for the help command, it is as-if the help command +belongs to that cog. All cog special methods will apply to the help +command and it will be automatically unset on unload.

+

To unbind the cog from the help command, you can set it to None.

+
+
Returns
+

The cog that is currently set for the help command.

+
+
Return type
+

Optional[Cog]

+
+
+
+ +
+
+command_not_found(string)
+

This function could be a coroutine.

+

A method called when a command is not found in the help command. +This is useful to override for i18n.

+

Defaults to No command called {0} found.

+
+
Parameters
+

string (str) – The string that contains the invalid command. Note that this has +had mentions removed to prevent abuse.

+
+
Returns
+

The string to use when a command has not been found.

+
+
Return type
+

str

+
+
+
+ +
+
+subcommand_not_found(command, string)
+

This function could be a coroutine.

+

A method called when a command did not have a subcommand requested in the help command. +This is useful to override for i18n.

+

Defaults to either:

+
    +
  • +
    'Command "{command.qualified_name}" has no subcommands.'
      +
    • If there is no subcommand in the command parameter.

    • +
    +
    +
    +
  • +
  • +
    'Command "{command.qualified_name}" has no subcommand named {string}'
      +
    • If the command parameter has subcommands but not one named string.

    • +
    +
    +
    +
  • +
+
+
Parameters
+
    +
  • command (Command) – The command that did not have the subcommand requested.

  • +
  • string (str) – The string that contains the invalid subcommand. Note that this has +had mentions removed to prevent abuse.

  • +
+
+
Returns
+

The string to use when the command did not have the subcommand requested.

+
+
Return type
+

str

+
+
+
+ +
+
+await filter_commands(commands, *, sort=False, key=None)
+

This function is a coroutine.

+

Returns a filtered list of commands and optionally sorts them.

+

This takes into account the verify_checks and show_hidden +attributes.

+
+
Parameters
+
    +
  • commands (Iterable[Command]) – An iterable of commands that are getting filtered.

  • +
  • sort (bool) – Whether to sort the result.

  • +
  • key (Optional[Callable[Command, Any]]) – An optional key function to pass to sorted() that +takes a Command as its sole parameter. If sort is +passed as True then this will default as the command name.

  • +
+
+
Returns
+

A list of commands that passed the filter.

+
+
Return type
+

List[Command]

+
+
+
+ +
+
+get_max_size(commands)
+

Returns the largest name length of the specified command list.

+
+
Parameters
+

commands (Sequence[Command]) – A sequence of commands to check for the largest size.

+
+
Returns
+

The maximum width of the commands.

+
+
Return type
+

int

+
+
+
+ +
+
+get_destination()
+

Returns the Messageable where the help command will be output.

+

You can override this method to customise the behaviour.

+

By default this returns the context’s channel.

+
+
Returns
+

The destination where the help command will be output.

+
+
Return type
+

abc.Messageable

+
+
+
+ +
+
+await send_error_message(error)
+

This function is a coroutine.

+

Handles the implementation when an error happens in the help command. +For example, the result of command_not_found() will be passed here.

+

You can override this method to customise the behaviour.

+

By default, this sends the error message to the destination +specified by get_destination().

+
+

Note

+

You can access the invocation context with HelpCommand.context.

+
+
+
Parameters
+

error (str) – The error message to display to the user. Note that this has +had mentions removed to prevent abuse.

+
+
+
+ +
+
+await on_help_command_error(ctx, error)
+

This function is a coroutine.

+

The help command’s error handler, as specified by Error Handling.

+

Useful to override if you need some specific behaviour when the error handler +is called.

+

By default this method does nothing and just propagates to the default +error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context.

  • +
  • error (CommandError) – The error that was raised.

  • +
+
+
+
+ +
+
+await send_bot_help(mapping)
+

This function is a coroutine.

+

Handles the implementation of the bot command page in the help command. +This function is called when the help command is called with no arguments.

+

It should be noted that this method does not return anything – rather the +actual message sending should be done inside this method. Well behaved subclasses +should use get_destination() to know where to send, as this is a customisation +point for other users.

+

You can override this method to customise the behaviour.

+
+

Note

+

You can access the invocation context with HelpCommand.context.

+

Also, the commands in the mapping are not filtered. To do the filtering +you will have to call filter_commands() yourself.

+
+
+
Parameters
+

mapping (Mapping[Optional[Cog], List[Command]]) – A mapping of cogs to commands that have been requested by the user for help. +The key of the mapping is the Cog that the command belongs to, or +None if there isn’t one, and the value is a list of commands that belongs to that cog.

+
+
+
+ +
+
+await send_cog_help(cog)
+

This function is a coroutine.

+

Handles the implementation of the cog page in the help command. +This function is called when the help command is called with a cog as the argument.

+

It should be noted that this method does not return anything – rather the +actual message sending should be done inside this method. Well behaved subclasses +should use get_destination() to know where to send, as this is a customisation +point for other users.

+

You can override this method to customise the behaviour.

+
+

Note

+

You can access the invocation context with HelpCommand.context.

+

To get the commands that belong to this cog see Cog.get_commands(). +The commands returned not filtered. To do the filtering you will have to call +filter_commands() yourself.

+
+
+
Parameters
+

cog (Cog) – The cog that was requested for help.

+
+
+
+ +
+
+await send_group_help(group)
+

This function is a coroutine.

+

Handles the implementation of the group page in the help command. +This function is called when the help command is called with a group as the argument.

+

It should be noted that this method does not return anything – rather the +actual message sending should be done inside this method. Well behaved subclasses +should use get_destination() to know where to send, as this is a customisation +point for other users.

+

You can override this method to customise the behaviour.

+
+

Note

+

You can access the invocation context with HelpCommand.context.

+

To get the commands that belong to this group without aliases see +Group.commands. The commands returned not filtered. To do the +filtering you will have to call filter_commands() yourself.

+
+
+
Parameters
+

group (Group) – The group that was requested for help.

+
+
+
+ +
+
+await send_command_help(command)
+

This function is a coroutine.

+

Handles the implementation of the single command page in the help command.

+

It should be noted that this method does not return anything – rather the +actual message sending should be done inside this method. Well behaved subclasses +should use get_destination() to know where to send, as this is a customisation +point for other users.

+

You can override this method to customise the behaviour.

+
+

Note

+

You can access the invocation context with HelpCommand.context.

+
+
+

Showing Help

+

There are certain attributes and methods that are helpful for a help command +to show such as the following:

+ +

There are more than just these attributes but feel free to play around with +these to help you get started to get the output that you want.

+
+
+
Parameters
+

command (Command) – The command that was requested for help.

+
+
+
+ +
+
+await prepare_help_command(ctx, command=None)
+

This function is a coroutine.

+

A low level method that can be used to prepare the help command +before it does anything. For example, if you need to prepare +some state in your subclass before the command does its processing +then this would be the place to do it.

+

The default implementation does nothing.

+
+

Note

+

This is called inside the help command callback body. So all +the usual rules that happen inside apply here as well.

+
+
+
Parameters
+
    +
  • ctx (Context) – The invocation context.

  • +
  • command (Optional[str]) – The argument passed to the help command.

  • +
+
+
+
+ +
+
+await command_callback(ctx, *, command=None)
+

This function is a coroutine.

+

The actual implementation of the help command.

+

It is not recommended to override this method and instead change +the behaviour through the methods that actually get dispatched.

+ +
+ +
+ +
+
+

DefaultHelpCommand

+
+
+class discord.ext.commands.DefaultHelpCommand(*args, **kwargs)
+

The implementation of the default help command.

+

This inherits from HelpCommand.

+

It extends it with the following attributes.

+
+
+width
+

The maximum number of characters that fit in a line. +Defaults to 80.

+
+
Type
+

int

+
+
+
+ +
+
+sort_commands
+

Whether to sort the commands in the output alphabetically. Defaults to True.

+
+
Type
+

bool

+
+
+
+ +
+
+dm_help
+

A tribool that indicates if the help command should DM the user instead of +sending it to the channel it received it from. If the boolean is set to +True, then all help output is DM’d. If False, none of the help +output is DM’d. If None, then the bot will only DM when the help +message becomes too long (dictated by more than dm_help_threshold characters). +Defaults to False.

+
+
Type
+

Optional[bool]

+
+
+
+ +
+
+dm_help_threshold
+

The number of characters the paginator must accumulate before getting DM’d to the +user if dm_help is set to None. Defaults to 1000.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+indent
+

How much to indent the commands from a heading. Defaults to 2.

+
+
Type
+

int

+
+
+
+ +
+
+commands_heading
+

The command list’s heading string used when the help command is invoked with a category name. +Useful for i18n. Defaults to "Commands:"

+
+
Type
+

str

+
+
+
+ +
+
+no_category
+

The string used when there is a command which does not belong to any category(cog). +Useful for i18n. Defaults to "No Category"

+
+
Type
+

str

+
+
+
+ +
+
+paginator
+

The paginator used to paginate the help command output.

+
+
Type
+

Paginator

+
+
+
+ +
+
+shorten_text(text)
+

str: Shortens text to fit into the width.

+
+ +
+
+get_ending_note()
+

str: Returns help command’s ending note. This is mainly useful to override for i18n purposes.

+
+ +
+
+add_indented_commands(commands, *, heading, max_size=None)
+

Indents a list of commands after the specified heading.

+

The formatting is added to the paginator.

+

The default implementation is the command name indented by +indent spaces, padded to max_size followed by +the command’s Command.short_doc and then shortened +to fit into the width.

+
+
Parameters
+
    +
  • commands (Sequence[Command]) – A list of commands to indent for output.

  • +
  • heading (str) – The heading to add to the output. This is only added +if the list of commands is greater than 0.

  • +
  • max_size (Optional[int]) – The max size to use for the gap between indents. +If unspecified, calls get_max_size() on the +commands parameter.

  • +
+
+
+
+ +
+
+await send_pages()
+

A helper utility to send the page output from paginator to the destination.

+
+ +
+
+add_command_formatting(command)
+

A utility function to format the non-indented block of commands and groups.

+
+
Parameters
+

command (Command) – The command to format.

+
+
+
+ +
+
+get_destination()
+

Returns the Messageable where the help command will be output.

+

You can override this method to customise the behaviour.

+

By default this returns the context’s channel.

+
+
Returns
+

The destination where the help command will be output.

+
+
Return type
+

abc.Messageable

+
+
+
+ +
+ +
+
+

MinimalHelpCommand

+
+
+class discord.ext.commands.MinimalHelpCommand(*args, **kwargs)
+

An implementation of a help command with minimal output.

+

This inherits from HelpCommand.

+
+
+sort_commands
+

Whether to sort the commands in the output alphabetically. Defaults to True.

+
+
Type
+

bool

+
+
+
+ +
+
+commands_heading
+

The command list’s heading string used when the help command is invoked with a category name. +Useful for i18n. Defaults to "Commands"

+
+
Type
+

str

+
+
+
+ +
+
+aliases_heading
+

The alias list’s heading string used to list the aliases of the command. Useful for i18n. +Defaults to "Aliases:".

+
+
Type
+

str

+
+
+
+ +
+
+dm_help
+

A tribool that indicates if the help command should DM the user instead of +sending it to the channel it received it from. If the boolean is set to +True, then all help output is DM’d. If False, none of the help +output is DM’d. If None, then the bot will only DM when the help +message becomes too long (dictated by more than dm_help_threshold characters). +Defaults to False.

+
+
Type
+

Optional[bool]

+
+
+
+ +
+
+dm_help_threshold
+

The number of characters the paginator must accumulate before getting DM’d to the +user if dm_help is set to None. Defaults to 1000.

+
+
Type
+

Optional[int]

+
+
+
+ +
+
+no_category
+

The string used when there is a command which does not belong to any category(cog). +Useful for i18n. Defaults to "No Category"

+
+
Type
+

str

+
+
+
+ +
+
+paginator
+

The paginator used to paginate the help command output.

+
+
Type
+

Paginator

+
+
+
+ +
+
+await send_pages()
+

A helper utility to send the page output from paginator to the destination.

+
+ +
+
+get_opening_note()
+

Returns help command’s opening note. This is mainly useful to override for i18n purposes.

+

The default implementation returns

+
Use `{prefix}{command_name} [command]` for more info on a command.
+You can also use `{prefix}{command_name} [category]` for more info on a category.
+
+
+
+
Returns
+

The help command opening note.

+
+
Return type
+

str

+
+
+
+ +
+
+get_command_signature(command)
+

Retrieves the signature portion of the help page.

+
+
Parameters
+

command (Command) – The command to get the signature of.

+
+
Returns
+

The signature for the command.

+
+
Return type
+

str

+
+
+
+ +
+
+get_ending_note()
+

Return the help command’s ending note. This is mainly useful to override for i18n purposes.

+

The default implementation does nothing.

+
+
Returns
+

The help command ending note.

+
+
Return type
+

str

+
+
+
+ +
+
+add_bot_commands_formatting(commands, heading)
+

Adds the minified bot heading with commands to the output.

+

The formatting should be added to the paginator.

+

The default implementation is a bold underline heading followed +by commands separated by an EN SPACE (U+2002) in the next line.

+
+
Parameters
+
    +
  • commands (Sequence[Command]) – A list of commands that belong to the heading.

  • +
  • heading (str) – The heading to add to the line.

  • +
+
+
+
+ +
+
+add_subcommand_formatting(command)
+

Adds formatting information on a subcommand.

+

The formatting should be added to the paginator.

+

The default implementation is the prefix and the Command.qualified_name +optionally followed by an En dash and the command’s Command.short_doc.

+
+
Parameters
+

command (Command) – The command to show information of.

+
+
+
+ +
+
+add_aliases_formatting(aliases)
+

Adds the formatting information on a command’s aliases.

+

The formatting should be added to the paginator.

+

The default implementation is the aliases_heading bolded +followed by a comma separated list of aliases.

+

This is not called if there are no aliases to format.

+
+
Parameters
+

aliases (Sequence[str]) – A list of aliases to format.

+
+
+
+ +
+
+add_command_formatting(command)
+

A utility function to format commands and groups.

+
+
Parameters
+

command (Command) – The command to format.

+
+
+
+ +
+
+get_destination()
+

Returns the Messageable where the help command will be output.

+

You can override this method to customise the behaviour.

+

By default this returns the context’s channel.

+
+
Returns
+

The destination where the help command will be output.

+
+
Return type
+

abc.Messageable

+
+
+
+ +
+ +
+
+

Paginator

+
+ +Attributes +
+ +Methods +
+
+class discord.ext.commands.Paginator(prefix='```', suffix='```', max_size=2000, linesep='\n')
+

A class that aids in paginating code blocks for Discord messages.

+
+
+
+len(x)
+

Returns the total number of characters in the paginator.

+
+ +
+
+
+prefix
+

The prefix inserted to every page. e.g. three backticks.

+
+
Type
+

str

+
+
+
+ +
+
+suffix
+

The suffix appended at the end of every page. e.g. three backticks.

+
+
Type
+

str

+
+
+
+ +
+
+max_size
+

The maximum amount of codepoints allowed in a page.

+
+
Type
+

int

+
+
+
+ +
+
+linesep
+
+
The character string inserted between lines. e.g. a newline character.
+

New in version 1.7.

+
+
+
+
+
Type
+

str

+
+
+
+ +
+
+clear()
+

Clears the paginator to have no pages.

+
+ +
+
+add_line(line='', *, empty=False)
+

Adds a line to the current page.

+

If the line exceeds the max_size then an exception +is raised.

+
+
Parameters
+
    +
  • line (str) – The line to add.

  • +
  • empty (bool) – Indicates if another empty line should be added.

  • +
+
+
Raises
+

RuntimeError – The line was too big for the current max_size.

+
+
+
+ +
+
+close_page()
+

Prematurely terminate a page.

+
+ +
+
+property pages
+

Returns the rendered list of pages.

+
+
Type
+

List[str]

+
+
+
+ +
+ +
+
+
+

Enums

+
+
+class discord.ext.commands.BucketType
+

Specifies a type of bucket for, e.g. a cooldown.

+
+
+default
+

The default bucket operates on a global basis.

+
+ +
+
+user
+

The user bucket operates on a per-user basis.

+
+ +
+
+guild
+

The guild bucket operates on a per-guild basis.

+
+ +
+
+channel
+

The channel bucket operates on a per-channel basis.

+
+ +
+
+member
+

The member bucket operates on a per-member basis.

+
+ +
+
+category
+

The category bucket operates on a per-category basis.

+
+ +
+
+role
+

The role bucket operates on a per-role basis.

+
+

New in version 1.3.

+
+
+ +
+ +
+
+

Checks

+
+
+@discord.ext.commands.check(predicate)
+

A decorator that adds a check to the Command or its +subclasses. These checks could be accessed via Command.checks.

+

These checks should be predicates that take in a single parameter taking +a Context. If the check returns a False-like value then +during invocation a CheckFailure exception is raised and sent to +the on_command_error() event.

+

If an exception should be thrown in the predicate then it should be a +subclass of CommandError. Any exception not subclassed from it +will be propagated while those subclassed will be sent to +on_command_error().

+

A special attribute named predicate is bound to the value +returned by this decorator to retrieve the predicate passed to the +decorator. This allows the following introspection and chaining to be done:

+
def owner_or_permissions(**perms):
+    original = commands.has_permissions(**perms).predicate
+    async def extended_check(ctx):
+        if ctx.guild is None:
+            return False
+        return ctx.guild.owner_id == ctx.author.id or await original(ctx)
+    return commands.check(extended_check)
+
+
+
+

Note

+

The function returned by predicate is always a coroutine, +even if the original function was not a coroutine.

+
+
+

Changed in version 1.3: The predicate attribute was added.

+
+

Examples

+

Creating a basic check to see if the command invoker is you.

+
def check_if_it_is_me(ctx):
+    return ctx.message.author.id == 85309593344815104
+
+@bot.command()
+@commands.check(check_if_it_is_me)
+async def only_for_me(ctx):
+    await ctx.send('I know you!')
+
+
+

Transforming common checks into its own decorator:

+
def is_me():
+    def predicate(ctx):
+        return ctx.message.author.id == 85309593344815104
+    return commands.check(predicate)
+
+@bot.command()
+@is_me()
+async def only_me(ctx):
+    await ctx.send('Only you!')
+
+
+
+
Parameters
+
    +
  • predicate (Callable[[Context], bool]) – The predicate to check if the command should be invoked.

  • +
  • **command_attrs (Dict[str, Any]) – key: value pairs to be added to the command’s attributes.

  • +
+
+
+
+ +
+
+@discord.ext.commands.check_any(*checks)
+

A check() that is added that checks if any of the checks passed +will pass, i.e. using logical OR.

+

If all checks fail then CheckAnyFailure is raised to signal the failure. +It inherits from CheckFailure.

+
+

Note

+

The predicate attribute for this function is a coroutine.

+
+
+

New in version 1.3.

+
+
+
Parameters
+

*checks (Callable[[Context], bool]) – An argument list of checks that have been decorated with +the check() decorator.

+
+
Raises
+

TypeError – A check passed has not been decorated with the check() + decorator.

+
+
+

Examples

+

Creating a basic check to see if it’s the bot owner or +the server owner:

+
def is_guild_owner():
+    def predicate(ctx):
+        return ctx.guild is not None and ctx.guild.owner_id == ctx.author.id
+    return commands.check(predicate)
+
+@bot.command()
+@commands.check_any(commands.is_owner(), is_guild_owner())
+async def only_for_owners(ctx):
+    await ctx.send('Hello mister owner!')
+
+
+
+ +
+
+@discord.ext.commands.has_role(item)
+

A check() that is added that checks if the member invoking the +command has the role specified via the name or ID specified.

+

If a string is specified, you must give the exact name of the role, including +caps and spelling.

+

If an integer is specified, you must give the exact snowflake ID of the role.

+

If the message is invoked in a private message context then the check will +return False.

+

This check raises one of two special exceptions, MissingRole if the user +is missing a role, or NoPrivateMessage if it is used in a private message. +Both inherit from CheckFailure.

+
+

Changed in version 1.1: Raise MissingRole or NoPrivateMessage +instead of generic CheckFailure

+
+
+
Parameters
+

item (Union[int, str]) – The name or ID of the role to check.

+
+
+
+ +
+
+@discord.ext.commands.has_permissions(**perms)
+

A check() that is added that checks if the member has all of +the permissions necessary.

+

Note that this check operates on the current channel permissions, not the +guild wide permissions.

+

The permissions passed in must be exactly like the properties shown under +discord.Permissions.

+

This check raises a special exception, MissingPermissions +that is inherited from CheckFailure.

+
+
Parameters
+

perms – An argument list of permissions to check for.

+
+
+

Example

+
@bot.command()
+@commands.has_permissions(manage_messages=True)
+async def test(ctx):
+    await ctx.send('You can manage messages.')
+
+
+
+ +
+
+@discord.ext.commands.has_guild_permissions(**perms)
+

Similar to has_permissions(), but operates on guild wide +permissions instead of the current channel permissions.

+

If this check is called in a DM context, it will raise an +exception, NoPrivateMessage.

+
+

New in version 1.3.

+
+
+ +
+
+@discord.ext.commands.has_any_role(*items)
+

A check() that is added that checks if the member invoking the +command has any of the roles specified. This means that if they have +one out of the three roles specified, then this check will return True.

+

Similar to has_role(), the names or IDs passed in must be exact.

+

This check raises one of two special exceptions, MissingAnyRole if the user +is missing all roles, or NoPrivateMessage if it is used in a private message. +Both inherit from CheckFailure.

+
+

Changed in version 1.1: Raise MissingAnyRole or NoPrivateMessage +instead of generic CheckFailure

+
+
+
Parameters
+

items (List[Union[str, int]]) – An argument list of names or IDs to check that the member has roles wise.

+
+
+

Example

+
@bot.command()
+@commands.has_any_role('Library Devs', 'Moderators', 492212595072434186)
+async def cool(ctx):
+    await ctx.send('You are cool indeed')
+
+
+
+ +
+
+@discord.ext.commands.bot_has_role(item)
+

Similar to has_role() except checks if the bot itself has the +role.

+

This check raises one of two special exceptions, BotMissingRole if the bot +is missing the role, or NoPrivateMessage if it is used in a private message. +Both inherit from CheckFailure.

+
+

Changed in version 1.1: Raise BotMissingRole or NoPrivateMessage +instead of generic CheckFailure

+
+
+ +
+
+@discord.ext.commands.bot_has_permissions(**perms)
+

Similar to has_permissions() except checks if the bot itself has +the permissions listed.

+

This check raises a special exception, BotMissingPermissions +that is inherited from CheckFailure.

+
+ +
+
+@discord.ext.commands.bot_has_guild_permissions(**perms)
+

Similar to has_guild_permissions(), but checks the bot +members guild permissions.

+
+

New in version 1.3.

+
+
+ +
+
+@discord.ext.commands.bot_has_any_role(*items)
+

Similar to has_any_role() except checks if the bot itself has +any of the roles listed.

+

This check raises one of two special exceptions, BotMissingAnyRole if the bot +is missing all roles, or NoPrivateMessage if it is used in a private message. +Both inherit from CheckFailure.

+
+

Changed in version 1.1: Raise BotMissingAnyRole or NoPrivateMessage +instead of generic checkfailure

+
+
+ +
+
+@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)
+

A decorator that adds a cooldown to a Command

+

A cooldown allows a command to only be used a specific amount +of times in a specific time frame. These cooldowns can be based +either on a per-guild, per-channel, per-user, per-role or global basis. +Denoted by the third argument of type which must be of enum +type BucketType.

+

If a cooldown is triggered, then CommandOnCooldown is triggered in +on_command_error() and the local error handler.

+

A command can only have a single cooldown.

+
+
Parameters
+
    +
  • rate (int) – The number of times a command can be used before triggering a cooldown.

  • +
  • per (float) – The amount of seconds to wait for a cooldown when it’s been triggered.

  • +
  • type (Union[BucketType, Callable[[Message], Any]]) –

    The type of cooldown to have. If callable, should return a key for the mapping.

    +
    +

    Changed in version 1.7: Callables are now supported for custom bucket types.

    +
    +

  • +
+
+
+
+ +
+
+@discord.ext.commands.dynamic_cooldown(cooldown, type=BucketType.default)
+

A decorator that adds a dynamic cooldown to a Command

+

This differs from cooldown() in that it takes a function that +accepts a single parameter of type discord.Message and must +return a Cooldown or None. If None is returned then +that cooldown is effectively bypassed.

+

A cooldown allows a command to only be used a specific amount +of times in a specific time frame. These cooldowns can be based +either on a per-guild, per-channel, per-user, per-role or global basis. +Denoted by the third argument of type which must be of enum +type BucketType.

+

If a cooldown is triggered, then CommandOnCooldown is triggered in +on_command_error() and the local error handler.

+

A command can only have a single cooldown.

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • cooldown (Callable[[discord.Message], Optional[Cooldown]]) – A function that takes a message and returns a cooldown that will +apply to this invocation or None if the cooldown should be bypassed.

  • +
  • type (BucketType) – The type of cooldown to have.

  • +
+
+
+
+ +
+
+@discord.ext.commands.max_concurrency(number, per=discord.ext.commands.BucketType.default, *, wait=False)
+

A decorator that adds a maximum concurrency to a Command or its subclasses.

+

This enables you to only allow a certain number of command invocations at the same time, +for example if a command takes too long or if only one user can use it at a time. This +differs from a cooldown in that there is no set waiting period or token bucket – only +a set number of people can run the command.

+
+

New in version 1.3.

+
+
+
Parameters
+
    +
  • number (int) – The maximum number of invocations of this command that can be running at the same time.

  • +
  • per (BucketType) – The bucket that this concurrency is based on, e.g. BucketType.guild would allow +it to be used up to number times per guild.

  • +
  • wait (bool) – Whether the command should wait for the queue to be over. If this is set to False +then instead of waiting until the command can run again, the command raises +MaxConcurrencyReached to its error handler. If this is set to True +then the command waits until it can be executed.

  • +
+
+
+
+ +
+
+@discord.ext.commands.before_invoke(coro)
+

A decorator that registers a coroutine as a pre-invoke hook.

+

This allows you to refer to one before invoke hook for several commands that +do not have to be within the same cog.

+
+

New in version 1.4.

+
+

Example

+
async def record_usage(ctx):
+    print(ctx.author, 'used', ctx.command, 'at', ctx.message.created_at)
+
+@bot.command()
+@commands.before_invoke(record_usage)
+async def who(ctx): # Output: <User> used who at <Time>
+    await ctx.send('i am a bot')
+
+class What(commands.Cog):
+
+    @commands.before_invoke(record_usage)
+    @commands.command()
+    async def when(self, ctx): # Output: <User> used when at <Time>
+        await ctx.send(f'and i have existed since {ctx.bot.user.created_at}')
+
+    @commands.command()
+    async def where(self, ctx): # Output: <Nothing>
+        await ctx.send('on Discord')
+
+    @commands.command()
+    async def why(self, ctx): # Output: <Nothing>
+        await ctx.send('because someone made me')
+
+bot.add_cog(What())
+
+
+
+ +
+
+@discord.ext.commands.after_invoke(coro)
+

A decorator that registers a coroutine as a post-invoke hook.

+

This allows you to refer to one after invoke hook for several commands that +do not have to be within the same cog.

+
+

New in version 1.4.

+
+
+ +
+
+@discord.ext.commands.guild_only()
+

A check() that indicates this command must only be used in a +guild context only. Basically, no private messages are allowed when +using the command.

+

This check raises a special exception, NoPrivateMessage +that is inherited from CheckFailure.

+
+ +
+
+@discord.ext.commands.dm_only()
+

A check() that indicates this command must only be used in a +DM context. Only private messages are allowed when +using the command.

+

This check raises a special exception, PrivateMessageOnly +that is inherited from CheckFailure.

+
+

New in version 1.1.

+
+
+ +
+
+@discord.ext.commands.is_owner()
+

A check() that checks if the person invoking this command is the +owner of the bot.

+

This is powered by Bot.is_owner().

+

This check raises a special exception, NotOwner that is derived +from CheckFailure.

+
+ +
+
+@discord.ext.commands.is_nsfw()
+

A check() that checks if the channel is a NSFW channel.

+

This check raises a special exception, NSFWChannelRequired +that is derived from CheckFailure.

+
+

Changed in version 1.1: Raise NSFWChannelRequired instead of generic CheckFailure. +DM channels will also now pass this check.

+
+
+ +
+
+

Cooldown

+
+ +Attributes +
+ +Methods +
+
+class discord.ext.commands.Cooldown(rate, per)
+

Represents a cooldown for a command.

+
+
+rate
+

The total number of tokens available per per seconds.

+
+
Type
+

int

+
+
+
+ +
+
+per
+

The length of the cooldown period in seconds.

+
+
Type
+

float

+
+
+
+ +
+
+get_tokens(current=None)
+

Returns the number of available tokens before rate limiting is applied.

+
+
Parameters
+

current (Optional[float]) – The time in seconds since Unix epoch to calculate tokens at. +If not supplied then time.time() is used.

+
+
Returns
+

The number of tokens available before the cooldown is to be applied.

+
+
Return type
+

int

+
+
+
+ +
+
+get_retry_after(current=None)
+

Returns the time in seconds until the cooldown will be reset.

+
+
Parameters
+

current (Optional[float]) – The current time in seconds since Unix epoch. +If not supplied, then time.time() is used.

+
+
Returns
+

The number of seconds to wait before this cooldown will be reset.

+
+
Return type
+

float

+
+
+
+ +
+
+update_rate_limit(current=None)
+

Updates the cooldown rate limit.

+
+
Parameters
+

current (Optional[float]) – The time in seconds since Unix epoch to update the rate limit at. +If not supplied, then time.time() is used.

+
+
Returns
+

The retry-after time in seconds if rate limited.

+
+
Return type
+

Optional[float]

+
+
+
+ +
+
+reset()
+

Reset the cooldown to its initial state.

+
+ +
+
+copy()
+

Creates a copy of this cooldown.

+
+
Returns
+

A new instance of this cooldown.

+
+
Return type
+

Cooldown

+
+
+
+ +
+ +
+
+

Context

+
+
+class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, subcommand_passed=None, command_failed=False, current_parameter=None)
+

Represents the context in which a command is being invoked under.

+

This class contains a lot of meta data to help you understand more about +the invocation context. This class is not created manually and is instead +passed around to commands as the first parameter.

+

This class implements the Messageable ABC.

+
+
+message
+

The message that triggered the command being executed.

+
+
Type
+

Message

+
+
+
+ +
+
+bot
+

The bot that contains the command being executed.

+
+
Type
+

Bot

+
+
+
+ +
+
+args
+

The list of transformed arguments that were passed into the command. +If this is accessed during the on_command_error() event +then this list could be incomplete.

+
+
Type
+

list

+
+
+
+ +
+
+kwargs
+

A dictionary of transformed arguments that were passed into the command. +Similar to args, if this is accessed in the +on_command_error() event then this dict could be incomplete.

+
+
Type
+

dict

+
+
+
+ +
+
+current_parameter
+

The parameter that is currently being inspected and converted. +This is only of use for within converters.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[inspect.Parameter]

+
+
+
+ +
+
+prefix
+

The prefix that was used to invoke the command.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+command
+

The command that is being invoked currently.

+
+
Type
+

Optional[Command]

+
+
+
+ +
+
+invoked_with
+

The command name that triggered this invocation. Useful for finding out +which alias called the command.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+invoked_parents
+

The command names of the parents that triggered this invocation. Useful for +finding out which aliases called the command.

+

For example in commands ?a b c test, the invoked parents are ['a', 'b', 'c'].

+
+

New in version 1.7.

+
+
+
Type
+

List[str]

+
+
+
+ +
+
+invoked_subcommand
+

The subcommand that was invoked. +If no valid subcommand was invoked then this is equal to None.

+
+
Type
+

Optional[Command]

+
+
+
+ +
+
+subcommand_passed
+

The string that was attempted to call a subcommand. This does not have +to point to a valid registered subcommand and could just point to a +nonsense string. If nothing was passed to attempt a call to a +subcommand then this is set to None.

+
+
Type
+

Optional[str]

+
+
+
+ +
+
+command_failed
+

A boolean that indicates if the command failed to be parsed, checked, +or invoked.

+
+
Type
+

bool

+
+
+
+ +
+
+async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
+

Returns an AsyncIterator that enables receiving the destination’s message history.

+

You must have read_message_history permissions to use this.

+

Examples

+

Usage

+
counter = 0
+async for message in channel.history(limit=200):
+    if message.author == client.user:
+        counter += 1
+
+
+

Flattening into a list:

+
messages = await channel.history(limit=123).flatten()
+# messages is now a list of Message...
+
+
+

All parameters are optional.

+
+
Parameters
+
    +
  • limit (Optional[int]) – The number of messages to retrieve. +If None, retrieves every message in the channel. Note, however, +that this would make it a slow operation.

  • +
  • before (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • after (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time.

  • +
  • around (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. +If a datetime is provided, it is recommended to use a UTC aware datetime. +If the datetime is naive, it is assumed to be local time. +When using this argument, the maximum limit is 101. Note that if the limit is an +even number then this will return at most limit + 1 messages.

  • +
  • oldest_first (Optional[bool]) – If set to True, return messages in oldest->newest order. Defaults to True if +after is specified, otherwise False.

  • +
+
+
Raises
+
    +
  • Forbidden – You do not have permissions to get channel message history.

  • +
  • HTTPException – The request to get message history failed.

  • +
+
+
Yields
+

Message – The message with the message data parsed.

+
+
+
+ +
+
+async with typing()
+

Returns a context manager that allows you to type for an indefinite period of time.

+

This is useful for denoting long computations in your bot.

+
+

Note

+

This is both a regular context manager and an async context manager. +This means that both with and async with work with this.

+
+

Example Usage:

+
async with channel.typing():
+    # simulate something heavy
+    await asyncio.sleep(10)
+
+await channel.send('done!')
+
+
+
+ +
+
+await invoke(command, /, *args, **kwargs)
+

This function is a coroutine.

+

Calls a command with the arguments given.

+

This is useful if you want to just call the callback that a +Command holds internally.

+
+

Note

+

This does not handle converters, checks, cooldowns, pre-invoke, +or after-invoke hooks in any matter. It calls the internal callback +directly as-if it was a regular function.

+

You must take care in passing the proper arguments when +using this function.

+
+
+
Parameters
+
    +
  • command (Command) – The command that is going to be called.

  • +
  • *args – The arguments to use.

  • +
  • **kwargs – The keyword arguments to use.

  • +
+
+
Raises
+

TypeError – The command argument to invoke is missing.

+
+
+
+ +
+
+await reinvoke(*, call_hooks=False, restart=True)
+

This function is a coroutine.

+

Calls the command again.

+

This is similar to invoke() except that it bypasses +checks, cooldowns, and error handlers.

+
+

Note

+

If you want to bypass UserInputError derived exceptions, +it is recommended to use the regular invoke() +as it will work more naturally. After all, this will end up +using the old arguments the user has used and will thus just +fail again.

+
+
+
Parameters
+
    +
  • call_hooks (bool) – Whether to call the before and after invoke hooks.

  • +
  • restart (bool) – Whether to start the call chain from the very beginning +or where we left off (i.e. the command that caused the error). +The default is to start where we left off.

  • +
+
+
Raises
+

ValueError – The context to reinvoke is not valid.

+
+
+
+ +
+
+property valid
+

Checks if the invocation context is valid to be invoked with.

+
+
Type
+

bool

+
+
+
+ +
+
+property clean_prefix
+

The cleaned up invoke prefix. i.e. mentions are @name instead of <@id>.

+
+

New in version 2.0.

+
+
+
Type
+

str

+
+
+
+ +
+
+property cog
+

Returns the cog associated with this context’s command. None if it does not exist.

+
+
Type
+

Optional[Cog]

+
+
+
+ +
+
+guild
+

Returns the guild associated with this context’s command. None if not available.

+
+
Type
+

Optional[Guild]

+
+
+
+ +
+
+channel
+

Returns the channel associated with this context’s command. +Shorthand for Message.channel.

+
+
Type
+

Union[abc.Messageable]

+
+
+
+ +
+
+author
+

Union[User, Member]: +Returns the author associated with this context’s command. Shorthand for Message.author

+
+ +
+
+me
+

Union[Member, ClientUser]: +Similar to Guild.me except it may return the ClientUser in private message contexts.

+
+ +
+
+property voice_client
+

A shortcut to Guild.voice_client, if applicable.

+
+
Type
+

Optional[VoiceProtocol]

+
+
+
+ +
+
+author_permissions()
+

Returns the author permissions in the given channel.

+
+

New in version 2.0.

+
+
+ +
+
+await send_help(entity=<bot>)
+

This function is a coroutine.

+

Shows the help command for the specified entity if given. +The entity can be a command or a cog.

+

If no entity is given, then it’ll show help for the +entire bot.

+

If the entity is a string, then it looks up whether it’s a +Cog or a Command.

+
+

Note

+

Due to the way this function works, instead of returning +something similar to command_not_found() +this returns None on bad input or no help command.

+
+
+
Parameters
+

entity (Optional[Union[Command, Cog, str]]) – The entity to show help for.

+
+
Returns
+

The result of the help command, if any.

+
+
Return type
+

Any

+
+
+
+ +
+
+await fetch_message(id, /)
+

This function is a coroutine.

+

Retrieves a single Message from the destination.

+
+
Parameters
+

id (int) – The message ID to look for.

+
+
Raises
+
    +
  • NotFound – The specified message was not found.

  • +
  • Forbidden – You do not have the permissions required to get a message.

  • +
  • HTTPException – Retrieving the message failed.

  • +
+
+
Returns
+

The message asked for.

+
+
Return type
+

Message

+
+
+
+ +
+
+await pins()
+

This function is a coroutine.

+

Retrieves all messages that are currently pinned in the channel.

+
+

Note

+

Due to a limitation with the Discord API, the Message +objects returned by this method do not contain complete +Message.reactions data.

+
+
+
Raises
+

HTTPException – Retrieving the pinned messages failed.

+
+
Returns
+

The messages that are currently pinned.

+
+
Return type
+

List[Message]

+
+
+
+ +
+
+await trigger_typing()
+

This function is a coroutine.

+

Triggers a typing indicator to the destination.

+

Typing indicator will go away after 10 seconds, or after a message is sent.

+
+ +
+
+await send(content=None, return_message=True, ephemeral=False, **kwargs)
+

This function is a coroutine.

+

A shortcut method to abc.Messageable.send() with interaction helpers.

+

This function takes all the parameters of abc.Messageable.send() plus the following:

+
+
Parameters
+
    +
  • return_message (bool) – Ignored if not in a slash command context. +If this is set to False more native interaction methods will be used.

  • +
  • ephemeral (bool) – Ignored if not in a slash command context. +Indicates if the message should only be visible to the user who started the interaction. +If a view is sent with an ephemeral message and it has no timeout set then the timeout +is set to 15 minutes.

  • +
+
+
Returns
+

In a slash command context, the message that was sent if return_message is True.

+

In a normal context, it always returns a Message

+

+
+
Return type
+

Optional[Union[Message, WebhookMessage]]

+
+
+
+ +
+
+await reply(content=None, **kwargs)
+

This function is a coroutine.

+

A shortcut method to abc.Messageable.send() to reply to the +Message.

+
+

New in version 1.6.

+
+
+
Raises
+
    +
  • HTTPException – Sending the message failed.

  • +
  • Forbidden – You do not have the proper permissions to send the message.

  • +
  • InvalidArgument – The files list is not of the appropriate size or + you specified both file and files.

  • +
+
+
Returns
+

The message that was sent.

+
+
Return type
+

Message

+
+
+
+ +
+ +
+
+

Converters

+
+
+class discord.ext.commands.Converter(*args, **kwargs)
+

The base class of custom converters that require the Context +to be passed to be useful.

+

This allows you to implement converters that function similar to the +special cased discord classes.

+

Classes that derive from this should override the convert() +method to do its conversion logic. This method must be a coroutine.

+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.ObjectConverter(*args, **kwargs)
+

Converts to a Object.

+

The argument must follow the valid ID or mention formats (e.g. <@80088516616269824>).

+
+

New in version 2.0.

+
+

The lookup strategy is as follows (in order):

+
    +
  1. Lookup by ID.

  2. +
  3. Lookup by member, role, or channel mention.

  4. +
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.MemberConverter(*args, **kwargs)
+

Converts to a Member.

+

All lookups are via the local guild. If in a DM context, then the lookup +is done by the global cache.

+

The lookup strategy is as follows (in order):

+
    +
  1. Lookup by ID.

  2. +
  3. Lookup by mention.

  4. +
  5. Lookup by name#discrim

  6. +
  7. Lookup by name

  8. +
  9. Lookup by nickname

  10. +
+
+

Changed in version 1.5: Raise MemberNotFound instead of generic BadArgument

+
+
+

Changed in version 1.5.1: This converter now lazily fetches members from the gateway and HTTP APIs, +optionally caching the result if MemberCacheFlags.joined is enabled.

+
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.UserConverter(*args, **kwargs)
+

Converts to a User.

+

All lookups are via the global user cache.

+

The lookup strategy is as follows (in order):

+
    +
  1. Lookup by ID.

  2. +
  3. Lookup by mention.

  4. +
  5. Lookup by name#discrim

  6. +
  7. Lookup by name

  8. +
+
+

Changed in version 1.5: Raise UserNotFound instead of generic BadArgument

+
+
+

Changed in version 1.6: This converter now lazily fetches users from the HTTP APIs if an ID is passed +and it’s not available in cache.

+
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.MessageConverter(*args, **kwargs)
+

Converts to a discord.Message.

+
+

New in version 1.1.

+
+

The lookup strategy is as follows (in order):

+
    +
  1. Lookup by “{channel ID}-{message ID}” (retrieved by shift-clicking on “Copy ID”)

  2. +
  3. Lookup by message ID (the message must be in the context channel)

  4. +
  5. Lookup by message URL

  6. +
+
+

Changed in version 1.5: Raise ChannelNotFound, MessageNotFound or ChannelNotReadable instead of generic BadArgument

+
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.PartialMessageConverter(*args, **kwargs)
+

Converts to a discord.PartialMessage.

+
+

New in version 1.7.

+
+

The creation strategy is as follows (in order):

+
    +
  1. By “{channel ID}-{message ID}” (retrieved by shift-clicking on “Copy ID”)

  2. +
  3. By message ID (The message is assumed to be in the context channel.)

  4. +
  5. By message URL

  6. +
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.GuildChannelConverter(*args, **kwargs)
+

Converts to a GuildChannel.

+

All lookups are via the local guild. If in a DM context, then the lookup +is done by the global cache.

+

The lookup strategy is as follows (in order):

+
    +
  1. Lookup by ID.

  2. +
  3. Lookup by mention.

  4. +
  5. Lookup by name.

  6. +
+
+

New in version 2.0.

+
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.TextChannelConverter(*args, **kwargs)
+

Converts to a TextChannel.

+

All lookups are via the local guild. If in a DM context, then the lookup +is done by the global cache.

+

The lookup strategy is as follows (in order):

+
    +
  1. Lookup by ID.

  2. +
  3. Lookup by mention.

  4. +
  5. Lookup by name

  6. +
+
+

Changed in version 1.5: Raise ChannelNotFound instead of generic BadArgument

+
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.VoiceChannelConverter(*args, **kwargs)
+

Converts to a VoiceChannel.

+

All lookups are via the local guild. If in a DM context, then the lookup +is done by the global cache.

+

The lookup strategy is as follows (in order):

+
    +
  1. Lookup by ID.

  2. +
  3. Lookup by mention.

  4. +
  5. Lookup by name

  6. +
+
+

Changed in version 1.5: Raise ChannelNotFound instead of generic BadArgument

+
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.StoreChannelConverter(*args, **kwargs)
+

Converts to a StoreChannel.

+

All lookups are via the local guild. If in a DM context, then the lookup +is done by the global cache.

+

The lookup strategy is as follows (in order):

+
    +
  1. Lookup by ID.

  2. +
  3. Lookup by mention.

  4. +
  5. Lookup by name.

  6. +
+
+

New in version 1.7.

+
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.StageChannelConverter(*args, **kwargs)
+

Converts to a StageChannel.

+
+

New in version 1.7.

+
+

All lookups are via the local guild. If in a DM context, then the lookup +is done by the global cache.

+

The lookup strategy is as follows (in order):

+
    +
  1. Lookup by ID.

  2. +
  3. Lookup by mention.

  4. +
  5. Lookup by name

  6. +
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.CategoryChannelConverter(*args, **kwargs)
+

Converts to a CategoryChannel.

+

All lookups are via the local guild. If in a DM context, then the lookup +is done by the global cache.

+

The lookup strategy is as follows (in order):

+
    +
  1. Lookup by ID.

  2. +
  3. Lookup by mention.

  4. +
  5. Lookup by name

  6. +
+
+

Changed in version 1.5: Raise ChannelNotFound instead of generic BadArgument

+
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.InviteConverter(*args, **kwargs)
+

Converts to a Invite.

+

This is done via an HTTP request using Bot.fetch_invite().

+
+

Changed in version 1.5: Raise BadInviteArgument instead of generic BadArgument

+
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.GuildConverter(*args, **kwargs)
+

Converts to a Guild.

+

The lookup strategy is as follows (in order):

+
    +
  1. Lookup by ID.

  2. +
  3. Lookup by name. (There is no disambiguation for Guilds with multiple matching names).

  4. +
+
+

New in version 1.7.

+
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.RoleConverter(*args, **kwargs)
+

Converts to a Role.

+

All lookups are via the local guild. If in a DM context, the converter raises +NoPrivateMessage exception.

+

The lookup strategy is as follows (in order):

+
    +
  1. Lookup by ID.

  2. +
  3. Lookup by mention.

  4. +
  5. Lookup by name

  6. +
+
+

Changed in version 1.5: Raise RoleNotFound instead of generic BadArgument

+
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.GameConverter(*args, **kwargs)
+

Converts to Game.

+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.ColourConverter(*args, **kwargs)
+

Converts to a Colour.

+
+

Changed in version 1.5: Add an alias named ColorConverter

+
+

The following formats are accepted:

+
    +
  • 0x<hex>

  • +
  • #<hex>

  • +
  • 0x#<hex>

  • +
  • rgb(<number>, <number>, <number>)

  • +
  • Any of the classmethod in Colour

    +
    +
      +
    • The _ in the name can be optionally replaced with spaces.

    • +
    +
    +
  • +
+

Like CSS, <number> can be either 0-255 or 0-100% and <hex> can be +either a 6 digit hex number or a 3 digit hex shortcut (e.g. #fff).

+
+

Changed in version 1.5: Raise BadColourArgument instead of generic BadArgument

+
+
+

Changed in version 1.7: Added support for rgb function and 3-digit hex shortcuts

+
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.EmojiConverter(*args, **kwargs)
+

Converts to a Emoji.

+

All lookups are done for the local guild first, if available. If that lookup +fails, then it checks the client’s global cache.

+

The lookup strategy is as follows (in order):

+
    +
  1. Lookup by ID.

  2. +
  3. Lookup by extracting ID from the emoji.

  4. +
  5. Lookup by name

  6. +
+
+

Changed in version 1.5: Raise EmojiNotFound instead of generic BadArgument

+
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.PartialEmojiConverter(*args, **kwargs)
+

Converts to a PartialEmoji.

+

This is done by extracting the animated flag, name and ID from the emoji.

+
+

Changed in version 1.5: Raise PartialEmojiConversionFailure instead of generic BadArgument

+
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.ThreadConverter(*args, **kwargs)
+

Coverts to a Thread.

+

All lookups are via the local guild.

+

The lookup strategy is as follows (in order):

+
    +
  1. Lookup by ID.

  2. +
  3. Lookup by mention.

  4. +
  5. Lookup by name.

  6. +
+
+

New in version 2.0.

+
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.GuildStickerConverter(*args, **kwargs)
+

Converts to a GuildSticker.

+

All lookups are done for the local guild first, if available. If that lookup +fails, then it checks the client’s global cache.

+

The lookup strategy is as follows (in order):

+

1. Lookup by ID. +3. Lookup by name

+
+

New in version 2.0.

+
+
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.clean_content(*, fix_channel_mentions=False, use_nicknames=True, escape_markdown=False, remove_markdown=False)
+

Converts the argument to mention scrubbed version of +said content.

+

This behaves similarly to clean_content.

+
+
+fix_channel_mentions
+

Whether to clean channel mentions.

+
+
Type
+

bool

+
+
+
+ +
+
+use_nicknames
+

Whether to use nicknames when transforming mentions.

+
+
Type
+

bool

+
+
+
+ +
+
+escape_markdown
+

Whether to also escape special markdown characters.

+
+
Type
+

bool

+
+
+
+ +
+
+remove_markdown
+

Whether to also remove special markdown characters. This option is not supported with escape_markdown

+
+

New in version 1.7.

+
+
+
Type
+

bool

+
+
+
+ +
+
+await convert(ctx, argument)
+

This function is a coroutine.

+

The method to override to do conversion logic.

+

If an error is found while converting, it is recommended to +raise a CommandError derived exception as it will +properly propagate to the error handlers.

+
+
Parameters
+
    +
  • ctx (Context) – The invocation context that the argument is being used in.

  • +
  • argument (str) – The argument that is being converted.

  • +
+
+
Raises
+
    +
  • CommandError – A generic exception occurred when converting the argument.

  • +
  • BadArgument – The converter failed to convert the argument.

  • +
+
+
+
+ +
+ +
+
+class discord.ext.commands.Greedy
+

A special converter that greedily consumes arguments until it can’t. +As a consequence of this behaviour, most input errors are silently discarded, +since it is used as an indicator of when to stop parsing.

+

When a parser error is met the greedy converter stops converting, undoes the +internal string parsing routine, and continues parsing regularly.

+

For example, in the following code:

+
@commands.command()
+async def test(ctx, numbers: Greedy[int], reason: str):
+    await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
+
+
+

An invocation of [p]test 1 2 3 4 5 6 hello would pass numbers with +[1, 2, 3, 4, 5, 6] and reason with hello.

+

For more information, check Special Converters.

+
+ +
+
+await discord.ext.commands.run_converters(ctx, converter, argument, param)
+

This function is a coroutine.

+

Runs converters for a given converter, argument, and parameter.

+

This function does the same work that the library does under the hood.

+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • ctx (Context) – The invocation context to run the converters under.

  • +
  • converter (Any) – The converter to run, this corresponds to the annotation in the function.

  • +
  • argument (str) – The argument to convert to.

  • +
  • param (inspect.Parameter) – The parameter being converted. This is mainly for error reporting.

  • +
+
+
Raises
+

CommandError – The converter failed to convert.

+
+
Returns
+

The resulting conversion.

+
+
Return type
+

Any

+
+
+
+ +
+

Option

+
+
+class discord.ext.commands.Option(default, *, description)
+

A special ‘converter’ to apply a description to slash command options.

+

For example in the following code:

+
@bot.command()
+async def ban(ctx,
+    member: discord.Member, *,
+    reason: str = commands.Option('no reason', description='the reason to ban this member')
+):
+    await member.ban(reason=reason)
+
+
+

The description would be the reason to ban this member and the default would be no reason

+
+

New in version 2.0.

+
+
+
+default
+

The default for this option, overwrites Option during parsing.

+
+
Type
+

Optional[Any]

+
+
+
+ +
+
+description
+

The description for this option, is unpacked to Command.option_descriptions

+
+
Type
+

str

+
+
+
+ +
+ +
+
+

Flag Converter

+
+
+class discord.ext.commands.FlagConverter
+

A converter that allows for a user-friendly flag syntax.

+

The flags are defined using PEP 526 type annotations similar +to the dataclasses Python module. For more information on +how this converter works, check the appropriate +documentation.

+
+
+
+iter(x)
+

Returns an iterator of (flag_name, flag_value) pairs. This allows it +to be, for example, constructed as a dict or a list of pairs. +Note that aliases are not shown.

+
+ +
+
+

New in version 2.0.

+
+
+
Parameters
+
    +
  • case_insensitive (bool) – A class parameter to toggle case insensitivity of the flag parsing. +If True then flags are parsed in a case insensitive manner. +Defaults to False.

  • +
  • prefix (str) – The prefix that all flags must be prefixed with. By default +there is no prefix.

  • +
  • delimiter (str) – The delimiter that separates a flag’s argument from the flag’s name. +By default this is :.

  • +
+
+
+
+
+classmethod get_flags()
+

Dict[str, Flag]: A mapping of flag name to flag object this converter has.

+
+ +
+
+classmethod await convert(ctx, argument)
+

This function is a coroutine.

+

The method that actually converters an argument to the flag mapping.

+
+
Parameters
+
    +
  • cls (Type[FlagConverter]) – The flag converter class.

  • +
  • ctx (Context) – The invocation context.

  • +
  • argument (str) – The argument to convert from.

  • +
+
+
Raises
+
+
+
Returns
+

The flag converter instance with all flags parsed.

+
+
Return type
+

FlagConverter

+
+
+
+ +
+ +
+
+class discord.ext.commands.Flag
+

Represents a flag parameter for FlagConverter.

+

The flag() function helps +create these flag objects, but it is not necessary to +do so. These cannot be constructed manually.

+
+
+name
+

The name of the flag.

+
+
Type
+

str

+
+
+
+ +
+
+aliases
+

The aliases of the flag name.

+
+
Type
+

List[str]

+
+
+
+ +
+
+attribute
+

The attribute in the class that corresponds to this flag.

+
+
Type
+

str

+
+
+
+ +
+
+default
+

The default value of the flag, if available.

+
+
Type
+

Any

+
+
+
+ +
+
+annotation
+

The underlying evaluated annotation of the flag.

+
+
Type
+

Any

+
+
+
+ +
+
+max_args
+

The maximum number of arguments the flag can accept. +A negative value indicates an unlimited amount of arguments.

+
+
Type
+

int

+
+
+
+ +
+
+override
+

Whether multiple given values overrides the previous value.

+
+
Type
+

bool

+
+
+
+ +
+
+property required
+

Whether the flag is required.

+

A required flag has no default value.

+
+
Type
+

bool

+
+
+
+ +
+ +
+
+discord.ext.commands.flag(*, name=..., aliases=..., default=..., max_args=..., override=...)
+

Override default functionality and parameters of the underlying FlagConverter +class attributes.

+
+
Parameters
+
    +
  • name (str) – The flag name. If not given, defaults to the attribute name.

  • +
  • aliases (List[str]) – Aliases to the flag name. If not given no aliases are set.

  • +
  • default (Any) – The default parameter. This could be either a value or a callable that takes +Context as its sole parameter. If not given then it defaults to +the default value given to the attribute.

  • +
  • max_args (int) – The maximum number of arguments the flag can accept. +A negative value indicates an unlimited amount of arguments. +The default value depends on the annotation given.

  • +
  • override (bool) – Whether multiple given values overrides the previous value. The default +value depends on the annotation given.

  • +
+
+
+
+ +
+
+
+

Exceptions

+
+
+exception discord.ext.commands.CommandError(message=None, *args)
+

The base exception type for all command related errors.

+

This inherits from discord.DiscordException.

+

This exception and exceptions inherited from it are handled +in a special way as they are caught and passed into a special event +from Bot, on_command_error().

+
+ +
+
+exception discord.ext.commands.ConversionError(converter, original)
+

Exception raised when a Converter class raises non-CommandError.

+

This inherits from CommandError.

+
+
+converter
+

The converter that failed.

+
+
Type
+

discord.ext.commands.Converter

+
+
+
+ +
+
+original
+

The original exception that was raised. You can also get this via +the __cause__ attribute.

+
+
Type
+

Exception

+
+
+
+ +
+ +
+
+exception discord.ext.commands.MissingRequiredArgument(param)
+

Exception raised when parsing a command and a parameter +that is required is not encountered.

+

This inherits from UserInputError

+
+
+param
+

The argument that is missing.

+
+
Type
+

inspect.Parameter

+
+
+
+ +
+ +
+
+exception discord.ext.commands.ArgumentParsingError(message=None, *args)
+

An exception raised when the parser fails to parse a user’s input.

+

This inherits from UserInputError.

+

There are child classes that implement more granular parsing errors for +i18n purposes.

+
+ +
+
+exception discord.ext.commands.UnexpectedQuoteError(quote)
+

An exception raised when the parser encounters a quote mark inside a non-quoted string.

+

This inherits from ArgumentParsingError.

+
+
+quote
+

The quote mark that was found inside the non-quoted string.

+
+
Type
+

str

+
+
+
+ +
+ +
+
+exception discord.ext.commands.InvalidEndOfQuotedStringError(char)
+

An exception raised when a space is expected after the closing quote in a string +but a different character is found.

+

This inherits from ArgumentParsingError.

+
+
+char
+

The character found instead of the expected string.

+
+
Type
+

str

+
+
+
+ +
+ +
+
+exception discord.ext.commands.ExpectedClosingQuoteError(close_quote)
+

An exception raised when a quote character is expected but not found.

+

This inherits from ArgumentParsingError.

+
+
+close_quote
+

The quote character expected.

+
+
Type
+

str

+
+
+
+ +
+ +
+
+exception discord.ext.commands.BadArgument(message=None, *args)
+

Exception raised when a parsing or conversion failure is encountered +on an argument to pass into a command.

+

This inherits from UserInputError

+
+ +
+
+exception discord.ext.commands.BadUnionArgument(param, converters, errors)
+

Exception raised when a typing.Union converter fails for all +its associated types.

+

This inherits from UserInputError

+
+
+param
+

The parameter that failed being converted.

+
+
Type
+

inspect.Parameter

+
+
+
+ +
+
+converters
+

A tuple of converters attempted in conversion, in order of failure.

+
+
Type
+

Tuple[Type, ...]

+
+
+
+ +
+
+errors
+

A list of errors that were caught from failing the conversion.

+
+
Type
+

List[CommandError]

+
+
+
+ +
+ +
+
+exception discord.ext.commands.BadLiteralArgument(param, literals, errors)
+

Exception raised when a typing.Literal converter fails for all +its associated values.

+

This inherits from UserInputError

+
+

New in version 2.0.

+
+
+
+param
+

The parameter that failed being converted.

+
+
Type
+

inspect.Parameter

+
+
+
+ +
+
+literals
+

A tuple of values compared against in conversion, in order of failure.

+
+
Type
+

Tuple[Any, ...]

+
+
+
+ +
+
+errors
+

A list of errors that were caught from failing the conversion.

+
+
Type
+

List[CommandError]

+
+
+
+ +
+ +
+
+exception discord.ext.commands.PrivateMessageOnly(message=None)
+

Exception raised when an operation does not work outside of private +message contexts.

+

This inherits from CheckFailure

+
+ +
+
+exception discord.ext.commands.NoPrivateMessage(message=None)
+

Exception raised when an operation does not work in private message +contexts.

+

This inherits from CheckFailure

+
+ +
+
+exception discord.ext.commands.CheckFailure(message=None, *args)
+

Exception raised when the predicates in Command.checks have failed.

+

This inherits from CommandError

+
+ +
+
+exception discord.ext.commands.CheckAnyFailure(checks, errors)
+

Exception raised when all predicates in check_any() fail.

+

This inherits from CheckFailure.

+
+

New in version 1.3.

+
+
+
+errors
+

A list of errors that were caught during execution.

+
+
Type
+

List[CheckFailure]

+
+
+
+ +
+
+checks
+

A list of check predicates that failed.

+
+
Type
+

List[Callable[[Context], bool]]

+
+
+
+ +
+ +
+
+exception discord.ext.commands.CommandNotFound(message=None, *args)
+

Exception raised when a command is attempted to be invoked +but no command under that name is found.

+

This is not raised for invalid subcommands, rather just the +initial main command that is attempted to be invoked.

+

This inherits from CommandError.

+
+ +
+
+exception discord.ext.commands.DisabledCommand(message=None, *args)
+

Exception raised when the command being invoked is disabled.

+

This inherits from CommandError

+
+ +
+
+exception discord.ext.commands.CommandInvokeError(e)
+

Exception raised when the command being invoked raised an exception.

+

This inherits from CommandError

+
+
+original
+

The original exception that was raised. You can also get this via +the __cause__ attribute.

+
+
Type
+

Exception

+
+
+
+ +
+ +
+
+exception discord.ext.commands.TooManyArguments(message=None, *args)
+

Exception raised when the command was passed too many arguments and its +Command.ignore_extra attribute was not set to True.

+

This inherits from UserInputError

+
+ +
+
+exception discord.ext.commands.UserInputError(message=None, *args)
+

The base exception type for errors that involve errors +regarding user input.

+

This inherits from CommandError.

+
+ +
+
+exception discord.ext.commands.CommandOnCooldown(cooldown, retry_after, type)
+

Exception raised when the command being invoked is on cooldown.

+

This inherits from CommandError

+
+
+cooldown
+

A class with attributes rate and per similar to the +cooldown() decorator.

+
+
Type
+

Cooldown

+
+
+
+ +
+
+type
+

The type associated with the cooldown.

+
+
Type
+

BucketType

+
+
+
+ +
+
+retry_after
+

The amount of seconds to wait before you can retry again.

+
+
Type
+

float

+
+
+
+ +
+ +
+
+exception discord.ext.commands.MaxConcurrencyReached(number, per)
+

Exception raised when the command being invoked has reached its maximum concurrency.

+

This inherits from CommandError.

+
+
+number
+

The maximum number of concurrent invokers allowed.

+
+
Type
+

int

+
+
+
+ +
+
+per
+

The bucket type passed to the max_concurrency() decorator.

+
+
Type
+

BucketType

+
+
+
+ +
+ +
+
+exception discord.ext.commands.NotOwner(message=None, *args)
+

Exception raised when the message author is not the owner of the bot.

+

This inherits from CheckFailure

+
+ +
+
+exception discord.ext.commands.MessageNotFound(argument)
+

Exception raised when the message provided was not found in the channel.

+

This inherits from BadArgument

+
+

New in version 1.5.

+
+
+
+argument
+

The message supplied by the caller that was not found

+
+
Type
+

str

+
+
+
+ +
+ +
+
+exception discord.ext.commands.MemberNotFound(argument)
+

Exception raised when the member provided was not found in the bot’s +cache.

+

This inherits from BadArgument

+
+

New in version 1.5.

+
+
+
+argument
+

The member supplied by the caller that was not found

+
+
Type
+

str

+
+
+
+ +
+ +
+
+exception discord.ext.commands.GuildNotFound(argument)
+

Exception raised when the guild provided was not found in the bot’s cache.

+

This inherits from BadArgument

+
+

New in version 1.7.

+
+
+
+argument
+

The guild supplied by the called that was not found

+
+
Type
+

str

+
+
+
+ +
+ +
+
+exception discord.ext.commands.UserNotFound(argument)
+

Exception raised when the user provided was not found in the bot’s +cache.

+

This inherits from BadArgument

+
+

New in version 1.5.

+
+
+
+argument
+

The user supplied by the caller that was not found

+
+
Type
+

str

+
+
+
+ +
+ +
+
+exception discord.ext.commands.ChannelNotFound(argument)
+

Exception raised when the bot can not find the channel.

+

This inherits from BadArgument

+
+

New in version 1.5.

+
+
+
+argument
+

The channel supplied by the caller that was not found

+
+
Type
+

str

+
+
+
+ +
+ +
+
+exception discord.ext.commands.ChannelNotReadable(argument)
+

Exception raised when the bot does not have permission to read messages +in the channel.

+

This inherits from BadArgument

+
+

New in version 1.5.

+
+
+
+argument
+

The channel supplied by the caller that was not readable

+
+
Type
+

Union[abc.GuildChannel, Thread]

+
+
+
+ +
+ +
+
+exception discord.ext.commands.ThreadNotFound(argument)
+

Exception raised when the bot can not find the thread.

+

This inherits from BadArgument

+
+

New in version 2.0.

+
+
+
+argument
+

The thread supplied by the caller that was not found

+
+
Type
+

str

+
+
+
+ +
+ +
+
+exception discord.ext.commands.BadColourArgument(argument)
+

Exception raised when the colour is not valid.

+

This inherits from BadArgument

+
+

New in version 1.5.

+
+
+
+argument
+

The colour supplied by the caller that was not valid

+
+
Type
+

str

+
+
+
+ +
+ +
+
+exception discord.ext.commands.RoleNotFound(argument)
+

Exception raised when the bot can not find the role.

+

This inherits from BadArgument

+
+

New in version 1.5.

+
+
+
+argument
+

The role supplied by the caller that was not found

+
+
Type
+

str

+
+
+
+ +
+ +
+
+exception discord.ext.commands.BadInviteArgument(argument)
+

Exception raised when the invite is invalid or expired.

+

This inherits from BadArgument

+
+

New in version 1.5.

+
+
+
+argument
+

The invite supplied by the caller that was not found

+
+
Type
+

str

+
+
+
+ +
+ +
+
+exception discord.ext.commands.EmojiNotFound(argument)
+

Exception raised when the bot can not find the emoji.

+

This inherits from BadArgument

+
+

New in version 1.5.

+
+
+
+argument
+

The emoji supplied by the caller that was not found

+
+
Type
+

str

+
+
+
+ +
+ +
+
+exception discord.ext.commands.PartialEmojiConversionFailure(argument)
+

Exception raised when the emoji provided does not match the correct +format.

+

This inherits from BadArgument

+
+

New in version 1.5.

+
+
+
+argument
+

The emoji supplied by the caller that did not match the regex

+
+
Type
+

str

+
+
+
+ +
+ +
+
+exception discord.ext.commands.GuildStickerNotFound(argument)
+

Exception raised when the bot can not find the sticker.

+

This inherits from BadArgument

+
+

New in version 2.0.

+
+
+
+argument
+

The sticker supplied by the caller that was not found

+
+
Type
+

str

+
+
+
+ +
+ +
+
+exception discord.ext.commands.BadBoolArgument(argument)
+

Exception raised when a boolean argument was not convertable.

+

This inherits from BadArgument

+
+

New in version 1.5.

+
+
+
+argument
+

The boolean argument supplied by the caller that is not in the predefined list

+
+
Type
+

str

+
+
+
+ +
+ +
+
+exception discord.ext.commands.MissingPermissions(missing_permissions, *args)
+

Exception raised when the command invoker lacks permissions to run a +command.

+

This inherits from CheckFailure

+
+
+missing_permissions
+

The required permissions that are missing.

+
+
Type
+

List[str]

+
+
+
+ +
+ +
+
+exception discord.ext.commands.BotMissingPermissions(missing_permissions, *args)
+

Exception raised when the bot’s member lacks permissions to run a +command.

+

This inherits from CheckFailure

+
+
+missing_permissions
+

The required permissions that are missing.

+
+
Type
+

List[str]

+
+
+
+ +
+ +
+
+exception discord.ext.commands.MissingRole(missing_role)
+

Exception raised when the command invoker lacks a role to run a command.

+

This inherits from CheckFailure

+
+

New in version 1.1.

+
+
+
+missing_role
+

The required role that is missing. +This is the parameter passed to has_role().

+
+
Type
+

Union[str, int]

+
+
+
+ +
+ +
+
+exception discord.ext.commands.BotMissingRole(missing_role)
+

Exception raised when the bot’s member lacks a role to run a command.

+

This inherits from CheckFailure

+
+

New in version 1.1.

+
+
+
+missing_role
+

The required role that is missing. +This is the parameter passed to has_role().

+
+
Type
+

Union[str, int]

+
+
+
+ +
+ +
+
+exception discord.ext.commands.MissingAnyRole(missing_roles)
+

Exception raised when the command invoker lacks any of +the roles specified to run a command.

+

This inherits from CheckFailure

+
+

New in version 1.1.

+
+
+
+missing_roles
+

The roles that the invoker is missing. +These are the parameters passed to has_any_role().

+
+
Type
+

List[Union[str, int]]

+
+
+
+ +
+ +
+
+exception discord.ext.commands.BotMissingAnyRole(missing_roles)
+

Exception raised when the bot’s member lacks any of +the roles specified to run a command.

+

This inherits from CheckFailure

+
+

New in version 1.1.

+
+
+
+missing_roles
+

The roles that the bot’s member is missing. +These are the parameters passed to has_any_role().

+
+
Type
+

List[Union[str, int]]

+
+
+
+ +
+ +
+
+exception discord.ext.commands.NSFWChannelRequired(channel)
+

Exception raised when a channel does not have the required NSFW setting.

+

This inherits from CheckFailure.

+
+

New in version 1.1.

+
+
+
Parameters
+

channel (Union[abc.GuildChannel, Thread]) – The channel that does not have NSFW enabled.

+
+
+
+ +
+
+exception discord.ext.commands.FlagError(message=None, *args)
+

The base exception type for all flag parsing related errors.

+

This inherits from BadArgument.

+
+

New in version 2.0.

+
+
+ +
+
+exception discord.ext.commands.BadFlagArgument(flag)
+

An exception raised when a flag failed to convert a value.

+

This inherits from FlagError

+
+

New in version 2.0.

+
+
+
+flag
+

The flag that failed to convert.

+
+
Type
+

Flag

+
+
+
+ +
+ +
+
+exception discord.ext.commands.MissingFlagArgument(flag)
+

An exception raised when a flag did not get a value.

+

This inherits from FlagError

+
+

New in version 2.0.

+
+
+
+flag
+

The flag that did not get a value.

+
+
Type
+

Flag

+
+
+
+ +
+ +
+
+exception discord.ext.commands.TooManyFlags(flag, values)
+

An exception raised when a flag has received too many values.

+

This inherits from FlagError.

+
+

New in version 2.0.

+
+
+
+flag
+

The flag that received too many values.

+
+
Type
+

Flag

+
+
+
+ +
+
+values
+

The values that were passed.

+
+
Type
+

List[str]

+
+
+
+ +
+ +
+
+exception discord.ext.commands.MissingRequiredFlag(flag)
+

An exception raised when a required flag was not given.

+

This inherits from FlagError

+
+

New in version 2.0.

+
+
+
+flag
+

The required flag that was not found.

+
+
Type
+

Flag

+
+
+
+ +
+ +
+
+exception discord.ext.commands.ExtensionError(message=None, *args, name)
+

Base exception for extension related errors.

+

This inherits from DiscordException.

+
+
+name
+

The extension that had an error.

+
+
Type
+

str

+
+
+
+ +
+ +
+
+exception discord.ext.commands.ExtensionAlreadyLoaded(name)
+

An exception raised when an extension has already been loaded.

+

This inherits from ExtensionError

+
+ +
+
+exception discord.ext.commands.ExtensionNotLoaded(name)
+

An exception raised when an extension was not loaded.

+

This inherits from ExtensionError

+
+ +
+
+exception discord.ext.commands.NoEntryPointError(name)
+

An exception raised when an extension does not have a setup entry point function.

+

This inherits from ExtensionError

+
+ +
+
+exception discord.ext.commands.ExtensionFailed(name, original)
+

An exception raised when an extension failed to load during execution of the module or setup entry point.

+

This inherits from ExtensionError

+
+
+name
+

The extension that had the error.

+
+
Type
+

str

+
+
+
+ +
+
+original
+

The original exception that was raised. You can also get this via +the __cause__ attribute.

+
+
Type
+

Exception

+
+
+
+ +
+ +
+
+exception discord.ext.commands.ExtensionNotFound(name)
+

An exception raised when an extension is not found.

+

This inherits from ExtensionError

+
+

Changed in version 1.3: Made the original attribute always None.

+
+
+
+name
+

The extension that had the error.

+
+
Type
+

str

+
+
+
+ +
+ +
+
+exception discord.ext.commands.CommandRegistrationError(name, *, alias_conflict=False)
+

An exception raised when the command can’t be added +because the name is already taken by a different command.

+

This inherits from discord.ClientException

+
+

New in version 1.4.

+
+
+
+name
+

The command name that had the error.

+
+
Type
+

str

+
+
+
+ +
+
+alias_conflict
+

Whether the name that conflicts is an alias of the command we try to add.

+
+
Type
+

bool

+
+
+
+ +
+ +
+

Exception Hierarchy

+ +
+
+
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/ext/commands/cogs.html b/docs/Python/html/ext/commands/cogs.html new file mode 100644 index 00000000..8a9dfe30 --- /dev/null +++ b/docs/Python/html/ext/commands/cogs.html @@ -0,0 +1,282 @@ + + + + + + Cogs + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

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:

+ +

It should be noted that cogs are typically used alongside with Extensions.

+
+

Quick Example

+

This example cog defines a Greetings category for your commands, with a single command named hello as well as a listener to listen 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: 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(f'Hello {member.name}~')
+        else:
+            await ctx.send(f'Hello {member.name}... This feels familiar.')
+        self._last_member = member
+
+
+

A couple of technical notes to take into consideration:

+
    +
  • All listeners must be explicitly marked via decorator, listener().

  • +
  • The name of the cog is automatically derived from the class name but can be overridden. See 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 add_cog() method.

+
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 Meta Options. So if we ever want to remove the cog eventually, we would have to do the following.

+
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:

+
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)
+
+
+
+
+

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:

+ +

You can visit the reference to get more detail.

+
+
+

Meta Options

+

At the heart of a cog resides a metaclass, 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:

+
class MyCog(commands.Cog, name='My Cog'):
+    pass
+
+
+

To see more options that you can set, see the documentation of commands.CogMeta.

+
+
+

Inspection

+

Since cogs ultimately are classes, we have some tools to help us inspect certain properties of the cog.

+

To get a list of commands, we can 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 well, we can use the 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 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)
+
+
+
+
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/ext/commands/commands.html b/docs/Python/html/ext/commands/commands.html new file mode 100644 index 00000000..508a8a0b --- /dev/null +++ b/docs/Python/html/ext/commands/commands.html @@ -0,0 +1,1021 @@ + + + + + + Commands + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

Commands

+

One of the most appealing aspects of the command extension is how easy it is to define commands and +how you can arbitrarily nest groups and commands to have a rich sub-command system.

+

Commands are defined by attaching it to a regular Python function. The command is then invoked by the user using a similar +signature to the Python function.

+

For example, in the given command definition:

+
@bot.command()
+async def foo(ctx, arg):
+    await ctx.send(arg)
+
+
+

With the following prefix ($), it would be invoked by the user via:

+
$foo abc
+
+
+

A command must always have at least one parameter, ctx, which is the Context as the first one.

+

There are two ways of registering a command. The first one is by using Bot.command() decorator, +as seen in the example above. The second is using the command() decorator followed by +Bot.add_command() on the instance.

+

Essentially, these two are equivalent:

+
from discord.ext import commands
+
+bot = commands.Bot(command_prefix='$')
+
+@bot.command()
+async def test(ctx):
+    pass
+
+# or:
+
+@commands.command()
+async def test(ctx):
+    pass
+
+bot.add_command(test)
+
+
+

Since the Bot.command() decorator is shorter and easier to comprehend, it will be the one used throughout the +documentation here.

+

Any parameter that is accepted by the Command constructor can be passed into the decorator. For example, to change +the name to something other than the function would be as simple as doing this:

+
@bot.command(name='list')
+async def _list(ctx, arg):
+    pass
+
+
+
+

Parameters

+

Since we define commands by making Python functions, we also define the argument passing behaviour by the function +parameters.

+

Certain parameter types do different things in the user side and most forms of parameter types are supported.

+
+

Positional

+

The most basic form of parameter passing is the positional parameter. This is where we pass a parameter as-is:

+
@bot.command()
+async def test(ctx, arg):
+    await ctx.send(arg)
+
+
+

On the bot using side, you can provide positional arguments by just passing a regular string:

+../../_images/positional1.png +

To make use of a word with spaces in between, you should quote it:

+../../_images/positional2.png +

As a note of warning, if you omit the quotes, you will only get the first word:

+../../_images/positional3.png +

Since positional arguments are just regular Python arguments, you can have as many as you want:

+
@bot.command()
+async def test(ctx, arg1, arg2):
+    await ctx.send(f'You passed {arg1} and {arg2}')
+
+
+
+
+

Variable

+

Sometimes you want users to pass in an undetermined number of parameters. The library supports this +similar to how variable list parameters are done in Python:

+
@bot.command()
+async def test(ctx, *args):
+    arguments = ', '.join(args)
+    await ctx.send(f'{len(args)} arguments: {arguments}')
+
+
+

This allows our user to accept either one or many arguments as they please. This works similar to positional arguments, +so multi-word parameters should be quoted.

+

For example, on the bot side:

+../../_images/variable1.png +

If the user wants to input a multi-word argument, they have to quote it like earlier:

+../../_images/variable2.png +

Do note that similar to the Python function behaviour, a user can technically pass no arguments +at all:

+../../_images/variable3.png +

Since the args variable is a tuple, +you can do anything you would usually do with one.

+
+

Slash Command Only

+

This functionally is currently not supported by the slash command API, so is turned into +a single STRING parameter on discord’s end which we do our own parsing on.

+
+
+
+

Keyword-Only Arguments

+

When you want to handle parsing of the argument yourself or do not feel like you want to wrap multi-word user input into +quotes, you can ask the library to give you the rest as a single argument. We do this by using a keyword-only argument, +seen below:

+
@bot.command()
+async def test(ctx, *, arg):
+    await ctx.send(arg)
+
+
+
+

Warning

+

You can only have one keyword-only argument due to parsing ambiguities.

+
+

On the bot side, we do not need to quote input with spaces:

+../../_images/keyword1.png +

Do keep in mind that wrapping it in quotes leaves it as-is:

+../../_images/keyword2.png +

By default, the keyword-only arguments are stripped of white space to make it easier to work with. This behaviour can be +toggled by the Command.rest_is_raw argument in the decorator.

+
+
+
+

Invocation Context

+

As seen earlier, every command must take at least a single parameter, called the Context.

+

This parameter gives you access to something called the “invocation context”. Essentially all the information you need to +know how the command was executed. It contains a lot of useful information:

+ +

The context implements the abc.Messageable interface, so anything you can do on a abc.Messageable you +can do on the Context.

+
+

Slash Command Only

+

Context.message will be fake if in a slash command, it is not +recommended to access if Context.interaction is not None as most +methods will error due to the message not actually existing.

+
+
+
+

Converters

+

Adding bot arguments with function parameters is only the first step in defining your bot’s command interface. To actually +make use of the arguments, we usually want to convert the data into a target type. We call these +Converters.

+

Converters come in a few flavours:

+
    +
  • A regular callable object that takes an argument as a sole parameter and returns a different type.

    +
    +
      +
    • These range from your own function, to something like bool or int.

    • +
    +
    +
  • +
  • A custom class that inherits from Converter.

  • +
+
+

Basic Converters

+

At its core, a basic converter is a callable that takes in an argument and turns it into something else.

+

For example, if we wanted to add two numbers together, we could request that they are turned into integers +for us by specifying the converter:

+
@bot.command()
+async def add(ctx, a: int, b: int):
+    await ctx.send(a + b)
+
+
+

We specify converters by using something called a function annotation. This is a Python 3 exclusive feature that was +introduced in PEP 3107.

+

This works with any callable, such as a function that would convert a string to all upper-case:

+
def to_upper(argument):
+    return argument.upper()
+
+@bot.command()
+async def up(ctx, *, content: to_upper):
+    await ctx.send(content)
+
+
+
+

bool

+

Unlike the other basic converters, the bool converter is treated slightly different. Instead of casting directly to the bool type, which would result in any non-empty argument returning True, it instead evaluates the argument as True or False based on its given content:

+
if lowered in ('yes', 'y', 'true', 't', '1', 'enable', 'on'):
+    return True
+elif lowered in ('no', 'n', 'false', 'f', '0', 'disable', 'off'):
+    return False
+
+
+
+
+
+

Advanced Converters

+

Sometimes a basic converter doesn’t have enough information that we need. For example, sometimes we want to get some +information from the Message that called the command or we want to do some asynchronous processing.

+

For this, the library provides the Converter interface. This allows you to have access to the +Context and have the callable be asynchronous. Defining a custom converter using this interface requires +overriding a single method, Converter.convert().

+

An example converter:

+
import random
+
+class Slapper(commands.Converter):
+    async def convert(self, ctx, argument):
+        to_slap = random.choice(ctx.guild.members)
+        return f'{ctx.author} slapped {to_slap} because *{argument}*'
+
+@bot.command()
+async def slap(ctx, *, reason: Slapper):
+    await ctx.send(reason)
+
+
+

The converter provided can either be constructed or not. Essentially these two are equivalent:

+
@bot.command()
+async def slap(ctx, *, reason: Slapper):
+    await ctx.send(reason)
+
+# is the same as...
+
+@bot.command()
+async def slap(ctx, *, reason: Slapper()):
+    await ctx.send(reason)
+
+
+

Having the possibility of the converter be constructed allows you to set up some state in the converter’s __init__ for +fine tuning the converter. An example of this is actually in the library, clean_content.

+
@bot.command()
+async def clean(ctx, *, content: commands.clean_content):
+    await ctx.send(content)
+
+# or for fine-tuning
+
+@bot.command()
+async def clean(ctx, *, content: commands.clean_content(use_nicknames=False)):
+    await ctx.send(content)
+
+
+

If a converter fails to convert an argument to its designated target type, the BadArgument exception must be +raised.

+
+
+

Inline Advanced Converters

+

If we don’t want to inherit from Converter, we can still provide a converter that has the +advanced functionalities of an advanced converter and save us from specifying two types.

+

For example, a common idiom would be to have a class and a converter for that class:

+
class JoinDistance:
+    def __init__(self, joined, created):
+        self.joined = joined
+        self.created = created
+
+    @property
+    def delta(self):
+        return self.joined - self.created
+
+class JoinDistanceConverter(commands.MemberConverter):
+    async def convert(self, ctx, argument):
+        member = await super().convert(ctx, argument)
+        return JoinDistance(member.joined_at, member.created_at)
+
+@bot.command()
+async def delta(ctx, *, member: JoinDistanceConverter):
+    is_new = member.delta.days < 100
+    if is_new:
+        await ctx.send("Hey you're pretty new!")
+    else:
+        await ctx.send("Hm you're not so new.")
+
+
+

This can get tedious, so an inline advanced converter is possible through a classmethod() inside the type:

+
class JoinDistance:
+    def __init__(self, joined, created):
+        self.joined = joined
+        self.created = created
+
+    @classmethod
+    async def convert(cls, ctx, argument):
+        member = await commands.MemberConverter().convert(ctx, argument)
+        return cls(member.joined_at, member.created_at)
+
+    @property
+    def delta(self):
+        return self.joined - self.created
+
+@bot.command()
+async def delta(ctx, *, member: JoinDistance):
+    is_new = member.delta.days < 100
+    if is_new:
+        await ctx.send("Hey you're pretty new!")
+    else:
+        await ctx.send("Hm you're not so new.")
+
+
+
+
+

Discord Converters

+

Working with Discord Models is a fairly common thing when defining commands, as a result the library makes +working with them easy.

+

For example, to receive a Member you can just pass it as a converter:

+
@bot.command()
+async def joined(ctx, *, member: discord.Member):
+    await ctx.send(f'{member} joined on {member.joined_at}')
+
+
+

When this command is executed, it attempts to convert the string given into a Member and then passes it as a +parameter for the function. This works by checking if the string is a mention, an ID, a nickname, a username + discriminator, +or just a regular username. The default set of converters have been written to be as easy to use as possible.

+

A lot of discord models work out of the gate as a parameter:

+ +

Having any of these set as the converter will intelligently convert the argument to the appropriate target type you +specify.

+

Under the hood, these are implemented by the Advanced Converters interface. A table of the equivalent +converter is given below:

+
+++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Discord Class

Converter

Supported By Slash Commands

Object

ObjectConverter

Not currently

Member

MemberConverter

Yes, as type 6 (USER)

User

UserConverter

Yes, as type 6 (USER)

Message

MessageConverter

Not currently

PartialMessage

PartialMessageConverter

Not currently

GuildChannel

GuildChannelConverter

Yes, as type 7 (CHANNEL)

TextChannel

TextChannelConverter

Yes, as type 7 (CHANNEL)

VoiceChannel

VoiceChannelConverter

Yes, as type 7 (CHANNEL)

StageChannel

StageChannelConverter

Yes, as type 7 (CHANNEL)

StoreChannel

StoreChannelConverter

Yes, as type 7 (CHANNEL)

CategoryChannel

CategoryChannelConverter

Yes, as type 7 (CHANNEL)

Thread

ThreadConverter

Yes, as type 7 (CHANNEL)

Invite

InviteConverter

Not currently

Guild

GuildConverter

Not currently

Role

RoleConverter

Yes, as type 8 (ROLE)

Game

GameConverter

Not currently

Colour

ColourConverter

Not currently

Emoji

EmojiConverter

Not currently

PartialEmoji

PartialEmojiConverter

Not currently

+
+

Slash Command Only

+

If a slash command is not marked on the table above as supported, it will be sent as type 3 (STRING) +and parsed by normal content parsing, see +the discord documentation +for all supported types by the API.

+
+

By providing the converter it allows us to use them as building blocks for another converter:

+
class MemberRoles(commands.MemberConverter):
+    async def convert(self, ctx, argument):
+        member = await super().convert(ctx, argument)
+        return [role.name for role in member.roles[1:]] # Remove everyone role!
+
+@bot.command()
+async def roles(ctx, *, member: MemberRoles):
+    """Tells you a member's roles."""
+    await ctx.send('I see the following roles: ' + ', '.join(member))
+
+
+
+
+

Special Converters

+

The command extension also has support for certain converters to allow for more advanced and intricate use cases that go +beyond the generic linear parsing. These converters allow you to introduce some more relaxed and dynamic grammar to your +commands in an easy to use manner.

+
+

typing.Union

+

A typing.Union is a special type hint that allows for the command to take in any of the specific types instead of +a singular type. For example, given the following:

+
import typing
+
+@bot.command()
+async def union(ctx, what: typing.Union[discord.TextChannel, discord.Member]):
+    await ctx.send(what)
+
+
+

The what parameter would either take a discord.TextChannel converter or a discord.Member converter. +The way this works is through a left-to-right order. It first attempts to convert the input to a +discord.TextChannel, and if it fails it tries to convert it to a discord.Member. If all converters fail, +then a special error is raised, BadUnionArgument.

+

Note that any valid converter discussed above can be passed in to the argument list of a typing.Union.

+
+

Slash Command Only

+

These are not currently supported by the Discord API and will be sent as type 3 (STRING)

+
+
+
+

typing.Optional

+

A typing.Optional is a special type hint that allows for “back-referencing” behaviour. If the converter fails to +parse into the specified type, the parser will skip the parameter and then either None or the specified default will be +passed into the parameter instead. The parser will then continue on to the next parameters and converters, if any.

+

Consider the following example:

+
import typing
+
+@bot.command()
+async def bottles(ctx, amount: typing.Optional[int] = 99, *, liquid="beer"):
+    await ctx.send(f'{amount} bottles of {liquid} on the wall!')
+
+
+../../_images/optional1.png +

In this example, since the argument could not be converted into an int, the default of 99 is passed and the parser +resumes handling, which in this case would be to pass it into the liquid parameter.

+
+

Note

+

This converter only works in regular positional parameters, not variable parameters or keyword-only parameters.

+
+
+
+

typing.Literal

+

A typing.Literal is a special type hint that requires the passed parameter to be equal to one of the listed values +after being converted to the same type. For example, given the following:

+
from typing import Literal
+
+@bot.command()
+async def shop(ctx, buy_sell: Literal['buy', 'sell'], amount: Literal[1, 2], *, item: str):
+    await ctx.send(f'{buy_sell.capitalize()}ing {amount} {item}(s)!')
+
+
+

The buy_sell parameter must be either the literal string "buy" or "sell" and amount must convert to the +int 1 or 2. If buy_sell or amount don’t match any value, then a special error is raised, +BadLiteralArgument. Any literal values can be mixed and matched within the same typing.Literal converter.

+

Note that typing.Literal[True] and typing.Literal[False] still follow the bool converter rules.

+
+
+

Greedy

+

The Greedy converter is a generalisation of the typing.Optional converter, except applied +to a list of arguments. In simple terms, this means that it tries to convert as much as it can until it can’t convert +any further.

+

Consider the following example:

+
@bot.command()
+async def slap(ctx, members: commands.Greedy[discord.Member], *, reason='no reason'):
+    slapped = ", ".join(x.name for x in members)
+    await ctx.send(f'{slapped} just got slapped for {reason}')
+
+
+

When invoked, it allows for any number of members to be passed in:

+../../_images/greedy1.png +

The type passed when using this converter depends on the parameter type that it is being attached to:

+
    +
  • Positional parameter types will receive either the default parameter or a list of the converted values.

  • +
  • Variable parameter types will be a tuple as usual.

  • +
  • Keyword-only parameter types will be the same as if Greedy was not passed at all.

  • +
+

Greedy parameters can also be made optional by specifying an optional value.

+

When mixed with the typing.Optional converter you can provide simple and expressive command invocation syntaxes:

+
import typing
+
+@bot.command()
+async def ban(ctx, members: commands.Greedy[discord.Member],
+                   delete_days: typing.Optional[int] = 0, *,
+                   reason: str):
+    """Mass bans members with an optional delete_days parameter"""
+    for member in members:
+        await member.ban(delete_message_days=delete_days, reason=reason)
+
+
+

This command can be invoked any of the following ways:

+
$ban @Member @Member2 spam bot
+$ban @Member @Member2 7 spam bot
+$ban @Member spam
+
+
+
+

Warning

+

The usage of Greedy and typing.Optional are powerful and useful, however as a +price, they open you up to some parsing ambiguities that might surprise some people.

+

For example, a signature expecting a typing.Optional of a discord.Member followed by a +int could catch a member named after a number due to the different ways a +MemberConverter decides to fetch members. You should take care to not introduce +unintended parsing ambiguities in your code. One technique would be to clamp down the expected syntaxes +allowed through custom converters or reordering the parameters to minimise clashes.

+

To help aid with some parsing ambiguities, str, None, typing.Optional and +Greedy are forbidden as parameters for the Greedy converter.

+
+
+
+
+

FlagConverter

+
+

New in version 2.0.

+
+

A FlagConverter allows the user to specify user-friendly “flags” using PEP 526 type annotations +or a syntax more reminiscent of the dataclasses module.

+

For example, the following code:

+
from discord.ext import commands
+import discord
+
+class BanFlags(commands.FlagConverter):
+    member: discord.Member
+    reason: str
+    days: int = 1
+
+@commands.command()
+async def ban(ctx, *, flags: BanFlags):
+    plural = f'{flags.days} days' if flags.days != 1 else f'{flags.days} day'
+    await ctx.send(f'Banned {flags.member} for {flags.reason!r} (deleted {plural} worth of messages)')
+
+
+

Allows the user to invoke the command using a simple flag-like syntax:

+../../_images/flags1.png +

Flags use a syntax that allows the user to not require quotes when passing in values to the flag. The goal of the +flag syntax is to be as user-friendly as possible. This makes flags a good choice for complicated commands that can have +multiple knobs to turn or simulating keyword-only parameters in your external command interface. It is recommended to use +keyword-only parameters with the flag converter. This ensures proper parsing and behaviour with quoting.

+

Internally, the FlagConverter class examines the class to find flags. A flag can either be a +class variable with a type annotation or a class variable that’s been assigned the result of the flag() +function. These flags are then used to define the interface that your users will use. The annotations correspond to +the converters that the flag arguments must adhere to.

+

For most use cases, no extra work is required to define flags. However, if customisation is needed to control the flag name +or the default value then the flag() function can come in handy:

+
from typing import List
+
+class BanFlags(commands.FlagConverter):
+    members: List[discord.Member] = commands.flag(name='member', default=lambda ctx: [])
+
+
+

This tells the parser that the members attribute is mapped to a flag named member and that +the default value is an empty list. For greater customisability, the default can either be a value or a callable +that takes the Context as a sole parameter. This callable can either be a function or a coroutine.

+

In order to customise the flag syntax we also have a few options that can be passed to the class parameter list:

+
# --hello world syntax
+class PosixLikeFlags(commands.FlagConverter, delimiter=' ', prefix='--'):
+    hello: str
+
+
+# /make food
+class WindowsLikeFlags(commands.FlagConverter, prefix='/', delimiter=''):
+    make: str
+
+# TOPIC: not allowed nsfw: yes Slowmode: 100
+class Settings(commands.FlagConverter, case_insensitive=True):
+    topic: Optional[str]
+    nsfw: Optional[bool]
+    slowmode: Optional[int]
+
+
+
+

Note

+

Despite the similarities in these examples to command like arguments, the syntax and parser is not +a command line parser. The syntax is mainly inspired by Discord’s search bar input and as a result +all flags need a corresponding value.

+
+
+

Slash Command Only

+

As these are built very similar to slash command options, they are converted into options and parsed +back into flags when the slash command is executed.

+
+

The flag converter is similar to regular commands and allows you to use most types of converters +(with the exception of Greedy) as the type annotation. Some extra support is added for specific +annotations as described below.

+
+

typing.List

+

If a list is given as a flag annotation it tells the parser that the argument can be passed multiple times.

+

For example, augmenting the example above:

+
from discord.ext import commands
+from typing import List
+import discord
+
+class BanFlags(commands.FlagConverter):
+    members: List[discord.Member] = commands.flag(name='member')
+    reason: str
+    days: int = 1
+
+@commands.command()
+async def ban(ctx, *, flags: BanFlags):
+    for member in flags.members:
+        await member.ban(reason=flags.reason, delete_message_days=flags.days)
+
+    members = ', '.join(str(member) for member in flags.members)
+    plural = f'{flags.days} days' if flags.days != 1 else f'{flags.days} day'
+    await ctx.send(f'Banned {members} for {flags.reason!r} (deleted {plural} worth of messages)')
+
+
+

This is called by repeatedly specifying the flag:

+../../_images/flags2.png +
+
+

typing.Tuple

+

Since the above syntax can be a bit repetitive when specifying a flag many times, the tuple type annotation +allows for “greedy-like” semantics using a variadic tuple:

+
from discord.ext import commands
+from typing import Tuple
+import discord
+
+class BanFlags(commands.FlagConverter):
+    members: Tuple[discord.Member, ...]
+    reason: str
+    days: int = 1
+
+
+

This allows the previous ban command to be called like this:

+../../_images/flags3.png +

The tuple annotation also allows for parsing of pairs. For example, given the following code:

+
# point: 10 11 point: 12 13
+class Coordinates(commands.FlagConverter):
+    point: Tuple[int, int]
+
+
+
+

Warning

+

Due to potential parsing ambiguities, the parser expects tuple arguments to be quoted +if they require spaces. So if one of the inner types is str and the argument requires spaces +then quotes should be used to disambiguate it from the other element of the tuple.

+
+
+
+

typing.Dict

+

A dict annotation is functionally equivalent to List[Tuple[K, V]] except with the return type +given as a dict rather than a list.

+
+
+
+
+

Error Handling

+

When our commands fail to parse we will, by default, receive a noisy error in stderr of our console that tells us +that an error has happened and has been silently ignored.

+

In order to handle our errors, we must use something called an error handler. There is a global error handler, called +on_command_error() which works like any other event in the Event Reference. This global error handler is +called for every error reached.

+

Most of the time however, we want to handle an error local to the command itself. Luckily, commands come with local error +handlers that allow us to do just that. First we decorate an error handler function with Command.error():

+
@bot.command()
+async def info(ctx, *, member: discord.Member):
+    """Tells you some info about the member."""
+    msg = f'{member} joined on {member.joined_at} and has {len(member.roles)} roles.'
+    await ctx.send(msg)
+
+@info.error
+async def info_error(ctx, error):
+    if isinstance(error, commands.BadArgument):
+        await ctx.send('I could not find that member...')
+
+
+

The first parameter of the error handler is the Context while the second one is an exception that is derived from +CommandError. A list of errors is found in the Exceptions page of the documentation.

+
+
+

Checks

+

There are cases when we don’t want a user to use our commands. They don’t have permissions to do so or maybe we blocked +them from using our bot earlier. The commands extension comes with full support for these things in a concept called a +Checks.

+

A check is a basic predicate that can take in a Context as its sole parameter. Within it, you have the following +options:

+
    +
  • Return True to signal that the person can run the command.

  • +
  • Return False to signal that the person cannot run the command.

  • +
  • Raise a CommandError derived exception to signal the person cannot run the command.

    +
    +
      +
    • This allows you to have custom error messages for you to handle in the +error handlers.

    • +
    +
    +
  • +
+

To register a check for a command, we would have two ways of doing so. The first is using the check() +decorator. For example:

+
async def is_owner(ctx):
+    return ctx.author.id == 316026178463072268
+
+@bot.command(name='eval')
+@commands.check(is_owner)
+async def _eval(ctx, *, code):
+    """A bad example of an eval command"""
+    await ctx.send(eval(code))
+
+
+

This would only evaluate the command if the function is_owner returns True. Sometimes we re-use a check often and +want to split it into its own decorator. To do that we can just add another level of depth:

+
def is_owner():
+    async def predicate(ctx):
+        return ctx.author.id == 316026178463072268
+    return commands.check(predicate)
+
+@bot.command(name='eval')
+@is_owner()
+async def _eval(ctx, *, code):
+    """A bad example of an eval command"""
+    await ctx.send(eval(code))
+
+
+

Since an owner check is so common, the library provides it for you (is_owner()):

+
@bot.command(name='eval')
+@commands.is_owner()
+async def _eval(ctx, *, code):
+    """A bad example of an eval command"""
+    await ctx.send(eval(code))
+
+
+

When multiple checks are specified, all of them must be True:

+
def is_in_guild(guild_id):
+    async def predicate(ctx):
+        return ctx.guild and ctx.guild.id == guild_id
+    return commands.check(predicate)
+
+@bot.command()
+@commands.is_owner()
+@is_in_guild(41771983423143937)
+async def secretguilddata(ctx):
+    """super secret stuff"""
+    await ctx.send('secret stuff')
+
+
+

If any of those checks fail in the example above, then the command will not be run.

+

When an error happens, the error is propagated to the error handlers. If you do not +raise a custom CommandError derived exception, then it will get wrapped up into a +CheckFailure exception as so:

+
@bot.command()
+@commands.is_owner()
+@is_in_guild(41771983423143937)
+async def secretguilddata(ctx):
+    """super secret stuff"""
+    await ctx.send('secret stuff')
+
+@secretguilddata.error
+async def secretguilddata_error(ctx, error):
+    if isinstance(error, commands.CheckFailure):
+        await ctx.send('nothing to see here comrade.')
+
+
+

If you want a more robust error system, you can derive from the exception and raise it instead of returning False:

+
class NoPrivateMessages(commands.CheckFailure):
+    pass
+
+def guild_only():
+    async def predicate(ctx):
+        if ctx.guild is None:
+            raise NoPrivateMessages('Hey no DMs!')
+        return True
+    return commands.check(predicate)
+
+@guild_only()
+async def test(ctx):
+    await ctx.send('Hey this is not a DM! Nice.')
+
+@test.error
+async def test_error(ctx, error):
+    if isinstance(error, NoPrivateMessages):
+        await ctx.send(error)
+
+
+
+

Note

+

Since having a guild_only decorator is pretty common, it comes built-in via guild_only().

+
+
+

Global Checks

+

Sometimes we want to apply a check to every command, not just certain commands. The library supports this as well +using the global check concept.

+

Global checks work similarly to regular checks except they are registered with the Bot.check() decorator.

+

For example, to block all DMs we could do the following:

+
@bot.check
+async def globally_block_dms(ctx):
+    return ctx.guild is not None
+
+
+
+

Warning

+

Be careful on how you write your global checks, as it could also lock you out of your own bot.

+
+
+
+
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/ext/commands/extensions.html b/docs/Python/html/ext/commands/extensions.html new file mode 100644 index 00000000..836a7fd4 --- /dev/null +++ b/docs/Python/html/ext/commands/extensions.html @@ -0,0 +1,200 @@ + + + + + + Extensions + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

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 Bot that loads the extension.

+

An example extension looks like this:

+
+
hello.py
+
from discord.ext import commands
+
+@commands.command()
+async def hello(ctx):
+    await ctx.send(f'Hello {ctx.author.display_name}.')
+
+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 Bot.load_extension(). To load this extension we call bot.load_extension('hello').

+
+

Cogs

+

Extensions are usually used in conjunction with cogs. To read more about them, check out the documentation, 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

+

When you make a change to the extension and want to reload the references, the library comes with a function to do this for you, Bot.reload_extension().

+
>>> bot.reload_extension('hello')
+
+
+

Once the extension reloads, any changes that we did will be applied. This is useful if we want to add or remove functionality without restarting our bot. If an error occurred during the reloading process, the bot will pretend as if the reload never happened.

+
+
+

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.

+
+
basic_ext.py
+
def setup(bot):
+    print('I am being loaded!')
+
+def teardown(bot):
+    print('I am being unloaded!')
+
+
+
+
+
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/ext/commands/index.html b/docs/Python/html/ext/commands/index.html new file mode 100644 index 00000000..1c0ebe52 --- /dev/null +++ b/docs/Python/html/ext/commands/index.html @@ -0,0 +1,184 @@ + + + + + + discord.ext.commands – Bot commands framework + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

discord.ext.commands – Bot commands framework

+

discord.py offers a lower level aspect on interacting with Discord. Often times, the library is used for the creation of +bots. However this task can be daunting and confusing to get correctly the first time. Many times there comes a repetition in +creating a bot command framework that is extensible, flexible, and powerful. For this reason, discord.py comes with an +extension library that handles this for you.

+ +
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/ext/commands/slash-commands.html b/docs/Python/html/ext/commands/slash-commands.html new file mode 100644 index 00000000..f62624f5 --- /dev/null +++ b/docs/Python/html/ext/commands/slash-commands.html @@ -0,0 +1,149 @@ + + + + + + Slash Commands + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

Slash Commands

+

Slash Commands are currently supported in enhanced-discord.py using a system on top of ext.commands.

+

This system is very simple to use, and can be enabled via Bot.slash_commands globally, +or only for specific commands via Command.slash_command.

+

There is also the parameter slash_command_guilds which can be passed to either Bot or the command +decorator in order to only upload the commands as guild commands to these specific guild IDs, however this +should only be used for testing or small (<10 guilds) bots.

+

If you want to add option descriptions to your commands, you should use Option

+

For troubleshooting, see the FAQ

+
+

Slash Command Only

+

For parts of the docs specific to slash commands, look for this box!

+
+
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/ext/tasks/index.html b/docs/Python/html/ext/tasks/index.html new file mode 100644 index 00000000..9f93ec21 --- /dev/null +++ b/docs/Python/html/ext/tasks/index.html @@ -0,0 +1,704 @@ + + + + + + discord.ext.tasks – asyncio.Task helpers + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

discord.ext.tasks – asyncio.Task helpers

+
+

New in version 1.1.0.

+
+

One of the most common operations when making a bot is having a loop run in the background at a specified interval. This pattern is very common but has a lot of things you need to look out for:

+
    +
  • How do I handle asyncio.CancelledError?

  • +
  • What do I do if the internet goes out?

  • +
  • What is the maximum number of seconds I can sleep anyway?

  • +
+

The goal of this discord.py extension is to abstract all these worries away from you.

+
+

Recipes

+

A simple background task in a Cog:

+
from discord.ext import tasks, commands
+
+class MyCog(commands.Cog):
+    def __init__(self):
+        self.index = 0
+        self.printer.start()
+
+    def cog_unload(self):
+        self.printer.cancel()
+
+    @tasks.loop(seconds=5.0)
+    async def printer(self):
+        print(self.index)
+        self.index += 1
+
+
+

Adding an exception to handle during reconnect:

+
import asyncpg
+from discord.ext import tasks, commands
+
+class MyCog(commands.Cog):
+    def __init__(self, bot):
+        self.bot = bot
+        self.data = []
+        self.batch_update.add_exception_type(asyncpg.PostgresConnectionError)
+        self.batch_update.start()
+
+    def cog_unload(self):
+        self.batch_update.cancel()
+
+    @tasks.loop(minutes=5.0)
+    async def batch_update(self):
+        async with self.bot.pool.acquire() as con:
+            # batch update here...
+            pass
+
+
+

Looping a certain amount of times before exiting:

+
from discord.ext import tasks
+
+@tasks.loop(seconds=5.0, count=5)
+async def slow_count():
+    print(slow_count.current_loop)
+
+@slow_count.after_loop
+async def after_slow_count():
+    print('done!')
+
+slow_count.start()
+
+
+

Waiting until the bot is ready before the loop starts:

+
from discord.ext import tasks, commands
+
+class MyCog(commands.Cog):
+    def __init__(self, bot):
+        self.index = 0
+        self.bot = bot
+        self.printer.start()
+
+    def cog_unload(self):
+        self.printer.cancel()
+
+    @tasks.loop(seconds=5.0)
+    async def printer(self):
+        print(self.index)
+        self.index += 1
+
+    @printer.before_loop
+    async def before_printer(self):
+        print('waiting...')
+        await self.bot.wait_until_ready()
+
+
+

Doing something during cancellation:

+
from discord.ext import tasks, commands
+import asyncio
+
+class MyCog(commands.Cog):
+    def __init__(self, bot):
+        self.bot= bot
+        self._batch = []
+        self.lock = asyncio.Lock()
+        self.bulker.start()
+
+    async def do_bulk(self):
+        # bulk insert data here
+        ...
+
+    @tasks.loop(seconds=10.0)
+    async def bulker(self):
+        async with self.lock:
+            await self.do_bulk()
+
+    @bulker.after_loop
+    async def on_bulker_cancel(self):
+        if self.bulker.is_being_cancelled() and len(self._batch) != 0:
+            # if we're cancelled and we have some data left...
+            # let's insert it to our database
+            await self.do_bulk()
+
+
+
+
+

API Reference

+
+ +Methods +
+
+class discord.ext.tasks.Loop
+

A background task helper that abstracts the loop and reconnection logic for you.

+

The main interface to create this is through loop().

+
+
+@after_loop
+

A decorator that register a coroutine to be called after the loop finished running.

+

The coroutine must take no arguments (except self in a class context).

+
+

Note

+

This coroutine is called even during cancellation. If it is desirable +to tell apart whether something was cancelled or not, check to see +whether is_being_cancelled() is True or not.

+
+
+
Parameters
+

coro (coroutine) – The coroutine to register after the loop finishes.

+
+
Raises
+

TypeError – The function was not a coroutine.

+
+
+
+ +
+
+@before_loop
+

A decorator that registers a coroutine to be called before the loop starts running.

+

This is useful if you want to wait for some bot state before the loop starts, +such as discord.Client.wait_until_ready().

+

The coroutine must take no arguments (except self in a class context).

+
+
Parameters
+

coro (coroutine) – The coroutine to register before the loop runs.

+
+
Raises
+

TypeError – The function was not a coroutine.

+
+
+
+ +
+
+@error
+

A decorator that registers a coroutine to be called if the task encounters an unhandled exception.

+

The coroutine must take only one argument the exception raised (except self in a class context).

+

By default this prints to sys.stderr however it could be +overridden to have a different implementation.

+
+

New in version 1.4.

+
+
+
Parameters
+

coro (coroutine) – The coroutine to register in the event of an unhandled exception.

+
+
Raises
+

TypeError – The function was not a coroutine.

+
+
+
+ +
+
+property seconds
+

Read-only value for the number of seconds +between each iteration. None if an explicit time value was passed instead.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[float]

+
+
+
+ +
+
+property minutes
+

Read-only value for the number of minutes +between each iteration. None if an explicit time value was passed instead.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[float]

+
+
+
+ +
+
+property hours
+

Read-only value for the number of hours +between each iteration. None if an explicit time value was passed instead.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[float]

+
+
+
+ +
+
+property time
+

Read-only list for the exact times this loop runs at. +None if relative times were passed instead.

+
+

New in version 2.0.

+
+
+
Type
+

Optional[List[datetime.time]]

+
+
+
+ +
+
+property current_loop
+

The current iteration of the loop.

+
+
Type
+

int

+
+
+
+ +
+
+property next_iteration
+

When the next iteration of the loop will occur.

+
+

New in version 1.3.

+
+
+
Type
+

Optional[datetime.datetime]

+
+
+
+ +
+
+await __call__(*args, **kwargs)
+

This function is a coroutine.

+

Calls the internal callback that the task holds.

+
+

New in version 1.6.

+
+
+
Parameters
+
    +
  • *args – The arguments to use.

  • +
  • **kwargs – The keyword arguments to use.

  • +
+
+
+
+ +
+
+start(*args, **kwargs)
+

Starts the internal task in the event loop.

+
+
Parameters
+
    +
  • *args – The arguments to use.

  • +
  • **kwargs – The keyword arguments to use.

  • +
+
+
Raises
+

RuntimeError – A task has already been launched and is running.

+
+
Returns
+

The task that has been created.

+
+
Return type
+

asyncio.Task

+
+
+
+ +
+
+stop()
+

Gracefully stops the task from running.

+

Unlike cancel(), this allows the task to finish its +current iteration before gracefully exiting.

+
+

Note

+

If the internal function raises an error that can be +handled before finishing then it will retry until +it succeeds.

+

If this is undesirable, either remove the error handling +before stopping via clear_exception_types() or +use cancel() instead.

+
+
+

New in version 1.2.

+
+
+ +
+
+cancel()
+

Cancels the internal task, if it is running.

+
+ +
+
+restart(*args, **kwargs)
+

A convenience method to restart the internal task.

+
+

Note

+

Due to the way this function works, the task is not +returned like start().

+
+
+
Parameters
+
    +
  • *args – The arguments to use.

  • +
  • **kwargs – The keyword arguments to use.

  • +
+
+
+
+ +
+
+add_exception_type(*exceptions)
+

Adds exception types to be handled during the reconnect logic.

+

By default the exception types handled are those handled by +discord.Client.connect(), which includes a lot of internet disconnection +errors.

+

This function is useful if you’re interacting with a 3rd party library that +raises its own set of exceptions.

+
+
Parameters
+

*exceptions (Type[BaseException]) – An argument list of exception classes to handle.

+
+
Raises
+

TypeError – An exception passed is either not a class or not inherited from BaseException.

+
+
+
+ +
+
+clear_exception_types()
+

Removes all exception types that are handled.

+
+

Note

+

This operation obviously cannot be undone!

+
+
+ +
+
+remove_exception_type(*exceptions)
+

Removes exception types from being handled during the reconnect logic.

+
+
Parameters
+

*exceptions (Type[BaseException]) – An argument list of exception classes to handle.

+
+
Returns
+

Whether all exceptions were successfully removed.

+
+
Return type
+

bool

+
+
+
+ +
+
+get_task()
+

Optional[asyncio.Task]: Fetches the internal task or None if there isn’t one running.

+
+ +
+
+is_being_cancelled()
+

Whether the task is being cancelled.

+
+ +
+
+failed()
+

bool: Whether the internal task has failed.

+
+

New in version 1.2.

+
+
+ +
+
+is_running()
+

bool: Check if the task is currently running.

+
+

New in version 1.4.

+
+
+ +
+
+change_interval(*, seconds=0, minutes=0, hours=0, time=...)
+

Changes the interval for the sleep time.

+
+

New in version 1.2.

+
+
+
Parameters
+
    +
  • seconds (float) – The number of seconds between every iteration.

  • +
  • minutes (float) – The number of minutes between every iteration.

  • +
  • hours (float) – The number of hours between every iteration.

  • +
  • time (Union[datetime.time, Sequence[datetime.time]]) –

    The exact times to run this loop at. Either a non-empty list or a single +value of datetime.time should be passed. +This cannot be used in conjunction with the relative time parameters.

    +
    +

    New in version 2.0.

    +
    +
    +

    Note

    +

    Duplicate times will be ignored, and only run once.

    +
    +

  • +
+
+
Raises
+
    +
  • ValueError – An invalid value was given.

  • +
  • TypeError – An invalid value for the time parameter was passed, or the + time parameter was passed in conjunction with relative time parameters.

  • +
+
+
+
+ +
+ +
+
+discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)
+

A decorator that schedules a task in the background for you with +optional reconnect logic. The decorator returns a Loop.

+
+
Parameters
+
    +
  • seconds (float) – The number of seconds between every iteration.

  • +
  • minutes (float) – The number of minutes between every iteration.

  • +
  • hours (float) – The number of hours between every iteration.

  • +
  • time (Union[datetime.time, Sequence[datetime.time]]) –

    The exact times to run this loop at. Either a non-empty list or a single +value of datetime.time should be passed. Timezones are supported. +If no timezone is given for the times, it is assumed to represent UTC time.

    +

    This cannot be used in conjunction with the relative time parameters.

    +
    +

    Note

    +

    Duplicate times will be ignored, and only run once.

    +
    +
    +

    New in version 2.0.

    +
    +

  • +
  • count (Optional[int]) – The number of loops to do, None if it should be an +infinite loop.

  • +
  • reconnect (bool) – Whether to handle errors and restart the task +using an exponential back-off algorithm similar to the +one used in discord.Client.connect().

  • +
  • loop (asyncio.AbstractEventLoop) – The loop to use to register the task, if not given +defaults to asyncio.get_event_loop().

  • +
+
+
Raises
+
    +
  • ValueError – An invalid value was given.

  • +
  • TypeError – The function was not a coroutine, an invalid value for the time parameter was passed, + or time parameter was passed in conjunction with relative time parameters.

  • +
+
+
+
+ +
+
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/faq.html b/docs/Python/html/faq.html new file mode 100644 index 00000000..0d0120d8 --- /dev/null +++ b/docs/Python/html/faq.html @@ -0,0 +1,601 @@ + + + + + + Frequently Asked Questions + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

Frequently Asked Questions

+

This is a list of Frequently Asked Questions regarding using discord.py and its extension modules. Feel free to suggest a +new question or submit one via pull requests.

+ +
+

Coroutines

+

Questions regarding coroutines and asyncio belong here.

+
+

What is a coroutine?

+

A coroutine is a function that must be invoked with await or yield from. When Python encounters an await it stops +the function’s execution at that point and works on other things until it comes back to that point and finishes off its work. +This allows for your program to be doing multiple things at the same time without using threads or complicated +multiprocessing.

+

If you forget to await a coroutine then the coroutine will not run. Never forget to await a coroutine.

+
+
+

Where can I use await?

+

You can only use await inside async def functions and nowhere else.

+
+
+

What does “blocking” mean?

+

In asynchronous programming a blocking call is essentially all the parts of the function that are not await. Do not +despair however, because not all forms of blocking are bad! Using blocking calls is inevitable, but you must work to make +sure that you don’t excessively block functions. Remember, if you block for too long then your bot will freeze since it has +not stopped the function’s execution at that point to do other things.

+

If logging is enabled, this library will attempt to warn you that blocking is occurring with the message: +Heartbeat blocked for more than N seconds. +See Setting Up Logging for details on enabling logging.

+

A common source of blocking for too long is something like time.sleep(). Don’t do that. Use asyncio.sleep() +instead. Similar to this example:

+
# bad
+time.sleep(10)
+
+# good
+await asyncio.sleep(10)
+
+
+

Another common source of blocking for too long is using HTTP requests with the famous module Requests: HTTP for Humans™. +While Requests: HTTP for Humans™ is an amazing module for non-asynchronous programming, it is not a good choice for +asyncio because certain requests can block the event loop too long. Instead, use the aiohttp library which +is installed on the side with this library.

+

Consider the following example:

+
# bad
+r = requests.get('http://aws.random.cat/meow')
+if r.status_code == 200:
+    js = r.json()
+    await channel.send(js['file'])
+
+# good
+async with aiohttp.ClientSession() as session:
+    async with session.get('http://aws.random.cat/meow') as r:
+        if r.status == 200:
+            js = await r.json()
+            await channel.send(js['file'])
+
+
+
+
+
+

General

+

General questions regarding library usage belong here.

+
+

Where can I find usage examples?

+

Example code can be found in the examples folder +in the repository.

+
+
+

How do I set the “Playing” status?

+

The activity keyword argument may be passed in the Client constructor or Client.change_presence(), given an Activity object.

+

The constructor may be used for static activities, while Client.change_presence() may be used to update the activity at runtime.

+
+

Warning

+

It is highly discouraged to use Client.change_presence() or API calls in on_ready() as this event may be called many times while running, not just once.

+

There is a high chance of disconnecting if presences are changed right after connecting.

+
+

The status type (playing, listening, streaming, watching) can be set using the ActivityType enum. +For memory optimisation purposes, some activities are offered in slimmed-down versions:

+ +

Putting both of these pieces of info together, you get the following:

+
client = discord.Client(activity=discord.Game(name='my game'))
+
+# or, for watching:
+activity = discord.Activity(name='my activity', type=discord.ActivityType.watching)
+client = discord.Client(activity=activity)
+
+
+
+
+

How do I send a message to a specific channel?

+

You must fetch the channel directly and then call the appropriate method. Example:

+
channel = client.get_channel(12324234183172)
+await channel.send('hello')
+
+
+
+
+

How do I send a DM?

+

Get the User or Member object and call abc.Messageable.send(). For example:

+
user = client.get_user(381870129706958858)
+await user.send('👀')
+
+
+

If you are responding to an event, such as on_message(), you already have the User object via Message.author:

+
await message.author.send('👋')
+
+
+
+
+

How do I get the ID of a sent message?

+

abc.Messageable.send() returns the Message that was sent. +The ID of a message can be accessed via Message.id:

+
message = await channel.send('hmm…')
+message_id = message.id
+
+
+
+
+

How do I upload an image?

+

To upload something to Discord you have to use the File object.

+

A File accepts two parameters, the file-like object (or file path) and the filename +to pass to Discord when uploading.

+

If you want to upload an image it’s as simple as:

+
await channel.send(file=discord.File('my_file.png'))
+
+
+

If you have a file-like object you can do as follows:

+
with open('my_file.png', 'rb') as fp:
+    await channel.send(file=discord.File(fp, 'new_filename.png'))
+
+
+

To upload multiple files, you can use the files keyword argument instead of file:

+
my_files = [
+    discord.File('result.zip'),
+    discord.File('teaser_graph.png'),
+]
+await channel.send(files=my_files)
+
+
+

If you want to upload something from a URL, you will have to use an HTTP request using aiohttp +and then pass an io.BytesIO instance to File like so:

+
import io
+import aiohttp
+
+async with aiohttp.ClientSession() as session:
+    async with session.get(my_url) as resp:
+        if resp.status != 200:
+            return await channel.send('Could not download file...')
+        data = io.BytesIO(await resp.read())
+        await channel.send(file=discord.File(data, 'cool_image.png'))
+
+
+
+
+

How can I add a reaction to a message?

+

You use the Message.add_reaction() method.

+

If you want to use unicode emoji, you must pass a valid unicode code point in a string. In your code, you can write this in a few different ways:

+
    +
  • '👍'

  • +
  • '\U0001F44D'

  • +
  • '\N{THUMBS UP SIGN}'

  • +
+

Quick example:

+
emoji = '\N{THUMBS UP SIGN}'
+# or '\U0001f44d' or '👍'
+await message.add_reaction(emoji)
+
+
+

In case you want to use emoji that come from a message, you already get their code points in the content without needing +to do anything special. You cannot send ':thumbsup:' style shorthands.

+

For custom emoji, you should pass an instance of Emoji. You can also pass a '<:name:id>' string, but if you +can use said emoji, you should be able to use Client.get_emoji() to get an emoji via ID or use utils.find()/ +utils.get() on Client.emojis or Guild.emojis collections.

+

The name and ID of a custom emoji can be found with the client by prefixing :custom_emoji: with a backslash. +For example, sending the message \:python3: with the client will result in <:python3:232720527448342530>.

+

Quick example:

+
# if you have the ID already
+emoji = client.get_emoji(310177266011340803)
+await message.add_reaction(emoji)
+
+# no ID, do a lookup
+emoji = discord.utils.get(guild.emojis, name='LUL')
+if emoji:
+    await message.add_reaction(emoji)
+
+# if you have the name and ID of a custom emoji:
+emoji = '<:python3:232720527448342530>'
+await message.add_reaction(emoji)
+
+
+
+
+

How do I pass a coroutine to the player’s “after” function?

+

The library’s music player launches on a separate thread, ergo it does not execute inside a coroutine. +This does not mean that it is not possible to call a coroutine in the after parameter. To do so you must pass a callable +that wraps up a couple of aspects.

+

The first gotcha that you must be aware of is that calling a coroutine is not a thread-safe operation. Since we are +technically in another thread, we must take caution in calling thread-safe operations so things do not bug out. Luckily for +us, asyncio comes with a asyncio.run_coroutine_threadsafe() function that allows us to call +a coroutine from another thread.

+

However, this function returns a Future and to actually call it we have to fetch its result. Putting all of +this together we can do the following:

+
def my_after(error):
+    coro = some_channel.send('Song is done!')
+    fut = asyncio.run_coroutine_threadsafe(coro, client.loop)
+    try:
+        fut.result()
+    except:
+        # an error happened sending the message
+        pass
+
+voice.play(discord.FFmpegPCMAudio(url), after=my_after)
+
+
+
+
+

How do I run something in the background?

+

Check the background_task.py example.

+
+
+

How do I get a specific model?

+

There are multiple ways of doing this. If you have a specific model’s ID then you can use +one of the following functions:

+ +

The following use an HTTP request:

+ +

If the functions above do not help you, then use of utils.find() or utils.get() would serve some use in finding +specific models.

+

Quick example:

+
# find a guild by name
+guild = discord.utils.get(client.guilds, name='My Server')
+
+# make sure to check if it's found
+if guild is not None:
+    # find a channel by name
+    channel = discord.utils.get(guild.text_channels, name='cool-channel')
+
+
+
+
+

How do I make a web request?

+

To make a request, you should use a non-blocking library. +This library already uses and requires a 3rd party library for making requests, aiohttp.

+

Quick example:

+
async with aiohttp.ClientSession() as session:
+    async with session.get('http://aws.random.cat/meow') as r:
+        if r.status == 200:
+            js = await r.json()
+
+
+

See aiohttp’s full documentation for more information.

+
+
+

How do I use a local image file for an embed image?

+

Discord special-cases uploading an image attachment and using it within an embed so that it will not +display separately, but instead in the embed’s thumbnail, image, footer or author icon.

+

To do so, upload the image normally with abc.Messageable.send(), +and set the embed’s image URL to attachment://image.png, +where image.png is the filename of the image you will send.

+

Quick example:

+
file = discord.File("path/to/my/image.png", filename="image.png")
+embed = discord.Embed()
+embed.set_image(url="attachment://image.png")
+await channel.send(file=file, embed=embed)
+
+
+
+

Note

+

Due to a Discord limitation, filenames may not include underscores.

+
+
+
+

Is there an event for audit log entries being created?

+

Since Discord does not dispatch this information in the gateway, the library cannot provide this information. +This is currently a Discord limitation.

+
+
+
+

Commands Extension

+

Questions regarding discord.ext.commands belong here.

+
+

Why does on_message make my commands stop working?

+

Overriding the default provided on_message forbids any extra commands from running. To fix this, add a +bot.process_commands(message) line at the end of your on_message. For example:

+
@bot.event
+async def on_message(message):
+    # do some extra stuff here
+
+    await bot.process_commands(message)
+
+
+

Alternatively, you can place your on_message logic into a listener. In this setup, you should not +manually call bot.process_commands(). This also allows you to do multiple things asynchronously in response +to a message. Example:

+
@bot.listen('on_message')
+async def whatever_you_want_to_call_it(message):
+    # do stuff here
+    # do not process commands here
+
+
+
+
+

Why do my arguments require quotes?

+

In a simple command defined as:

+
@bot.command()
+async def echo(ctx, message: str):
+    await ctx.send(message)
+
+
+

Calling it via ?echo a b c will only fetch the first argument and disregard the rest. To fix this you should either call +it via ?echo "a b c" or change the signature to have “consume rest” behaviour. Example:

+
@bot.command()
+async def echo(ctx, *, message: str):
+    await ctx.send(message)
+
+
+

This will allow you to use ?echo a b c without needing the quotes.

+
+
+

How do I get the original message?

+

The Context contains an attribute, message to get the original +message.

+

Example:

+
@bot.command()
+async def length(ctx):
+    await ctx.send(f'Your message is {len(ctx.message.content)} characters long.')
+
+
+
+
+

How do I make a subcommand?

+

Use the group() decorator. This will transform the callback into a Group which will allow you to add commands into +the group operating as “subcommands”. These groups can be arbitrarily nested as well.

+

Example:

+
@bot.group()
+async def git(ctx):
+    if ctx.invoked_subcommand is None:
+        await ctx.send('Invalid git command passed...')
+
+@git.command()
+async def push(ctx, remote: str, branch: str):
+    await ctx.send(f'Pushing to {remote} {branch}')
+
+
+

This could then be used as ?git push origin master.

+
+
+

How do I make slash commands?

+

See Slash Commands

+
+
+

My slash commands aren’t showing up!

+

You need to invite your bot with the application.commands scope on each guild and +you need the Permissions.use_slash_commands permission in order to see slash commands.

+The scopes checkbox with "bot" and "applications.commands" ticked. +

Global slash commands (created by not specifying slash_command_guilds) will also take up an +hour to refresh on discord’s end, so it is recommended to set slash_command_guilds for development.

+

If none of this works, make sure you are actually running enhanced-discord.py by doing print(bot.slash_commands)

+
+
+

My bot won’t start after enabling slash commands!

+

This means some of your command metadata is invalid for slash commands. +Make sure your command names and option names are lowercase, and they have to match the regex ^[\w-]{1,32}$

+

If you cannot figure out the problem, you should disable slash commands globally (slash_commands=False) +then go through commands, enabling them specifically with slash_command=True until it +errors, then you can debug the problem with that command specifically.

+
+
+
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/genindex.html b/docs/Python/html/genindex.html new file mode 100644 index 00000000..86f34031 --- /dev/null +++ b/docs/Python/html/genindex.html @@ -0,0 +1,5392 @@ + + + + + + Index + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ + + +

Index

+ +
+ _ + | A + | B + | C + | D + | E + | F + | G + | H + | I + | J + | K + | L + | M + | N + | O + | P + | Q + | R + | S + | T + | U + | V + | W + | Y + +
+

_

+ + + +
+ +

A

+ + + +
+ +

B

+ + + +
+ +

C

+ + + +
+ +

D

+ + + +
+ +

E

+ + + +
+ +

F

+ + + +
+ +

G

+ + + +
+ +

H

+ + + +
+ +

I

+ + + +
+ +

J

+ + + +
+ +

K

+ + + +
+ +

L

+ + + +
+ +

M

+ + + +
+ +

N

+ + + +
+ +

O

+ + + +
+ +

P

+ + + +
+ +

Q

+ + + +
+ +

R

+ + + +
+ +

S

+ + + +
+ +

T

+ + + +
+ +

U

+ + + +
+ +

V

+ + + +
+ +

W

+ + + +
+ +

Y

+ + +
+ + + + + + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/index.html b/docs/Python/html/index.html new file mode 100644 index 00000000..5bbd6577 --- /dev/null +++ b/docs/Python/html/index.html @@ -0,0 +1,213 @@ + + + + + + Welcome to discord.py + + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

Welcome to discord.py

+_images/snake.svg_images/snake_dark.svg

discord.py is a modern, easy to use, feature-rich, and async ready API wrapper +for Discord.

+

Features:

+
    +
  • Modern Pythonic API using async/await syntax

  • +
  • Sane rate limit handling that prevents 429s

  • +
  • Command extension to aid with bot creation

  • +
  • Easy to use with an object oriented design

  • +
  • Optimised for both speed and memory

  • +
+
+

Getting started

+

Is this your first time using the library? This is the place to get started!

+ +
+
+

Getting help

+

If you’re having trouble with something, these resources might help.

+ +
+
+

Extensions

+

These extensions help you during development when it comes to common tasks.

+ +
+
+

Manuals

+

These pages go into great detail about everything the API can do.

+ +
+
+

Meta

+

If you’re looking for something related to the project itself, it’s here.

+ +
+
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/intents.html b/docs/Python/html/intents.html new file mode 100644 index 00000000..f62fd39a --- /dev/null +++ b/docs/Python/html/intents.html @@ -0,0 +1,331 @@ + + + + + + A Primer to Gateway Intents + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

New in version 1.5.

+
+
+

A Primer to Gateway Intents

+

In version 1.5 comes the introduction of Intents. This is a radical change in how bots are written. An intent basically allows a bot to subscribe to specific buckets of events. The events that correspond to each intent is documented in the individual attribute of the Intents documentation.

+

These intents are passed to the constructor of Client or its subclasses (AutoShardedClient, AutoShardedBot, Bot) with the intents argument.

+

If intents are not passed, then the library defaults to every intent being enabled except the privileged intents, currently Intents.members and Intents.presences.

+
+

What intents are needed?

+

The intents that are necessary for your bot can only be dictated by yourself. Each attribute in the Intents class documents what events it corresponds to and what kind of cache it enables.

+

For example, if you want a bot that functions without spammy events like presences or typing then we could do the following:

+
 import discord
+ intents = discord.Intents.default()
+ intents.typing = False
+ intents.presences = False
+
+ # Somewhere else:
+ # client = discord.Client(intents=intents)
+ # or
+ # from discord.ext import commands
+ # bot = commands.Bot(command_prefix='!', intents=intents)
+
+
+

Note that this doesn’t enable Intents.members since it’s a privileged intent.

+

Another example showing a bot that only deals with messages and guild information:

+
 import discord
+ intents = discord.Intents(messages=True, guilds=True)
+ # If you also want reaction events enable the following:
+ # intents.reactions = True
+
+ # Somewhere else:
+ # client = discord.Client(intents=intents)
+ # or
+ # from discord.ext import commands
+ # bot = commands.Bot(command_prefix='!', intents=intents)
+
+
+
+
+

Privileged Intents

+

With the API change requiring bot authors to specify intents, some intents were restricted further and require more manual steps. These intents are called privileged intents.

+

A privileged intent is one that requires you to go to the developer portal and manually enable it. To enable privileged intents do the following:

+
    +
  1. Make sure you’re logged on to the Discord website.

  2. +
  3. Navigate to the application page.

  4. +
  5. Click on the bot you want to enable privileged intents for.

  6. +
  7. Navigate to the bot tab on the left side of the screen.

    +
    +
    The bot tab in the application page. +
    +
  8. +
  9. Scroll down to the “Privileged Gateway Intents” section and enable the ones you want.

    +
    +
    The privileged gateway intents selector. +
    +
  10. +
+
+

Warning

+

Enabling privileged intents when your bot is in over 100 guilds requires going through bot verification. If your bot is already verified and you would like to enable a privileged intent you must go through Discord support and talk to them about it.

+
+
+

Note

+

Even if you enable intents through the developer portal, you still have to enable the intents +through code as well.

+
+
+

Do I need privileged intents?

+

This is a quick checklist to see if you need specific privileged intents.

+
+

Presence Intent

+ +
+
+

Member Intent

+
    +
  • Whether you track member joins or member leaves, corresponds to on_member_join() and on_member_remove() events.

  • +
  • Whether you want to track member updates such as nickname or role changes.

  • +
  • Whether you want to track user updates such as usernames, avatars, discriminators, etc.

  • +
  • Whether you want to request the guild member list through Guild.chunk() or Guild.fetch_members().

  • +
  • Whether you want high accuracy member cache under Guild.members.

  • +
+
+
+
+
+

Member Cache

+

Along with intents, Discord now further restricts the ability to cache members and expects bot authors to cache as little as is necessary. However, to properly maintain a cache the Intents.members intent is required in order to track the members who left and properly evict them.

+

To aid with member cache where we don’t need members to be cached, the library now has a MemberCacheFlags flag to control the member cache. The documentation page for the class goes over the specific policies that are possible.

+

It should be noted that certain things do not need a member cache since Discord will provide full member information if possible. For example:

+
    +
  • on_message() will have Message.author be a member even if cache is disabled.

  • +
  • on_voice_state_update() will have the member parameter be a member even if cache is disabled.

  • +
  • on_reaction_add() will have the user parameter be a member when in a guild even if cache is disabled.

  • +
  • on_raw_reaction_add() will have RawReactionActionEvent.member be a member when in a guild even if cache is disabled.

  • +
  • The reaction add events do not contain additional information when in direct messages. This is a Discord limitation.

  • +
  • The reaction removal events do not have member information. This is a Discord limitation.

  • +
+

Other events that take a Member will require the use of the member cache. If absolute accuracy over the member cache is desirable, then it is advisable to have the Intents.members intent enabled.

+
+
+

Retrieving Members

+

If the cache is disabled or you disable chunking guilds at startup, we might still need a way to load members. The library offers a few ways to do this:

+
    +
  • +
    Guild.query_members()
      +
    • Used to query members by a prefix matching nickname or username.

    • +
    • This can also be used to query members by their user ID.

    • +
    • This uses the gateway and not the HTTP.

    • +
    +
    +
    +
  • +
  • +
    Guild.chunk()
      +
    • This can be used to fetch the entire member list through the gateway.

    • +
    +
    +
    +
  • +
  • +
    Guild.fetch_member()
      +
    • Used to fetch a member by ID through the HTTP API.

    • +
    +
    +
    +
  • +
  • +
    Guild.fetch_members()
      +
    • used to fetch a large number of members through the HTTP API.

    • +
    +
    +
    +
  • +
+

It should be noted that the gateway has a strict rate limit of 120 requests per 60 seconds.

+
+
+

Troubleshooting

+

Some common issues relating to the mandatory intent change.

+
+

Where’d my members go?

+

Due to an API change Discord is now forcing developers who want member caching to explicitly opt-in to it. This is a Discord mandated change and there is no way to bypass it. In order to get members back you have to explicitly enable the members privileged intent and change the Intents.members attribute to true.

+

For example:

+
 import discord
+ intents = discord.Intents.default()
+ intents.members = True
+
+ # Somewhere else:
+ # client = discord.Client(intents=intents)
+ # or
+ # from discord.ext import commands
+ # bot = commands.Bot(command_prefix='!', intents=intents)
+
+
+
+
+

Why does on_ready take so long to fire?

+

As part of the API change regarding intents, Discord also changed how members are loaded in the beginning. Originally the library could request 75 guilds at once and only request members from guilds that have the Guild.large attribute set to True. With the new intent changes, Discord mandates that we can only send 1 guild per request. This causes a 75x slowdown which is further compounded by the fact that all guilds, not just large guilds are being requested.

+

There are a few solutions to fix this.

+

The first solution is to request the privileged presences intent along with the privileged members intent and enable both of them. This allows the initial member list to contain online members just like the old gateway. Note that we’re still limited to 1 guild per request but the number of guilds we request is significantly reduced.

+

The second solution is to disable member chunking by setting chunk_guilds_at_startup to False when constructing a client. Then, when chunking for a guild is necessary you can use the various techniques to retrieve members.

+

To illustrate the slowdown caused by the API change, take a bot who is in 840 guilds and 95 of these guilds are “large” (over 250 members).

+

Under the original system this would result in 2 requests to fetch the member list (75 guilds, 20 guilds) roughly taking 60 seconds. With Intents.members but not Intents.presences this requires 840 requests, with a rate limit of 120 requests per 60 seconds means that due to waiting for the rate limit it totals to around 7 minutes of waiting for the rate limit to fetch all the members. With both Intents.members and Intents.presences we mostly get the old behaviour so we’re only required to request for the 95 guilds that are large, this is slightly less than our rate limit so it’s close to the original timing to fetch the member list.

+

Unfortunately due to this change being required from Discord there is nothing that the library can do to mitigate this.

+

If you truly dislike the direction Discord is going with their API, you can contact them via support.

+
+
+
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/intro.html b/docs/Python/html/intro.html new file mode 100644 index 00000000..e05f9cf1 --- /dev/null +++ b/docs/Python/html/intro.html @@ -0,0 +1,242 @@ + + + + + + Introduction + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

Introduction

+

This is the documentation for discord.py, a library for Python to aid +in creating applications that utilise the Discord API.

+
+

Prerequisites

+

discord.py works with Python 3.8 or higher. Support for earlier versions of Python +is not provided. Python 2.7 or lower is not supported. Python 3.7 or lower is not supported.

+
+
+

Installing

+

You can get the library directly from PyPI:

+
python3 -m pip install -U discord.py
+
+
+

If you are using Windows, then the following should be used instead:

+
py -3 -m pip install -U discord.py
+
+
+

To get voice support, you should use discord.py[voice] instead of discord.py, e.g.

+
python3 -m pip install -U discord.py[voice]
+
+
+

On Linux environments, installing voice requires getting the following dependencies:

+ +

For a Debian-based system, the following command will get these dependencies:

+
$ apt install libffi-dev libnacl-dev python3-dev
+
+
+

Remember to check your permissions!

+
+

Virtual Environments

+

Sometimes you want to keep libraries from polluting system installs or use a different version of +libraries than the ones installed on the system. You might also not have permissions to install libraries system-wide. +For this purpose, the standard library as of Python 3.3 comes with a concept called “Virtual Environment”s to +help maintain these separate versions.

+

A more in-depth tutorial is found on Virtual Environments and Packages.

+

However, for the quick and dirty:

+
    +
  1. Go to your project’s working directory:

    +
    +
    $ cd your-bot-source
    +$ python3 -m venv bot-env
    +
    +
    +
    +
  2. +
  3. Activate the virtual environment:

    +
    +
    $ source bot-env/bin/activate
    +
    +
    +

    On Windows you activate it with:

    +
    $ bot-env\Scripts\activate.bat
    +
    +
    +
    +
  4. +
  5. Use pip like usual:

    +
    +
    $ pip install -U discord.py
    +
    +
    +
    +
  6. +
+

Congratulations. You now have a virtual environment all set up.

+
+
+
+

Basic Concepts

+

discord.py revolves around the concept of events. +An event is something you listen to and then respond to. For example, when a message +happens, you will receive an event about it that you can respond to.

+

A quick example to showcase how events work:

+
import discord
+
+class MyClient(discord.Client):
+    async def on_ready(self):
+        print(f'Logged on as {self.user}!')
+
+    async def on_message(self, message):
+        print(f'Message from {messsage.author}: {message.content}')
+
+client = MyClient()
+client.run('my token goes here')
+
+
+
+
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/logging.html b/docs/Python/html/logging.html new file mode 100644 index 00000000..8665e20a --- /dev/null +++ b/docs/Python/html/logging.html @@ -0,0 +1,171 @@ + + + + + + Setting Up Logging + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

New in version 0.6.0.

+
+
+

Setting Up Logging

+

discord.py logs errors and debug information via the logging python +module. It is strongly recommended that the logging module is +configured, as no errors or warnings will be output if it is not set up. +Configuration of the logging module can be as simple as:

+
import logging
+
+logging.basicConfig(level=logging.INFO)
+
+
+

Placed at the start of the application. This will output the logs from +discord as well as other libraries that use the logging module +directly to the console.

+

The optional level argument specifies what level of events to log +out and can be any of CRITICAL, ERROR, WARNING, INFO, and +DEBUG and if not specified defaults to WARNING.

+

More advanced setups are possible with the logging module. For +example to write the logs to a file called discord.log instead of +outputting them to the console the following snippet can be used:

+
import discord
+import logging
+
+logger = logging.getLogger('discord')
+logger.setLevel(logging.DEBUG)
+handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
+handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
+logger.addHandler(handler)
+
+
+

This is recommended, especially at verbose levels such as INFO +and DEBUG, as there are a lot of events logged and it would clog the +stdout of your program.

+

For more information, check the documentation and tutorial of the +logging module.

+
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/migrating.html b/docs/Python/html/migrating.html new file mode 100644 index 00000000..b7eda147 --- /dev/null +++ b/docs/Python/html/migrating.html @@ -0,0 +1,1462 @@ + + + + + + Migrating to v1.0 + + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

Migrating to v1.0

+

v1.0 is one of the biggest breaking changes in the library due to a complete +redesign.

+

The amount of changes are so massive and long that for all intents and purposes, it is a completely +new library.

+

Part of the redesign involves making things more easy to use and natural. Things are done on the +models instead of requiring a Client instance to do any work.

+
+

Python Version Change

+

In order to make development easier and also to allow for our dependencies to upgrade to allow usage of 3.7 or higher, +the library had to remove support for Python versions lower than 3.5.3, which essentially means that support for Python 3.4 +is dropped.

+
+
+

Major Model Changes

+

Below are major model changes that have happened in v1.0

+
+

Snowflakes are int

+

Before v1.0, all snowflakes (the id attribute) were strings. This has been changed to int.

+

Quick example:

+
# before
+ch = client.get_channel('84319995256905728')
+if message.author.id == '80528701850124288':
+    ...
+
+# after
+ch = client.get_channel(84319995256905728)
+if message.author.id == 80528701850124288:
+    ...
+
+
+

This change allows for fewer errors when using the Copy ID feature in the official client since you no longer have +to wrap it in quotes and allows for optimisation opportunities by allowing ETF to be used instead of JSON internally.

+
+
+

Server is now Guild

+

The official API documentation calls the “Server” concept a “Guild” instead. In order to be more consistent with the +API documentation when necessary, the model has been renamed to Guild and all instances referring to it has +been changed as well.

+

A list of changes is as follows:

+
++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Before

After

Message.server

Message.guild

Channel.server

GuildChannel.guild

Client.servers

Client.guilds

Client.get_server

Client.get_guild()

Emoji.server

Emoji.guild

Role.server

Role.guild

Invite.server

Invite.guild

Member.server

Member.guild

Permissions.manage_server

Permissions.manage_guild

VoiceClient.server

VoiceClient.guild

Client.create_server

Client.create_guild()

+
+
+

Models are Stateful

+

As mentioned earlier, a lot of functionality was moved out of Client and +put into their respective model.

+

A list of these changes is enumerated below.

+
++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Before

After

Client.add_reaction

Message.add_reaction()

Client.add_roles

Member.add_roles()

Client.ban

Member.ban() or Guild.ban()

Client.change_nickname

Member.edit()

Client.clear_reactions

Message.clear_reactions()

Client.create_channel

Guild.create_text_channel() and Guild.create_voice_channel()

Client.create_custom_emoji

Guild.create_custom_emoji()

Client.create_invite

abc.GuildChannel.create_invite()

Client.create_role

Guild.create_role()

Client.delete_channel

abc.GuildChannel.delete()

Client.delete_channel_permissions

abc.GuildChannel.set_permissions() with overwrite set to None

Client.delete_custom_emoji

Emoji.delete()

Client.delete_invite

Invite.delete() or Client.delete_invite()

Client.delete_message

Message.delete()

Client.delete_messages

TextChannel.delete_messages()

Client.delete_role

Role.delete()

Client.delete_server

Guild.delete()

Client.edit_channel

TextChannel.edit() or VoiceChannel.edit()

Client.edit_channel_permissions

abc.GuildChannel.set_permissions()

Client.edit_custom_emoji

Emoji.edit()

Client.edit_message

Message.edit()

Client.edit_profile

ClientUser.edit() (you get this from Client.user)

Client.edit_role

Role.edit()

Client.edit_server

Guild.edit()

Client.estimate_pruned_members

Guild.estimate_pruned_members()

Client.get_all_emojis

Client.emojis

Client.get_bans

Guild.bans()

Client.get_invite

Client.fetch_invite()

Client.get_message

abc.Messageable.fetch_message()

Client.get_reaction_users

Reaction.users()

Client.get_user_info

Client.fetch_user()

Client.invites_from

abc.GuildChannel.invites() or Guild.invites()

Client.join_voice_channel

VoiceChannel.connect() (see Voice Changes)

Client.kick

Guild.kick() or Member.kick()

Client.leave_server

Guild.leave()

Client.logs_from

abc.Messageable.history() (see Asynchronous Iterators)

Client.move_channel

TextChannel.edit() or VoiceChannel.edit()

Client.move_member

Member.edit()

Client.move_role

Role.edit()

Client.pin_message

Message.pin()

Client.pins_from

abc.Messageable.pins()

Client.prune_members

Guild.prune_members()

Client.purge_from

TextChannel.purge()

Client.remove_reaction

Message.remove_reaction()

Client.remove_roles

Member.remove_roles()

Client.replace_roles

Member.edit()

Client.send_file

abc.Messageable.send() (see Sending Messages)

Client.send_message

abc.Messageable.send() (see Sending Messages)

Client.send_typing

abc.Messageable.trigger_typing() (use abc.Messageable.typing())

Client.server_voice_state

Member.edit()

Client.start_private_message

User.create_dm()

Client.unban

Guild.unban() or Member.unban()

Client.unpin_message

Message.unpin()

Client.wait_for_message

Client.wait_for() (see Waiting For Events)

Client.wait_for_reaction

Client.wait_for() (see Waiting For Events)

Client.wait_until_login

Removed

Client.wait_until_ready

No change

+
+
+

Property Changes

+

In order to be a bit more consistent, certain things that were properties were changed to methods instead.

+

The following are now methods instead of properties (requires parentheses):

+ +
+
+

Dict Value Change

+

Prior to v1.0 some aggregating properties that retrieved models would return “dict view” objects.

+

As a consequence, when the dict would change size while you would iterate over it, a RuntimeError would +be raised and crash the task. To alleviate this, the “dict view” objects were changed into lists.

+

The following views were changed to a list:

+ +
+
+

Voice State Changes

+

Earlier, in v0.11.0 a VoiceState class was added to refer to voice states along with a +Member.voice attribute to refer to it.

+

However, it was transparent to the user. In an effort to make the library save more memory, the +voice state change is now more visible.

+

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.

+

Quick example:

+
# 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:

+ +

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:

+ +

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

    +
    +
    +
    +
  • +
  • Client.messages

    +
    +
    +
    +
  • +
  • Client.wait_for_message and Client.wait_for_reaction are gone.

    +
    +
    +
    +
  • +
  • Channel.voice_members

    +
    +
    +
    +
  • +
  • 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 and Channel.is_default

    +
    +
      +
    • The concept of a default channel was removed from Discord. +See #329.

    • +
    +
    +
  • +
  • Message.edited_timestamp

    +
    +
    +
    +
  • +
  • Message.timestamp

    +
    +
    +
    +
  • +
  • Colour.to_tuple()

    +
    +
    +
    +
  • +
  • Permissions.view_audit_logs

    +
    +
    +
    +
  • +
  • Member.game

    +
    +
    +
    +
  • +
  • Guild.role_hierarchy / Server.role_hierarchy

    +
    +
      +
    • Use Guild.roles instead. Note that while sorted, it is in the opposite order +of what the old Guild.role_hierarchy used to be.

    • +
    +
    +
  • +
+

Changed

+ +

Added

+ +
+
+
+

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 of Client.join_voice_channel.

  • +
  • You no longer create players and operate on them (you no longer store them).

  • +
  • You instead request VoiceClient to play an AudioSource via VoiceClient.play().

  • +
  • There are different built-in AudioSources.

    + +
  • +
  • create_ffmpeg_player/create_stream_player/create_ytdl_player have all been removed.

    + +
  • +
  • Using VoiceClient.play() will not return an AudioPlayer.

    +
      +
    • Instead, it’s “flattened” like User -> Member is.

    • +
    +
  • +
  • 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.

+
+
+

Sharding

+

The library has received significant changes on how it handles sharding and now has sharding as a first-class citizen.

+

If using a Bot account and you want to shard your bot in a single process then you can use the AutoShardedClient.

+

This class allows you to use sharding without having to launch multiple processes or deal with complicated IPC.

+

It should be noted that the sharded client does not support user accounts. This is due to the changes in connection +logic and state handling.

+

Usage is as simple as doing:

+
client = discord.AutoShardedClient()
+
+
+

instead of using Client.

+

This will launch as many shards as your bot needs using the /gateway/bot endpoint, which allocates about 1000 guilds +per shard.

+

If you want more control over the sharding you can specify shard_count and shard_ids.

+
# launch 10 shards regardless
+client = discord.AutoShardedClient(shard_count=10)
+
+# launch specific shard IDs in this process
+client = discord.AutoShardedClient(shard_count=10, shard_ids=(1, 2, 5, 6))
+
+
+

For users of the command extension, there is also AutoShardedBot which behaves similarly.

+
+
+

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 Models are Stateful 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 for ctx.message.author.

  • +
  • ctx.guild is a shortcut for ctx.message.guild.

  • +
  • ctx.channel is a shortcut for ctx.message.channel.

  • +
  • ctx.me is a shortcut for ctx.message.guild.me or ctx.bot.user.

  • +
  • ctx.voice_client is a shortcut for ctx.message.guild.voice_client.

  • +
+

New Functionality

+ +
+

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:

+
++++ + + + + + + + + + + + + + + + + + + + + +

Before

After

Bot.say

Context.send()

Bot.upload

Context.send()

Bot.whisper

ctx.author.send

Bot.type

Context.typing() or Context.trigger_typing()

Bot.reply

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:

+
    +
  1. signature to get the signature of the command.

  2. +
  3. usage, an attribute to override the default signature.

  4. +
  5. root_parent to get the root parent group of a subcommand.

  6. +
+

For Group and Bot the following changed:

+ +
+
+

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.

+ +
+
+

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.

+ +

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.

+ +

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:

+
    +
  1. Command local before invocation hook

  2. +
  3. Cog local before invocation hook

  4. +
  5. Global before invocation hook

  6. +
  7. The actual command

  8. +
  9. Command local after invocation hook

  10. +
  11. Cog local after invocation hook

  12. +
  13. Global after invocation hook

  14. +
+
+
+

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:

+ +
+
+
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/migrating_to_async.html b/docs/Python/html/migrating_to_async.html new file mode 100644 index 00000000..b9b57e42 --- /dev/null +++ b/docs/Python/html/migrating_to_async.html @@ -0,0 +1,457 @@ + + + + + + Migrating to v0.10.0 + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

Migrating to v0.10.0

+

v0.10.0 is one of the biggest breaking changes in the library due to massive +fundamental changes in how the library operates.

+

The biggest major change is that the library has dropped support to all versions prior to +Python 3.4.2. This was made to support asyncio, in which more detail can be seen +in the corresponding issue. To reiterate this, the implication is that +python version 2.7 and 3.3 are no longer supported.

+

Below are all the other major changes from v0.9.0 to v0.10.0.

+
+

Event Registration

+

All events before were registered using Client.event(). While this is still +possible, the events must be decorated with @asyncio.coroutine.

+

Before:

+
@client.event
+def on_message(message):
+    pass
+
+
+

After:

+
@client.event
+@asyncio.coroutine
+def on_message(message):
+    pass
+
+
+

Or in Python 3.5+:

+
@client.event
+async def on_message(message):
+    pass
+
+
+

Because there is a lot of typing, a utility decorator (Client.async_event()) is provided +for easier registration. For example:

+
@client.async_event
+def on_message(message):
+    pass
+
+
+

Be aware however, that this is still a coroutine and your other functions that are coroutines must +be decorated with @asyncio.coroutine or be async def.

+
+
+

Event Changes

+

Some events in v0.9.0 were considered pretty useless due to having no separate states. The main +events that were changed were the _update events since previously they had no context on what +was changed.

+

Before:

+
def on_channel_update(channel): pass
+def on_member_update(member): pass
+def on_status(member): pass
+def on_server_role_update(role): pass
+def on_voice_state_update(member): pass
+def on_socket_raw_send(payload, is_binary): pass
+
+
+

After:

+
def on_channel_update(before, after): pass
+def on_member_update(before, after): pass
+def on_server_role_update(before, after): pass
+def on_voice_state_update(before, after): pass
+def on_socket_raw_send(payload): pass
+
+
+

Note that on_status was removed. If you want its functionality, use on_member_update(). +See Event Reference for more information. Other removed events include on_socket_closed, on_socket_receive, and on_socket_opened.

+
+
+

Coroutines

+

The biggest change that the library went through is that almost every function in Client +was changed to be a coroutine. Functions +that are marked as a coroutine in the documentation must be awaited from or yielded from in order +for the computation to be done. For example…

+

Before:

+
client.send_message(message.channel, 'Hello')
+
+
+

After:

+
yield from client.send_message(message.channel, 'Hello')
+
+# or in python 3.5+
+await client.send_message(message.channel, 'Hello')
+
+
+

In order for you to yield from or await a coroutine then your function must be decorated +with @asyncio.coroutine or async def.

+
+
+

Iterables

+

For performance reasons, many of the internal data structures were changed into a dictionary to support faster +lookup. As a consequence, this meant that some lists that were exposed via the API have changed into iterables +and not sequences. In short, this means that certain attributes now only support iteration and not any of the +sequence functions.

+

The affected attributes are as follows:

+ +

Some examples of previously valid behaviour that is now invalid

+
if client.servers[0].name == "test":
+    # do something
+
+
+

Since they are no longer lists, they no longer support indexing or any operation other than iterating. +In order to get the old behaviour you should explicitly cast it to a list.

+
servers = list(client.servers)
+# work with servers
+
+
+
+

Warning

+

Due to internal changes of the structure, the order you receive the data in +is not in a guaranteed order.

+
+
+
+

Enumerations

+

Due to dropping support for versions lower than Python 3.4.2, the library can now use +enum — Support for enumerations in places where it makes sense.

+

The common places where this was changed was in the server region, member status, and channel type.

+

Before:

+
server.region == 'us-west'
+member.status == 'online'
+channel.type == 'text'
+
+
+

After:

+
server.region == discord.ServerRegion.us_west
+member.status = discord.Status.online
+channel.type == discord.ChannelType.text
+
+
+

The main reason for this change was to reduce the use of finicky strings in the API as this +could give users a false sense of power. More information can be found in the Enumerations page.

+
+
+

Properties

+

A lot of function calls that returned constant values were changed into Python properties for ease of use +in format strings.

+

The following functions were changed into properties:

+
++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Before

After

User.avatar_url()

User.avatar_url

User.mention()

User.mention

Channel.mention()

Channel.mention

Channel.is_default_channel()

Channel.is_default

Role.is_everyone()

Role.is_everyone

Server.get_default_role()

Server.default_role

Server.icon_url()

Server.icon_url

Server.get_default_channel()

Server.default_channel

Message.get_raw_mentions()

Message.raw_mentions

Message.get_raw_channel_mentions()

Message.raw_channel_mentions

+
+
+

Member Management

+

Functions that involved banning and kicking were changed.

+
++++ + + + + + + + + + + + +

Before

After

Client.ban(server, user)

Client.ban(member)

Client.kick(server, user)

Client.kick(member)

+
+
+

Renamed Functions

+

Functions have been renamed.

+
++++ + + + + + + + + +

Before

After

Client.set_channel_permissions

Client.edit_channel_permissions()

+

All the Permissions related attributes have been renamed and the can_ prefix has been +dropped. So for example, can_manage_messages has become manage_messages.

+
+
+

Forced Keyword Arguments

+

Since 3.0+ of Python, we can now force questions to take in forced keyword arguments. A keyword argument is when you +explicitly specify the name of the variable and assign to it, for example: foo(name='test'). Due to this support, +some functions in the library were changed to force things to take said keyword arguments. This is to reduce errors of +knowing the argument order and the issues that could arise from them.

+

The following parameters are now exclusively keyword arguments:

+
    +
  • +
    Client.send_message()
      +
    • tts

    • +
    +
    +
    +
  • +
  • +
    Client.logs_from()
      +
    • before

    • +
    • after

    • +
    +
    +
    +
  • +
  • +
    Client.edit_channel_permissions()
      +
    • allow

    • +
    • deny

    • +
    +
    +
    +
  • +
+

In the documentation you can tell if a function parameter is a forced keyword argument if it is after \*, +in the function signature.

+
+
+

Running the Client

+

In earlier versions of discord.py, client.run() was a blocking call to the main thread +that called it. In v0.10.0 it is still a blocking call but it handles the event loop for you. +However, in order to do that you must pass in your credentials to Client.run().

+

Basically, before:

+
client.login('token')
+client.run()
+
+
+

After:

+
client.run('token')
+
+
+
+

Warning

+

Like in the older Client.run function, the newer one must be the one of +the last functions to call. This is because the function is blocking. Registering +events or doing anything after Client.run() will not execute until the function +returns.

+
+

This is a utility function that abstracts the event loop for you. There’s no need for +the run call to be blocking and out of your control. Indeed, if you want control of the +event loop then doing so is quite straightforward:

+
import discord
+import asyncio
+
+client = discord.Client()
+
+@asyncio.coroutine
+def main_task():
+    yield from client.login('token')
+    yield from client.connect()
+
+loop = asyncio.get_event_loop()
+try:
+    loop.run_until_complete(main_task())
+except:
+    loop.run_until_complete(client.logout())
+finally:
+    loop.close()
+
+
+
+
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/objects.inv b/docs/Python/html/objects.inv new file mode 100644 index 00000000..d5b57e08 Binary files /dev/null and b/docs/Python/html/objects.inv differ diff --git a/docs/Python/html/quickstart.html b/docs/Python/html/quickstart.html new file mode 100644 index 00000000..af564f68 --- /dev/null +++ b/docs/Python/html/quickstart.html @@ -0,0 +1,205 @@ + + + + + + Quickstart + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

Quickstart

+

This page gives a brief introduction to the library. It assumes you have the library installed, +if you don’t check the Installing portion.

+
+

A Minimal Bot

+

Let’s make a bot that responds to a specific message and walk you through it.

+

It looks something like this:

+
import discord
+
+client = discord.Client()
+
+@client.event
+async def on_ready():
+    print(f'We have logged in as {client.user}')
+
+@client.event
+async def on_message(message):
+    if message.author == client.user:
+        return
+
+    if message.content.startswith('$hello'):
+        await message.channel.send('Hello!')
+
+client.run('your token here')
+
+
+

Let’s name this file example_bot.py. Make sure not to name it discord.py as that’ll conflict +with the library.

+

There’s a lot going on here, so let’s walk you through it step by step.

+
    +
  1. The first line just imports the library, if this raises a ModuleNotFoundError or ImportError +then head on over to Installing section to properly install.

  2. +
  3. Next, we create an instance of a Client. This client is our connection to Discord.

  4. +
  5. We then use the Client.event() decorator to register an event. This library has many events. +Since this library is asynchronous, we do things in a “callback” style manner.

    +

    A callback is essentially a function that is called when something happens. In our case, +the on_ready() event is called when the bot has finished logging in and setting things +up and the on_message() event is called when the bot has received a message.

    +
  6. +
  7. Since the on_message() event triggers for every message received, we have to make +sure that we ignore messages from ourselves. We do this by checking if the Message.author +is the same as the Client.user.

  8. +
  9. Afterwards, we check if the Message.content starts with '$hello'. If it does, +then we send a message in the channel it was used in with 'Hello!'. This is a basic way of +handling commands, which can be later automated with the discord.ext.commands – Bot commands framework framework.

  10. +
  11. Finally, we run the bot with our login token. If you need help getting your token or creating a bot, +look in the Creating a Bot Account section.

  12. +
+

Now that we’ve made a bot, we have to run the bot. Luckily, this is simple since this is just a +Python script, we can run it directly.

+

On Windows:

+
$ py -3 example_bot.py
+
+
+

On other systems:

+
$ python3 example_bot.py
+
+
+

Now you can try playing around with your basic bot.

+
+
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/search.html b/docs/Python/html/search.html new file mode 100644 index 00000000..8ccd1291 --- /dev/null +++ b/docs/Python/html/search.html @@ -0,0 +1,167 @@ + + + + + + Search + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +

Search

+ + + + +

+ Searching for multiple words only shows matches that contain + all words. +

+ + +
+ + + +
+ + + +
+ +
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/searchindex.js b/docs/Python/html/searchindex.js new file mode 100644 index 00000000..91211e34 --- /dev/null +++ b/docs/Python/html/searchindex.js @@ -0,0 +1 @@ +Search.setIndex({docnames:["api","discord","ext/commands/api","ext/commands/cogs","ext/commands/commands","ext/commands/extensions","ext/commands/index","ext/commands/slash-commands","ext/tasks/index","faq","index","intents","intro","logging","migrating","migrating_to_async","quickstart","version_guarantees","whats_new"],envversion:{"sphinx.domains.c":2,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":4,"sphinx.domains.index":1,"sphinx.domains.javascript":2,"sphinx.domains.math":2,"sphinx.domains.python":3,"sphinx.domains.rst":2,"sphinx.domains.std":2,"sphinx.ext.intersphinx":1,sphinx:56},filenames:["api.rst","discord.rst","ext\\commands\\api.rst","ext\\commands\\cogs.rst","ext\\commands\\commands.rst","ext\\commands\\extensions.rst","ext\\commands\\index.rst","ext\\commands\\slash-commands.rst","ext\\tasks\\index.rst","faq.rst","index.rst","intents.rst","intro.rst","logging.rst","migrating.rst","migrating_to_async.rst","quickstart.rst","version_guarantees.rst","whats_new.rst"],objects:{"discord.ActionRow":{children:[0,1,1,""],type:[0,1,1,""]},"discord.Activity":{application_id:[0,1,1,""],assets:[0,1,1,""],buttons:[0,1,1,""],details:[0,1,1,""],emoji:[0,1,1,""],end:[0,2,1,""],large_image_text:[0,2,1,""],large_image_url:[0,2,1,""],name:[0,1,1,""],party:[0,1,1,""],small_image_text:[0,2,1,""],small_image_url:[0,2,1,""],start:[0,2,1,""],state:[0,1,1,""],timestamps:[0,1,1,""],type:[0,1,1,""],url:[0,1,1,""]},"discord.ActivityType":{competing:[0,1,1,""],custom:[0,1,1,""],listening:[0,1,1,""],playing:[0,1,1,""],streaming:[0,1,1,""],unknown:[0,1,1,""],watching:[0,1,1,""]},"discord.AllowedMentions":{all:[0,3,1,""],everyone:[0,1,1,""],none:[0,3,1,""],replied_user:[0,1,1,""],roles:[0,1,1,""],users:[0,1,1,""]},"discord.AppInfo":{bot_public:[0,1,1,""],bot_require_code_grant:[0,1,1,""],cover_image:[0,2,1,""],description:[0,1,1,""],guild:[0,2,1,""],guild_id:[0,1,1,""],icon:[0,2,1,""],id:[0,1,1,""],name:[0,1,1,""],owner:[0,1,1,""],primary_sku_id:[0,1,1,""],privacy_policy_url:[0,1,1,""],rpc_origins:[0,1,1,""],slug:[0,1,1,""],summary:[0,1,1,""],team:[0,1,1,""],terms_of_service_url:[0,1,1,""],verify_key:[0,1,1,""]},"discord.ApplicationFlags":{embedded:[0,1,1,""],gateway_guild_members:[0,1,1,""],gateway_guild_members_limited:[0,1,1,""],gateway_presence:[0,1,1,""],gateway_presence_limited:[0,1,1,""],value:[0,1,1,""],verification_pending_guild_limit:[0,1,1,""]},"discord.Asset":{is_animated:[0,3,1,""],key:[0,2,1,""],read:[0,3,1,""],replace:[0,3,1,""],save:[0,3,1,""],url:[0,2,1,""],with_format:[0,3,1,""],with_size:[0,3,1,""],with_static_format:[0,3,1,""]},"discord.AsyncIterator":{chunk:[0,3,1,""],filter:[0,3,1,""],find:[0,3,1,""],flatten:[0,3,1,""],get:[0,3,1,""],map:[0,3,1,""],next:[0,3,1,""]},"discord.Attachment":{content_type:[0,1,1,""],ephemeral:[0,1,1,""],filename:[0,1,1,""],height:[0,1,1,""],id:[0,1,1,""],is_spoiler:[0,3,1,""],proxy_url:[0,1,1,""],read:[0,3,1,""],save:[0,3,1,""],size:[0,1,1,""],to_file:[0,3,1,""],url:[0,1,1,""],width:[0,1,1,""]},"discord.AudioSource":{cleanup:[0,3,1,""],is_opus:[0,3,1,""],read:[0,3,1,""]},"discord.AuditLogAction":{ban:[0,1,1,""],bot_add:[0,1,1,""],channel_create:[0,1,1,""],channel_delete:[0,1,1,""],channel_update:[0,1,1,""],emoji_create:[0,1,1,""],emoji_delete:[0,1,1,""],emoji_update:[0,1,1,""],guild_update:[0,1,1,""],integration_create:[0,1,1,""],integration_delete:[0,1,1,""],integration_update:[0,1,1,""],invite_create:[0,1,1,""],invite_delete:[0,1,1,""],invite_update:[0,1,1,""],kick:[0,1,1,""],member_disconnect:[0,1,1,""],member_move:[0,1,1,""],member_prune:[0,1,1,""],member_role_update:[0,1,1,""],member_update:[0,1,1,""],message_bulk_delete:[0,1,1,""],message_delete:[0,1,1,""],message_pin:[0,1,1,""],message_unpin:[0,1,1,""],overwrite_create:[0,1,1,""],overwrite_delete:[0,1,1,""],overwrite_update:[0,1,1,""],role_create:[0,1,1,""],role_delete:[0,1,1,""],role_update:[0,1,1,""],stage_instance_create:[0,1,1,""],stage_instance_delete:[0,1,1,""],stage_instance_update:[0,1,1,""],sticker_create:[0,1,1,""],sticker_delete:[0,1,1,""],sticker_update:[0,1,1,""],thread_create:[0,1,1,""],thread_delete:[0,1,1,""],thread_update:[0,1,1,""],unban:[0,1,1,""],webhook_create:[0,1,1,""],webhook_delete:[0,1,1,""],webhook_update:[0,1,1,""]},"discord.AuditLogActionCategory":{"delete":[0,1,1,""],create:[0,1,1,""],update:[0,1,1,""]},"discord.AuditLogChanges":{after:[0,1,1,""],before:[0,1,1,""]},"discord.AuditLogDiff":{afk_channel:[0,1,1,""],afk_timeout:[0,1,1,""],allow:[0,1,1,""],archived:[0,1,1,""],auto_archive_duration:[0,1,1,""],available:[0,1,1,""],avatar:[0,1,1,""],banner:[0,1,1,""],bitrate:[0,1,1,""],channel:[0,1,1,""],code:[0,1,1,""],color:[0,1,1,""],colour:[0,1,1,""],deaf:[0,1,1,""],default_auto_archive_duration:[0,1,1,""],default_message_notifications:[0,1,1,""],default_notifications:[0,1,1,""],deny:[0,1,1,""],description:[0,1,1,""],discovery_splash:[0,1,1,""],emoji:[0,1,1,""],explicit_content_filter:[0,1,1,""],format_type:[0,1,1,""],hoist:[0,1,1,""],icon:[0,1,1,""],id:[0,1,1,""],inviter:[0,1,1,""],locked:[0,1,1,""],max_age:[0,1,1,""],max_uses:[0,1,1,""],mentionable:[0,1,1,""],mfa_level:[0,1,1,""],mute:[0,1,1,""],name:[0,1,1,""],nick:[0,1,1,""],overwrites:[0,1,1,""],owner:[0,1,1,""],permissions:[0,1,1,""],position:[0,1,1,""],privacy_level:[0,1,1,""],public_updates_channel:[0,1,1,""],region:[0,1,1,""],roles:[0,1,1,""],rtc_region:[0,1,1,""],rules_channel:[0,1,1,""],slowmode_delay:[0,1,1,""],splash:[0,1,1,""],system_channel:[0,1,1,""],temporary:[0,1,1,""],topic:[0,1,1,""],type:[0,1,1,""],uses:[0,1,1,""],vanity_url_code:[0,1,1,""],verification_level:[0,1,1,""],video_quality_mode:[0,1,1,""],widget_channel:[0,1,1,""],widget_enabled:[0,1,1,""]},"discord.AuditLogEntry":{action:[0,1,1,""],after:[0,1,1,""],before:[0,1,1,""],category:[0,1,1,""],changes:[0,1,1,""],created_at:[0,1,1,""],extra:[0,1,1,""],id:[0,1,1,""],reason:[0,1,1,""],target:[0,1,1,""],user:[0,1,1,""]},"discord.AutoShardedClient":{change_presence:[0,3,1,""],close:[0,3,1,""],connect:[0,3,1,""],get_shard:[0,3,1,""],is_ws_ratelimited:[0,3,1,""],latencies:[0,2,1,""],latency:[0,2,1,""],shard_ids:[0,1,1,""],shards:[0,2,1,""]},"discord.BanEntry":{reason:[0,1,1,""],user:[0,1,1,""]},"discord.BaseActivity":{created_at:[0,2,1,""]},"discord.BotIntegration":{account:[0,1,1,""],application:[0,1,1,""],enabled:[0,1,1,""],guild:[0,1,1,""],id:[0,1,1,""],name:[0,1,1,""],type:[0,1,1,""],user:[0,1,1,""]},"discord.Button":{custom_id:[0,1,1,""],disabled:[0,1,1,""],emoji:[0,1,1,""],label:[0,1,1,""],style:[0,1,1,""],url:[0,1,1,""]},"discord.ButtonStyle":{blurple:[0,1,1,""],danger:[0,1,1,""],gray:[0,1,1,""],green:[0,1,1,""],grey:[0,1,1,""],link:[0,1,1,""],primary:[0,1,1,""],red:[0,1,1,""],secondary:[0,1,1,""],success:[0,1,1,""],url:[0,1,1,""]},"discord.CategoryChannel":{"delete":[0,3,1,""],category:[0,2,1,""],changed_roles:[0,2,1,""],channels:[0,2,1,""],clone:[0,3,1,""],create_invite:[0,3,1,""],create_stage_channel:[0,3,1,""],create_text_channel:[0,3,1,""],create_voice_channel:[0,3,1,""],created_at:[0,2,1,""],edit:[0,3,1,""],guild:[0,1,1,""],id:[0,1,1,""],invites:[0,3,1,""],is_nsfw:[0,3,1,""],mention:[0,2,1,""],move:[0,3,1,""],name:[0,1,1,""],nsfw:[0,1,1,""],overwrites:[0,2,1,""],overwrites_for:[0,3,1,""],permissions_for:[0,3,1,""],permissions_synced:[0,2,1,""],position:[0,1,1,""],set_permissions:[0,3,1,""],stage_channels:[0,2,1,""],text_channels:[0,2,1,""],type:[0,2,1,""],voice_channels:[0,2,1,""]},"discord.ChannelType":{"private":[0,1,1,""],category:[0,1,1,""],group:[0,1,1,""],news:[0,1,1,""],news_thread:[0,1,1,""],private_thread:[0,1,1,""],public_thread:[0,1,1,""],stage_voice:[0,1,1,""],store:[0,1,1,""],text:[0,1,1,""],voice:[0,1,1,""]},"discord.Client":{activity:[0,2,1,""],add_view:[0,3,1,""],allowed_mentions:[0,2,1,""],application_flags:[0,2,1,""],application_id:[0,2,1,""],application_info:[0,3,1,""],before_identify_hook:[0,3,1,""],cached_messages:[0,2,1,""],change_presence:[0,3,1,""],clear:[0,3,1,""],close:[0,3,1,""],connect:[0,3,1,""],create_dm:[0,3,1,""],create_guild:[0,3,1,""],delete_invite:[0,3,1,""],emojis:[0,2,1,""],event:[0,3,1,""],fetch_channel:[0,3,1,""],fetch_guild:[0,3,1,""],fetch_guilds:[0,3,1,""],fetch_invite:[0,3,1,""],fetch_premium_sticker_packs:[0,3,1,""],fetch_stage_instance:[0,3,1,""],fetch_sticker:[0,3,1,""],fetch_template:[0,3,1,""],fetch_user:[0,3,1,""],fetch_webhook:[0,3,1,""],fetch_widget:[0,3,1,""],get_all_channels:[0,3,1,""],get_all_members:[0,3,1,""],get_channel:[0,3,1,""],get_emoji:[0,3,1,""],get_guild:[0,3,1,""],get_partial_messageable:[0,3,1,""],get_stage_instance:[0,3,1,""],get_sticker:[0,3,1,""],get_user:[0,3,1,""],guilds:[0,2,1,""],intents:[0,2,1,""],is_closed:[0,3,1,""],is_ready:[0,3,1,""],is_ws_ratelimited:[0,3,1,""],latency:[0,2,1,""],login:[0,3,1,""],loop:[0,1,1,""],on_error:[0,3,1,""],persistent_views:[0,2,1,""],private_channels:[0,2,1,""],run:[0,3,1,""],setup:[0,3,1,""],start:[0,3,1,""],status:[0,2,1,""],stickers:[0,2,1,""],try_user:[0,3,1,""],user:[0,2,1,""],users:[0,2,1,""],voice_clients:[0,2,1,""],wait_for:[0,3,1,""],wait_until_ready:[0,3,1,""],ws:[0,1,1,""]},"discord.ClientUser":{accent_color:[0,2,1,""],accent_colour:[0,2,1,""],avatar:[0,2,1,""],banner:[0,2,1,""],bot:[0,1,1,""],color:[0,2,1,""],colour:[0,2,1,""],created_at:[0,2,1,""],default_avatar:[0,2,1,""],discriminator:[0,1,1,""],display_avatar:[0,2,1,""],display_name:[0,2,1,""],edit:[0,3,1,""],id:[0,1,1,""],locale:[0,1,1,""],mention:[0,2,1,""],mentioned_in:[0,3,1,""],mfa_enabled:[0,1,1,""],name:[0,1,1,""],public_flags:[0,2,1,""],system:[0,1,1,""],verified:[0,1,1,""]},"discord.Colour":{"default":[0,3,1,""],b:[0,2,1,""],blue:[0,3,1,""],blurple:[0,3,1,""],brand_green:[0,3,1,""],brand_red:[0,3,1,""],dark_blue:[0,3,1,""],dark_blurple:[0,3,1,""],dark_gold:[0,3,1,""],dark_gray:[0,3,1,""],dark_green:[0,3,1,""],dark_grey:[0,3,1,""],dark_magenta:[0,3,1,""],dark_orange:[0,3,1,""],dark_purple:[0,3,1,""],dark_red:[0,3,1,""],dark_teal:[0,3,1,""],dark_theme:[0,3,1,""],darker_gray:[0,3,1,""],darker_grey:[0,3,1,""],from_hsv:[0,3,1,""],from_rgb:[0,3,1,""],fuchsia:[0,3,1,""],g:[0,2,1,""],gold:[0,3,1,""],green:[0,3,1,""],greyple:[0,3,1,""],light_gray:[0,3,1,""],light_grey:[0,3,1,""],lighter_gray:[0,3,1,""],lighter_grey:[0,3,1,""],magenta:[0,3,1,""],nitro_booster:[0,3,1,""],og_blurple:[0,3,1,""],orange:[0,3,1,""],purple:[0,3,1,""],r:[0,2,1,""],random:[0,3,1,""],red:[0,3,1,""],teal:[0,3,1,""],to_rgb:[0,3,1,""],value:[0,1,1,""],yellow:[0,3,1,""]},"discord.Component":{type:[0,1,1,""]},"discord.ComponentType":{action_row:[0,1,1,""],button:[0,1,1,""],select:[0,1,1,""]},"discord.ConnectionClosed":{code:[0,1,1,""],reason:[0,1,1,""],shard_id:[0,1,1,""]},"discord.ContentFilter":{all_members:[0,1,1,""],disabled:[0,1,1,""],no_role:[0,1,1,""]},"discord.CustomActivity":{emoji:[0,1,1,""],name:[0,1,1,""],type:[0,2,1,""]},"discord.DMChannel":{created_at:[0,2,1,""],fetch_message:[0,3,1,""],get_partial_message:[0,3,1,""],history:[0,3,1,""],id:[0,1,1,""],me:[0,1,1,""],permissions_for:[0,3,1,""],pins:[0,3,1,""],recipient:[0,1,1,""],send:[0,3,1,""],trigger_typing:[0,3,1,""],type:[0,2,1,""],typing:[0,3,1,""]},"discord.DefaultAvatar":{blurple:[0,1,1,""],gray:[0,1,1,""],green:[0,1,1,""],grey:[0,1,1,""],orange:[0,1,1,""],red:[0,1,1,""]},"discord.DeletedReferencedMessage":{channel_id:[0,2,1,""],guild_id:[0,2,1,""],id:[0,2,1,""]},"discord.Embed":{Empty:[0,1,1,""],add_field:[0,3,1,""],author:[0,2,1,""],clear_fields:[0,3,1,""],colour:[0,1,1,""],copy:[0,3,1,""],description:[0,1,1,""],fields:[0,2,1,""],footer:[0,2,1,""],from_dict:[0,3,1,""],image:[0,2,1,""],insert_field_at:[0,3,1,""],provider:[0,2,1,""],remove_author:[0,3,1,""],remove_field:[0,3,1,""],remove_footer:[0,3,1,""],set_author:[0,3,1,""],set_field_at:[0,3,1,""],set_footer:[0,3,1,""],set_image:[0,3,1,""],set_thumbnail:[0,3,1,""],thumbnail:[0,2,1,""],timestamp:[0,1,1,""],title:[0,1,1,""],to_dict:[0,3,1,""],type:[0,1,1,""],url:[0,1,1,""],video:[0,2,1,""]},"discord.Emoji":{"delete":[0,3,1,""],animated:[0,1,1,""],available:[0,1,1,""],created_at:[0,2,1,""],edit:[0,3,1,""],guild:[0,2,1,""],guild_id:[0,1,1,""],id:[0,1,1,""],is_usable:[0,3,1,""],managed:[0,1,1,""],name:[0,1,1,""],read:[0,3,1,""],require_colons:[0,1,1,""],roles:[0,2,1,""],save:[0,3,1,""],url:[0,2,1,""],user:[0,1,1,""]},"discord.ExpireBehaviour":{kick:[0,1,1,""],remove_role:[0,1,1,""]},"discord.FFmpegAudio":{cleanup:[0,3,1,""]},"discord.FFmpegOpusAudio":{from_probe:[0,3,1,""],is_opus:[0,3,1,""],probe:[0,3,1,""],read:[0,3,1,""]},"discord.FFmpegPCMAudio":{is_opus:[0,3,1,""],read:[0,3,1,""]},"discord.File":{filename:[0,1,1,""],fp:[0,1,1,""],spoiler:[0,1,1,""]},"discord.Game":{end:[0,2,1,""],name:[0,1,1,""],start:[0,2,1,""],type:[0,2,1,""]},"discord.GroupChannel":{created_at:[0,2,1,""],fetch_message:[0,3,1,""],history:[0,3,1,""],icon:[0,2,1,""],id:[0,1,1,""],leave:[0,3,1,""],me:[0,1,1,""],name:[0,1,1,""],owner:[0,1,1,""],owner_id:[0,1,1,""],permissions_for:[0,3,1,""],pins:[0,3,1,""],recipients:[0,1,1,""],send:[0,3,1,""],trigger_typing:[0,3,1,""],type:[0,2,1,""],typing:[0,3,1,""]},"discord.Guild":{"delete":[0,3,1,""],active_threads:[0,3,1,""],afk_channel:[0,1,1,""],afk_timeout:[0,1,1,""],audit_logs:[0,3,1,""],ban:[0,3,1,""],banner:[0,2,1,""],bans:[0,3,1,""],bitrate_limit:[0,2,1,""],bots:[0,2,1,""],by_category:[0,3,1,""],categories:[0,2,1,""],change_voice_state:[0,3,1,""],channels:[0,2,1,""],chunk:[0,3,1,""],chunked:[0,2,1,""],create_category:[0,3,1,""],create_category_channel:[0,3,1,""],create_custom_emoji:[0,3,1,""],create_integration:[0,3,1,""],create_role:[0,3,1,""],create_stage_channel:[0,3,1,""],create_sticker:[0,3,1,""],create_template:[0,3,1,""],create_text_channel:[0,3,1,""],create_voice_channel:[0,3,1,""],created_at:[0,2,1,""],default_notifications:[0,1,1,""],default_role:[0,2,1,""],delete_emoji:[0,3,1,""],delete_sticker:[0,3,1,""],description:[0,1,1,""],discovery_splash:[0,2,1,""],edit:[0,3,1,""],edit_role_positions:[0,3,1,""],edit_widget:[0,3,1,""],emoji_limit:[0,2,1,""],emojis:[0,1,1,""],estimate_pruned_members:[0,3,1,""],explicit_content_filter:[0,1,1,""],features:[0,1,1,""],fetch_ban:[0,3,1,""],fetch_channel:[0,3,1,""],fetch_channels:[0,3,1,""],fetch_emoji:[0,3,1,""],fetch_emojis:[0,3,1,""],fetch_member:[0,3,1,""],fetch_members:[0,3,1,""],fetch_roles:[0,3,1,""],fetch_sticker:[0,3,1,""],fetch_stickers:[0,3,1,""],filesize_limit:[0,2,1,""],get_channel:[0,3,1,""],get_channel_or_thread:[0,3,1,""],get_member:[0,3,1,""],get_member_named:[0,3,1,""],get_role:[0,3,1,""],get_stage_instance:[0,3,1,""],get_thread:[0,3,1,""],humans:[0,2,1,""],icon:[0,2,1,""],id:[0,1,1,""],integrations:[0,3,1,""],invites:[0,3,1,""],kick:[0,3,1,""],large:[0,2,1,""],leave:[0,3,1,""],max_members:[0,1,1,""],max_presences:[0,1,1,""],max_video_channel_users:[0,1,1,""],me:[0,2,1,""],member_count:[0,2,1,""],members:[0,2,1,""],mfa_level:[0,1,1,""],name:[0,1,1,""],nsfw_level:[0,1,1,""],owner:[0,2,1,""],owner_id:[0,1,1,""],preferred_locale:[0,1,1,""],premium_subscriber_role:[0,2,1,""],premium_subscribers:[0,2,1,""],premium_subscription_count:[0,1,1,""],premium_tier:[0,1,1,""],prune_members:[0,3,1,""],public_updates_channel:[0,2,1,""],query_members:[0,3,1,""],region:[0,1,1,""],roles:[0,2,1,""],rules_channel:[0,2,1,""],self_role:[0,2,1,""],shard_id:[0,2,1,""],splash:[0,2,1,""],stage_channels:[0,2,1,""],stage_instances:[0,2,1,""],sticker_limit:[0,2,1,""],stickers:[0,1,1,""],system_channel:[0,2,1,""],system_channel_flags:[0,2,1,""],templates:[0,3,1,""],text_channels:[0,2,1,""],threads:[0,2,1,""],try_member:[0,3,1,""],unavailable:[0,1,1,""],unban:[0,3,1,""],vanity_invite:[0,3,1,""],verification_level:[0,1,1,""],voice_channels:[0,2,1,""],voice_client:[0,2,1,""],webhooks:[0,3,1,""],widget:[0,3,1,""]},"discord.GuildSticker":{"delete":[0,3,1,""],available:[0,1,1,""],description:[0,1,1,""],edit:[0,3,1,""],emoji:[0,1,1,""],format:[0,1,1,""],guild:[0,1,1,""],guild_id:[0,1,1,""],id:[0,1,1,""],name:[0,1,1,""],user:[0,1,1,""]},"discord.HTTPException":{code:[0,1,1,""],response:[0,1,1,""],status:[0,1,1,""],text:[0,1,1,""]},"discord.Integration":{"delete":[0,3,1,""],account:[0,1,1,""],enabled:[0,1,1,""],guild:[0,1,1,""],id:[0,1,1,""],name:[0,1,1,""],type:[0,1,1,""],user:[0,1,1,""]},"discord.IntegrationAccount":{id:[0,1,1,""],name:[0,1,1,""]},"discord.IntegrationApplication":{description:[0,1,1,""],icon:[0,1,1,""],id:[0,1,1,""],name:[0,1,1,""],summary:[0,1,1,""],user:[0,1,1,""]},"discord.Intents":{all:[0,3,1,""],bans:[0,1,1,""],dm_messages:[0,1,1,""],dm_reactions:[0,1,1,""],dm_typing:[0,1,1,""],emojis:[0,1,1,""],emojis_and_stickers:[0,1,1,""],guild_messages:[0,1,1,""],guild_reactions:[0,1,1,""],guild_typing:[0,1,1,""],guilds:[0,1,1,""],integrations:[0,1,1,""],invites:[0,1,1,""],members:[0,1,1,""],messages:[0,1,1,""],none:[0,3,1,""],presences:[0,1,1,""],reactions:[0,1,1,""],typing:[0,1,1,""],value:[0,1,1,""],voice_states:[0,1,1,""],webhooks:[0,1,1,""]},"discord.Interaction":{application_id:[0,1,1,""],channel:[0,1,1,""],channel_id:[0,1,1,""],data:[0,1,1,""],delete_original_message:[0,3,1,""],edit_original_message:[0,3,1,""],followup:[0,1,1,""],guild:[0,2,1,""],guild_id:[0,1,1,""],id:[0,1,1,""],message:[0,1,1,""],original_message:[0,3,1,""],permissions:[0,2,1,""],response:[0,1,1,""],token:[0,1,1,""],type:[0,1,1,""],user:[0,1,1,""]},"discord.InteractionMessage":{"delete":[0,3,1,""],edit:[0,3,1,""]},"discord.InteractionResponded":{interaction:[0,1,1,""]},"discord.InteractionResponse":{defer:[0,3,1,""],edit_message:[0,3,1,""],is_done:[0,3,1,""],pong:[0,3,1,""],send_message:[0,3,1,""]},"discord.InteractionResponseType":{channel_message:[0,1,1,""],deferred_channel_message:[0,1,1,""],deferred_message_update:[0,1,1,""],message_update:[0,1,1,""],pong:[0,1,1,""]},"discord.InteractionType":{application_command:[0,1,1,""],component:[0,1,1,""],ping:[0,1,1,""]},"discord.Invite":{"delete":[0,3,1,""],approximate_member_count:[0,1,1,""],approximate_presence_count:[0,1,1,""],channel:[0,1,1,""],code:[0,1,1,""],created_at:[0,1,1,""],expires_at:[0,1,1,""],guild:[0,1,1,""],id:[0,2,1,""],inviter:[0,1,1,""],max_age:[0,1,1,""],max_uses:[0,1,1,""],revoked:[0,1,1,""],target_application:[0,1,1,""],target_type:[0,1,1,""],target_user:[0,1,1,""],temporary:[0,1,1,""],url:[0,2,1,""],uses:[0,1,1,""]},"discord.InviteTarget":{embedded_application:[0,1,1,""],stream:[0,1,1,""],unknown:[0,1,1,""]},"discord.Member":{accent_color:[0,2,1,""],accent_colour:[0,2,1,""],activities:[0,1,1,""],activity:[0,2,1,""],add_roles:[0,3,1,""],avatar:[0,2,1,""],ban:[0,3,1,""],banner:[0,2,1,""],bot:[0,2,1,""],color:[0,2,1,""],colour:[0,2,1,""],create_dm:[0,3,1,""],created_at:[0,2,1,""],default_avatar:[0,2,1,""],desktop_status:[0,2,1,""],discriminator:[0,2,1,""],display_avatar:[0,2,1,""],display_name:[0,2,1,""],dm_channel:[0,2,1,""],edit:[0,3,1,""],fetch_message:[0,3,1,""],get_role:[0,3,1,""],guild:[0,1,1,""],guild_avatar:[0,2,1,""],guild_permissions:[0,2,1,""],history:[0,3,1,""],id:[0,2,1,""],is_on_mobile:[0,3,1,""],joined_at:[0,1,1,""],kick:[0,3,1,""],mention:[0,2,1,""],mentioned_in:[0,3,1,""],mobile_status:[0,2,1,""],move_to:[0,3,1,""],mutual_guilds:[0,2,1,""],name:[0,2,1,""],nick:[0,1,1,""],pending:[0,1,1,""],pins:[0,3,1,""],premium_since:[0,1,1,""],public_flags:[0,2,1,""],raw_status:[0,2,1,""],remove_roles:[0,3,1,""],request_to_speak:[0,3,1,""],roles:[0,2,1,""],send:[0,3,1,""],status:[0,2,1,""],system:[0,2,1,""],top_role:[0,2,1,""],trigger_typing:[0,3,1,""],typing:[0,3,1,""],unban:[0,3,1,""],voice:[0,2,1,""],web_status:[0,2,1,""]},"discord.MemberCacheFlags":{all:[0,3,1,""],from_intents:[0,3,1,""],joined:[0,1,1,""],none:[0,3,1,""],value:[0,1,1,""],voice:[0,1,1,""]},"discord.Message":{"delete":[0,3,1,""],activity:[0,1,1,""],add_reaction:[0,3,1,""],application:[0,1,1,""],attachments:[0,1,1,""],author:[0,1,1,""],channel:[0,1,1,""],channel_mentions:[0,1,1,""],clean_content:[0,1,1,""],clear_reaction:[0,3,1,""],clear_reactions:[0,3,1,""],components:[0,1,1,""],content:[0,1,1,""],create_thread:[0,3,1,""],created_at:[0,2,1,""],edit:[0,3,1,""],edited_at:[0,2,1,""],embeds:[0,1,1,""],flags:[0,1,1,""],guild:[0,1,1,""],id:[0,1,1,""],is_system:[0,3,1,""],jump_url:[0,2,1,""],mention_everyone:[0,1,1,""],mentions:[0,1,1,""],nonce:[0,1,1,""],pin:[0,3,1,""],pinned:[0,1,1,""],publish:[0,3,1,""],raw_channel_mentions:[0,1,1,""],raw_mentions:[0,1,1,""],raw_role_mentions:[0,1,1,""],reactions:[0,1,1,""],reference:[0,1,1,""],remove_reaction:[0,3,1,""],reply:[0,3,1,""],role_mentions:[0,1,1,""],stickers:[0,1,1,""],system_content:[0,1,1,""],to_reference:[0,3,1,""],tts:[0,1,1,""],type:[0,1,1,""],unpin:[0,3,1,""],webhook_id:[0,1,1,""]},"discord.MessageFlags":{crossposted:[0,1,1,""],ephemeral:[0,1,1,""],has_thread:[0,1,1,""],is_crossposted:[0,1,1,""],source_message_deleted:[0,1,1,""],suppress_embeds:[0,1,1,""],urgent:[0,1,1,""],value:[0,1,1,""]},"discord.MessageReference":{cached_message:[0,2,1,""],channel_id:[0,1,1,""],fail_if_not_exists:[0,1,1,""],from_message:[0,3,1,""],guild_id:[0,1,1,""],jump_url:[0,2,1,""],message_id:[0,1,1,""],resolved:[0,1,1,""]},"discord.MessageType":{"default":[0,1,1,""],application_command:[0,1,1,""],call:[0,1,1,""],channel_follow_add:[0,1,1,""],channel_icon_change:[0,1,1,""],channel_name_change:[0,1,1,""],guild_discovery_disqualified:[0,1,1,""],guild_discovery_grace_period_final_warning:[0,1,1,""],guild_discovery_grace_period_initial_warning:[0,1,1,""],guild_discovery_requalified:[0,1,1,""],guild_invite_reminder:[0,1,1,""],guild_stream:[0,1,1,""],new_member:[0,1,1,""],pins_add:[0,1,1,""],premium_guild_subscription:[0,1,1,""],premium_guild_tier_1:[0,1,1,""],premium_guild_tier_2:[0,1,1,""],premium_guild_tier_3:[0,1,1,""],recipient_add:[0,1,1,""],recipient_remove:[0,1,1,""],reply:[0,1,1,""],thread_created:[0,1,1,""],thread_starter_message:[0,1,1,""]},"discord.NSFWLevel":{"default":[0,1,1,""],age_restricted:[0,1,1,""],explicit:[0,1,1,""],safe:[0,1,1,""]},"discord.NotificationLevel":{all_messages:[0,1,1,""],only_mentions:[0,1,1,""]},"discord.Object":{created_at:[0,2,1,""],id:[0,1,1,""]},"discord.PCMAudio":{read:[0,3,1,""],stream:[0,1,1,""]},"discord.PCMVolumeTransformer":{cleanup:[0,3,1,""],read:[0,3,1,""],volume:[0,2,1,""]},"discord.PartialAppInfo":{description:[0,1,1,""],icon:[0,2,1,""],id:[0,1,1,""],name:[0,1,1,""],privacy_policy_url:[0,1,1,""],rpc_origins:[0,1,1,""],summary:[0,1,1,""],terms_of_service_url:[0,1,1,""],verify_key:[0,1,1,""]},"discord.PartialEmoji":{animated:[0,1,1,""],created_at:[0,2,1,""],from_str:[0,3,1,""],id:[0,1,1,""],is_custom_emoji:[0,3,1,""],is_unicode_emoji:[0,3,1,""],name:[0,1,1,""],read:[0,3,1,""],save:[0,3,1,""],url:[0,2,1,""]},"discord.PartialInviteChannel":{created_at:[0,2,1,""],id:[0,1,1,""],mention:[0,2,1,""],name:[0,1,1,""],type:[0,1,1,""]},"discord.PartialInviteGuild":{banner:[0,2,1,""],created_at:[0,2,1,""],description:[0,1,1,""],features:[0,1,1,""],icon:[0,2,1,""],id:[0,1,1,""],name:[0,1,1,""],splash:[0,2,1,""],verification_level:[0,1,1,""]},"discord.PartialMessage":{"delete":[0,3,1,""],add_reaction:[0,3,1,""],channel:[0,1,1,""],clear_reaction:[0,3,1,""],clear_reactions:[0,3,1,""],created_at:[0,2,1,""],edit:[0,3,1,""],fetch:[0,3,1,""],guild:[0,1,1,""],id:[0,1,1,""],jump_url:[0,2,1,""],pin:[0,3,1,""],publish:[0,3,1,""],remove_reaction:[0,3,1,""],reply:[0,3,1,""],to_reference:[0,3,1,""],unpin:[0,3,1,""]},"discord.PartialMessageable":{fetch_message:[0,3,1,""],get_partial_message:[0,3,1,""],history:[0,3,1,""],id:[0,1,1,""],pins:[0,3,1,""],send:[0,3,1,""],trigger_typing:[0,3,1,""],type:[0,1,1,""],typing:[0,3,1,""]},"discord.PartialWebhookChannel":{id:[0,1,1,""],name:[0,1,1,""]},"discord.PartialWebhookGuild":{icon:[0,2,1,""],id:[0,1,1,""],name:[0,1,1,""]},"discord.PermissionOverwrite":{from_pair:[0,3,1,""],is_empty:[0,3,1,""],pair:[0,3,1,""],update:[0,3,1,""]},"discord.Permissions":{add_reactions:[0,1,1,""],admin:[0,1,1,""],administrator:[0,1,1,""],advanced:[0,3,1,""],all:[0,3,1,""],all_channel:[0,3,1,""],attach_files:[0,1,1,""],ban_members:[0,1,1,""],change_nickname:[0,1,1,""],connect:[0,1,1,""],create_instant_invite:[0,1,1,""],create_private_threads:[0,1,1,""],create_public_threads:[0,1,1,""],deafen_members:[0,1,1,""],embed_links:[0,1,1,""],external_emojis:[0,1,1,""],external_stickers:[0,1,1,""],general:[0,3,1,""],is_strict_subset:[0,3,1,""],is_strict_superset:[0,3,1,""],is_subset:[0,3,1,""],is_superset:[0,3,1,""],kick_members:[0,1,1,""],manage_channels:[0,1,1,""],manage_emojis:[0,1,1,""],manage_emojis_and_stickers:[0,1,1,""],manage_events:[0,1,1,""],manage_guild:[0,1,1,""],manage_messages:[0,1,1,""],manage_nicknames:[0,1,1,""],manage_permissions:[0,1,1,""],manage_roles:[0,1,1,""],manage_threads:[0,1,1,""],manage_webhooks:[0,1,1,""],membership:[0,3,1,""],mention_everyone:[0,1,1,""],move_members:[0,1,1,""],mute_members:[0,1,1,""],none:[0,3,1,""],priority_speaker:[0,1,1,""],read_message_history:[0,1,1,""],read_messages:[0,1,1,""],request_to_speak:[0,1,1,""],send_messages:[0,1,1,""],send_messages_in_threads:[0,1,1,""],send_tts_messages:[0,1,1,""],speak:[0,1,1,""],stage:[0,3,1,""],stage_moderator:[0,3,1,""],stream:[0,1,1,""],text:[0,3,1,""],update:[0,3,1,""],use_external_emojis:[0,1,1,""],use_external_stickers:[0,1,1,""],use_slash_commands:[0,1,1,""],use_voice_activation:[0,1,1,""],value:[0,1,1,""],view_audit_log:[0,1,1,""],view_channel:[0,1,1,""],view_guild_insights:[0,1,1,""],voice:[0,3,1,""]},"discord.PrivilegedIntentsRequired":{shard_id:[0,1,1,""]},"discord.PublicUserFlags":{all:[0,3,1,""],bug_hunter:[0,1,1,""],bug_hunter_level_2:[0,1,1,""],discord_certified_moderator:[0,1,1,""],early_supporter:[0,1,1,""],early_verified_bot_developer:[0,1,1,""],hypesquad:[0,1,1,""],hypesquad_balance:[0,1,1,""],hypesquad_bravery:[0,1,1,""],hypesquad_brilliance:[0,1,1,""],partner:[0,1,1,""],staff:[0,1,1,""],system:[0,1,1,""],team_user:[0,1,1,""],value:[0,1,1,""],verified_bot:[0,1,1,""],verified_bot_developer:[0,1,1,""]},"discord.RawBulkMessageDeleteEvent":{cached_messages:[0,1,1,""],channel_id:[0,1,1,""],guild_id:[0,1,1,""],message_ids:[0,1,1,""]},"discord.RawIntegrationDeleteEvent":{application_id:[0,1,1,""],guild_id:[0,1,1,""],integration_id:[0,1,1,""]},"discord.RawMessageDeleteEvent":{cached_message:[0,1,1,""],channel_id:[0,1,1,""],guild_id:[0,1,1,""],message_id:[0,1,1,""]},"discord.RawMessageUpdateEvent":{cached_message:[0,1,1,""],channel_id:[0,1,1,""],data:[0,1,1,""],guild_id:[0,1,1,""],message_id:[0,1,1,""]},"discord.RawReactionActionEvent":{channel_id:[0,1,1,""],emoji:[0,1,1,""],event_type:[0,1,1,""],guild_id:[0,1,1,""],member:[0,1,1,""],message_id:[0,1,1,""],user_id:[0,1,1,""]},"discord.RawReactionClearEmojiEvent":{channel_id:[0,1,1,""],emoji:[0,1,1,""],guild_id:[0,1,1,""],message_id:[0,1,1,""]},"discord.RawReactionClearEvent":{channel_id:[0,1,1,""],guild_id:[0,1,1,""],message_id:[0,1,1,""]},"discord.RawTypingEvent":{channel_id:[0,1,1,""],guild_id:[0,1,1,""],member:[0,1,1,""],user_id:[0,1,1,""],when:[0,1,1,""]},"discord.Reaction":{clear:[0,3,1,""],count:[0,1,1,""],emoji:[0,1,1,""],is_custom_emoji:[0,3,1,""],me:[0,1,1,""],message:[0,1,1,""],remove:[0,3,1,""],users:[0,3,1,""]},"discord.Role":{"delete":[0,3,1,""],color:[0,2,1,""],colour:[0,2,1,""],created_at:[0,2,1,""],edit:[0,3,1,""],guild:[0,1,1,""],hoist:[0,1,1,""],id:[0,1,1,""],is_assignable:[0,3,1,""],is_bot_managed:[0,3,1,""],is_default:[0,3,1,""],is_integration:[0,3,1,""],is_premium_subscriber:[0,3,1,""],managed:[0,1,1,""],members:[0,2,1,""],mention:[0,2,1,""],mentionable:[0,1,1,""],name:[0,1,1,""],permissions:[0,2,1,""],position:[0,1,1,""],tags:[0,1,1,""]},"discord.RoleTags":{bot_id:[0,1,1,""],integration_id:[0,1,1,""],is_bot_managed:[0,3,1,""],is_integration:[0,3,1,""],is_premium_subscriber:[0,3,1,""]},"discord.SelectMenu":{custom_id:[0,1,1,""],disabled:[0,1,1,""],max_values:[0,1,1,""],min_values:[0,1,1,""],options:[0,1,1,""],placeholder:[0,1,1,""]},"discord.SelectOption":{"default":[0,1,1,""],description:[0,1,1,""],emoji:[0,1,1,""],label:[0,1,1,""],value:[0,1,1,""]},"discord.ShardInfo":{connect:[0,3,1,""],disconnect:[0,3,1,""],id:[0,1,1,""],is_closed:[0,3,1,""],is_ws_ratelimited:[0,3,1,""],latency:[0,2,1,""],reconnect:[0,3,1,""],shard_count:[0,1,1,""]},"discord.Spotify":{album:[0,2,1,""],album_cover_url:[0,2,1,""],artist:[0,2,1,""],artists:[0,2,1,""],color:[0,2,1,""],colour:[0,2,1,""],created_at:[0,2,1,""],duration:[0,2,1,""],end:[0,2,1,""],name:[0,2,1,""],party_id:[0,2,1,""],start:[0,2,1,""],title:[0,2,1,""],track_id:[0,2,1,""],track_url:[0,2,1,""],type:[0,2,1,""]},"discord.StageChannel":{"delete":[0,3,1,""],bitrate:[0,1,1,""],category:[0,2,1,""],category_id:[0,1,1,""],changed_roles:[0,2,1,""],clone:[0,3,1,""],connect:[0,3,1,""],create_instance:[0,3,1,""],create_invite:[0,3,1,""],created_at:[0,2,1,""],edit:[0,3,1,""],fetch_instance:[0,3,1,""],guild:[0,1,1,""],id:[0,1,1,""],instance:[0,2,1,""],invites:[0,3,1,""],listeners:[0,2,1,""],members:[0,2,1,""],mention:[0,2,1,""],moderators:[0,2,1,""],move:[0,3,1,""],name:[0,1,1,""],overwrites:[0,2,1,""],overwrites_for:[0,3,1,""],permissions_for:[0,3,1,""],permissions_synced:[0,2,1,""],position:[0,1,1,""],requesting_to_speak:[0,2,1,""],rtc_region:[0,1,1,""],set_permissions:[0,3,1,""],speakers:[0,2,1,""],topic:[0,1,1,""],type:[0,2,1,""],user_limit:[0,1,1,""],video_quality_mode:[0,1,1,""],voice_states:[0,2,1,""]},"discord.StageInstance":{"delete":[0,3,1,""],channel:[0,1,1,""],channel_id:[0,1,1,""],discoverable_disabled:[0,1,1,""],edit:[0,3,1,""],guild:[0,1,1,""],id:[0,1,1,""],privacy_level:[0,1,1,""],topic:[0,1,1,""]},"discord.StagePrivacyLevel":{"public":[0,1,1,""],closed:[0,1,1,""],guild_only:[0,1,1,""]},"discord.StandardSticker":{description:[0,1,1,""],format:[0,1,1,""],id:[0,1,1,""],name:[0,1,1,""],pack:[0,3,1,""],pack_id:[0,1,1,""],sort_value:[0,1,1,""],tags:[0,1,1,""]},"discord.Status":{dnd:[0,1,1,""],do_not_disturb:[0,1,1,""],idle:[0,1,1,""],invisible:[0,1,1,""],offline:[0,1,1,""],online:[0,1,1,""]},"discord.Sticker":{created_at:[0,2,1,""],description:[0,1,1,""],format:[0,1,1,""],id:[0,1,1,""],name:[0,1,1,""],pack_id:[0,1,1,""],url:[0,1,1,""]},"discord.StickerFormatType":{apng:[0,1,1,""],lottie:[0,1,1,""],png:[0,1,1,""]},"discord.StickerItem":{fetch:[0,3,1,""],format:[0,1,1,""],id:[0,1,1,""],name:[0,1,1,""],url:[0,1,1,""]},"discord.StickerPack":{banner:[0,2,1,""],cover_sticker:[0,1,1,""],cover_sticker_id:[0,1,1,""],description:[0,1,1,""],id:[0,1,1,""],name:[0,1,1,""],sku_id:[0,1,1,""],stickers:[0,1,1,""]},"discord.StickerType":{guild:[0,1,1,""],standard:[0,1,1,""]},"discord.StoreChannel":{"delete":[0,3,1,""],category:[0,2,1,""],category_id:[0,1,1,""],changed_roles:[0,2,1,""],clone:[0,3,1,""],create_invite:[0,3,1,""],created_at:[0,2,1,""],edit:[0,3,1,""],guild:[0,1,1,""],id:[0,1,1,""],invites:[0,3,1,""],is_nsfw:[0,3,1,""],mention:[0,2,1,""],move:[0,3,1,""],name:[0,1,1,""],nsfw:[0,1,1,""],overwrites:[0,2,1,""],overwrites_for:[0,3,1,""],permissions_for:[0,3,1,""],permissions_synced:[0,2,1,""],position:[0,1,1,""],set_permissions:[0,3,1,""],type:[0,2,1,""]},"discord.StreamIntegration":{account:[0,1,1,""],edit:[0,3,1,""],enable_emoticons:[0,1,1,""],enabled:[0,1,1,""],expire_behavior:[0,2,1,""],expire_behaviour:[0,1,1,""],expire_grace_period:[0,1,1,""],guild:[0,1,1,""],id:[0,1,1,""],name:[0,1,1,""],role:[0,2,1,""],sync:[0,3,1,""],synced_at:[0,1,1,""],syncing:[0,1,1,""],type:[0,1,1,""],user:[0,1,1,""]},"discord.Streaming":{assets:[0,1,1,""],details:[0,1,1,""],game:[0,1,1,""],name:[0,1,1,""],platform:[0,1,1,""],twitch_name:[0,2,1,""],type:[0,2,1,""],url:[0,1,1,""]},"discord.SyncWebhook":{"delete":[0,3,1,""],avatar:[0,2,1,""],channel:[0,2,1,""],channel_id:[0,1,1,""],created_at:[0,2,1,""],delete_message:[0,3,1,""],edit:[0,3,1,""],edit_message:[0,3,1,""],fetch:[0,3,1,""],fetch_message:[0,3,1,""],from_url:[0,3,1,""],guild:[0,2,1,""],guild_id:[0,1,1,""],id:[0,1,1,""],is_authenticated:[0,3,1,""],is_partial:[0,3,1,""],name:[0,1,1,""],partial:[0,3,1,""],send:[0,3,1,""],source_channel:[0,1,1,""],source_guild:[0,1,1,""],token:[0,1,1,""],type:[0,1,1,""],url:[0,2,1,""],user:[0,1,1,""]},"discord.SyncWebhookMessage":{"delete":[0,3,1,""],edit:[0,3,1,""]},"discord.SystemChannelFlags":{guild_reminder_notifications:[0,1,1,""],join_notifications:[0,1,1,""],premium_subscriptions:[0,1,1,""],value:[0,1,1,""]},"discord.Team":{icon:[0,2,1,""],id:[0,1,1,""],members:[0,1,1,""],name:[0,1,1,""],owner:[0,2,1,""],owner_id:[0,1,1,""]},"discord.TeamMember":{avatar:[0,1,1,""],bot:[0,1,1,""],discriminator:[0,1,1,""],id:[0,1,1,""],membership_state:[0,1,1,""],name:[0,1,1,""],team:[0,1,1,""]},"discord.TeamMembershipState":{accepted:[0,1,1,""],invited:[0,1,1,""]},"discord.Template":{"delete":[0,3,1,""],code:[0,1,1,""],create_guild:[0,3,1,""],created_at:[0,1,1,""],creator:[0,1,1,""],description:[0,1,1,""],edit:[0,3,1,""],is_dirty:[0,1,1,""],name:[0,1,1,""],source_guild:[0,1,1,""],sync:[0,3,1,""],updated_at:[0,1,1,""],url:[0,2,1,""],uses:[0,1,1,""]},"discord.TextChannel":{"delete":[0,3,1,""],archived_threads:[0,3,1,""],bots:[0,2,1,""],category:[0,2,1,""],category_id:[0,1,1,""],changed_roles:[0,2,1,""],clone:[0,3,1,""],create_invite:[0,3,1,""],create_thread:[0,3,1,""],create_webhook:[0,3,1,""],created_at:[0,2,1,""],default_auto_archive_duration:[0,1,1,""],delete_messages:[0,3,1,""],edit:[0,3,1,""],fetch_message:[0,3,1,""],follow:[0,3,1,""],get_partial_message:[0,3,1,""],get_thread:[0,3,1,""],guild:[0,1,1,""],history:[0,3,1,""],humans:[0,2,1,""],id:[0,1,1,""],invites:[0,3,1,""],is_news:[0,3,1,""],is_nsfw:[0,3,1,""],last_message:[0,2,1,""],last_message_id:[0,1,1,""],members:[0,2,1,""],mention:[0,2,1,""],move:[0,3,1,""],name:[0,1,1,""],nsfw:[0,1,1,""],overwrites:[0,2,1,""],overwrites_for:[0,3,1,""],permissions_for:[0,3,1,""],permissions_synced:[0,2,1,""],pins:[0,3,1,""],position:[0,1,1,""],purge:[0,3,1,""],send:[0,3,1,""],set_permissions:[0,3,1,""],slowmode_delay:[0,1,1,""],threads:[0,2,1,""],topic:[0,1,1,""],trigger_typing:[0,3,1,""],type:[0,2,1,""],typing:[0,3,1,""],webhooks:[0,3,1,""]},"discord.Thread":{"delete":[0,3,1,""],add_user:[0,3,1,""],archive_timestamp:[0,1,1,""],archived:[0,1,1,""],archiver_id:[0,1,1,""],auto_archive_duration:[0,1,1,""],category:[0,2,1,""],category_id:[0,2,1,""],delete_messages:[0,3,1,""],edit:[0,3,1,""],fetch_members:[0,3,1,""],fetch_message:[0,3,1,""],get_partial_message:[0,3,1,""],guild:[0,1,1,""],history:[0,3,1,""],id:[0,1,1,""],invitable:[0,1,1,""],is_news:[0,3,1,""],is_nsfw:[0,3,1,""],is_private:[0,3,1,""],join:[0,3,1,""],last_message:[0,2,1,""],last_message_id:[0,1,1,""],leave:[0,3,1,""],locked:[0,1,1,""],me:[0,1,1,""],member_count:[0,1,1,""],members:[0,2,1,""],mention:[0,2,1,""],message_count:[0,1,1,""],name:[0,1,1,""],owner:[0,2,1,""],owner_id:[0,1,1,""],parent:[0,2,1,""],parent_id:[0,1,1,""],permissions_for:[0,3,1,""],pins:[0,3,1,""],purge:[0,3,1,""],remove_user:[0,3,1,""],send:[0,3,1,""],slowmode_delay:[0,1,1,""],trigger_typing:[0,3,1,""],type:[0,2,1,""],typing:[0,3,1,""]},"discord.ThreadMember":{fetch_member:[0,3,1,""],get_member:[0,3,1,""],id:[0,1,1,""],joined_at:[0,1,1,""],thread:[0,2,1,""],thread_id:[0,1,1,""]},"discord.User":{accent_color:[0,2,1,""],accent_colour:[0,2,1,""],avatar:[0,2,1,""],banner:[0,2,1,""],bot:[0,1,1,""],color:[0,2,1,""],colour:[0,2,1,""],create_dm:[0,3,1,""],created_at:[0,2,1,""],default_avatar:[0,2,1,""],discriminator:[0,1,1,""],display_avatar:[0,2,1,""],display_name:[0,2,1,""],dm_channel:[0,2,1,""],fetch_message:[0,3,1,""],history:[0,3,1,""],id:[0,1,1,""],mention:[0,2,1,""],mentioned_in:[0,3,1,""],mutual_guilds:[0,2,1,""],name:[0,1,1,""],pins:[0,3,1,""],public_flags:[0,2,1,""],send:[0,3,1,""],system:[0,1,1,""],trigger_typing:[0,3,1,""],typing:[0,3,1,""]},"discord.UserFlags":{bug_hunter:[0,1,1,""],bug_hunter_level_2:[0,1,1,""],discord_certified_moderator:[0,1,1,""],early_supporter:[0,1,1,""],has_unread_urgent_messages:[0,1,1,""],hypesquad:[0,1,1,""],hypesquad_balance:[0,1,1,""],hypesquad_bravery:[0,1,1,""],hypesquad_brilliance:[0,1,1,""],mfa_sms:[0,1,1,""],partner:[0,1,1,""],premium_promo_dismissed:[0,1,1,""],staff:[0,1,1,""],system:[0,1,1,""],team_user:[0,1,1,""],verified_bot:[0,1,1,""],verified_bot_developer:[0,1,1,""]},"discord.VerificationLevel":{high:[0,1,1,""],highest:[0,1,1,""],low:[0,1,1,""],medium:[0,1,1,""],none:[0,1,1,""]},"discord.VideoQualityMode":{auto:[0,1,1,""],full:[0,1,1,""]},"discord.VoiceChannel":{"delete":[0,3,1,""],bitrate:[0,1,1,""],category:[0,2,1,""],category_id:[0,1,1,""],changed_roles:[0,2,1,""],clone:[0,3,1,""],connect:[0,3,1,""],create_invite:[0,3,1,""],created_at:[0,2,1,""],edit:[0,3,1,""],guild:[0,1,1,""],id:[0,1,1,""],invites:[0,3,1,""],members:[0,2,1,""],mention:[0,2,1,""],move:[0,3,1,""],name:[0,1,1,""],overwrites:[0,2,1,""],overwrites_for:[0,3,1,""],permissions_for:[0,3,1,""],permissions_synced:[0,2,1,""],position:[0,1,1,""],rtc_region:[0,1,1,""],set_permissions:[0,3,1,""],type:[0,2,1,""],user_limit:[0,1,1,""],video_quality_mode:[0,1,1,""],voice_states:[0,2,1,""]},"discord.VoiceClient":{average_latency:[0,2,1,""],channel:[0,1,1,""],disconnect:[0,3,1,""],endpoint:[0,1,1,""],guild:[0,2,1,""],is_connected:[0,3,1,""],is_paused:[0,3,1,""],is_playing:[0,3,1,""],latency:[0,2,1,""],loop:[0,1,1,""],move_to:[0,3,1,""],pause:[0,3,1,""],play:[0,3,1,""],resume:[0,3,1,""],send_audio_packet:[0,3,1,""],session_id:[0,1,1,""],source:[0,2,1,""],stop:[0,3,1,""],token:[0,1,1,""],user:[0,2,1,""]},"discord.VoiceProtocol":{cleanup:[0,3,1,""],connect:[0,3,1,""],disconnect:[0,3,1,""],on_voice_server_update:[0,3,1,""],on_voice_state_update:[0,3,1,""]},"discord.VoiceRegion":{amsterdam:[0,1,1,""],brazil:[0,1,1,""],dubai:[0,1,1,""],eu_central:[0,1,1,""],eu_west:[0,1,1,""],europe:[0,1,1,""],frankfurt:[0,1,1,""],hongkong:[0,1,1,""],india:[0,1,1,""],japan:[0,1,1,""],london:[0,1,1,""],russia:[0,1,1,""],singapore:[0,1,1,""],south_korea:[0,1,1,""],southafrica:[0,1,1,""],sydney:[0,1,1,""],us_central:[0,1,1,""],us_east:[0,1,1,""],us_south:[0,1,1,""],us_west:[0,1,1,""],vip_amsterdam:[0,1,1,""],vip_us_east:[0,1,1,""],vip_us_west:[0,1,1,""]},"discord.VoiceState":{afk:[0,1,1,""],channel:[0,1,1,""],deaf:[0,1,1,""],mute:[0,1,1,""],requested_to_speak_at:[0,1,1,""],self_deaf:[0,1,1,""],self_mute:[0,1,1,""],self_stream:[0,1,1,""],self_video:[0,1,1,""],suppress:[0,1,1,""]},"discord.Webhook":{"delete":[0,3,1,""],avatar:[0,2,1,""],channel:[0,2,1,""],channel_id:[0,1,1,""],created_at:[0,2,1,""],delete_message:[0,3,1,""],edit:[0,3,1,""],edit_message:[0,3,1,""],fetch:[0,3,1,""],fetch_message:[0,3,1,""],from_url:[0,3,1,""],guild:[0,2,1,""],guild_id:[0,1,1,""],id:[0,1,1,""],is_authenticated:[0,3,1,""],is_partial:[0,3,1,""],name:[0,1,1,""],partial:[0,3,1,""],send:[0,3,1,""],source_channel:[0,1,1,""],source_guild:[0,1,1,""],token:[0,1,1,""],type:[0,1,1,""],url:[0,2,1,""],user:[0,1,1,""]},"discord.WebhookMessage":{"delete":[0,3,1,""],edit:[0,3,1,""]},"discord.WebhookType":{application:[0,1,1,""],channel_follower:[0,1,1,""],incoming:[0,1,1,""]},"discord.Widget":{channels:[0,1,1,""],created_at:[0,2,1,""],fetch_invite:[0,3,1,""],id:[0,1,1,""],invite_url:[0,2,1,""],json_url:[0,2,1,""],members:[0,1,1,""],name:[0,1,1,""]},"discord.WidgetChannel":{created_at:[0,2,1,""],id:[0,1,1,""],mention:[0,2,1,""],name:[0,1,1,""],position:[0,1,1,""]},"discord.WidgetMember":{accent_color:[0,2,1,""],accent_colour:[0,2,1,""],activity:[0,1,1,""],avatar:[0,1,1,""],banner:[0,2,1,""],bot:[0,1,1,""],color:[0,2,1,""],colour:[0,2,1,""],connected_channel:[0,1,1,""],created_at:[0,2,1,""],deafened:[0,1,1,""],default_avatar:[0,2,1,""],discriminator:[0,1,1,""],display_avatar:[0,2,1,""],display_name:[0,2,1,""],id:[0,1,1,""],mention:[0,2,1,""],mentioned_in:[0,3,1,""],muted:[0,1,1,""],name:[0,1,1,""],nick:[0,1,1,""],public_flags:[0,2,1,""],status:[0,1,1,""],suppress:[0,1,1,""]},"discord.abc":{Connectable:[0,0,1,""],GuildChannel:[0,0,1,""],Messageable:[0,0,1,""],PrivateChannel:[0,0,1,""],Snowflake:[0,0,1,""],User:[0,0,1,""]},"discord.abc.GuildChannel":{"delete":[0,3,1,""],category:[0,2,1,""],changed_roles:[0,2,1,""],clone:[0,3,1,""],create_invite:[0,3,1,""],created_at:[0,2,1,""],guild:[0,1,1,""],invites:[0,3,1,""],mention:[0,2,1,""],move:[0,3,1,""],name:[0,1,1,""],overwrites:[0,2,1,""],overwrites_for:[0,3,1,""],permissions_for:[0,3,1,""],permissions_synced:[0,2,1,""],position:[0,1,1,""],set_permissions:[0,3,1,""]},"discord.abc.Messageable":{fetch_message:[0,3,1,""],history:[0,3,1,""],pins:[0,3,1,""],send:[0,3,1,""],trigger_typing:[0,3,1,""],typing:[0,3,1,""]},"discord.abc.PrivateChannel":{me:[0,1,1,""]},"discord.abc.Snowflake":{id:[0,1,1,""]},"discord.abc.User":{avatar:[0,1,1,""],bot:[0,1,1,""],discriminator:[0,1,1,""],display_name:[0,2,1,""],mention:[0,2,1,""],name:[0,1,1,""]},"discord.discord.ext.commands":{on_command:[2,6,1,""],on_command_completion:[2,6,1,""],on_command_error:[2,6,1,""]},"discord.ext.commands":{ArgumentParsingError:[2,4,1,""],AutoShardedBot:[2,0,1,""],BadArgument:[2,4,1,""],BadBoolArgument:[2,4,1,""],BadColourArgument:[2,4,1,""],BadFlagArgument:[2,4,1,""],BadInviteArgument:[2,4,1,""],BadLiteralArgument:[2,4,1,""],BadUnionArgument:[2,4,1,""],Bot:[2,0,1,""],BotMissingAnyRole:[2,4,1,""],BotMissingPermissions:[2,4,1,""],BotMissingRole:[2,4,1,""],BucketType:[2,0,1,""],CategoryChannelConverter:[2,0,1,""],ChannelNotFound:[2,4,1,""],ChannelNotReadable:[2,4,1,""],CheckAnyFailure:[2,4,1,""],CheckFailure:[2,4,1,""],Cog:[2,0,1,""],CogMeta:[2,0,1,""],ColourConverter:[2,0,1,""],Command:[2,0,1,""],CommandError:[2,4,1,""],CommandInvokeError:[2,4,1,""],CommandNotFound:[2,4,1,""],CommandOnCooldown:[2,4,1,""],CommandRegistrationError:[2,4,1,""],Context:[2,0,1,""],ConversionError:[2,4,1,""],Converter:[2,0,1,""],Cooldown:[2,0,1,""],DefaultHelpCommand:[2,0,1,""],DisabledCommand:[2,4,1,""],EmojiConverter:[2,0,1,""],EmojiNotFound:[2,4,1,""],ExpectedClosingQuoteError:[2,4,1,""],ExtensionAlreadyLoaded:[2,4,1,""],ExtensionError:[2,4,1,""],ExtensionFailed:[2,4,1,""],ExtensionNotFound:[2,4,1,""],ExtensionNotLoaded:[2,4,1,""],Flag:[2,0,1,""],FlagConverter:[2,0,1,""],FlagError:[2,4,1,""],GameConverter:[2,0,1,""],Greedy:[2,0,1,""],Group:[2,0,1,""],GroupMixin:[2,0,1,""],GuildChannelConverter:[2,0,1,""],GuildConverter:[2,0,1,""],GuildNotFound:[2,4,1,""],GuildStickerConverter:[2,0,1,""],GuildStickerNotFound:[2,4,1,""],HelpCommand:[2,0,1,""],InvalidEndOfQuotedStringError:[2,4,1,""],InviteConverter:[2,0,1,""],MaxConcurrencyReached:[2,4,1,""],MemberConverter:[2,0,1,""],MemberNotFound:[2,4,1,""],MessageConverter:[2,0,1,""],MessageNotFound:[2,4,1,""],MinimalHelpCommand:[2,0,1,""],MissingAnyRole:[2,4,1,""],MissingFlagArgument:[2,4,1,""],MissingPermissions:[2,4,1,""],MissingRequiredArgument:[2,4,1,""],MissingRequiredFlag:[2,4,1,""],MissingRole:[2,4,1,""],NSFWChannelRequired:[2,4,1,""],NoEntryPointError:[2,4,1,""],NoPrivateMessage:[2,4,1,""],NotOwner:[2,4,1,""],ObjectConverter:[2,0,1,""],Option:[2,0,1,""],Paginator:[2,0,1,""],PartialEmojiConversionFailure:[2,4,1,""],PartialEmojiConverter:[2,0,1,""],PartialMessageConverter:[2,0,1,""],PrivateMessageOnly:[2,4,1,""],RoleConverter:[2,0,1,""],RoleNotFound:[2,4,1,""],StageChannelConverter:[2,0,1,""],StoreChannelConverter:[2,0,1,""],TextChannelConverter:[2,0,1,""],ThreadConverter:[2,0,1,""],ThreadNotFound:[2,4,1,""],TooManyArguments:[2,4,1,""],TooManyFlags:[2,4,1,""],UnexpectedQuoteError:[2,4,1,""],UserConverter:[2,0,1,""],UserInputError:[2,4,1,""],UserNotFound:[2,4,1,""],VoiceChannelConverter:[2,0,1,""],after_invoke:[2,6,1,""],before_invoke:[2,6,1,""],bot_has_any_role:[2,6,1,""],bot_has_guild_permissions:[2,6,1,""],bot_has_permissions:[2,6,1,""],bot_has_role:[2,6,1,""],check:[2,6,1,""],check_any:[2,6,1,""],clean_content:[2,0,1,""],command:[2,6,1,""],cooldown:[2,6,1,""],dm_only:[2,6,1,""],dynamic_cooldown:[2,6,1,""],flag:[2,6,1,""],group:[2,6,1,""],guild_only:[2,6,1,""],has_any_role:[2,6,1,""],has_guild_permissions:[2,6,1,""],has_permissions:[2,6,1,""],has_role:[2,6,1,""],is_nsfw:[2,6,1,""],is_owner:[2,6,1,""],max_concurrency:[2,6,1,""],run_converters:[2,6,1,""],when_mentioned:[2,6,1,""],when_mentioned_or:[2,6,1,""]},"discord.ext.commands.BadBoolArgument":{argument:[2,1,1,""]},"discord.ext.commands.BadColourArgument":{argument:[2,1,1,""]},"discord.ext.commands.BadFlagArgument":{flag:[2,1,1,""]},"discord.ext.commands.BadInviteArgument":{argument:[2,1,1,""]},"discord.ext.commands.BadLiteralArgument":{errors:[2,1,1,""],literals:[2,1,1,""],param:[2,1,1,""]},"discord.ext.commands.BadUnionArgument":{converters:[2,1,1,""],errors:[2,1,1,""],param:[2,1,1,""]},"discord.ext.commands.Bot":{activity:[2,2,1,""],add_check:[2,3,1,""],add_cog:[2,3,1,""],add_command:[2,3,1,""],add_listener:[2,3,1,""],add_view:[2,3,1,""],after_invoke:[2,3,1,""],allowed_mentions:[2,2,1,""],application_flags:[2,2,1,""],application_id:[2,2,1,""],application_info:[2,3,1,""],before_identify_hook:[2,3,1,""],before_invoke:[2,3,1,""],cached_messages:[2,2,1,""],case_insensitive:[2,1,1,""],change_presence:[2,3,1,""],check:[2,3,1,""],check_once:[2,3,1,""],clear:[2,3,1,""],close:[2,3,1,""],cogs:[2,2,1,""],command:[2,3,1,""],command_prefix:[2,1,1,""],commands:[2,2,1,""],connect:[2,3,1,""],create_dm:[2,3,1,""],create_guild:[2,3,1,""],delete_invite:[2,3,1,""],description:[2,1,1,""],emojis:[2,2,1,""],event:[2,3,1,""],extensions:[2,2,1,""],fetch_channel:[2,3,1,""],fetch_guild:[2,3,1,""],fetch_guilds:[2,3,1,""],fetch_invite:[2,3,1,""],fetch_premium_sticker_packs:[2,3,1,""],fetch_stage_instance:[2,3,1,""],fetch_sticker:[2,3,1,""],fetch_template:[2,3,1,""],fetch_user:[2,3,1,""],fetch_webhook:[2,3,1,""],fetch_widget:[2,3,1,""],get_all_channels:[2,3,1,""],get_all_members:[2,3,1,""],get_channel:[2,3,1,""],get_cog:[2,3,1,""],get_command:[2,3,1,""],get_context:[2,3,1,""],get_emoji:[2,3,1,""],get_guild:[2,3,1,""],get_partial_messageable:[2,3,1,""],get_prefix:[2,3,1,""],get_stage_instance:[2,3,1,""],get_sticker:[2,3,1,""],get_user:[2,3,1,""],group:[2,3,1,""],guilds:[2,2,1,""],help_command:[2,1,1,""],intents:[2,2,1,""],invoke:[2,3,1,""],is_closed:[2,3,1,""],is_owner:[2,3,1,""],is_ready:[2,3,1,""],is_ws_ratelimited:[2,3,1,""],latency:[2,2,1,""],listen:[2,3,1,""],load_extension:[2,3,1,""],login:[2,3,1,""],message_commands:[2,1,1,""],on_command_error:[2,3,1,""],on_error:[2,3,1,""],owner_id:[2,1,1,""],owner_ids:[2,1,1,""],persistent_views:[2,2,1,""],populate_owners:[2,3,1,""],private_channels:[2,2,1,""],process_commands:[2,3,1,""],process_slash_commands:[2,3,1,""],reload_extension:[2,3,1,""],remove_check:[2,3,1,""],remove_cog:[2,3,1,""],remove_command:[2,3,1,""],remove_listener:[2,3,1,""],run:[2,3,1,""],setup:[2,3,1,""],slash_command_guilds:[2,1,1,""],slash_commands:[2,1,1,""],start:[2,3,1,""],status:[2,2,1,""],stickers:[2,2,1,""],strip_after_prefix:[2,1,1,""],try_owners:[2,3,1,""],try_user:[2,3,1,""],unload_extension:[2,3,1,""],user:[2,2,1,""],users:[2,2,1,""],voice_clients:[2,2,1,""],wait_for:[2,3,1,""],wait_until_ready:[2,3,1,""],walk_commands:[2,3,1,""]},"discord.ext.commands.BotMissingAnyRole":{missing_roles:[2,1,1,""]},"discord.ext.commands.BotMissingPermissions":{missing_permissions:[2,1,1,""]},"discord.ext.commands.BotMissingRole":{missing_role:[2,1,1,""]},"discord.ext.commands.BucketType":{"default":[2,1,1,""],category:[2,1,1,""],channel:[2,1,1,""],guild:[2,1,1,""],member:[2,1,1,""],role:[2,1,1,""],user:[2,1,1,""]},"discord.ext.commands.CategoryChannelConverter":{convert:[2,3,1,""]},"discord.ext.commands.ChannelNotFound":{argument:[2,1,1,""]},"discord.ext.commands.ChannelNotReadable":{argument:[2,1,1,""]},"discord.ext.commands.CheckAnyFailure":{checks:[2,1,1,""],errors:[2,1,1,""]},"discord.ext.commands.Cog":{bot_check:[2,3,1,""],bot_check_once:[2,3,1,""],cog_after_invoke:[2,3,1,""],cog_before_invoke:[2,3,1,""],cog_check:[2,3,1,""],cog_command_error:[2,3,1,""],cog_unload:[2,3,1,""],description:[2,2,1,""],get_commands:[2,3,1,""],get_listeners:[2,3,1,""],has_error_handler:[2,3,1,""],listener:[2,3,1,""],qualified_name:[2,2,1,""],walk_commands:[2,3,1,""]},"discord.ext.commands.CogMeta":{command_attrs:[2,1,1,""],description:[2,1,1,""],name:[2,1,1,""]},"discord.ext.commands.ColourConverter":{convert:[2,3,1,""]},"discord.ext.commands.Command":{__call__:[2,3,1,""],add_check:[2,3,1,""],after_invoke:[2,3,1,""],aliases:[2,1,1,""],before_invoke:[2,3,1,""],brief:[2,1,1,""],callback:[2,1,1,""],can_run:[2,3,1,""],checks:[2,1,1,""],clean_params:[2,2,1,""],cog:[2,1,1,""],cog_name:[2,2,1,""],cooldown_after_parsing:[2,1,1,""],copy:[2,3,1,""],description:[2,1,1,""],enabled:[2,1,1,""],error:[2,3,1,""],extras:[2,1,1,""],full_parent_name:[2,2,1,""],get_cooldown_retry_after:[2,3,1,""],has_error_handler:[2,3,1,""],help:[2,1,1,""],hidden:[2,1,1,""],ignore_extra:[2,1,1,""],invoked_subcommand:[2,1,1,""],is_on_cooldown:[2,3,1,""],message_command:[2,1,1,""],name:[2,1,1,""],option_descriptions:[2,1,1,""],parent:[2,1,1,""],parents:[2,2,1,""],qualified_name:[2,2,1,""],remove_check:[2,3,1,""],require_var_positional:[2,1,1,""],reset_cooldown:[2,3,1,""],rest_is_raw:[2,1,1,""],root_parent:[2,2,1,""],short_doc:[2,2,1,""],signature:[2,2,1,""],slash_command:[2,1,1,""],slash_command_guilds:[2,1,1,""],update:[2,3,1,""],usage:[2,1,1,""]},"discord.ext.commands.CommandInvokeError":{original:[2,1,1,""]},"discord.ext.commands.CommandOnCooldown":{cooldown:[2,1,1,""],retry_after:[2,1,1,""],type:[2,1,1,""]},"discord.ext.commands.CommandRegistrationError":{alias_conflict:[2,1,1,""],name:[2,1,1,""]},"discord.ext.commands.Context":{args:[2,1,1,""],author:[2,1,1,""],author_permissions:[2,3,1,""],bot:[2,1,1,""],channel:[2,1,1,""],clean_prefix:[2,2,1,""],cog:[2,2,1,""],command:[2,1,1,""],command_failed:[2,1,1,""],current_parameter:[2,1,1,""],fetch_message:[2,3,1,""],guild:[2,1,1,""],history:[2,3,1,""],invoke:[2,3,1,""],invoked_parents:[2,1,1,""],invoked_subcommand:[2,1,1,""],invoked_with:[2,1,1,""],kwargs:[2,1,1,""],me:[2,1,1,""],message:[2,1,1,""],pins:[2,3,1,""],prefix:[2,1,1,""],reinvoke:[2,3,1,""],reply:[2,3,1,""],send:[2,3,1,""],send_help:[2,3,1,""],subcommand_passed:[2,1,1,""],trigger_typing:[2,3,1,""],typing:[2,3,1,""],valid:[2,2,1,""],voice_client:[2,2,1,""]},"discord.ext.commands.ConversionError":{converter:[2,1,1,""],original:[2,1,1,""]},"discord.ext.commands.Converter":{convert:[2,3,1,""]},"discord.ext.commands.Cooldown":{copy:[2,3,1,""],get_retry_after:[2,3,1,""],get_tokens:[2,3,1,""],per:[2,1,1,""],rate:[2,1,1,""],reset:[2,3,1,""],update_rate_limit:[2,3,1,""]},"discord.ext.commands.DefaultHelpCommand":{add_command_formatting:[2,3,1,""],add_indented_commands:[2,3,1,""],commands_heading:[2,1,1,""],dm_help:[2,1,1,""],dm_help_threshold:[2,1,1,""],get_destination:[2,3,1,""],get_ending_note:[2,3,1,""],indent:[2,1,1,""],no_category:[2,1,1,""],paginator:[2,1,1,""],send_pages:[2,3,1,""],shorten_text:[2,3,1,""],sort_commands:[2,1,1,""],width:[2,1,1,""]},"discord.ext.commands.EmojiConverter":{convert:[2,3,1,""]},"discord.ext.commands.EmojiNotFound":{argument:[2,1,1,""]},"discord.ext.commands.ExpectedClosingQuoteError":{close_quote:[2,1,1,""]},"discord.ext.commands.ExtensionError":{name:[2,1,1,""]},"discord.ext.commands.ExtensionFailed":{name:[2,1,1,""],original:[2,1,1,""]},"discord.ext.commands.ExtensionNotFound":{name:[2,1,1,""]},"discord.ext.commands.Flag":{"default":[2,1,1,""],aliases:[2,1,1,""],annotation:[2,1,1,""],attribute:[2,1,1,""],max_args:[2,1,1,""],name:[2,1,1,""],override:[2,1,1,""],required:[2,2,1,""]},"discord.ext.commands.FlagConverter":{convert:[2,3,1,""],get_flags:[2,3,1,""]},"discord.ext.commands.GameConverter":{convert:[2,3,1,""]},"discord.ext.commands.Group":{add_check:[2,3,1,""],add_command:[2,3,1,""],after_invoke:[2,3,1,""],before_invoke:[2,3,1,""],can_run:[2,3,1,""],case_insensitive:[2,1,1,""],clean_params:[2,2,1,""],cog_name:[2,2,1,""],command:[2,3,1,""],commands:[2,2,1,""],copy:[2,3,1,""],error:[2,3,1,""],full_parent_name:[2,2,1,""],get_command:[2,3,1,""],get_cooldown_retry_after:[2,3,1,""],group:[2,3,1,""],has_error_handler:[2,3,1,""],invoke_without_command:[2,1,1,""],is_on_cooldown:[2,3,1,""],parents:[2,2,1,""],qualified_name:[2,2,1,""],remove_check:[2,3,1,""],remove_command:[2,3,1,""],reset_cooldown:[2,3,1,""],root_parent:[2,2,1,""],short_doc:[2,2,1,""],signature:[2,2,1,""],update:[2,3,1,""],walk_commands:[2,3,1,""]},"discord.ext.commands.GroupMixin":{add_command:[2,3,1,""],all_commands:[2,1,1,""],case_insensitive:[2,1,1,""],command:[2,3,1,""],commands:[2,2,1,""],get_command:[2,3,1,""],group:[2,3,1,""],remove_command:[2,3,1,""],walk_commands:[2,3,1,""]},"discord.ext.commands.GuildChannelConverter":{convert:[2,3,1,""]},"discord.ext.commands.GuildConverter":{convert:[2,3,1,""]},"discord.ext.commands.GuildNotFound":{argument:[2,1,1,""]},"discord.ext.commands.GuildStickerConverter":{convert:[2,3,1,""]},"discord.ext.commands.GuildStickerNotFound":{argument:[2,1,1,""]},"discord.ext.commands.HelpCommand":{add_check:[2,3,1,""],cog:[2,2,1,""],command_attrs:[2,1,1,""],command_callback:[2,3,1,""],command_not_found:[2,3,1,""],context:[2,1,1,""],filter_commands:[2,3,1,""],get_bot_mapping:[2,3,1,""],get_command_signature:[2,3,1,""],get_destination:[2,3,1,""],get_max_size:[2,3,1,""],invoked_with:[2,2,1,""],on_help_command_error:[2,3,1,""],prepare_help_command:[2,3,1,""],remove_check:[2,3,1,""],remove_mentions:[2,3,1,""],send_bot_help:[2,3,1,""],send_cog_help:[2,3,1,""],send_command_help:[2,3,1,""],send_error_message:[2,3,1,""],send_group_help:[2,3,1,""],show_hidden:[2,1,1,""],subcommand_not_found:[2,3,1,""],verify_checks:[2,1,1,""]},"discord.ext.commands.InvalidEndOfQuotedStringError":{"char":[2,1,1,""]},"discord.ext.commands.InviteConverter":{convert:[2,3,1,""]},"discord.ext.commands.MaxConcurrencyReached":{number:[2,1,1,""],per:[2,1,1,""]},"discord.ext.commands.MemberConverter":{convert:[2,3,1,""]},"discord.ext.commands.MemberNotFound":{argument:[2,1,1,""]},"discord.ext.commands.MessageConverter":{convert:[2,3,1,""]},"discord.ext.commands.MessageNotFound":{argument:[2,1,1,""]},"discord.ext.commands.MinimalHelpCommand":{add_aliases_formatting:[2,3,1,""],add_bot_commands_formatting:[2,3,1,""],add_command_formatting:[2,3,1,""],add_subcommand_formatting:[2,3,1,""],aliases_heading:[2,1,1,""],commands_heading:[2,1,1,""],dm_help:[2,1,1,""],dm_help_threshold:[2,1,1,""],get_command_signature:[2,3,1,""],get_destination:[2,3,1,""],get_ending_note:[2,3,1,""],get_opening_note:[2,3,1,""],no_category:[2,1,1,""],paginator:[2,1,1,""],send_pages:[2,3,1,""],sort_commands:[2,1,1,""]},"discord.ext.commands.MissingAnyRole":{missing_roles:[2,1,1,""]},"discord.ext.commands.MissingFlagArgument":{flag:[2,1,1,""]},"discord.ext.commands.MissingPermissions":{missing_permissions:[2,1,1,""]},"discord.ext.commands.MissingRequiredArgument":{param:[2,1,1,""]},"discord.ext.commands.MissingRequiredFlag":{flag:[2,1,1,""]},"discord.ext.commands.MissingRole":{missing_role:[2,1,1,""]},"discord.ext.commands.ObjectConverter":{convert:[2,3,1,""]},"discord.ext.commands.Option":{"default":[2,1,1,""],description:[2,1,1,""]},"discord.ext.commands.Paginator":{add_line:[2,3,1,""],clear:[2,3,1,""],close_page:[2,3,1,""],linesep:[2,1,1,""],max_size:[2,1,1,""],pages:[2,2,1,""],prefix:[2,1,1,""],suffix:[2,1,1,""]},"discord.ext.commands.PartialEmojiConversionFailure":{argument:[2,1,1,""]},"discord.ext.commands.PartialEmojiConverter":{convert:[2,3,1,""]},"discord.ext.commands.PartialMessageConverter":{convert:[2,3,1,""]},"discord.ext.commands.RoleConverter":{convert:[2,3,1,""]},"discord.ext.commands.RoleNotFound":{argument:[2,1,1,""]},"discord.ext.commands.StageChannelConverter":{convert:[2,3,1,""]},"discord.ext.commands.StoreChannelConverter":{convert:[2,3,1,""]},"discord.ext.commands.TextChannelConverter":{convert:[2,3,1,""]},"discord.ext.commands.ThreadConverter":{convert:[2,3,1,""]},"discord.ext.commands.ThreadNotFound":{argument:[2,1,1,""]},"discord.ext.commands.TooManyFlags":{flag:[2,1,1,""],values:[2,1,1,""]},"discord.ext.commands.UnexpectedQuoteError":{quote:[2,1,1,""]},"discord.ext.commands.UserConverter":{convert:[2,3,1,""]},"discord.ext.commands.UserNotFound":{argument:[2,1,1,""]},"discord.ext.commands.VoiceChannelConverter":{convert:[2,3,1,""]},"discord.ext.commands.clean_content":{convert:[2,3,1,""],escape_markdown:[2,1,1,""],fix_channel_mentions:[2,1,1,""],remove_markdown:[2,1,1,""],use_nicknames:[2,1,1,""]},"discord.ext.tasks":{Loop:[8,0,1,""],loop:[8,6,1,""]},"discord.ext.tasks.Loop":{__call__:[8,3,1,""],add_exception_type:[8,3,1,""],after_loop:[8,3,1,""],before_loop:[8,3,1,""],cancel:[8,3,1,""],change_interval:[8,3,1,""],clear_exception_types:[8,3,1,""],current_loop:[8,2,1,""],error:[8,3,1,""],failed:[8,3,1,""],get_task:[8,3,1,""],hours:[8,2,1,""],is_being_cancelled:[8,3,1,""],is_running:[8,3,1,""],minutes:[8,2,1,""],next_iteration:[8,2,1,""],remove_exception_type:[8,3,1,""],restart:[8,3,1,""],seconds:[8,2,1,""],start:[8,3,1,""],stop:[8,3,1,""],time:[8,2,1,""]},"discord.opus":{OpusError:[0,4,1,""],OpusNotLoaded:[0,4,1,""],is_loaded:[0,6,1,""],load_opus:[0,6,1,""]},"discord.opus.OpusError":{code:[0,1,1,""]},"discord.ui":{Button:[0,0,1,""],Item:[0,0,1,""],Select:[0,0,1,""],View:[0,0,1,""],button:[0,6,1,""],select:[0,6,1,""]},"discord.ui.Button":{callback:[0,3,1,""],custom_id:[0,2,1,""],disabled:[0,2,1,""],emoji:[0,2,1,""],label:[0,2,1,""],style:[0,2,1,""],url:[0,2,1,""],view:[0,2,1,""]},"discord.ui.Item":{callback:[0,3,1,""],view:[0,2,1,""]},"discord.ui.Select":{add_option:[0,3,1,""],append_option:[0,3,1,""],callback:[0,3,1,""],custom_id:[0,2,1,""],disabled:[0,2,1,""],max_values:[0,2,1,""],min_values:[0,2,1,""],options:[0,2,1,""],placeholder:[0,2,1,""],values:[0,2,1,""],view:[0,2,1,""]},"discord.ui.View":{add_item:[0,3,1,""],children:[0,1,1,""],clear_items:[0,3,1,""],from_message:[0,3,1,""],interaction_check:[0,3,1,""],is_dispatching:[0,3,1,""],is_finished:[0,3,1,""],is_persistent:[0,3,1,""],on_error:[0,3,1,""],on_timeout:[0,3,1,""],remove_item:[0,3,1,""],stop:[0,3,1,""],timeout:[0,1,1,""],wait:[0,3,1,""]},"discord.utils":{as_chunks:[0,6,1,""],escape_markdown:[0,6,1,""],escape_mentions:[0,6,1,""],find:[0,6,1,""],format_dt:[0,6,1,""],get:[0,6,1,""],oauth_url:[0,6,1,""],remove_markdown:[0,6,1,""],resolve_invite:[0,6,1,""],resolve_template:[0,6,1,""],sleep_until:[0,6,1,""],snowflake_time:[0,6,1,""],utcnow:[0,6,1,""]},discord:{ActionRow:[0,0,1,""],Activity:[0,0,1,""],ActivityType:[0,0,1,""],AllowedMentions:[0,0,1,""],AppInfo:[0,0,1,""],ApplicationFlags:[0,0,1,""],Asset:[0,0,1,""],AsyncIterator:[0,0,1,""],Attachment:[0,0,1,""],AudioSource:[0,0,1,""],AuditLogAction:[0,0,1,""],AuditLogActionCategory:[0,0,1,""],AuditLogChanges:[0,0,1,""],AuditLogDiff:[0,0,1,""],AuditLogEntry:[0,0,1,""],AutoShardedClient:[0,0,1,""],BanEntry:[0,0,1,""],BaseActivity:[0,0,1,""],BotIntegration:[0,0,1,""],Button:[0,0,1,""],ButtonStyle:[0,0,1,""],CategoryChannel:[0,0,1,""],ChannelType:[0,0,1,""],Client:[0,0,1,""],ClientException:[0,4,1,""],ClientUser:[0,0,1,""],Colour:[0,0,1,""],Component:[0,0,1,""],ComponentType:[0,0,1,""],ConnectionClosed:[0,4,1,""],ContentFilter:[0,0,1,""],CustomActivity:[0,0,1,""],DMChannel:[0,0,1,""],DefaultAvatar:[0,0,1,""],DeletedReferencedMessage:[0,0,1,""],DiscordException:[0,4,1,""],DiscordServerError:[0,4,1,""],Embed:[0,0,1,""],Emoji:[0,0,1,""],ExpireBehaviour:[0,0,1,""],FFmpegAudio:[0,0,1,""],FFmpegOpusAudio:[0,0,1,""],FFmpegPCMAudio:[0,0,1,""],File:[0,0,1,""],Forbidden:[0,4,1,""],Game:[0,0,1,""],GatewayNotFound:[0,4,1,""],GroupChannel:[0,0,1,""],Guild:[0,0,1,""],GuildSticker:[0,0,1,""],HTTPException:[0,4,1,""],Integration:[0,0,1,""],IntegrationAccount:[0,0,1,""],IntegrationApplication:[0,0,1,""],Intents:[0,0,1,""],Interaction:[0,0,1,""],InteractionMessage:[0,0,1,""],InteractionResponded:[0,4,1,""],InteractionResponse:[0,0,1,""],InteractionResponseType:[0,0,1,""],InteractionType:[0,0,1,""],InvalidArgument:[0,4,1,""],InvalidData:[0,4,1,""],Invite:[0,0,1,""],InviteTarget:[0,0,1,""],LoginFailure:[0,4,1,""],Member:[0,0,1,""],MemberCacheFlags:[0,0,1,""],Message:[0,0,1,""],MessageFlags:[0,0,1,""],MessageReference:[0,0,1,""],MessageType:[0,0,1,""],NSFWLevel:[0,0,1,""],NoMoreItems:[0,4,1,""],NotFound:[0,4,1,""],NotificationLevel:[0,0,1,""],Object:[0,0,1,""],PCMAudio:[0,0,1,""],PCMVolumeTransformer:[0,0,1,""],PartialAppInfo:[0,0,1,""],PartialEmoji:[0,0,1,""],PartialInviteChannel:[0,0,1,""],PartialInviteGuild:[0,0,1,""],PartialMessage:[0,0,1,""],PartialMessageable:[0,0,1,""],PartialWebhookChannel:[0,0,1,""],PartialWebhookGuild:[0,0,1,""],PermissionOverwrite:[0,0,1,""],Permissions:[0,0,1,""],PrivilegedIntentsRequired:[0,4,1,""],PublicUserFlags:[0,0,1,""],RawBulkMessageDeleteEvent:[0,0,1,""],RawIntegrationDeleteEvent:[0,0,1,""],RawMessageDeleteEvent:[0,0,1,""],RawMessageUpdateEvent:[0,0,1,""],RawReactionActionEvent:[0,0,1,""],RawReactionClearEmojiEvent:[0,0,1,""],RawReactionClearEvent:[0,0,1,""],RawTypingEvent:[0,0,1,""],Reaction:[0,0,1,""],Role:[0,0,1,""],RoleTags:[0,0,1,""],SelectMenu:[0,0,1,""],SelectOption:[0,0,1,""],ShardInfo:[0,0,1,""],Spotify:[0,0,1,""],StageChannel:[0,0,1,""],StageInstance:[0,0,1,""],StagePrivacyLevel:[0,0,1,""],StandardSticker:[0,0,1,""],Status:[0,0,1,""],Sticker:[0,0,1,""],StickerFormatType:[0,0,1,""],StickerItem:[0,0,1,""],StickerPack:[0,0,1,""],StickerType:[0,0,1,""],StoreChannel:[0,0,1,""],StreamIntegration:[0,0,1,""],Streaming:[0,0,1,""],SyncWebhook:[0,0,1,""],SyncWebhookMessage:[0,0,1,""],SystemChannelFlags:[0,0,1,""],Team:[0,0,1,""],TeamMember:[0,0,1,""],TeamMembershipState:[0,0,1,""],Template:[0,0,1,""],TextChannel:[0,0,1,""],Thread:[0,0,1,""],ThreadMember:[0,0,1,""],User:[0,0,1,""],UserFlags:[0,0,1,""],VerificationLevel:[0,0,1,""],VideoQualityMode:[0,0,1,""],VoiceChannel:[0,0,1,""],VoiceClient:[0,0,1,""],VoiceProtocol:[0,0,1,""],VoiceRegion:[0,0,1,""],VoiceState:[0,0,1,""],Webhook:[0,0,1,""],WebhookMessage:[0,0,1,""],WebhookType:[0,0,1,""],Widget:[0,0,1,""],WidgetChannel:[0,0,1,""],WidgetMember:[0,0,1,""],__version__:[0,5,1,""],on_bulk_message_delete:[0,6,1,""],on_connect:[0,6,1,""],on_disconnect:[0,6,1,""],on_error:[0,6,1,""],on_group_join:[0,6,1,""],on_group_remove:[0,6,1,""],on_guild_available:[0,6,1,""],on_guild_channel_create:[0,6,1,""],on_guild_channel_delete:[0,6,1,""],on_guild_channel_pins_update:[0,6,1,""],on_guild_channel_update:[0,6,1,""],on_guild_emojis_update:[0,6,1,""],on_guild_integrations_update:[0,6,1,""],on_guild_join:[0,6,1,""],on_guild_remove:[0,6,1,""],on_guild_role_create:[0,6,1,""],on_guild_role_delete:[0,6,1,""],on_guild_role_update:[0,6,1,""],on_guild_stickers_update:[0,6,1,""],on_guild_unavailable:[0,6,1,""],on_guild_update:[0,6,1,""],on_integration_create:[0,6,1,""],on_integration_update:[0,6,1,""],on_interaction:[0,6,1,""],on_invite_create:[0,6,1,""],on_invite_delete:[0,6,1,""],on_member_ban:[0,6,1,""],on_member_join:[0,6,1,""],on_member_remove:[0,6,1,""],on_member_unban:[0,6,1,""],on_member_update:[0,6,1,""],on_message:[0,6,1,""],on_message_delete:[0,6,1,""],on_message_edit:[0,6,1,""],on_presence_update:[0,6,1,""],on_private_channel_pins_update:[0,6,1,""],on_private_channel_update:[0,6,1,""],on_raw_bulk_message_delete:[0,6,1,""],on_raw_integration_delete:[0,6,1,""],on_raw_message_delete:[0,6,1,""],on_raw_message_edit:[0,6,1,""],on_raw_reaction_add:[0,6,1,""],on_raw_reaction_clear:[0,6,1,""],on_raw_reaction_clear_emoji:[0,6,1,""],on_raw_reaction_remove:[0,6,1,""],on_raw_typing:[0,6,1,""],on_reaction_add:[0,6,1,""],on_reaction_clear:[0,6,1,""],on_reaction_clear_emoji:[0,6,1,""],on_reaction_remove:[0,6,1,""],on_ready:[0,6,1,""],on_resumed:[0,6,1,""],on_shard_connect:[0,6,1,""],on_shard_disconnect:[0,6,1,""],on_shard_ready:[0,6,1,""],on_shard_resumed:[0,6,1,""],on_socket_event_type:[0,6,1,""],on_socket_raw_receive:[0,6,1,""],on_socket_raw_send:[0,6,1,""],on_stage_instance_create:[0,6,1,""],on_stage_instance_delete:[0,6,1,""],on_stage_instance_update:[0,6,1,""],on_thread_delete:[0,6,1,""],on_thread_join:[0,6,1,""],on_thread_member_join:[0,6,1,""],on_thread_member_remove:[0,6,1,""],on_thread_remove:[0,6,1,""],on_thread_update:[0,6,1,""],on_typing:[0,6,1,""],on_user_update:[0,6,1,""],on_voice_state_update:[0,6,1,""],on_webhooks_update:[0,6,1,""],version_info:[0,5,1,""]}},objnames:{"0":["py","class","Python class"],"1":["py","attribute","Python attribute"],"2":["py","property","Python property"],"3":["py","method","Python method"],"4":["py","exception","Python exception"],"5":["py","data","Python data"],"6":["py","function","Python function"]},objtypes:{"0":"py:class","1":"py:attribute","2":"py:property","3":"py:method","4":"py:exception","5":"py:data","6":"py:function"},terms:{"0":[0,2,3,4,8,10,13],"0001":0,"05":0,"0rc1":0,"0x":2,"0x11806a":0,"0x1abc9c":0,"0x1f8b4c":0,"0x206694":0,"0x2ecc71":0,"0x3498db":0,"0x36393f":0,"0x4e5d94":0,"0x546e7a":0,"0x57f287":0,"0x5865f2":0,"0x607d8b":0,"0x71368a":0,"0x7289da":0,"0x95a5a6":0,"0x979c9f":0,"0x992d22":0,"0x99aab5":0,"0x9b59b6":0,"0xa84300":0,"0xad1457":0,"0xc27c0e":0,"0xe67e22":0,"0xe74c3c":0,"0xe91e63":0,"0xeb459":0,"0xed4245":0,"0xf1c40f":0,"0xf47fff":0,"0xfee75c":0,"1":[0,2,3,4,8,9,11,14],"10":[0,2,4,7,8,9,14],"100":[0,2,4,11,18],"1000":[0,2,14,18],"10080":0,"101":[0,2],"106k":18,"1083":18,"109":18,"11":[4,14],"12":4,"120":11,"123":[0,2],"12324234183172":9,"128":[0,2],"13":4,"14":0,"1440":0,"15":[0,2],"150":[0,2],"1584":18,"16":0,"17":0,"1738":0,"176995180300206080":14,"180":0,"1874":18,"1986":18,"2":[0,2,4,8,11,12,14,15],"20":[0,11,18],"200":[0,2,9],"2000":2,"2002":2,"2008":18,"2016":0,"2051":18,"2056":18,"2061":18,"2063":18,"2077":18,"2085":18,"2086":18,"2093":18,"2094":18,"2095":18,"20m":0,"2101":18,"2104":18,"2107":18,"2113":18,"2117":18,"2118":18,"2123":[2,18],"2135":18,"2139":18,"2140":18,"2143":18,"2145":18,"2154":18,"2158":18,"21600":0,"2162":18,"2169":18,"2170":18,"2178":18,"2185":18,"2198":18,"22":0,"2201":18,"2204":18,"2208":18,"2213":18,"2218":18,"2232":18,"2237":18,"2239":18,"2244":18,"2251":18,"2253":18,"2258":18,"2265":18,"2272":18,"2274":18,"2275":18,"2287":18,"2291":18,"2294":18,"2300":18,"2301":18,"2305":18,"2314":18,"2324":18,"232720527448342530":9,"2331":18,"2333":18,"2343":18,"2349":18,"2354":18,"2358":18,"2360":18,"2364":18,"2367":18,"2368":18,"2369":18,"2372":18,"2373":18,"2374":18,"2375":18,"2376":18,"2377":18,"2380":18,"2400":18,"2411":18,"2415":18,"2420":18,"2427":18,"2433":18,"2441":18,"2443":18,"2445":18,"2446":18,"2453":18,"2460":18,"2463":18,"2465":18,"2470":18,"2471":18,"2482":18,"2489":18,"2490":18,"2496":18,"2498":18,"25":0,"250":[0,11],"2501":18,"2502":18,"2504":18,"2516":18,"2517":18,"2519":18,"2531":18,"2535":18,"2539":18,"2540":18,"2544":18,"255":2,"2570":18,"2572":18,"2577":18,"2591":18,"2619":18,"2621":18,"2623":18,"2650":18,"2652":18,"2654":18,"27k":18,"2fa":[0,1,18],"2x":18,"3":[0,2,4,8,12,14,15,16],"303":18,"309":18,"3090":18,"310177266011340803":9,"3107":4,"316026178463072268":4,"32":[9,18],"329":14,"3300":18,"340":18,"381870129706958858":9,"3996":18,"3999":18,"3rd":[8,9],"4":[0,2,8,14,15],"4000":18,"4002":18,"4015":18,"4016":18,"4019":18,"4021":18,"403":0,"4036":18,"404":[0,18],"4043":18,"4047":18,"4049":18,"4053":18,"4057":18,"4058":18,"4068":18,"4071":18,"4074":18,"4082":18,"4087":18,"4095":18,"4112":18,"4114":18,"4115":18,"4120":18,"4121":18,"4152":18,"4153":18,"4157":18,"41771983423143937":4,"4180":18,"4181":18,"4182":18,"4186":18,"42":18,"420":18,"4206":18,"4207":18,"4210":18,"4217":18,"429":[10,18],"4320":0,"440":0,"477":18,"48k":18,"48khz":0,"492212595072434186":2,"4x":18,"5":[0,2,3,8,11,14,15],"50":0,"500":[0,18],"5000":18,"502":18,"503":18,"504":18,"5068":18,"5086":18,"5088":18,"5109":18,"5124":18,"512kbp":18,"5130":18,"5133":18,"5143":18,"5154":18,"5181":18,"5188":18,"5191":18,"5193":18,"5195":18,"5197":18,"5198":18,"5207":18,"5210":18,"5212":18,"5213":18,"5221":18,"5233":18,"526":[2,4],"53":0,"57":[0,18],"5748":18,"5754":18,"5756":18,"5757":18,"5762":18,"5763":18,"5772":18,"5773":18,"5785":18,"5789":18,"5793":18,"5797":18,"5798":18,"5799":18,"58":0,"5800":18,"5804":18,"5808":18,"5819":18,"5823":18,"5832":18,"5834":18,"5835":18,"5849":18,"5866":18,"5888":18,"5897":18,"5901":18,"5904":18,"5905":18,"5923":18,"5929":18,"5930":18,"5945":18,"5946":18,"5949":18,"5953":18,"5970":18,"5975":18,"5984":18,"5986":18,"5x":18,"6":[0,2,4,8,13,14],"60":[0,2,11,14],"6000":0,"6002":18,"6016":18,"6028":18,"6038":18,"6039":18,"6044":18,"6058":18,"6061":18,"6067":18,"6082":18,"6093":18,"6095":18,"6100":18,"6113":18,"6128":18,"6153":18,"6161":18,"6162":18,"6172":18,"6192":18,"6195":18,"6217":18,"6308":18,"6309":18,"6313":18,"6315":18,"6316":18,"6317":18,"6318":18,"6341":18,"6365":18,"6374":18,"639":0,"6390":18,"64":0,"64000":0,"6430":18,"6431":18,"6436":18,"6444":18,"6445":18,"6446":18,"6451":18,"6458":18,"6462":18,"6476":18,"6478":18,"6483":18,"6484":18,"6489":18,"6495":18,"6529":18,"6530":18,"6531":18,"6538":18,"6562":18,"6563":18,"6568":18,"6573":18,"6574":18,"6602":18,"6603":18,"6606":18,"6608":18,"6618":18,"67":18,"6726":18,"6730":18,"6744":18,"6x":18,"7":[0,2,4,11,12,14,15],"735":18,"75":11,"75x":11,"7th":18,"8":[2,4,12,13,18],"80":2,"80088516616269824":2,"80528701850124288":14,"840":[0,11],"84319995256905728":14,"85309593344815104":2,"9":[15,18],"95":11,"953":18,"99":4,"abstract":[2,8,14,15],"boolean":[0,2],"break":[14,15],"byte":[0,2,18],"case":[0,2,4,5,9,14,16,18],"catch":[2,4],"char":2,"class":[2,3,4,8,11,12,14,17,18],"default":[0,2,4,8,9,11,13,14,17,18],"do":[0,1,2,3,4,5,8,10,14,15,16,18],"enum":[0,6,9,15,18],"final":[0,2,5,15,16,18],"float":[0,2,8],"function":[1,2,3,4,5,6,7,8,10,11,12,13,14,16,17,18],"import":[0,2,4,5,8,9,11,12,13,15,16,18],"int":[0,2,3,4,8,18],"long":[0,2,9,14,18],"new":[0,1,2,4,8,9,11,13,14,17],"null":18,"public":[0,1,17,18],"return":[0,2,3,4,8,9,14,15,16,18],"short":[0,2,15],"static":[0,9],"super":4,"switch":18,"throw":[0,18],"true":[0,2,4,8,9,11,14,18],"try":[0,2,9,10,14,15,16],"while":[0,2,4,9,14,15,18],A:[0,2,3,4,8,9,10,12,14,15,18],AND:0,And:[1,14],As:[0,2,3,4,11,14,15,18],At:[3,4],Be:[4,15],But:14,By:[0,2,4,8,14,18],For:[0,2,3,4,5,6,7,9,11,12,13,15,18],If:[0,1,2,3,4,5,7,8,9,10,11,12,14,15,16,17,18],In:[0,1,2,4,5,9,11,14,15,16],Is:10,It:[0,1,2,3,4,5,9,11,13,14,16,18],Its:0,No:[0,2,14,18],Not:[0,4,18],OR:[0,2,18],Of:14,On:[0,4,12,16],One:[0,4,8,14],Or:[14,15],That:[0,2],The:[0,1,2,3,4,5,8,9,11,13,14,15,16,17,18],Then:[11,14],There:[0,2,3,4,5,7,9,11,14,15,16,18],These:[0,2,4,9,10,11,14,18],To:[0,2,3,4,5,9,11,12,14,15,18],With:[4,11,14],_:[0,2,18],__call__:[2,8,18],__cause__:2,__eq__:18,__init__:[0,2,3,4,8,14,18],__iter__:18,__name__:2,__path__:18,__repr__:18,__slots__:[0,17,18],__str__:18,__version__:0,_batch:8,_eval:4,_last_memb:3,_list:4,_original_help_command:14,_updat:15,abc:[0,2,4,9,14,18],abcmeta:2,abil:[5,11,14,18],abl:[0,9,18],about:[0,2,4,5,10,11,12,14,18],abov:[0,4,9],absolut:11,abstracteventloop:[0,8],abus:[0,2],accent:0,accent_color:0,accent_colour:[0,18],accept:[0,2,4,9,14,18],accept_invit:14,access:[0,2,4,9,14,18],accident:1,accommod:18,accompani:14,accomplish:[0,14],accord:0,account:[0,2,10,14,16,18],accumul:2,accur:0,accuraci:11,achiev:0,ack:18,acknowledg:0,acquir:8,act:[0,2,18],action:[0,1,14],action_row:0,activ:[2,9,11,12,14,18],active_thread:[0,18],activitytyp:[0,9,18],actual:[0,1,2,3,4,9,14,18],ad:[0,1,2,3,4,5,8,14,17,18],add:[0,1,2,4,5,7,8,11,14,18],add_aliases_format:2,add_bot_commands_format:2,add_check:[2,18],add_cog:[2,3],add_command:[2,4,5],add_command_format:2,add_exception_typ:[8,18],add_field:0,add_indented_command:2,add_item:0,add_lin:2,add_listen:2,add_opt:0,add_react:[0,9,14,18],add_rol:[0,14],add_subcommand_format:2,add_us:0,add_view:[0,2],addhandl:13,addit:[0,11,18],adher:4,admin:0,admin_rol:0,administr:[0,1],advanc:[0,13],advis:[0,11],affect:[0,15],afk:[0,2,18],afk_channel:0,afk_timeout:0,africa:0,after:[0,2,4,8,15,18],after_any_command:14,after_foo_command:14,after_invok:[2,14,18],after_loop:8,after_slow_count:8,afterward:[2,16],ag:0,again:[0,2,14,18],against:2,age_restrict:0,aggreg:14,ago:0,aid:[0,2,4,10,11,12,18],aiohttp:[0,9,14,18],aka:0,akin:14,album:0,album_cover_url:0,algorithm:[0,8],alia:[0,2,17,18],alias:[0,2,14,18],alias_conflict:2,aliases_head:2,aliv:[0,18],all:[0,1,2,3,4,8,9,10,11,12,14,15,18],all_channel:0,all_command:[2,14],all_memb:0,all_messag:0,allevi:14,alloc:14,allow:[0,2,3,4,8,9,11,14,15,18],allowed_command:2,allowed_ment:[0,2,18],allowedment:[2,18],almost:[0,15,18],alon:[0,18],along:[0,2,11,14,17,18],alongsid:3,alpha:[0,18],alphabet:2,alreadi:[0,2,8,9,11,18],also:[0,1,2,3,4,5,7,9,11,12,14,18],altern:[0,2,9],although:[0,5],alwai:[0,2,4,14,18],am:[2,5],amaz:9,ambigu:4,amount:[0,2,4,8,14,18],amsterdam:0,an:[0,1,2,3,4,5,6,8,10,11,12,14,16,17,18],analog:0,analogu:0,analysi:0,ani:[0,1,2,4,5,9,13,14,15,18],anim:[0,2,18],animated_icon:0,annot:[2,4],announc:[0,18],anonym:0,anoth:[0,2,4,5,9,11,14,18],answer:10,anticip:18,anymor:[0,18],anyon:0,anyth:[0,2,4,9,15],anywai:8,anywher:0,apart:[8,18],api:[1,4,6,9,10,11,12,14,15,17],apng:0,appeal:4,appear:[0,18],append:[0,2],append_opt:0,appinfo:[2,18],appli:[0,2,4,5,14,17,18],applic:[1,2,9,11,12,13,14],application_command:0,application_flag:[0,2],application_id:[0,2],application_info:[0,2,14,18],applicationflag:2,approach:14,appropri:[0,2,4,9,14,18],approxim:0,approximate_member_count:[0,2],approximate_presence_count:[0,2],apt:12,ar:[0,1,2,3,4,5,7,8,9,10,12,13,15,17,18],arbitrari:0,arbitrarili:[4,9],archiv:0,archive_timestamp:0,archived_thread:0,archiver_id:0,aren:[0,18],arg1:4,arg2:4,arg:[0,2,4,8],argument:[0,2,3,8,11,13,14,18],argumentparsingerror:2,aris:15,around:[0,2,11,12,16,18],arrai:0,arrang:0,artist:0,as_chunk:0,as_need:0,asctim:13,ask:[0,2,4,10],aspect:[0,2,4,6,9,14],asset:18,assign:[0,2,4,14,15],associ:[0,2,14],assum:[0,2,8,16],assume_synced_clock:18,assume_unsync_clock:0,async:[2,3,4,5,8,9,10,12,14,15,16],async_ev:15,asynchron:[0,2,4,9,16],asyncio:[0,2,9,10,14,15,18],asynciter:[0,2,14,18],asyncpg:8,atom:[0,2],attach:[2,4,9,14,18],attach_fil:0,attempt:[0,2,4,9,18],attr:[0,2],attribut:[0,2,3,4,8,9,11,14,15,17,18],attributeerror:[0,18],audio:[0,14,18],audioplay:14,audiosourc:14,audit:[14,18],audit_log:[0,14],auditlogact:0,auditlogactioncategori:0,auditlogentri:18,augment:4,authent:[0,2],author:[0,1,2,3,4,5,9,11,12,14,16,18],author__nam:0,author_permiss:2,authoris:0,auto:[0,14],auto_archive_dur:0,autom:16,automat:[0,2,3,14,18],autoshardedbot:[11,14,18],autoshardedcli:[2,11,14,18],avail:[0,2,10,18],avatar:[0,11,14,18],avatar_url:[0,14,15,18],avatar_url_a:14,avconv:0,averag:0,average_lat:[0,18],avoid:[0,2,18],avprob:0,aw:9,awai:[0,2,8],await:[0,2,3,4,5,8,10,14,15,16],awar:[0,1,2,9,15],b:[0,2,4,9],back:[0,2,4,8,9,11,14,18],background:[0,8,18],background_task:9,backport:18,backslash:9,backtick:2,backward:[14,18],bad:[0,2,4,9],badargu:[2,4,18],badboolargu:2,badcolourargu:2,badflagargu:2,badinviteargu:2,badliteralargu:[2,4],badunionargu:[2,4],balanc:0,ban:[0,1,2,4,14,15,18],ban_memb:[0,18],banentri:0,banflag:4,banner:[0,18],bar:[2,4],base:[2,4,12,14,18],baseact:2,baseconnector:0,baseexcept:8,basi:[0,2,14,18],basic:[0,2,11,14,15,16],basic_ext:5,basicauth:0,basicconfig:13,bat:12,batch:8,batch_upd:8,becaus:[0,2,4,9,14,15],becom:[0,2,15],been:[0,2,4,8,14,15,18],beer:4,befor:[0,2,8,15,18],before_any_command:14,before_foo_command:14,before_identify_hook:[0,2,18],before_invok:[2,14,18],before_loop:[8,18],before_opt:0,before_print:8,beforehand:0,begin:[0,2,11],behav:[2,14],behaviour:[0,2,3,4,9,11,14,15,17,18],being:[0,2,3,4,5,8,11,14,18],belong:[0,2,9,14],below:[0,2,4,14,15,17,18],benefit:14,best:[0,18],beta:0,better:[14,18],between:[0,2,4,8,14,18],beyond:4,big:[2,18],biggest:[14,15],bin:12,binari:[0,18],bind:[3,14],bit:[0,4,14,18],bitrat:[0,18],bitrate_limit:[0,18],blank:[0,2],block:[0,2,4,15,18],blue:0,blurpl:0,bodi:[0,2,18],bold:2,bool:[0,2,8],boost:[0,18],booster:18,boot:18,bot:[3,4,5,7,8,10,11,12,14,18],bot_add:0,bot_check:[2,3,14],bot_check_onc:[2,3,14],bot_has_any_rol:2,bot_has_guild_permiss:[2,18],bot_has_permiss:2,bot_has_rol:2,bot_id:0,bot_publ:0,bot_require_code_gr:0,bot_token:0,both:[0,2,9,10,11,18],botintegr:0,botmissinganyrol:2,botmissingpermiss:2,botmissingrol:2,bots_rol:0,bottl:4,bottom:0,bound:[0,2,17],box:7,branch:9,brand:0,brand_green:[0,18],brand_r:[0,18],braveri:0,brazil:[0,18],brief:[2,16],brillianc:0,bring:[0,18],broadcast:0,browser:1,bucket:[0,2,11,18],buckettyp:[2,18],buffer:0,bufferediobas:0,bug:[0,9,10,17],bug_hunt:0,bug_hunter_level_2:0,bui:4,build:[4,18],built:[0,2,4,5,14,18],bulk:[0,8,18],bulker:8,bump:18,button:[1,18],buttonstyl:[0,18],buy_sel:4,by_categori:[0,14,18],bypass:[0,2,11,14],bytearrai:0,bytesio:[0,9,18],c:[2,3,9],cach:[0,2,14,18],cache_auth:18,cached_messag:[0,2,14,18],calcul:[0,2,18],call:[0,2,3,4,5,8,9,11,12,13,14,15,16,18],call_hook:2,call_onc:2,callabl:[0,2,4,9,14,18],callback:[0,2,8,9,16],caller:[0,2],callmessag:18,came:[14,18],camera:0,can:[0,1,2,3,4,6,7,8,10,11,12,13,14,15,16,17,18],can_:15,can_manage_messag:15,can_run:[2,18],cancel:[0,2,8,14,18],cancellederror:[8,18],candid:[0,2],cannot:[0,2,4,8,9,18],cap:[0,2],capabl:0,capit:4,care:[0,2,4],carri:2,case_insensit:[2,4],cast:[0,4,15,18],cat:9,categori:[0,2,3,14,18],categoris:0,category_id:0,categorychannel:[2,4,14],categorychannelconvert:[2,4],caught:[0,2],caus:[0,2,11,18],caution:9,caveat:[14,18],cd:12,cdn:[0,18],central:0,certain:[0,1,2,3,4,8,9,11,14,15,18],certifi:0,ch:14,chain:[0,2,14],chanc:[0,9],chang:[0,2,3,4,5,8,9,11],change_interv:[8,18],change_nicknam:[0,14,18],change_pres:[0,2,9,18],change_statu:18,change_voice_st:[0,18],changed_rol:0,changelog:10,changeset:18,channel:[0,2,3,4,15,16,18],channel_cr:0,channel_delet:0,channel_follow:0,channel_follow_add:[0,18],channel_icon_chang:0,channel_id:[0,2,18],channel_ment:0,channel_messag:0,channel_name_chang:0,channel_upd:0,channelconvert:14,channelnotfound:2,channelnotread:2,channeltyp:[0,2,15,18],charact:[0,2,9,18],check:[0,1,5,6,8,9,11,12,13,16,18],check_ani:[2,18],check_command:2,check_if_it_is_m:2,check_onc:[2,14],checkanyfailur:2,checkbox:1,checkfailur:[2,4],checklist:11,child:2,children:0,choic:[0,4,9],choos:[0,1,2],chosen:0,chunk:[0,11,14,18],chunk_guilds_at_startup:[0,11],circumst:0,citizen:14,cl:[0,2,4,14,18],clamp:4,clash:4,classmethod:[0,2,4],clean:[0,2,4,6,14],clean_cont:[0,2,4,14,18],clean_param:2,clean_prefix:[2,14,18],cleandoc:2,cleanup:[0,14,18],clear:[0,2,18],clear_exception_typ:8,clear_field:0,clear_item:0,clear_react:[0,14,18],clever:0,click:[0,1,2,11],client:[1,2,8,9,11,12,14,16,18],client_id:0,clientexcept:[0,2,18],clientrespons:0,clientsess:[0,9,14],clientus:[2,14],clock:[0,18],clog:13,clone:[0,18],close:[0,2,11,14,15,18],close_pag:2,close_quot:2,closur:0,cloudflar:18,cluster:[0,18],cn:0,co:[0,2],code:[0,1,2,4,5,9,11,18],codec:0,codepoint:[0,2],cog:[6,8,18],cog_after_invok:[2,3,14],cog_before_invok:[2,3,14],cog_check:[2,3,14],cog_command_error:[2,3,14],cog_nam:2,cog_unload:[2,3,8,14],cogabcmeta:2,cogmeta:[3,14],coincid:0,coinflip:3,collect:[0,2,3,9],colon:0,color:0,colorconvert:[2,18],colour:[2,4,14,18],colourconvert:[2,4,18],com:[0,18],combin:[0,14],combo:0,come:[0,3,4,5,6,9,10,11,12,14,17,18],comma:2,command:[0,3,5,8,10,11,12,16],command_attr:[2,18],command_callback:2,command_fail:[2,14],command_nam:2,command_not_found:[2,14],command_prefix:[2,4,11,18],commanderror:[2,4],commandinvokeerror:2,commandnotfound:2,commandoncooldown:[2,18],commandregistrationerror:[2,18],commands_head:2,commerc:0,common:[0,2,4,8,9,10,11,14,15],commun:[0,2,3],compar:[0,2,18],comparison:[0,18],compart:0,compat:[0,18],compet:[0,18],complet:[0,2,14,18],complic:[0,3,4,9,14],compon:[2,18],componenttyp:0,compos:0,compound:11,comprehend:4,compress:18,compris:[0,2],comput:[0,2,15,18],compute_prune_count:0,compute_prune_memb:18,comrad:4,con:8,concept:[0,4,5,14],concret:[0,18],concurr:[2,18],condit:[2,18],configur:[0,2,13],conflict:[0,2,16,18],confus:[2,6],congratul:12,conjunct:[5,8],connect:[2,8,9,15,16,18],connected_channel:0,connectionclos:[0,2],connector:0,consequ:[0,1,2,14,15,18],consid:[0,2,4,9,15,17,18],consider:[0,3,18],consist:[0,14,18],consol:[4,13],constant:15,constraint:18,construct:[0,2,4,11,14,18],constructor:[0,2,4,9,11,18],consum:[2,9],contact:11,contain:[0,2,4,9,11,18],content:[0,2,4,9,12,14,16,18],content_typ:[0,18],contentfilt:0,context:[0,6,8,9,15,18],continu:[0,1,2,4],contribut:18,contributor:18,control:[0,2,4,11,14,15,18],conveni:[0,8],convers:[0,2,14],conversionerror:2,convert:[0,6,18],cool:[0,2,9,14],cool_filenam:14,cool_imag:9,cooldown:[6,14,18],cooldown_after_pars:2,coordin:4,copi:[0,1,2,14,18],core:[4,5,18],coro:[2,8,9],coroutin:[0,1,2,3,4,5,6,7,8,10,11,12,13,14,16,17,18],correct:[0,2,18],correctli:[2,6],correspond:[0,2,4,11,14,15],cost:0,could:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18],count:[0,2,8,18],counter:[0,2],counterpart:[0,18],coupl:[0,3,9,14,18],cours:14,cover:0,cover_imag:0,cover_image_url_a:18,cover_stick:0,cover_sticker_id:0,covert:2,cpu:18,crash:[14,18],creat:[0,2,4,6,8,10,12,14,16,18],create_categori:[0,18],create_category_channel:0,create_channel:14,create_custom_emoji:[0,14,18],create_dm:[0,2,14],create_ffmpeg_play:[14,18],create_guild:[0,2,14,18],create_inst:0,create_instant_invit:0,create_integr:[0,18],create_invit:[0,14],create_private_thread:0,create_public_thread:0,create_rol:[0,14,18],create_serv:[14,18],create_stage_channel:0,create_stick:0,create_stream_play:14,create_templ:0,create_text_channel:[0,14],create_thread:[0,18],create_voice_channel:[0,14],create_webhook:0,create_ytdl_play:14,created_at:[0,2,4,14,18],creation:[0,2,6,10,18],creator:0,credenti:[0,2,15,18],criteria:0,critic:13,crosspost:0,css:[2,18],ctx:[2,3,4,5,9,14],ctype:0,cumul:18,current:[0,2,4,7,8,9,11,18],current_loop:8,current_paramet:2,current_s:0,custom:[0,2,4,9,14,18],custom_emoji:9,custom_id:[0,2],custom_prob:0,customact:18,customis:[2,3,4,14],d:[0,2,18],dai:[0,4],danger:0,danni:18,dark:[0,18],dark_blu:0,dark_blurpl:0,dark_gold:0,dark_grai:0,dark_green:0,dark_grei:0,dark_magenta:0,dark_orang:0,dark_purpl:0,dark_r:0,dark_teal:0,dark_them:[0,18],darker_grai:0,darker_grei:0,dash:2,data:[2,3,4,8,9,15,17,18],databas:[2,8,14],dataclass:[2,4],date:[0,2,14,18],datetim:[0,2,8,18],daunt:6,dave:0,deaf:[0,14],deafen:[0,18],deafen_memb:0,deal:[0,2,11,14,18],dealloc:18,debian:12,debug:[0,9,13,18],decid:[0,2,4,14,18],decod:2,decompress:18,decor:[0,3,4,7,8,9,14,15,16,18],dedic:18,deep:2,def:[0,2,3,4,5,8,9,12,14,15,16],default_auto_archive_dur:[0,18],default_avatar:0,default_channel:[14,15],default_message_notif:0,default_notif:0,default_rol:[0,15,18],defaultavatar:0,defaulthelpcommand:14,defer:0,deferred_channel_messag:0,deferred_message_upd:0,defin:[0,2,3,4,5,9],definit:[3,4,14],delai:[0,18],delet:[0,4,14,18],delete_aft:0,delete_channel:14,delete_channel_permiss:14,delete_custom_emoji:[14,18],delete_dai:4,delete_emoji:0,delete_invit:[0,2,14,18],delete_members_dai:0,delete_messag:[0,14],delete_message_dai:[0,4],delete_original_messag:[0,18],delete_rol:14,delete_serv:14,delete_stick:0,delimit:[2,4],delta:4,deni:[0,15],denot:[0,2,14,18],departur:18,depend:[0,2,4,12,17,18],deposit_monei:3,deprec:[14,18],depth:[4,12],deriv:[2,3,4,14],describ:4,descript:[0,2,7,18],design:[4,10,14],desir:[8,11,18],desktop:0,desktop_statu:0,despair:9,despit:[4,18],destin:[0,2],detail:[0,2,3,9,10,14,15,18],detect:0,determin:0,dev:[2,12],develop:[0,1,3,5,9,10,11,14,18],devic:0,diagnost:0,dict:[0,2,18],dictat:[0,2,11],dictionari:[0,2,14,15,18],did:[0,2,5,14,18],diff:0,differ:[0,2,4,8,9,12,14],differenti:[0,14],digit:[0,2],direct:[0,11],directli:[0,2,4,9,12,13,16],directori:12,dirti:12,disabl:[0,2,4,9,11,14,18],disable_guild_select:0,disabledcommand:2,disallow:[0,18],disambigu:[2,4,18],discard:[2,18],discern:17,disconnect:[0,2,8,9,14,18],discord:[1,2,3,5,7,9,11,12,13,14,15,16,17],discord_certified_moder:0,discordapp:18,discordexcept:[0,2],discordservererror:[0,18],discourag:9,discover:0,discoverable_dis:0,discoverable_en:18,discoveri:[0,18],discovery_splash:0,discovery_splash_url:18,discrim:2,discrimin:[0,4,11,18],discuss:[4,10],dislik:11,dismiss:0,dispatch:[0,2,9,18],displai:[0,2,9,18],display_avatar:[0,18],display_nam:[0,5],dispos:14,disregard:9,disturb:[0,18],dll:0,dm:[0,2,4,14,18],dm_channel:0,dm_help:2,dm_help_threshold:2,dm_messag:0,dm_onli:[2,18],dm_reaction:0,dm_type:0,dmchannel:[2,14,18],dnd:[0,18],do_bulk:8,do_not_disturb:[0,18],doc:[0,7,18],docstr:[2,18],document:[0,2,3,4,5,9,11,12,13,14,15,17,18],doe:[0,2,14,16],doesn:[0,2,4,11,14,18],domain:18,don:[0,2,4,9,11,16,18],done:[0,2,4,8,9,14,15,18],dot:[0,2,5],down:[0,4,9,11,18],download:[0,9,18],drive:0,drop:[0,14,15,18],dropdown:0,dt:0,dubai:[0,18],duck:18,due:[0,2,4,8,9,11,14,15,17,18],duplic:[2,8,18],durat:0,dure:[0,2,5,8,10,18],dy:18,dynam:[0,1,2,4,14,17,18],dynamic_cooldown:2,e:[0,2,12,14,18],each:[0,3,8,9,11],earli:0,earlier:[4,12,14,15],early_support:0,early_verified_bot_develop:[0,18],eas:[0,2,15],easi:[0,4,10,14,18],easier:[0,4,14,15,18],easili:[0,14,18],east:0,echo:9,economi:3,edit:[0,2,14,18],edit_channel:14,edit_channel_permiss:[14,15],edit_custom_emoji:[14,18],edit_messag:[0,14,18],edit_original_messag:[0,18],edit_profil:14,edit_rol:14,edit_role_posit:[0,18],edit_serv:[14,18],edit_widget:0,edited_at:[0,14,18],edited_timestamp:14,effect:2,effort:[14,18],either:[0,2,4,7,8,9,14,18],eject:[2,18],elaps:0,elem:0,element:[0,3,4,14,17],elif:4,elig:0,els:[0,1,2,3,4,9,11,14,17],email:[0,14,18],emb:[14,18],embed:0,embed_link:0,embedded_appl:0,embedproxi:0,emoji:[2,4,9,14,18],emoji_cr:0,emoji_delet:0,emoji_id:0,emoji_limit:[0,18],emoji_upd:0,emojiconvert:[2,4],emojinotfound:2,emojis_and_stick:0,emoticon:0,employe:0,empti:[0,2,4,8,18],emptiv:18,en:[0,2],enabl:[0,1,2,4,7,11,14,18],enable_debug_ev:[0,18],enable_emoticon:0,encod:[0,2,13,18],encount:[0,2,8,9,18],encrypt:18,end:[0,2,4,9,18],endian:18,endless:1,endpoint:[0,14,18],english:0,enhanc:[7,9,18],enough:[2,4],ensur:[0,2,4,18],entir:[0,2,3,11,14,18],entiti:[2,14],entri:[0,2,5],enumer:[14,18],env:12,environ:0,ephemer:[0,2,18],epoch:[0,2],equal:[0,2,4,18],equival:[0,2,4,14,18],ergo:[9,14],error:[0,2,5,6,8,9,13,14,15,18],escap:[0,2,18],escape_markdown:[0,2,18],escape_ment:0,especi:[2,13],essenti:[0,1,4,9,14,16],establish:0,estim:0,estimate_pruned_memb:[0,14,18],etc:[0,2,11,14,18],etf:14,eu:0,eu_centr:[0,18],eu_west:[0,18],europ:[0,18],eval:[4,18],evalu:[2,4],even:[0,2,8,11,18],event:[3,4,6,8,11,12,13,16,17,18],event_method:[0,2],event_typ:[0,18],eventu:[0,3,14],ever:3,everi:[0,2,3,4,8,11,14,15,16,17],everyon:[0,1,2,4,14,18],everyth:[0,10,14],evict:[11,18],exact:[0,2,8],exactli:2,examin:4,exampl:[0,2,4,5,6,10,11,12,13,14,15,18],example_bot:16,exc_info:0,exce:[0,2,18],exceed:0,except:[4,5,6,8,9,11,14,15,18],excess:9,exclud:0,exclus:[0,4,15],execut:[0,2,4,9,15,18],exercis:18,exhaust:[0,17,18],exist:[0,2,4,14,18],exit:8,expand:14,expect:[0,2,4,11,14,18],expectedclosingquoteerror:2,experi:[0,18],experienc:18,expir:[0,2],expire_behavior:0,expire_behaviour:0,expire_grace_period:0,expirebehavior:0,expirebehaviour:0,expires_at:[0,2],explicit:[0,8],explicit_content_filt:[0,14],explicitli:[0,2,3,11,14,15,18],exponenti:[8,14],expos:[2,15,18],express:[0,4],ext:[2,4,5,7,9,10,11,16],extend:[0,2,5,18],extended_check:2,extens:[0,2,3,4,6,8,18],extensionalreadyload:2,extensionerror:2,extensionfail:2,extensionnotfound:[2,18],extensionnotload:2,extern:[0,2,4],external_emoji:[0,18],external_stick:0,extra:[0,2,4,9,18],extract:2,extran:[0,2,14],extrem:[0,18],f:[0,2,3,4,5,9,12,16],face:18,facil:18,facilit:[2,14,18],fact:[0,2,11,18],factor:0,factori:[0,2,18],fail:[0,2,4,8,14,18],fail_if_not_exist:[0,18],failur:[0,2,18],fairli:[4,17],fake:4,fall:0,fallback:[0,18],fals:[0,2,4,9,11,14,15,18],falsei:18,familiar:3,famou:9,faq:7,far:0,fast:18,faster:[15,18],favour:[14,18],featur:[0,4,10,14],feel:[2,3,4,9,18],fetch:[2,4,8,9,11,14,18],fetch_ban:0,fetch_channel:[0,2,18],fetch_emoji:[0,9],fetch_guild:[0,2,9],fetch_inst:0,fetch_invit:[0,2,14,18],fetch_memb:[0,9,11,18],fetch_messag:[0,2,9,14],fetch_offline_memb:18,fetch_premium_sticker_pack:[0,2],fetch_rol:[0,18],fetch_stage_inst:[0,2],fetch_stick:[0,2],fetch_templ:[0,2,18],fetch_us:[0,2,9,14,18],fetch_webhook:[0,2],fetch_widget:[0,2],few:[0,4,9,11,18],fewer:[0,14],fff:2,ffmpeg:[0,18],ffmpegopusaudio:18,ffmpegpcmaudio:[9,14,18],ffprobe:0,field:[0,2,18],figur:[0,9,18],file:[2,5,13,14,16,18],filehandl:13,filenam:[0,9,13,14],filesize_limit:[0,18],fill:[0,2],filter:[0,2,14,18],filter_command:2,find:[0,2,4,14],find_librari:0,fine:[0,2,4],finer:0,finicki:15,finish:[0,8,9,16],fire:[0,2,18],first:[0,1,2,3,4,6,9,10,11,14,16,17],fit:2,five:0,fix:[9,11,17],fix_channel_ment:2,flag:[0,4,11,18],flag_nam:2,flag_valu:2,flagconvert:2,flagerror:2,flatten:[0,2,14],flavour:4,flexibl:6,flip:18,flow:[0,18],fluent:0,folder:[5,9],follow:[0,2,3,4,9,11,12,13,14,15,17,18],followup:0,foo:[0,2,4,14,15],food:4,footer:[0,9],forbid:9,forbidden:[0,2,4,18],forc:[0,11,18],forget:9,form:[0,4,9],format:[0,2,14,15,18],format_dt:0,format_typ:0,formatt:[2,13],former:0,found:[0,2,4,9,12,14,15,18],fp:[0,9],fragment:[0,18],frame:[0,2],framework:[5,10,14,16],frankfurt:0,free:[2,9,18],freez:9,frequenc:18,frequent:[10,14],friendli:[0,2,4,18],from:[0,2,3,4,5,8,9,11,12,13,14,15,16,18],from_dict:0,from_hsv:0,from_int:0,from_messag:[0,18],from_pair:0,from_prob:0,from_rgb:[0,14],from_str:0,from_url:0,fuchsia:0,full:[0,2,4,9,11,14,18],full_parent_nam:2,fulli:[0,2,18],func:[0,2,3],fundament:15,further:[4,11],fut:9,futur:[0,9,14,18],g:[0,2,12,14,18],gain:[0,14],gambl:3,game:[2,4,9,14,18],gameconvert:[2,4],gamesdk:0,gap:[0,2,18],gate:[4,18],gatewai:[0,2,9,10,14,18],gateway_guild_memb:0,gateway_guild_members_limit:0,gateway_pres:0,gateway_presence_limit:0,gatewaynotfound:[0,2],gather:0,gb:0,gc:18,gener:[0,1,2,3,4,14,18],generalis:[4,14],get:[0,2,3,4,6,11,12,14,15,16,18],get_:18,get_all_channel:[0,2],get_all_emoji:[14,18],get_all_memb:[0,2],get_ban:[14,18],get_bot_map:[2,18],get_channel:[0,2,9,14],get_channel_or_thread:[0,18],get_cog:[2,3],get_command:[2,3,18],get_command_signatur:[2,14],get_context:[2,14],get_cooldown_retry_aft:[2,18],get_default_channel:15,get_default_rol:15,get_destin:[2,14],get_emoji:[0,2,9],get_ending_not:2,get_event_loop:[0,8,15],get_flag:2,get_guild:[0,2,9,14],get_invit:14,get_listen:[2,3],get_max_s:2,get_memb:[0,9],get_member_nam:0,get_messag:14,get_opening_not:2,get_partial_messag:[0,2,18],get_prefix:2,get_raw_channel_ment:15,get_raw_ment:15,get_reaction_us:[14,18],get_retry_aft:2,get_rol:[0,9,14],get_serv:14,get_shard:[0,18],get_stage_inst:[0,2],get_stick:[0,2],get_task:8,get_thread:[0,18],get_token:2,get_us:[0,2,9,14],get_user_info:[14,18],getlogg:13,getticket:0,gg:[0,2],gh:[0,2,18],gib:18,gif:0,gigant:18,gist:3,git:9,github:10,give:[0,1,2,4,15,16],given:[0,2,4,8,9],global:[2,7,9,14,18],globally_block_dm:4,go:[0,1,2,4,9,10,12,14,16,18],goal:[0,4,8,14],goe:[0,8,11,12,14],gold:0,gone:[0,14,18],good:[4,9],googl:0,got:[0,4,10,14,18],gotcha:9,grab:0,grace:0,gracefulli:[8,18],grai:[0,18],grain:[0,2],grammar:4,grant:[0,1],granular:[0,2,18],great:10,greater:[0,2,4],greatli:18,greedi:[2,18],greedili:2,green:0,greet:[0,2,3],grei:[0,18],greypl:0,ground:18,group:[0,4,9,14,18],groupcal:18,groupchannel:[14,18],guarante:[0,2,10,15],guild:[2,3,4,7,9,11,18],guild__nam:0,guild_avatar:[0,18],guild_creat:[0,18],guild_discovery_disqualifi:0,guild_discovery_grace_period_final_warn:0,guild_discovery_grace_period_initial_warn:0,guild_discovery_requalifi:0,guild_id:[0,2,4,18],guild_invite_remind:0,guild_member_upd:18,guild_messag:0,guild_onli:[0,2,4,14],guild_permiss:0,guild_react:0,guild_ready_timeout:[0,18],guild_reminder_notif:0,guild_stream:0,guild_typ:0,guild_upd:0,guildchannel:[2,4,14,18],guildchannelconvert:[2,4],guildconvert:[2,4,18],guildnotfound:2,guildstick:2,guildstickerconvert:2,guildstickernotfound:2,h:0,ha:[0,2,4,8,9,11,14,15,16,18],had:[0,2,14,15,18],handi:[4,14],handl:[0,2,6,8,10,14,15,16,17,18],handler:[0,2,4,13,14,18],handshak:[0,14,18],hang:[10,18],happen:[0,2,4,5,9,12,14,16,18],hard:[0,17],has_any_rol:2,has_error_handl:[2,18],has_guild_permiss:[2,18],has_permiss:2,has_rol:2,has_thread:0,has_unread_urgent_messag:0,hash:[0,18],hashabl:[0,18],have:[0,1,2,3,4,8,9,10,11,12,14,15,16,18],head:[2,14,16],header:18,heard:0,heart:3,heartbeat:[0,2,9,18],heartbeat_ack:[0,2,18],heartbeat_timeout:0,heavi:[0,2],hei:4,height:0,held:18,hello:[0,2,3,4,5,9,14,15,16],help:[0,3,4,6,9,12,16,18],help_command:[2,14],helpcommand:[14,18],helper:[0,6,10,18],helpformatt:18,here:[0,2,3,4,8,9,10,12,14,16,17,18],hex:[0,2],hidden:[2,18],hierarchi:[14,18],high:[0,9,11],higher:[0,12,14,18],highest:0,highli:[0,9,18],hint:[4,14,18],histori:[0,2,14,18],hit:[0,18],hm:4,hmm:9,hoist:0,hold:[0,2,8],hong:0,hongkong:0,hood:[2,4],hook:[0,2,18],hot:5,hour:[8,9],hover:0,how:[0,2,4,8,11,12,14,15,18],howev:[0,2,4,6,7,8,9,11,12,14,15,17,18],hsv:0,http:[0,2,9,11,17,18],httpexcept:[0,2,18],hue:0,human:[0,9,18],hunter:0,hypesquad:0,hypesquad_bal:0,hypesquad_braveri:0,hypesquad_brilli:0,i18n:2,i:[0,2,4,5,8,14,18],icon:[0,2,9,18],icon_url:[0,15,18],icon_url_a:18,id:[0,2,3,4,7,11,14,18],ideal:[0,2,14],idempot:2,ident:0,identifi:[0,2,18],idiom:4,idl:[0,2],ie:0,ietf:0,ignor:[0,2,4,8,16,18],ignore_extra:2,ignore_link:0,illustr:[0,11],imag:[0,2,14,18],immedi:18,implement:[0,2,3,4,8,14,18],impli:0,implic:[0,15],implicit:[0,18],implicitli:[0,18],importerror:[16,18],imposs:0,improp:0,improperli:18,inaccess:0,inact:0,includ:[0,2,8,9,14,15,17,18],inclus:0,incom:0,incompat:[14,17],incomplet:[2,18],incorrect:[0,2,14,18],increas:0,incred:0,incur:18,inde:[2,15],indefinit:[0,2],indent:2,independ:0,index:[0,8,10,15],indexerror:0,india:[0,18],indic:[0,2,18],individu:[0,11],inevit:9,infinit:8,info:[2,4,9,13,18],info_error:4,inform:[0,1,2,4,9,11,13,14,15,18],infrastructur:0,ing:4,inher:0,inherit:[0,2,4,8,14],initi:[0,2,11,14],initialis:[0,2],inject:18,inlin:0,inner:[4,18],input:[0,2,4,18],insensit:2,insert:[0,2,8],insert_field_at:[0,18],insid:[0,1,2,4,9,14,18],insight:0,inspect:[2,6],inspir:4,instal:[0,9,16],instanc:[0,2,3,4,9,14,16,18],instant:0,instanti:0,instantli:0,instead:[0,2,4,8,9,12,13,14,18],integ:[0,2,4],integr:18,integration_cr:0,integration_delet:0,integration_id:0,integration_upd:0,integrationaccount:[0,18],integrationappl:0,intellig:4,intend:[0,18],intent:[2,10,14,18],intention:0,inter:3,interact:[2,4,6,8,18],interaction_check:0,interactionmessag:18,interactionrespond:[0,18],interactionresponsetyp:0,interactiontyp:0,interfac:[0,1,2,4,8,14,18],intermix:2,intern:[0,2,4,8,14,15,17,18],internet:[0,2,8,14],interpret:0,intersect:18,interv:[8,18],intric:4,introduc:[4,18],introduct:[10,11,16],introspect:2,invalid:[0,2,8,9,15,18],invalidargu:[0,2],invaliddata:[0,2],invalidendofquotedstringerror:2,invis:[0,18],invit:[2,4,9,14,18],invite_cr:0,invite_delet:0,invite_splash:0,invite_upd:0,invite_url:0,inviteconvert:[2,4],invites_from:[14,18],invitetarget:0,invoc:[0,2,6],invok:[0,2,4,9,14,18],invoke_without_command:2,invoked_par:[2,18],invoked_subcommand:[2,9,18],invoked_with:[2,18],involv:[0,2,14,15,18],io:[0,9,18],ipc:[0,14],irrelev:18,is_anim:0,is_assign:0,is_authent:0,is_being_cancel:8,is_binari:15,is_bot_manag:[0,18],is_clos:[0,2,14],is_connect:0,is_crosspost:0,is_custom_emoji:0,is_default:[0,14,15],is_default_channel:15,is_dirti:0,is_dispatch:0,is_don:0,is_empti:[0,18],is_everyon:[15,18],is_finish:0,is_guild_own:2,is_icon_anim:18,is_in_guild:4,is_integr:[0,18],is_load:[0,18],is_m:[0,2],is_new:[0,4],is_nsfw:[0,2,14,18],is_on_cooldown:2,is_on_mobil:0,is_opu:0,is_own:[2,4,14],is_parti:0,is_paus:0,is_persist:0,is_plai:[0,14],is_premium_subscrib:[0,18],is_priv:[0,14],is_readi:[0,2,14],is_run:[8,18],is_spoil:0,is_strict_subset:0,is_strict_superset:0,is_subset:0,is_superset:0,is_system:[0,18],is_unicode_emoji:0,is_us:[0,18],is_ws_ratelimit:[0,2,18],isinst:[0,4,14],isn:[0,2,8,14,17],iso:0,issu:[2,10,11,15,18],issubclass:0,item:[2,4,18],iter:[2,8,18],its:[0,2,3,4,5,8,9,11,14,15,18],itself:[0,2,3,4,10,14],ja:0,jake:0,japan:0,japanes:18,join:[0,2,4,11,18],join_notif:0,join_voice_channel:14,joindist:4,joindistanceconvert:4,joined_at:[0,4],jpeg:[0,18],jpg:[0,2],js:9,json:[0,9,14],json_url:0,jump:0,jump_url:[0,18],just:[0,2,3,4,9,11,14,16,18],k:4,kbp:0,keep:[0,4,12,14,17,18],kei:[0,2,18],kept:[0,14,18],keyboardinterrupt:[0,2],keyword:[0,2,3,8,9,14,18],kick:[0,14,15,18],kick_memb:[0,18],kind:11,knob:4,know:[0,2,4,5,14,15,18],known:[0,2],kong:0,korea:0,kwarg:[0,2,8],la:[0,14],label:[0,18],lack:[2,17],lambda:[0,4,14,18],languag:0,laps:0,larg:[0,11,18],large_imag:0,large_image_text:0,large_image_url:0,large_text:0,large_threshold:0,largest:2,last:[0,2,15,18],last_messag:0,last_message_id:0,last_pin:0,latenc:[0,2,18],later:[0,2,16],latest:[0,18],launch:[0,8,9,14,18],lavalink:0,layer:18,lazili:[2,18],lead:[0,2,18],leader:0,leak:[1,18],learn:0,least:[0,2,4],leav:[0,1,4,11,14],leave_serv:14,led:0,left:[0,2,4,8,11,18],legaci:18,len:[0,2,4,8,9],length:[0,2,9],less:[0,2,11,18],let:[0,2,8,16],level:[0,2,4,6,13,14,18],levelnam:13,lib:0,libffi:12,libnacl:12,libopu:0,librari:[1,2,4,5,6,8,9,10,11,12,13,14,15,16,17,18],lifecycl:[0,2],light_grai:0,light_grei:0,lighter_grai:0,lighter_grei:0,like:[0,2,4,5,8,9,11,12,14,15,16,18],likewis:[0,18],limit:[0,2,9,10,11,18],line:[0,2,3,4,9,14,16,18],linear:[0,4],linesep:[2,18],linger:[0,2,18],link:[0,18],linter:18,linux:[0,12,18],liquid:4,list:[0,2,3,8,9,11,14,15,17,18],listen:[0,2,3,9,12,14],liter:2,littl:[11,18],live:[0,18],ll:[0,2,16],load:[0,2,5,11,18],load_extens:[2,5],load_opu:0,local:[0,2,4,14],locat:0,lock:[0,4,8,18],log:[1,2,10,11,12,14,16,18],logger:13,logic:[0,2,8,9,14,18],login:[0,1,2,14,15,16,18],loginfailur:[0,2],logout:15,logs_from:[14,15,18],london:0,longer:[0,2,14,15,18],look:[0,2,5,7,8,10,14,16],lookup:[0,2,9,15,18],loop:[0,2,8,9,15,18],lose:0,lost:0,lot:[0,2,4,8,13,14,15,16,18],lotti:0,low:[0,2],lower:[0,4,6,12,14,15,18],lowercas:9,lowest:0,luckili:[4,9,16],lul:9,m:[0,2,12,14,18],m_id:14,machin:[0,18],machineri:[0,14],made:[0,1,2,4,15,16,18],magenta:0,magic:18,mai:[0,2,9,18],main:[0,2,8,15,18],main_task:15,mainli:[0,2,4,18],maintain:[3,11,12],mainten:18,major:[15,17,18],make:[0,1,2,4,5,8,11,14,15,16,18],malici:1,manag:[0,1,2,18],manage_channel:[0,2],manage_emoji:[0,18],manage_emojis_and_stick:0,manage_ev:0,manage_guild:[0,14],manage_messag:[0,2,15],manage_nicknam:0,manage_permiss:[0,18],manage_rol:0,manage_serv:14,manage_thread:0,manage_webhook:[0,18],mandat:11,mandatori:11,mani:[0,2,4,6,9,10,14,15,16,18],manner:[0,2,4,16],manual:[0,2,9,11,18],map:[0,2,4,14],mark:[0,2,3,4,14,15],markdown:[0,2,18],mask:18,mass:[0,4],massiv:[14,15],master:9,match:[0,2,4,9,11,18],mate:[0,2],matter:2,max:[0,2,18],max_ag:0,max_arg:2,max_concurr:[2,18],max_memb:0,max_messag:[0,18],max_pres:0,max_siz:[0,2,18],max_us:0,max_valu:0,max_video_channel_us:[0,18],maxconcurrencyreach:2,maximum:[0,2,8,18],maximum_s:0,mayb:[4,18],me:[0,2,14,18],mean:[0,2,4,5,11,14,15,17,18],meant:[0,2,15,18],measur:[0,2],mechan:[2,5,18],media:0,medium:0,meet:[0,2,14],member2:4,member:[1,2,3,4,9,18],member_cache_flag:0,member_count:[0,18],member_disconnect:0,member_id:0,member_mov:0,member_prun:0,member_role_upd:0,member_upd:0,member_verification_gate_en:0,membercacheflag:[2,11,18],memberconvert:[2,4,18],membernotfound:2,memberrol:4,members_remov:0,membership:[0,18],membership_st:0,memori:[0,9,10,14,18],mention:[0,2,3,4,14,15,18],mention_author:[0,18],mention_everyon:0,mentioned_in:[0,18],menu:0,meow:9,merg:0,merger:14,messag:[2,4,11,12,13,15,16,18],message_bulk_delet:0,message_command:2,message_count:0,message_delet:0,message_id:[0,2,9,18],message_length:0,message_pin:0,message_reaction_remov:18,message_reaction_remove_al:18,message_unpin:0,message_upd:0,messageconvert:[2,4,18],messageflag:18,messagenotfound:2,messagerefer:18,messagetyp:[0,18],messsag:12,met:2,meta:[2,6],metaclass:[2,3,14],metadata:[0,9],method:[0,2,4,6,8,9,14,18],mfa:0,mfa_en:0,mfa_level:[0,18],mfa_sm:0,mid:2,might:[0,4,10,11,12,18],mighti:0,migrat:[10,18],millisecond:[0,18],mimic:0,min_valu:0,mind:[0,4,14,17],miniatur:0,minifi:2,minim:2,minimalhelpcommand:[14,18],minimalist:14,minimis:4,minimum:0,minor:18,minut:[0,2,8,11],mirror:[0,2,18],misc:0,miscellan:[0,2],mismatch:[0,18],miss:[0,2,18],missing_permiss:2,missing_rol:2,missinganyrol:2,missingflagargu:2,missingpermiss:2,missingrequiredargu:2,missingrequiredflag:2,missingrol:2,mister:2,misus:14,mitig:11,mix:[0,4],mixin:2,mobil:0,mobile_statu:0,mode:[0,13,18],model:4,moder:[0,2],modern:10,modif:2,modifi:[0,17],modul:[0,2,4,9,13,14,18],modulenotfounderror:16,moduletyp:2,moment:0,monei:3,monet:0,monetization_en:0,month:18,more:[0,1,2,3,4,5,9,11,12,13,14,15,18],more_emoji:0,more_stick:0,most:[0,2,4,8,14,18],mostli:11,move:[0,14,18],move_channel:14,move_memb:[0,14,18],move_rol:14,move_to:[0,18],movement:0,mp3:14,msg:[0,2,4,14],much:[0,2,4,14,18],multi:[0,4,18],multipl:[0,2,4,9,14,18],multiprocess:9,music:9,must:[0,1,2,3,4,5,8,9,11,14,15],mute:[0,18],mute_memb:0,mutual:[0,18],mutual_guild:[0,18],my:[2,3,12,14],my_aft:9,my_fil:[9,14],my_last_messag:14,my_messag:2,my_url:9,my_whitelist:2,mybot:14,myclient:[0,12],mycog:[2,3,8,14],mycontext:14,myconvert:14,myhelpcommand:14,n:[2,4,9,18],naiv:[0,2],name:[0,1,2,3,4,5,9,13,14,15,16,18],namedtupl:[0,14,18],namespac:0,nan:0,nativ:[0,2],natur:[0,2,14,17],navig:[1,11,18],nearli:0,necessari:[0,2,11,14],need:[0,1,2,3,4,5,8,9,14,15,16,18],neg:[0,2],nest:[0,4,9],never:[0,1,2,5,9],new_filenam:9,new_memb:0,newer:[15,18],newest:[0,2],newli:0,newlin:2,news_thread:0,next:[0,2,4,8,16,18],next_iter:[8,18],nice:4,nicer:0,nick:0,nicknam:[0,2,4,11,18],nitro:[0,18],nitro_boost:0,no_categori:2,no_pm:14,no_rol:0,nobodi:0,noentrypointerror:2,nois:18,noisi:4,nomoreitem:0,non:[0,2,4,8,9,18],nonc:[0,18],none:[0,2,3,4,8,9,14,18],nonsens:2,noprivatemessag:[2,4],nor:0,normal:[0,2,4,9,14,18],note:[0,1,2,3,4,11,14,15,18],notfound:[0,2,18],noth:[0,2,4,11],notic:0,notif:[0,18],notifi:0,notificationlevel:0,notown:2,now:[0,1,2,3,5,11,12,15,16,18],nowher:9,nsfw:[0,2,4,14,18],nsfw_level:0,nsfwchannelrequir:2,nsfwlevel:0,ntp:0,number:[0,2,4,8,11,18],o:18,oauth2:[0,1],oauth_url:[0,1,18],obj:[0,18],object:[2,4,9,10,14,18],objectconvert:[2,4],obtain:0,obvious:8,occur:[0,2,5,8,9,18],octob:18,off:[0,2,4,8,9,14,18],offer:[0,6,9,11],offici:[0,14,18],offlin:[0,14,18],offset:0,often:[0,4,6,18],og_blurpl:0,okai:18,old:[0,1,2,11,14,15,17,18],older:[0,15],oldest:[0,2],oldest_first:[0,2],omit:[0,4],on_:[0,2],on_bulk_message_delet:0,on_bulker_cancel:8,on_channel_:14,on_channel_cr:14,on_channel_delet:14,on_channel_upd:[14,15],on_command:[2,14],on_command_complet:[2,14],on_command_error:[2,4,14,18],on_connect:[0,2],on_disconnect:0,on_error:[0,2],on_group_join:0,on_group_remov:0,on_guild_avail:[0,14],on_guild_channel_:14,on_guild_channel_cr:[0,14],on_guild_channel_delet:[0,14],on_guild_channel_pins_upd:0,on_guild_channel_upd:[0,14],on_guild_emojis_upd:[0,14],on_guild_integrations_upd:0,on_guild_join:[0,14],on_guild_remov:[0,14],on_guild_role_cr:[0,14],on_guild_role_delet:[0,14],on_guild_role_upd:[0,14],on_guild_stickers_upd:0,on_guild_unavail:[0,14],on_guild_upd:[0,14],on_help_command_error:[2,14,18],on_integration_cr:0,on_integration_upd:0,on_interact:[0,2],on_invite_cr:[0,18],on_invite_delet:[0,18],on_member_ban:[0,14,18],on_member_join:[0,3,11],on_member_remov:[0,11],on_member_unban:[0,18],on_member_upd:[0,15,18],on_messag:[0,2,11,12,14,15,16],on_message_delet:0,on_message_edit:0,on_presence_upd:[0,18],on_private_channel_:14,on_private_channel_cr:14,on_private_channel_delet:14,on_private_channel_pins_upd:0,on_private_channel_upd:[0,14],on_raw_bulk_message_delet:0,on_raw_integration_delet:0,on_raw_message_delet:0,on_raw_message_edit:0,on_raw_reaction_add:[0,11],on_raw_reaction_clear:0,on_raw_reaction_clear_emoji:[0,18],on_raw_reaction_remov:0,on_raw_typ:0,on_reaction_add:[0,11,18],on_reaction_clear:[0,18],on_reaction_clear_emoji:[0,18],on_reaction_remov:[0,18],on_readi:[0,2,9,12,16,18],on_resum:[0,18],on_server_avail:14,on_server_emojis_upd:[14,18],on_server_join:14,on_server_remov:14,on_server_role_cr:14,on_server_role_delet:14,on_server_role_upd:[14,15],on_server_unavail:14,on_server_upd:14,on_shard_connect:[0,18],on_shard_disconnect:[0,18],on_shard_readi:[0,18],on_shard_resum:[0,18],on_socket_clos:15,on_socket_event_typ:[0,18],on_socket_open:15,on_socket_raw_rec:[0,18],on_socket_raw_send:[0,15,18],on_socket_rec:15,on_socket_respons:18,on_stage_instance_cr:0,on_stage_instance_delet:0,on_stage_instance_upd:0,on_statu:15,on_thread_delet:0,on_thread_join:[0,18],on_thread_member_join:0,on_thread_member_remov:[0,18],on_thread_remov:0,on_thread_upd:0,on_timeout:0,on_typ:[0,18],on_user_upd:[0,18],on_voice_server_upd:0,on_voice_state_upd:[0,11,14,15,18],on_webhooks_upd:0,onc:[0,2,3,5,8,9,11,14,18],one:[0,1,2,3,4,8,9,11,14,15,18],ones:[0,2,11,12,14],onli:[0,2,8,9,11,14,15,17,18],onlin:[0,2,11,15],only_for_m:2,only_for_own:2,only_m:2,only_ment:0,onto:[0,2],opcod:18,open:[0,2,4,9,18],oper:[0,2,8,9,14,15],opportun:14,opportunist:0,opposit:14,opt:[0,11,18],optim:18,optimis:[0,9,10,14],option:[0,6,7,8,9,13,14,18],option_descript:2,opu:18,opuserror:0,opusnotload:0,orang:0,order:[0,1,2,4,7,9,11,14,15,18],organ:3,orient:10,origin:[0,2,11,18],original_messag:[0,18],os:0,other:[0,1,2,4,9,11,13,14,15,16,18],otherwis:[0,2,17,18],our:[0,4,5,8,10,11,14,16],ourselv:[0,16],out:[0,2,4,5,8,9,10,13,14,15,18],outag:[0,2],outlin:[0,2],output:[0,2,13,18],outsid:[0,2,14],over:[0,2,11,14,16,18],overal:0,overrid:[0,2,3,4,9,14],overridden:[0,2,3,8,14],overriden:0,overwrit:[0,2,14,18],overwrite_cr:0,overwrite_delet:0,overwrite_upd:0,overwrites_for:0,overwritten:[2,18],own:[0,2,4,8,18],owner:[0,1,2,4,14,18],owner_id:[0,2,14,18],owner_or_permiss:2,ownership:0,p:[2,18],pack:[0,2],pack_id:0,packag:[2,12,18],packet:0,pad:2,page:[0,1,2,4,10,11,14,15,16,18],pagin:[0,18],pair:[0,2,4],param:2,paramet:[0,2,3,5,6,7,8,9,11,14,15,17,18],parent:[0,2,14,18],parent_id:0,parenthes:[14,18],pars:[0,2,4,18],parser:[2,4],part:[0,2,7,9,11,14,17],parti:[0,8,9],partial:[0,2],partialemoji:[2,4,18],partialemojiconversionfailur:2,partialemojiconvert:[2,4],partialinvitechannel:2,partialinviteguild:[2,18],partialmessag:[2,4,18],partialmessageconvert:[2,4,18],particip:[0,2],particular:[0,14],partli:18,partner:[0,18],party_id:0,pass:[0,2,3,4,7,8,11,14,15,18],pass_context:14,password:[1,14],past:[0,1],patch:14,path:[0,2,5,9,18],pathlik:0,patienc:18,pattern:8,paus:[0,14],payload:[0,2,15,18],pcm:0,pcmvolumetransform:14,pend:[0,18],penultim:0,peopl:[0,2,4],pep:[0,2,4],per:[0,2,11,14,18],percentag:0,perform:[0,2,15],period:[0,2],perm:[0,2],permiss:[1,2,4,9,12,14,15,18],permissionoverwrit:18,permissions_for:[0,2,18],permissions_in:18,permissions_sync:[0,18],permit:0,persist:[0,2,18],persistent_view:[0,2],person:[1,2,4],perspect:0,phone:0,piec:[0,9],pin:[0,2,14,18],pin_messag:14,ping:[0,1],pins_add:[0,18],pins_from:14,pip:12,pipe:0,pixel:0,pjsalt:0,place:[0,2,9,10,13,15,18],placehold:0,plai:[0,2,14,16,18],plain:5,plan:18,platform:[0,18],player:[0,14,18],pleas:[0,1,2,4,18],plu:2,plug:14,plugin:5,plural:4,png:[0,2,9,14],po:18,point:[0,2,3,4,5,9],pointless:0,pointlessli:0,polici:[0,11,18],pollut:12,pong:0,pool:[0,2,8],popen:0,popul:2,populate_own:2,pornographi:0,port:18,portal:[0,11],portion:[0,2,16],posit:[0,2,14,18],posix:2,posixlikeflag:4,possibl:[0,1,4,9,11,13,15,18],post:[0,2,14],postgresconnectionerror:8,potenti:[0,4,18],power:[2,4,6,14,15,18],pre:[0,2,18],precis:[0,18],pred:14,predefin:2,predic:[0,2,4,18],prefer:0,prefer_auth:0,preferred_local:0,prefix:[0,4,6,9,11,15,18],prefixes_for:2,prematur:2,premium:[0,2,18],premium_guild_subscript:0,premium_guild_tier_1:0,premium_guild_tier_2:0,premium_guild_tier_3:0,premium_promo_dismiss:0,premium_sinc:[0,18],premium_subscrib:[0,18],premium_subscriber_rol:[0,18],premium_subscript:0,premium_subscription_count:[0,18],premium_ti:[0,18],prepar:[0,2,18],prepare_help_command:[2,14],presenc:[0,2,9,14,18],present:[0,14],press:0,pretend:[5,14],pretti:[1,4,15],prevent:[0,2,10,18],preview_en:0,previou:[0,2,4,14,18],previous:[0,2,15,18],price:4,primari:0,primary_sku_id:0,primer:[6,10,18],principl:17,print:[0,2,3,5,8,9,12,14,16],printer:8,prior:[0,2,14,15],priority_speak:0,privaci:0,privacy_level:0,privacy_policy_url:0,privat:[0,2,14,17,18],private_channel:[0,2,15],private_thread:0,privatechannel:[2,14],privatemessageonli:2,privileg:[0,18],privilegedintentsrequir:0,probabl:[0,2],probe:0,problem:[0,9,14],procedur:2,process:[0,1,2,4,5,9,14,18],process_command:[2,9],process_slash_command:2,produc:0,profil:[0,18],program:[0,2,9,13],project:[10,12],promis:0,promot:0,prone:0,proof:14,propag:[0,2,4,18],proper:[0,2,4,18],properli:[0,2,11,16,18],properti:[0,2,3,4,8,18],protocol:[0,2,3],provid:[0,2,4,9,11,12,14,15,18],proxi:0,proxy_auth:0,proxy_url:0,prune:[0,18],prune_memb:[0,14,18],pseudo:14,public_flag:[0,18],public_thread:0,public_updates_channel:[0,18],publicli:[0,17,18],publicuserflag:18,publish:0,pull:9,pure:[0,2],purg:[0,14],purge_from:14,purpl:0,purpos:[0,2,9,12,14],push:9,put:[9,14],py:[0,2,5,6,7,8,9,12,13,15,16,18],pypi:12,pyright:18,python3:[9,12,16],python:[0,2,3,4,5,9,10,12,13,15,16,17,18],qualifi:[2,5],qualified_nam:[2,3,14],qualiti:0,queri:[0,2,3,11,18],query_memb:[0,11,18],question:[10,15],queue:2,quick:[6,9,11,12,14],quickli:[5,18],quickstart:10,quirk:0,quit:15,quot:[2,4,14,18],r:[0,4,9,14],race:[2,18],radic:11,raffl:0,rais:[0,2,4,8,14,16,18],ram:18,randint:3,random:[0,3,4,9,18],randomli:18,rang:[0,4],rare:[0,2,5],rate:[0,2,10,11,18],ratelimit:0,rather:[0,2,4,18],raw:[0,2,18],raw_channel_ment:[0,15],raw_ment:[0,15],raw_role_ment:0,raw_statu:0,rawmessageupdateev:18,rawreactionactionev:[11,18],rb:[0,9],re:[0,1,2,4,8,10,11,14,18],reach:[0,2,4,14,18],react:[0,2,18],reaction:[2,11,14,18],reaction_add:[0,2,14],reaction_remov:0,read:[0,2,5,8,9,14,18],read_messag:[0,18],read_message_histori:[0,2],readabl:2,reader:18,readi:[0,2,8,10,18],realiti:0,realli:0,reason:[0,2,4,6,14,15,18],reassign:18,receiv:[0,2,4,12,14,15,16,18],recent:[0,2],recipi:0,recipient_add:0,recipient_remov:0,recognis:[0,18],recommend:[0,2,4,9,13,14,18],reconnect:[0,2,8,14,18],record_usag:2,recoveri:0,recurs:[0,2],red:0,redesign:[14,18],redirect:[0,18],redirect_uri:0,reduc:[11,15,18],refer:[3,4,5,6,10,14,15,18],referenc:[0,4],refresh:[0,2,9],regard:[2,9,11,18],regardless:[0,2,14],regener:1,regex:[2,9,18],region:[0,2,14,15,18],regist:[0,2,3,4,8,14,15,16,18],registr:[0,2,6,14],regress:18,regular:[0,2,4,14,18],regularli:2,reinvok:[2,14,18],reiter:15,rejoin:0,rel:[0,2,8,18],relat:[2,10,11,14,15,18],relationship:0,relax:4,releas:18,releaselevel:0,relev:14,reli:[0,2,18],reliabl:18,reload:[2,6],reload_extens:[2,5],remain:[0,18],rememb:[9,12],remind:0,reminisc:4,remot:9,remov:[0,2,3,4,5,8,11,15,17,18],remove_author:[0,18],remove_check:[2,18],remove_cog:[2,3],remove_command:[2,18],remove_exception_typ:8,remove_field:0,remove_foot:0,remove_item:0,remove_listen:2,remove_markdown:[0,2,18],remove_ment:2,remove_react:[0,14,18],remove_rol:[0,14],remove_us:0,renam:[14,17,18],render:[0,2,18],reorder:4,repeat:0,repeatedli:[4,18],repetit:[4,6],replac:[0,2,14,18],replace_rol:14,repli:[0,2,14,18],replied_us:[0,18],report:[0,2,10],repositori:[9,10],repres:[0,2,8,14,18],represent:[0,18],request:[0,2,4,11,14,18],request_to_speak:[0,18],requested_to_speak_at:0,requesting_to_speak:0,requestswebhookadapt:18,requir:[0,1,2,4,11,12,14,18],require_colon:0,require_var_posit:[2,18],resend:18,reset:[0,2,18],reset_cooldown:2,resid:3,resili:14,resolut:[0,18],resolv:[0,2,18],resolve_invit:0,resolve_templ:0,resourc:[0,10,14],resp:[9,14],respect:[0,2,14],respond:[0,9,12,16,18],respons:[0,9,18],rest:[2,4,9],rest_is_raw:[2,4],restart:[0,2,5,8,18],restrict:[11,18],result:[0,1,2,4,9,11,14,18],resum:[0,2,4,14,18],retri:[2,8,14,18],retriev:[0,2,3,14,18],retry_aft:[2,18],return_messag:2,reus:0,revamp:14,revert:[14,18],revok:[0,1,2,18],revolv:12,rework:18,rewritten:18,rgb:[0,2,14,18],rich:[0,4,10,14,18],right:[0,4,9,14],rng:0,robust:4,role:[2,4,11,14,15,18],role_a:18,role_b:18,role_cr:0,role_delet:0,role_hierarchi:[14,18],role_id:0,role_ment:0,role_upd:0,roleconvert:[2,4],rolenotfound:2,roll:2,root:[2,14],root_par:[2,14],roughli:[0,2,11],routin:2,row:0,rpc:0,rpc_origin:0,rtc_region:[0,18],rule:[0,2,4,18],rules_channel:[0,18],run:[0,1,2,4,5,8,12,14,16,18],run_convert:2,run_coroutine_threadsaf:9,run_until_complet:[0,2,15],runtim:[2,9,14,18],runtime_check:0,runtimeerror:[2,8,14],russia:0,s:[0,1,2,3,4,5,8,10,11,12,13,14,15,16,17,18],safe:[0,9],safeti:[0,18],sai:[0,2,3,14],said:[0,2,9,14,15],same:[0,2,3,4,9,16,18],san:2,sane:10,satur:0,save:[0,4,14,18],scenario:[0,2],schedul:8,scheme:18,scope:[0,1,9,18],screen:[0,11,18],script:[12,16,18],scroll:11,scrub:[2,14],search:[0,2,4,10],second:[0,2,3,4,8,9,11,18],secondari:0,secret:[0,1,4,14],secret_cog_data:14,secretguilddata:4,secretguilddata_error:4,section:[0,2,11,16],see:[0,2,3,4,7,8,9,11,14,15,18],seed:[0,18],seek:0,seek_begin:0,seem:18,seemingli:18,seen:[0,4,15],selectopt:18,self:[0,2,3,4,8,12,14],self_deaf:0,self_mut:0,self_rol:[0,18],self_stream:[0,18],self_video:0,sell:[0,4],semant:[4,17],send:[0,2,3,4,5,11,16,18],send_audio_packet:0,send_bot_help:[2,14],send_cog_help:[2,14],send_command_help:[2,14],send_error_messag:[2,14],send_fil:[14,18],send_group_help:[2,14],send_help:[2,14,18],send_messag:[0,14,15,18],send_messages_in_thread:0,send_pag:2,send_tts_messag:0,send_typ:14,sens:15,sent:[0,2,4,18],sentinel:0,separ:[0,2,9,12,15,18],seq:0,sequenc:[0,2,8,15,18],seri:18,serialis:18,serv:9,server:[0,1,2,9,10,15,18],server_permiss:18,server_voice_st:[14,18],serverregion:[15,18],servic:[0,1],sess:14,session:[0,2,9,14,18],session_id:0,set:[0,2,3,4,8,10,11,12,14,16,18],set_author:0,set_channel_permiss:15,set_field_at:0,set_foot:0,set_imag:[0,9],set_permiss:[0,14],set_thumbnail:0,setformatt:13,setlevel:13,settabl:0,setup:[0,2,5,9,13],seven:0,seven_day_thread_arch:0,sever:[2,14],shallow:0,shard:[0,2,18],shard_count:[0,14],shard_id:[0,2,14],shardinfo:18,share:[0,1,2,3],shift:[0,2],shim:18,shop:4,short_doc:2,shortcut:[0,2,14,18],shorten:2,shorten_text:2,shorter:4,shorthand:[0,2,9],should:[0,1,2,3,4,7,8,9,11,12,14,15,18],shouldn:18,show:[0,11,14,18],show_hidden:2,showcas:12,shown:[0,2,18],side:[4,9,11,17],sidestep:18,sign:9,signal:[0,2,4,18],signatur:[2,4,9,14,15,18],signific:14,significantli:[11,14,18],silent:[0,2,4],similar:[0,2,4,5,8,9,14,18],similarli:[0,2,4,14],simpl:[4,5,7,8,9,13,14,16,18],simplifi:18,simul:[0,2,4],sinc:[0,2,3,4,9,11,14,15,16,18],singapor:0,singl:[0,2,3,4,5,8,14,18],singular:[4,14],situat:0,size:[0,2,14,18],skip:[0,4],sku:0,sku_id:0,slap:4,slapper:4,slash:[0,2,6],slash_command:[2,7,9],slash_command_guild:[2,7,9],slate:18,sleep:[0,2,8,9,18],sleep_until:[0,18],slightli:[0,4,11],slim:[0,9],slot:[0,18],slow:[0,2],slow_count:8,slowdown:11,slowmod:[0,4],slowmode_delai:[0,18],slug:0,sm:0,small:[0,7,18],small_imag:0,small_image_text:0,small_image_url:0,small_text:0,snippet:[13,14],snowflak:2,snowflake_tim:0,so:[0,1,2,3,4,9,14,15,16,18],socket:0,sold:0,sole:[0,2,4],solut:11,some:[0,2,3,4,8,9,11,14,15,18],some_channel:9,some_filenam:0,some_fp:14,somecogmixin:2,somehow:[0,2,18],somemixin:2,someon:[0,1,2,18],someth:[0,2,4,8,10,12,14,15,16,17,18],sometim:[0,4,5,12,18],somewhat:18,somewher:11,song:[0,9],soon:[0,1],sort:[0,2,14],sort_command:2,sort_valu:0,sourc:[0,9,12,14,18],source_channel:0,source_guild:0,source_message_delet:0,south:0,south_korea:[0,18],southafrica:0,space:[2,4,14],spam:[4,18],spammi:11,spawn:18,speak:[0,18],speaker:0,special:[0,2,6,9,14],specif:[0,2,4,7,10,11,14,16,18],specifi:[0,2,4,8,9,11,13,14,15,18],spectat:0,speech:0,speed:10,spell:2,spent:18,spike:18,splash:[0,18],split:[0,4],spoiler:[0,18],spotifi:18,stack:18,staff:0,stage:[0,2,18],stage_channel:0,stage_inst:0,stage_instance_cr:0,stage_instance_delet:0,stage_instance_id:0,stage_instance_upd:0,stage_moder:0,stage_voic:0,stagechannel:[2,4,18],stagechannelconvert:[2,4],stageinst:2,stageprivacylevel:0,stale:18,stand:[0,18],standard:[0,2,12,18],standardstick:2,start:[0,2,8,13,14,16,17,18],start_private_messag:14,start_thread:18,starter:18,startswith:[0,2,16],startup:11,state:[0,2,3,4,8,15,18],statement:0,static_format:[0,18],statu:[0,2,11,14,15,18],status:[11,18],status_cod:9,stderr:[0,2,4,8,18],stdin:[0,18],stdout:13,step:[0,4,5,10,11,16],stereo:0,sticker:[2,18],sticker_cr:0,sticker_delet:0,sticker_id:[0,2],sticker_limit:0,sticker_upd:0,stickerformattyp:0,stickerpack:2,stickertyp:0,still:[0,2,4,11,15,18],stop:[0,2,8,14,18],store:[0,14,18],storechannel:[2,4,18],storechannelconvert:[2,4,18],str:[0,2,4,9,18],straightforward:[1,15],strang:[0,18],strategi:2,stream:[9,18],streamintegr:0,streamplay:18,strict:[0,11],string:[0,2,4,5,9,14,15,18],stringli:0,strip:[2,4,18],strip_after_prefix:[2,18],strongli:13,structur:[15,18],stuff:[0,4,9],style:[0,9,16,18],sub:[0,2,4],subclass:[0,2,3,11,18],subcommand:[2,3,14],subcommand_not_found:[2,14],subcommand_pass:[2,18],subject:[0,18],submit:9,subprocess:0,subprocess_kwarg:0,subscrib:[0,11],subscript:[0,18],subsequ:[0,3],subset:0,substitut:0,subtl:0,succe:[2,8],succeed:2,success:[0,18],successfulli:[0,8],suffix:[2,18],suggest:9,suit:[0,18],suitabl:0,summari:0,superset:0,suppli:[0,2],support:[1,2,4,7,8,11,12,14,15,18],suppress:[0,18],suppress_emb:0,sure:[1,2,9,11,16],surpass:0,surpris:[4,18],swallow:0,sy:[0,2,8],sydnei:0,sync:[0,18],sync_permiss:0,synced_at:0,synchron:[0,2,14],syncwebhook:18,syntax:[0,2,4,10],syntaxerror:18,system:[0,2,4,7,11,12,14,16,18],system_channel:[0,3,18],system_channel_flag:[0,18],system_cont:[0,18],systemchannelflag:18,t:[0,2,4,8,11,14,16,17,18],tab:[1,11],tabl:[0,4],tag:[0,18],take:[0,2,3,4,5,8,9,14,15,18],taken:[0,2,18],talk:[0,11],target:[0,4],target_appl:0,target_application_id:0,target_typ:0,target_us:0,targettyp:0,task:[0,2,6,10,14,18],teal:0,team:[2,18],team_us:[0,18],teammembershipst:0,teardown:[2,5],teaser_graph:9,technic:[0,3,4,9,18],techniqu:[4,11],tediou:4,tell:[2,3,4,8,15,18],templat:[2,18],temporari:[0,18],ten:0,term:[0,2,4],termin:[0,2,18],terms_of_service_url:0,test:[2,4,7,14,15],test_error:4,tester_rol:0,text:[0,2,14,15,18],text_channel:[0,9,14],textchannel:[2,4,14,18],textchannelconvert:[2,4,14],than:[0,2,4,9,11,12,14,15,18],thank:18,thei:[0,2,3,4,9,14,15,18],them:[0,2,3,4,5,9,11,13,14,15,18],theme:[0,18],themselv:0,thi:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18],thing:[0,1,4,8,9,11,14,15,16,17,18],third:2,those:[0,2,4,8,14,18],though:[0,18],thousand:18,thread:[2,4,9,15,18],thread_creat:0,thread_delet:0,thread_id:0,thread_starter_messag:0,thread_upd:0,threadconvert:[2,4],threadmemb:18,threadnotfound:2,three:[0,2],three_day_thread_arch:0,through:[0,2,3,4,8,9,11,14,15,16,18],throughout:4,thrown:[0,2],thu:[0,2,14,17],thumb:[0,2,9],thumbnail:[0,9,18],thumbsup:9,ti:0,tick:[0,1],ticket:0,ticketed_events_en:0,tier:0,tighten:18,time:[0,1,2,4,5,6,8,9,10,11,14,17,18],timedelta:0,timeout:[0,2,14,18],timeouterror:[0,2,14],timestamp:[0,14,18],timezon:[0,8],tip:0,titl:[0,14],to_dict:0,to_fil:[0,18],to_refer:[0,18],to_rgb:[0,14],to_slap:4,to_tupl:14,to_upp:4,togeth:[2,4,9,14],toggl:[2,4,18],token:[0,1,2,12,14,15,16,18],too:[0,2,9,14,18],took:[0,14],tool:[2,3,18],toomanyargu:2,toomanyflag:2,top:[0,7],top_rol:[0,18],topic:[0,4],total:[0,2,11],toward:14,trace:18,traceback:0,track:[0,11],track_id:0,track_url:0,tracker:10,tradit:0,traffic:0,trait:0,transfer:0,transform:[0,2,9],transmit:0,transpar:[0,2,14],trap:18,treat:4,tri:[0,2,4,18],tribool:2,trigger:[0,2,16,18],trigger_typ:[0,2,14],trim:0,troubl:10,troubleshoot:7,truli:11,trust:[0,18],try_memb:0,try_own:2,try_us:[0,2],tt:[0,15],tuesdai:0,tune:4,tupl:[0,2,3,14,18],turn:[0,4,14],tutori:[12,13],twice:18,twitch:0,twitch_nam:0,two:[0,2,4,9,14,18],type:[0,2,8,9,11,15,18],typeerror:[0,2,8,18],typic:[0,2,3],u0001f44d:9,u:[2,12,14],ui:[2,18],ultim:[3,5],un:[0,2],unabl:0,unarch:0,unarchiv:[0,18],unauthent:0,unavail:[0,18],unban:[0,14,18],unbind:2,unbound:14,unboundlocalerror:18,uncaught:0,unchang:2,uncheck:1,uncondition:18,under:[0,1,2,4,11,18],undergo:14,underli:[0,2,14],underlin:2,underscor:[9,17],understand:2,undesir:8,undetermin:4,undo:[0,2],undocu:18,undon:[0,8],unexpect:[0,2,18],unexpectedquoteerror:2,unfortun:11,unhandl:8,unicod:[0,9,18],uninitialis:18,unintend:[2,4],union:[0,2,8],uniqu:[0,2],unix:[0,2],unknown:[0,2,18],unless:[0,1,2,14],unlik:[0,2,4,8],unlimit:[0,2],unload:[2,5,14,18],unload_extens:2,unlock:0,unnecessari:[0,18],unpack:[2,18],unpin:[0,14,18],unpin_messag:14,unread:0,unrestrict:0,unset:2,unspecifi:[0,2],unsuppress:0,unsur:1,unsync:0,until:[0,2,4,8,9,15,18],unus:18,up:[0,2,4,6,10,12,14,16,18],updat:[0,2,8,9,11,14,17,18],update_rate_limit:2,updated_at:0,upgrad:[17,18],upload:[0,2,7,14,18],upon:[0,2,18],upper:4,urgent:0,uri:0,url:[0,1,2,9,14,18],url_a:18,us:[0,1,2,4,5,6,7,8,10,11,12,13,14,15,16,18],us_centr:0,us_east:0,us_south:0,us_west:[0,2,15],usabl:[0,2,18],usag:[0,2,3,4,14,18],use_cach:[0,18],use_external_emoji:[0,18],use_external_stick:0,use_nicknam:[2,4],use_private_thread:0,use_slash_command:[0,9,18],use_thread:0,use_voice_activ:0,useless:15,user:[1,2,4,9,11,12,15,16,18],user_id:[0,2,18],user_limit:0,userbot:18,userconvert:[2,4,14,18],userflag:0,userinputerror:[2,18],usernam:[0,4,11,18],usernotfound:2,usual:[0,2,4,5,12],utc:[0,2,8],utcnow:0,utf:[2,13],util:[1,2,9,14,15,18],utilis:12,v0:14,v1:[4,10],v2:[4,14],v5:18,v6:18,v:[0,4],valid:[0,2,4,9,14,15,18],valu:[0,2,4,8,15,17,18],valueerror:[0,2,8,18],vaniti:[0,14],vanity_cod:0,vanity_invit:[0,14],vanity_url:0,vanity_url_cod:0,variabl:[0,14,15],variad:[2,4],variou:[3,11,18],vc:14,ve:[0,1,14,16],venv:12,verbos:13,veri:[0,2,4,7,8],verif:[0,11,18],verifi:[0,2,11,18],verification_level:[0,18],verification_pending_guild_limit:0,verificationlevel:[0,18],verified_bot:0,verified_bot_develop:[0,18],verify_check:[2,18],verify_kei:0,version:[2,4,8,9,10,11,12,13,15,18],version_info:[0,18],versionad:0,very_high:18,via:[0,2,3,4,7,8,9,11,13,14,15,18],video:0,video_quality_mod:0,videoqualitymod:0,view:[2,14,18],view_audit_log:[0,14],view_channel:[0,18],view_guild_insight:[0,18],viewabl:0,vip:[0,18],vip_amsterdam:0,vip_region:0,vip_us_east:0,vip_us_west:0,visibl:[0,2,14,18],visit:3,voic:[2,9,12,18],voice_channel:[0,14],voice_cli:[0,2,14,18],voice_client_in:18,voice_memb:14,voice_server_upd:0,voice_st:[0,18],voice_state_upd:0,voicechannel:[2,4,14,18],voicechannelconvert:[2,4,14],voicecli:[2,14,18],voiceprotocol:[2,18],voiceregion:[0,2,18],voicest:[14,18],volum:[0,14],vs:0,w:[9,13],wa:[0,2,4,8,9,14,15,16,18],wai:[0,2,4,8,9,11,14,16,18],wait:[0,2,8,11,18],wait_for:[0,2,14],wait_for_messag:[14,18],wait_for_react:[14,18],wait_until_login:[14,18],wait_until_readi:[0,2,8,14,18],walk:[2,16],walk_command:[2,3,18],wall:4,want:[0,1,2,3,4,5,7,8,9,11,12,14,15,18],warn:[0,4,9,13,18],watch:[0,9],we:[0,1,2,3,4,5,8,9,11,14,15,16,18],web:0,web_statu:0,webhook:[2,14,18],webhook_cr:0,webhook_delet:0,webhook_id:[0,2,14],webhook_upd:0,webhookmessag:[2,18],webhooktyp:[0,18],webm:0,webp:0,websit:[1,11],websocket:[0,2,14,18],week:0,welcom:[0,3],welcome_screen_en:0,well:[0,2,3,4,9,11,13,14,18],went:15,were:[0,2,8,11,14,15,18],west:[0,2,15],what:[0,2,4,5,8,13,14,15,17,18],whatev:[0,18],whatever_you_want_to_call_it:9,when:[0,1,2,3,4,5,8,9,10,11,12,14,15,16,17,18],when_ment:2,when_mentioned_or:2,whenev:[0,2,14],where:[0,2,3,4,14,15,18],whether:[0,2,8,11,14,18],which:[0,2,3,4,5,7,8,9,11,14,15,16,17,18],whisper:14,white:4,whitelist:2,whitespac:[2,18],who:[0,2,11,18],whose:0,why:2,wide:[0,1,2,12],widget:[2,18],widget_channel:0,widget_en:0,width:[0,2,18],window:[0,12,16,18],windowslikeflag:4,winner:0,wise:[0,2,14,18],wish:[0,2],with_:18,with_count:[0,2],with_expir:[0,2],with_format:0,with_siz:0,with_static_format:0,withdraw_monei:3,within:[0,2,4,9,18],without:[0,2,5,9,11,14,17,18],won:0,word:4,work:[0,1,2,4,8,10,12,14,15,18],world:[0,4],worri:8,worth:[0,1,4],would:[0,2,3,4,9,11,13,14,18],wrap:[0,4,9,14,18],wrapper:10,write:[4,9,13,18],written:[0,4,11],wrong:[0,2],ws:[0,18],www:18,x:[0,2,4,14,18],x__y:0,xsalsa20_poly1305_lit:18,y:[0,4],ye:[1,4],year:0,yellow:0,yet:[0,18],yield:[0,2,9,15,18],you:[0,1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,18],your:[0,2,3,4,7,9,10,11,12,13,14,15,16,18],yourself:[0,2,4,11,14],youtub:[0,18],zero:0,zerodivisionerror:18,zh:0,zip:9},titles:["API Reference","Creating a Bot Account","API Reference","Cogs","Commands","Extensions","discord.ext.commands \u2013 Bot commands framework","Slash Commands","discord.ext.tasks \u2013 asyncio.Task helpers","Frequently Asked Questions","Welcome to discord.py","A Primer to Gateway Intents","Introduction","Setting Up Logging","Migrating to v1.0","Migrating to v0.10.0","Quickstart","Version Guarantees","Changelog"],titleterms:{"0":[14,15,18],"1":18,"10":[15,18],"11":18,"12":18,"13":18,"14":18,"15":18,"16":18,"2":18,"3":18,"4":18,"5":18,"6":18,"7":18,"abstract":0,"break":[17,18],"class":0,"do":[9,11],"enum":2,"function":[0,9,15],"int":14,"long":11,"new":18,A:[11,16],For:14,Is:9,account:1,actionrow:0,activ:0,add:9,advanc:4,after:[9,14],allowedment:0,an:9,api:[0,2,8,18],appinfo:0,applic:0,applicationflag:0,ar:[11,14],aren:9,argument:[4,9,15],ask:9,asset:0,async:0,asynchron:14,asyncio:8,attach:0,audiosourc:0,audit:[0,9],auditlogchang:0,auditlogdiff:0,auditlogentri:0,autoshardedbot:2,autoshardedcli:0,await:9,background:9,base:0,baseact:0,basic:[4,12],befor:14,being:9,block:9,bool:4,bot:[0,1,2,6,9,16],bug:18,button:0,cach:11,can:9,categorychannel:0,chang:[14,15,17,18],changelog:18,channel:[9,14],check:[2,4,14],clean:5,client:[0,15],clientus:0,cog:[2,3,5,14],cogmeta:2,colour:0,command:[2,4,6,7,9,14,18],compon:0,concept:12,connect:[0,14],context:[2,4,14],convert:[2,4,14],cooldown:2,coroutin:[9,15],creat:[1,9],customact:0,d:11,data:0,decor:2,defaulthelpcommand:2,deletedreferencedmessag:0,depend:14,dict:[4,14],discord:[0,4,6,8,10,18],dm:9,dmchannel:0,doe:[9,11],emb:[0,9],emoji:0,enabl:9,entri:9,enumer:[0,15],environ:12,error:4,event:[0,2,9,14,15],exampl:[3,9,17],except:[0,2],ext:[6,8,18],extens:[5,9,10,14],featur:18,fetch:0,ffmpegaudio:0,ffmpegopusaudio:0,ffmpegpcmaudio:0,file:[0,9],find:9,fire:11,fix:18,flag:2,flagconvert:4,forc:15,framework:6,frequent:9,game:0,gatewai:11,gener:9,get:[9,10],global:4,go:11,greedi:4,group:2,groupchannel:0,groupmixin:2,guarante:17,guild:[0,14],guildchannel:0,guildstick:0,handl:4,help:[2,10,14],helpcommand:2,helper:[2,8,14],helpformatt:14,hierarchi:[0,2],hook:14,how:9,i:[9,11],id:9,imag:9,improv:[14,18],info:0,inlin:4,inspect:3,instal:12,integr:0,intent:[0,11],interact:0,interactionmessag:0,interactionrespons:0,introduct:12,invit:[0,1],invoc:[4,14],item:0,iter:[0,14,15],keyword:[4,15],kit:0,librari:0,list:4,liter:4,local:9,log:[0,9,13],major:14,make:9,manag:15,manual:10,mean:9,member:[0,11,14,15],membercacheflag:0,messag:[0,9,14],messageflag:0,messagerefer:0,meta:[3,10],method:3,migrat:[14,15],minim:16,minimalhelpcommand:2,miscellan:[14,18],model:[0,9,14],my:[9,11],need:11,network:0,non:17,now:14,object:0,on_messag:9,on_readi:11,onli:[4,7],option:[2,3,4],opu:0,origin:9,pagin:2,paramet:4,partialappinfo:0,partialemoji:0,partialinvitechannel:0,partialinviteguild:0,partialmessag:0,partialwebhookchannel:0,partialwebhookguild:0,pass:9,pcmaudio:0,pcmvolumetransform:0,perform:18,permiss:0,permissionoverwrit:0,plai:9,player:9,posit:4,prefix:2,prerequisit:12,presenc:11,primer:[5,11],privatechannel:0,privileg:11,properti:[14,15],publicuserflag:0,py:10,python:14,question:9,quick:3,quickstart:16,quot:9,rawbulkmessagedeleteev:0,rawintegrationdeleteev:0,rawmessagedeleteev:0,rawmessageupdateev:0,rawreactionactionev:0,rawreactionclearemojiev:0,rawreactionclearev:0,rawtypingev:0,reaction:[0,9],recip:8,refer:[0,2,8],registr:[3,15],relat:0,reliabl:0,reload:5,remov:14,renam:15,request:9,requir:9,retriev:11,role:0,roletag:0,run:[9,15],s:9,select:0,selectmenu:0,selectopt:0,send:[9,14],sent:9,server:14,set:[9,13],shard:14,shardinfo:0,show:[2,9],slash:[4,7,9],snowflak:[0,14],so:11,someth:9,special:[3,4],specif:9,split:14,spotifi:0,stagechannel:0,stageinst:0,standardstick:0,start:[9,10],state:14,statu:9,sticker:0,stickeritem:0,stickerpack:0,stop:9,storechannel:0,stream:0,subclass:14,subcommand:9,support:0,syncwebhook:0,syncwebhookmessag:0,systemchannelflag:0,t:9,take:11,task:8,team:0,teammemb:0,templat:0,textchannel:0,thread:0,threadmemb:0,troubleshoot:11,tupl:4,type:[4,14],ui:0,union:4,up:[5,9,13],upgrad:14,upload:9,us:[3,9],usag:9,user:[0,14],util:0,v0:[15,18],v1:[14,18],v2:18,valu:14,variabl:4,version:[0,14,17],view:0,virtual:12,voic:[0,14],voicechannel:0,voicecli:0,voiceprotocol:0,voicest:0,wait:14,web:9,webhook:0,webhookmessag:0,welcom:10,what:[9,11],where:[9,11],why:[9,11],widget:0,widgetchannel:0,widgetmemb:0,won:9,work:9,your:1}}) \ No newline at end of file diff --git a/docs/Python/html/version_guarantees.html b/docs/Python/html/version_guarantees.html new file mode 100644 index 00000000..9861d93a --- /dev/null +++ b/docs/Python/html/version_guarantees.html @@ -0,0 +1,174 @@ + + + + + + Version Guarantees + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

Version Guarantees

+

The library follows a semantic versioning principle which means that the major version is updated every time there is an incompatible API change. However due to the lack of guarantees on the Discord side when it comes to breaking changes along with the fairly dynamic nature of Python it can be hard to discern what can be considered a breaking change and what isn’t.

+

The first thing to keep in mind is that breaking changes only apply to publicly documented functions and classes. If it’s not listed in the documentation here then it is not part of the public API and is thus bound to change. This includes attributes that start with an underscore or functions without an underscore that are not documented.

+
+

Note

+

The examples below are non-exhaustive.

+
+
+

Examples of Breaking Changes

+
    +
  • Changing the default parameter value to something else.

  • +
  • Renaming a function without an alias to an old function.

  • +
  • Adding or removing parameters to an event.

  • +
+
+
+

Examples of Non-Breaking Changes

+
    +
  • Adding or removing private underscored attributes.

  • +
  • Adding an element into the __slots__ of a data class.

  • +
  • Changing the behaviour of a function to fix a bug.

  • +
  • Changes in the documentation.

  • +
  • Modifying the internal HTTP handling.

  • +
  • Upgrading the dependencies to a new version, major or otherwise.

  • +
+
+
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/Python/html/whats_new.html b/docs/Python/html/whats_new.html new file mode 100644 index 00000000..dc637d88 --- /dev/null +++ b/docs/Python/html/whats_new.html @@ -0,0 +1,1885 @@ + + + + + + Changelog + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+ + + + settings +
+ +
+ +
+

Changelog

+

This page keeps a detailed human friendly rendering of what’s new and changed +in specific versions.

+
+

v2.0.0

+

This version was partly developed by Danny, and partly by the enhanced-discord.py contributors. +The library has been updated with breaking changes, and as such the major version was changed.

+
    +
  • +
    Performance of the library has improved significantly (all times with 1 process and 1 AutoShardedBot):
      +
    • 735 guilds boot up time (with chunking): 57s/1.7 GiB RAM -> 42s/1.4 GiB RAM

    • +
    • 27k guilds boot up time (with chunking): 477s/8 GiB RAM -> 303s/7.2 GiB RAM

    • +
    • 48k guilds boot up time (without chunking): 109s -> 67s

    • +
    • 106k guilds boot up time (without chunking): 3300s -> 3090s

    • +
    +
    +
    +
  • +
  • +
    The entire public API of the library is now completely type hinted.
      +
    • There may still be bugs however.

    • +
    • For best type hinting experience consider using Pyright.

    • +
    +
    +
    +
  • +
  • Almost all edit methods now return their updated counterpart rather than doing an in-place edit.

  • +
  • Japanese docs were removed, as we are no longer able to keep them in sync.

  • +
+
+

Breaking Changes

+ +
+
+

New Features

+ +
+
+

Bug Fixes

+ +
+
+
+

v1.7.3

+
+

Bug Fixes

+ +
+
+
+

v1.7.2

+
+

Bug Fixes

+ +
+
+
+

v1.7.1

+
+

Bug Fixes

+ +
+
+
+

v1.7.0

+

This version is mainly for improvements and bug fixes. This is more than likely the last major version in the 1.x series. +Work after this will be spent on v2.0. As a result, this is the last version to support Python 3.5. +Likewise, this is the last version to support user bots.

+

Development of v2.0 will have breaking changes and support for newer API features.

+
+

New Features

+ +
+
+

Bug Fixes

+ +
+
+

Miscellaneous

+
    +
  • User endpoints and all userbot related functionality has been deprecated and will be removed in the next major version of the library.

  • +
  • Permission class methods were updated to match the UI of the Discord client (GH-6476)

  • +
  • _ and - characters are now stripped when making a new cog using the discord package (GH-6313)

  • +
+
+
+
+

v1.6.0

+

This version comes with support for replies and stickers.

+
+

New Features

+ +
+
+

Bug Fixes

+ +
+
+

Miscellaneous

+ +
+
+
+

v1.5.1

+
+

Bug Fixes

+
    +
  • Fix utils.escape_markdown() not escaping quotes properly (GH-5897)

  • +
  • Fix Message not being hashable (GH-5901, GH-5866)

  • +
  • Fix moving channels to the end of the channel list (GH-5923)

  • +
  • Fix seemingly strange behaviour in __eq__ for PermissionOverwrite (GH-5929)

  • +
  • Fix aliases showing up in __iter__ for Intents (GH-5945)

  • +
  • Fix the bot disconnecting from voice when moving them to another channel (GH-5904)

  • +
  • Fix attribute errors when chunking times out sometimes during delayed on_ready dispatching.

  • +
  • Ensure that the bot’s own member is not evicted from the cache (GH-5949)

  • +
+
+
+

Miscellaneous

+
    +
  • Members are now loaded during GUILD_MEMBER_UPDATE events if MemberCacheFlags.joined is set. (GH-5930)

  • +
  • +
    [ext.commands] MemberConverter now properly lazily fetches members if not available from cache.
      +
    • This is the same as having discord.Member as the type-hint.

    • +
    +
    +
    +
  • +
  • Guild.chunk() now allows concurrent calls without spamming the gateway with requests.

  • +
+
+
+
+

v1.5.0

+

This version came with forced breaking changes that Discord is requiring all bots to go through on October 7th. It is highly recommended to read the documentation on intents, A Primer to Gateway Intents.

+
+

API Changes

+
    +
  • Members and presences will no longer be retrieved due to an API change. See Privileged Intents for more info.

  • +
  • As a consequence, fetching offline members is disabled if the members intent is not enabled.

  • +
+
+
+

New Features

+ +
+
+

Bug Fixes

+ +
+
+

Miscellaneous

+
    +
  • Webhook requests are now logged (GH-5798)

  • +
  • Remove caching layer from AutoShardedClient.shards. This was causing issues if queried before launching shards.

  • +
  • Gateway rate limits are now handled.

  • +
  • Warnings logged due to missed caches are now changed to DEBUG log level.

  • +
  • Some strings are now explicitly interned to reduce memory usage.

  • +
  • Usage of namedtuples has been reduced to avoid potential breaking changes in the future (GH-5834)

  • +
  • [ext.commands] All BadArgument exceptions from the built-in converters now raise concrete exceptions to better tell them apart (GH-5748)

  • +
  • [ext.tasks] Lazily fetch the event loop to prevent surprises when changing event loop policy (GH-5808)

  • +
+
+
+
+

v1.4.2

+

This is a maintenance release with backports from v1.5.0.

+
+

Bug Fixes

+ +
+
+

Miscellaneous

+
    +
  • Remove caching layer from AutoShardedClient.shards. This was causing issues if queried before launching shards.

  • +
  • [ext.tasks] Lazily fetch the event loop to prevent surprises when changing event loop policy (GH-5808)

  • +
+
+
+
+

v1.4.1

+
+

Bug Fixes

+
    +
  • Properly terminate the connection when Client.close() is called (GH-5207)

  • +
  • Fix error being raised when clearing embed author or image when it was already cleared (GH-5210, GH-5212)

  • +
  • Fix __path__ to allow editable extensions (GH-5213)

  • +
+
+
+
+

v1.4.0

+

Another version with a long development time. Features like Intents are slated to be released in a v1.5 release. Thank you for your patience!

+
+

New Features

+ +
+
+

Bug Fixes

+ +
+
+

Miscellaneous

+ +
+
+
+

v1.3.4

+
+

Bug Fixes

+
    +
  • Fix an issue with channel overwrites causing multiple issues including crashes (GH-5109)

  • +
+
+
+
+

v1.3.3

+
+

Bug Fixes

+
    +
  • +
    Change default WS close to 4000 instead of 1000.
      +
    • The previous close code caused sessions to be invalidated at a higher frequency than desired.

    • +
    +
    +
    +
  • +
  • Fix None appearing in Member.activities. (GH-2619)

  • +
+
+
+
+

v1.3.2

+

Another minor bug fix release.

+
+

Bug Fixes

+ +
+
+
+

v1.3.1

+

Minor bug fix release.

+
+

Bug Fixes

+
    +
  • Fix fetching invites in guilds that the user is not in.

  • +
  • Fix the channel returned from Client.fetch_channel() raising when sending messages. (GH-2531)

  • +
+
+
+

Miscellaneous

+
    +
  • Fix compatibility warnings when using the Python 3.9 alpha.

  • +
  • Change the unknown event logging from WARNING to DEBUG to reduce noise.

  • +
+
+
+
+

v1.3.0

+

This version comes with a lot of bug fixes and new features. It’s been in development for a lot longer than was anticipated!

+
+

New Features

+ +
+
+

Bug Fixes

+ +
+
+

Miscellaneous

+
    +
  • The library now fully supports Python 3.8 without warnings.

  • +
  • Bump the dependency of websockets to 8.0 for those who can use it. (GH-2453)

  • +
  • Due to Discord providing Member data in mentions, users will now be upgraded to Member more often if mentioned.

  • +
  • utils.escape_markdown() now properly escapes new quote markdown.

  • +
  • The message cache can now be disabled by passing None to max_messages in Client.

  • +
  • The default message cache size has changed from 5000 to 1000 to accommodate small bots.

  • +
  • Lower memory usage by only creating certain objects as needed in Role.

  • +
  • There is now a sleep of 5 seconds before re-IDENTIFYing during a reconnect to prevent long loops of session invalidation.

  • +
  • +
    The rate limiting code now uses millisecond precision to have more granular rate limit handling.
      +
    • Along with that, the rate limiting code now uses Discord’s response to wait. If you need to use the system clock again for whatever reason, consider passing assume_synced_clock in Client.

    • +
    +
    +
    +
  • +
  • The performance of Guild.default_role has been improved from O(N) to O(1). (GH-2375)

  • +
  • The performance of Member.roles has improved due to usage of caching to avoid surprising performance traps.

  • +
  • The GC is manually triggered during things that cause large deallocations (such as guild removal) to prevent memory fragmentation.

  • +
  • There have been many changes to the documentation for fixes both for usability, correctness, and to fix some linter errors. Thanks to everyone who contributed to those.

  • +
  • The loading of the opus module has been delayed which would make the result of opus.is_loaded() somewhat surprising.

  • +
  • [ext.commands] Usernames prefixed with @ inside DMs will properly convert using the User converter. (GH-2498)

  • +
  • [ext.tasks] The task sleeping time will now take into consideration the amount of time the task body has taken before sleeping. (GH-2516)

  • +
+
+
+
+

v1.2.5

+
+

Bug Fixes

+
    +
  • Fix a bug that caused crashes due to missing animated field in Emoji structures in reactions.

  • +
+
+
+
+

v1.2.4

+
+

Bug Fixes

+ +
+
+
+

v1.2.3

+
+

Bug Fixes

+ +
+
+
+

v1.2.2

+
+

Bug Fixes

+
    +
  • Audit log related attribute access have been fixed to not error out when they shouldn’t have.

  • +
+
+
+
+

v1.2.1

+
+

Bug Fixes

+
    +
  • User.avatar_url and related attributes no longer raise an error.

  • +
  • More compatibility shims with the enum.Enum code.

  • +
+
+
+
+

v1.2.0

+

This update mainly brings performance improvements and various nitro boosting attributes (referred to in the API as “premium guilds”).

+
+

New Features

+ +
+
+

Bug Fixes

+ +
+
+

Miscellaneous

+
    +
  • +
    Improve performance of all Enum related code significantly.
      +
    • This was done by replacing the enum.Enum code with an API compatible one.

    • +
    • This should not be a breaking change for most users due to duck-typing.

    • +
    +
    +
    +
  • +
  • Improve performance of message creation by about 1.5x.

  • +
  • Improve performance of message editing by about 1.5-4x depending on payload size.

  • +
  • Improve performance of attribute access on Member about by 2x.

  • +
  • Improve performance of utils.get() by around 4-6x depending on usage.

  • +
  • Improve performance of event parsing lookup by around 2.5x.

  • +
  • Keyword arguments in Client.start() and Client.run() are now validated (GH-953, GH-2170)

  • +
  • The Discord error code is now shown in the exception message for HTTPException.

  • +
  • Internal tasks launched by the library will now have their own custom __repr__.

  • +
  • All public facing types should now have a proper and more detailed __repr__.

  • +
  • [ext.tasks] Errors are now logged via the standard logging module.

  • +
+
+
+
+

v1.1.1

+
+

Bug Fixes

+
    +
  • Webhooks do not overwrite data on retrying their HTTP requests (GH-2140)

  • +
+
+
+

Miscellaneous

+
    +
  • Add back signal handling to Client.run() due to issues some users had with proper cleanup.

  • +
+
+
+
+

v1.1.0

+
+

New Features

+ +
+

discord.ext.commands

+ +
+
+
+

Bug Fixes

+ +
+

discord.ext.commands

+
    +
  • Fix lambda converters in a non-module context (e.g. eval).

  • +
  • +
    Use message creation time for reference time when computing cooldowns.
      +
    • This prevents cooldowns from triggering during e.g. a RESUME session.

    • +
    +
    +
    +
  • +
  • Fix the default on_command_error() to work with new-style cogs (GH-2094)

  • +
  • DM channels are now recognised as NSFW in is_nsfw() check.

  • +
  • Fix race condition with help commands (GH-2123)

  • +
  • Fix cog descriptions not showing in MinimalHelpCommand (GH-2139)

  • +
+
+
+
+

Miscellaneous

+
    +
  • Improve the performance of internal enum creation in the library by about 5x.

  • +
  • Make the output of python -m discord --version a bit more useful.

  • +
  • The loop cleanup facility has been rewritten again.

  • +
  • The signal handling in Client.run() has been removed.

  • +
+
+

discord.ext.commands

+
    +
  • Custom exception classes are now used for all default checks in the library (GH-2101)

  • +
+
+
+
+
+

v1.0.1

+
+

Bug Fixes

+
    +
  • Fix issue with speaking state being cast to int when it was invalid.

  • +
  • Fix some issues with loop cleanup that some users experienced on Linux machines.

  • +
  • Fix voice handshake race condition (GH-2056, GH-2063)

  • +
+
+
+
+

v1.0.0

+

The changeset for this version are too big to be listed here, for more information please +see the migrating page.

+
+
+

v0.16.6

+
+

Bug Fixes

+
    +
  • Fix issue with Client.create_server() that made it stop working.

  • +
  • Fix main thread being blocked upon calling StreamPlayer.stop.

  • +
  • Handle HEARTBEAT_ACK and resume gracefully when it occurs.

  • +
  • Fix race condition when pre-emptively rate limiting that caused releasing an already released lock.

  • +
  • Fix invalid state errors when immediately cancelling a coroutine.

  • +
+
+
+
+

v0.16.1

+

This release is just a bug fix release with some better rate limit implementation.

+
+

Bug Fixes

+
    +
  • Servers are now properly chunked for user bots.

  • +
  • The CDN URL is now used instead of the API URL for assets.

  • +
  • Rate limit implementation now tries to use header information if possible.

  • +
  • Event loop is now properly propagated (GH-420)

  • +
  • Allow falsey values in Client.send_message() and Client.send_file().

  • +
+
+
+
+

v0.16.0

+
+

New Features

+
    +
  • Add Channel.overwrites to get all the permission overwrites of a channel.

  • +
  • Add Server.features to get information about partnered servers.

  • +
+
+
+

Bug Fixes

+
    +
  • Timeout when waiting for offline members while triggering on_ready().

    +
    +
      +
    • The fact that we did not timeout caused a gigantic memory leak in the library that caused +thousands of duplicate Member instances causing big memory spikes.

    • +
    +
    +
  • +
  • Discard null sequences in the gateway.

    +
    +
      +
    • The fact these were not discarded meant that on_ready() kept being called instead of +on_resumed(). Since this has been corrected, in most cases on_ready() will be +called once or twice with on_resumed() being called much more often.

    • +
    +
    +
  • +
+
+
+
+

v0.15.1

+
    +
  • Fix crash on duplicate or out of order reactions.

  • +
+
+
+

v0.15.0

+
+

New Features

+
    +
  • Rich Embeds for messages are now supported.

    +
    +
      +
    • To do so, create your own Embed and pass the instance to the embed keyword argument to Client.send_message() or Client.edit_message().

    • +
    +
    +
  • +
  • Add Client.clear_reactions() to remove all reactions from a message.

  • +
  • Add support for MESSAGE_REACTION_REMOVE_ALL event, under on_reaction_clear().

  • +
  • Add Permissions.update() and PermissionOverwrite.update() for bulk permission updates.

    +
    +
      +
    • This allows you to use e.g. p.update(read_messages=True, send_messages=False) in a single line.

    • +
    +
    +
  • +
  • Add PermissionOverwrite.is_empty() to check if the overwrite is empty (i.e. has no overwrites set explicitly as true or false).

  • +
+

For the command extension, the following changed:

+
    +
  • Context is no longer slotted to facilitate setting dynamic attributes.

  • +
+
+
+
+

v0.14.3

+
+

Bug Fixes

+
    +
  • Fix crash when dealing with MESSAGE_REACTION_REMOVE

  • +
  • Fix incorrect buckets for reactions.

  • +
+
+
+
+

v0.14.2

+
+

New Features

+
    +
  • +
    Client.wait_for_reaction() now returns a namedtuple with reaction and user attributes.
      +
    • This is for better support in the case that None is returned since tuple unpacking can lead to issues.

    • +
    +
    +
    +
  • +
+
+
+

Bug Fixes

+
    +
  • Fix bug that disallowed None to be passed for emoji parameter in Client.wait_for_reaction().

  • +
+
+
+
+

v0.14.1

+
+

Bug fixes

+
    +
  • +
    Fix bug with Reaction not being visible at import.
      +
    • This was also breaking the documentation.

    • +
    +
    +
    +
  • +
+
+
+
+

v0.14.0

+

This update adds new API features and a couple of bug fixes.

+
+

New Features

+
    +
  • Add support for Manage Webhooks permission under Permissions.manage_webhooks

  • +
  • Add support for around argument in 3.5+ Client.logs_from().

  • +
  • +
    Add support for reactions.
    +
    +
    +
  • +
+
+
+

Bug Fixes

+ +
+
+
+

v0.13.0

+

This is a backwards compatible update with new features.

+
+

New Features

+
    +
  • Add the ability to manage emojis.

    +
    +
      +
    • Client.create_custom_emoji() to create new emoji.

    • +
    • Client.edit_custom_emoji() to edit an old emoji.

    • +
    • Client.delete_custom_emoji() to delete a custom emoji.

    • +
    +
    +
  • +
  • Add new Permissions.manage_emojis toggle.

    +
    +
    +
    +
  • +
  • Add new statuses for Status.

    +
    +
    +
    +
  • +
  • Deprecate Client.change_status()

    +
    +
      +
    • Use Client.change_presence() instead for better more up to date functionality.

    • +
    • This method is subject for removal in a future API version.

    • +
    +
    +
  • +
  • Add Client.change_presence() for changing your status with the new Discord API change.

    +
    +
      +
    • This is the only method that allows changing your status to invisible or do not disturb.

    • +
    +
    +
  • +
+
+
+

Bug Fixes

+
    +
  • Paginator pages do not exceed their max_size anymore (GH-340)

  • +
  • Do Not Disturb users no longer show up offline due to the new Status changes.

  • +
+
+
+
+

v0.12.0

+

This is a bug fix update that also comes with new features.

+
+

New Features

+
    +
  • Add custom emoji support.

    +
    +
      +
    • Adds a new class to represent a custom Emoji named Emoji

    • +
    • Adds a utility generator function, Client.get_all_emojis().

    • +
    • Adds a list of emojis on a server, Server.emojis.

    • +
    • Adds a new event, on_server_emojis_update().

    • +
    +
    +
  • +
  • Add new server regions to ServerRegion

    +
    +
      +
    • ServerRegion.eu_central and ServerRegion.eu_west.

    • +
    +
    +
  • +
  • Add support for new pinned system message under MessageType.pins_add.

  • +
  • Add order comparisons for Role to allow it to be compared with regards to hierarchy.

    +
    +
      +
    • This means that you can now do role_a > role_b etc to check if role_b is lower in the hierarchy.

    • +
    +
    +
  • +
  • Add Server.role_hierarchy to get the server’s role hierarchy.

  • +
  • Add Member.server_permissions to get a member’s server permissions without their channel specific overwrites.

  • +
  • Add Client.get_user_info() to retrieve a user’s info from their ID.

  • +
  • Add a new Player property, Player.error to fetch the error that stopped the player.

    +
    +
      +
    • To help with this change, a player’s after function can now take a single parameter denoting the current player.

    • +
    +
    +
  • +
  • Add support for server verification levels.

    +
    +
      +
    • Adds a new enum called VerificationLevel.

    • +
    • This enum can be used in Client.edit_server() under the verification_level keyword argument.

    • +
    • Adds a new attribute in the server, Server.verification_level.

    • +
    +
    +
  • +
  • Add Server.voice_client shortcut property for Client.voice_client_in().

    +
    +
      +
    • This is technically old (was added in v0.10.0) but was undocumented until v0.12.0.

    • +
    +
    +
  • +
+

For the command extension, the following are new:

+
    +
  • Add custom emoji converter.

  • +
  • All default converters that can take IDs can now convert via ID.

  • +
  • Add coroutine support for Bot.command_prefix.

  • +
  • Add a method to reset command cooldown.

  • +
+
+
+

Bug Fixes

+
    +
  • Fix bug that caused the library to not work with the latest websockets library.

  • +
  • Fix bug that leaked keep alive threads (GH-309)

  • +
  • Fix bug that disallowed ServerRegion from being used in Client.edit_server().

  • +
  • Fix bug in Channel.permissions_for() that caused permission resolution to happen out of order.

  • +
  • Fix bug in Member.top_role that did not account for same-position roles.

  • +
+
+
+
+

v0.11.0

+

This is a minor bug fix update that comes with a gateway update (v5 -> v6).

+
+

Breaking Changes

+ +
+
+

New Features

+
    +
  • Add the ability to prune members via Client.prune_members().

  • +
  • Switch the websocket gateway version to v6 from v5. This allows the library to work with group DMs and 1-on-1 calls.

  • +
  • Add AppInfo.owner attribute.

  • +
  • Add CallMessage for group voice call messages.

  • +
  • Add GroupCall for group voice call information.

  • +
  • Add Message.system_content to get the system message.

  • +
  • Add the remaining VIP servers and the Brazil servers into ServerRegion enum.

  • +
  • Add stderr argument to VoiceClient.create_ffmpeg_player() to redirect stderr.

  • +
  • The library now handles implicit permission resolution in Channel.permissions_for().

  • +
  • Add Server.mfa_level to query a server’s 2FA requirement.

  • +
  • Add Permissions.external_emojis permission.

  • +
  • Add Member.voice attribute that refers to a VoiceState.

    +
    +
      +
    • For backwards compatibility, the member object will have properties mirroring the old behaviour.

    • +
    +
    +
  • +
+

For the command extension, the following are new:

+
    +
  • Command cooldown system with the cooldown decorator.

  • +
  • UserInputError exception for the hierarchy for user input related errors.

  • +
+
+
+

Bug Fixes

+
    +
  • Client.email is now saved when using a token for user accounts.

  • +
  • Fix issue when removing roles out of order.

  • +
  • Fix bug where discriminators would not update.

  • +
  • Handle cases where HEARTBEAT opcode is received. This caused bots to disconnect seemingly randomly.

  • +
+

For the command extension, the following bug fixes apply:

+
    +
  • Bot.check decorator is actually a decorator not requiring parentheses.

  • +
  • Bot.remove_command and Group.remove_command no longer throw if the command doesn’t exist.

  • +
  • Command names are no longer forced to be lower().

  • +
  • Fix a bug where Member and User converters failed to work in private message contexts.

  • +
  • HelpFormatter now ignores hidden commands when deciding the maximum width.

  • +
+
+
+
+

v0.10.0

+

For breaking changes, see Migrating to v0.10.0. The breaking changes listed there will not be enumerated below. Since this version is rather a big departure from v0.9.2, this change log will be non-exhaustive.

+
+

New Features

+
    +
  • The library is now fully asyncio compatible, allowing you to write non-blocking code a lot more easily.

  • +
  • The library now fully handles 429s and unconditionally retries on 502s.

  • +
  • A new command extension module was added but is currently undocumented. Figuring it out is left as an exercise to the reader.

  • +
  • Two new exception types, Forbidden and NotFound to denote permission errors or 404 errors.

  • +
  • Added Client.delete_invite() to revoke invites.

  • +
  • Added support for sending voice. Check VoiceClient for more details.

  • +
  • Added Client.wait_for_message() coroutine to aid with follow up commands.

  • +
  • Added version_info named tuple to check version info of the library.

  • +
  • Login credentials are now cached to have a faster login experience. You can disable this by passing in cache_auth=False +when constructing a Client.

  • +
  • New utility function, discord.utils.get() to simplify retrieval of items based on attributes.

  • +
  • All data classes now support !=, ==, hash(obj) and str(obj).

  • +
  • Added Client.get_bans() to get banned members from a server.

  • +
  • Added Client.invites_from() to get currently active invites in a server.

  • +
  • Added Server.me attribute to get the Member version of Client.user.

  • +
  • Most data classes now support a hash(obj) function to allow you to use them in set or dict classes or subclasses.

  • +
  • Add Message.clean_content() to get a text version of the content with the user and channel mentioned changed into their names.

  • +
  • Added a way to remove the messages of the user that just got banned in Client.ban().

  • +
  • Added Client.wait_until_ready() to facilitate easy creation of tasks that require the client cache to be ready.

  • +
  • Added Client.wait_until_login() to facilitate easy creation of tasks that require the client to be logged in.

  • +
  • Add discord.Game to represent any game with custom text to send to Client.change_status().

  • +
  • Add Message.nonce attribute.

  • +
  • Add Member.permissions_in() as another way of doing Channel.permissions_for().

  • +
  • Add Client.move_member() to move a member to another voice channel.

  • +
  • You can now create a server via Client.create_server().

  • +
  • Added Client.edit_server() to edit existing servers.

  • +
  • Added Client.server_voice_state() to server mute or server deafen a member.

  • +
  • If you are being rate limited, the library will now handle it for you.

  • +
  • Add on_member_ban() and on_member_unban() events that trigger when a member is banned/unbanned.

  • +
+
+
+

Performance Improvements

+
    +
  • All data classes now use __slots__ which greatly reduce the memory usage of things kept in cache.

  • +
  • Due to the usage of asyncio, the CPU usage of the library has gone down significantly.

  • +
  • A lot of the internal cache lists were changed into dictionaries to change the O(n) lookup into O(1).

  • +
  • Compressed READY is now on by default. This means if you’re on a lot of servers (or maybe even a few) you would +receive performance improvements by having to download and process less data.

  • +
  • While minor, change regex from \d+ to [0-9]+ to avoid unnecessary unicode character lookups.

  • +
+
+
+

Bug Fixes

+
    +
  • Fix bug where guilds being updated did not edit the items in cache.

  • +
  • Fix bug where member.roles were empty upon joining instead of having the @everyone role.

  • +
  • Fix bug where Role.is_everyone() was not being set properly when the role was being edited.

  • +
  • Client.logs_from() now handles cases where limit > 100 to sidestep the discord API limitation.

  • +
  • Fix bug where a role being deleted would trigger a ValueError.

  • +
  • Fix bug where Permissions.kick_members() and Permissions.ban_members() were flipped.

  • +
  • Mentions are now triggered normally. This was changed due to the way discord handles it internally.

  • +
  • Fix issue when a Message would attempt to upgrade a Message.server when the channel is +a Object.

  • +
  • Unavailable servers were not being added into cache, this has been corrected.

  • +
+
+
+
+ + +
+
+ © Copyright 2015-present, Rapptz. + Created using Sphinx 4.2.0. +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/api.rst b/docs/api.rst index 5fc56af1..beec9a97 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -197,6 +197,428 @@ to handle it, which defaults to print a traceback and ignoring the exception. errors. In order to turn a function into a coroutine they must be ``async def`` functions. +Channels +~~~~~~~~~ + +.. function:: on_guild_channel_delete(channel) + on_guild_channel_create(channel) + + Called whenever a guild channel is deleted or created. + + Note that you can get the guild from :attr:`~abc.GuildChannel.guild`. + + This requires :attr:`Intents.guilds` to be enabled. + + :param channel: The guild channel that got created or deleted. + :type channel: :class:`abc.GuildChannel` + +.. function:: on_guild_channel_update(before, after) + + Called whenever a guild channel is updated. e.g. changed name, topic, permissions. + + This requires :attr:`Intents.guilds` to be enabled. + + :param before: The updated guild channel's old info. + :type before: :class:`abc.GuildChannel` + :param after: The updated guild channel's new info. + :type after: :class:`abc.GuildChannel` + +.. function:: on_private_channel_update(before, after) + + Called whenever a private group DM is updated. e.g. changed name or topic. + + This requires :attr:`Intents.messages` to be enabled. + + :param before: The updated group channel's old info. + :type before: :class:`GroupChannel` + :param after: The updated group channel's new info. + :type after: :class:`GroupChannel` + +.. function:: on_guild_channel_pins_update(channel, last_pin) + + Called whenever a message is pinned or unpinned from a guild channel. + + This requires :attr:`Intents.guilds` to be enabled. + + :param channel: The guild channel that had its pins updated. + :type channel: Union[:class:`abc.GuildChannel`, :class:`Thread`] + :param last_pin: The latest message that was pinned as an aware datetime in UTC. Could be ``None``. + :type last_pin: Optional[:class:`datetime.datetime`] + +.. function:: on_private_channel_pins_update(channel, last_pin) + + Called whenever a message is pinned or unpinned from a private channel. + + :param channel: The private channel that had its pins updated. + :type channel: :class:`abc.PrivateChannel` + :param last_pin: The latest message that was pinned as an aware datetime in UTC. Could be ``None``. + :type last_pin: Optional[:class:`datetime.datetime`] + +Guilds +~~~~~~~ + +.. function:: on_guild_available(guild) + on_guild_unavailable(guild) + + Called when a guild becomes available or unavailable. The guild must have + existed in the :attr:`Client.guilds` cache. + + This requires :attr:`Intents.guilds` to be enabled. + + :param guild: The :class:`Guild` that has changed availability. + +.. function:: on_guild_join(guild) + + Called when a :class:`Guild` is either created by the :class:`Client` or when the + :class:`Client` joins a guild. + + This requires :attr:`Intents.guilds` to be enabled. + + :param guild: The guild that was joined. + :type guild: :class:`Guild` + +.. function:: on_guild_remove(guild) + + Called when a :class:`Guild` is removed from the :class:`Client`. + + This happens through, but not limited to, these circumstances: + + - The client got banned. + - The client got kicked. + - The client left the guild. + - The client or the guild owner deleted the guild. + + In order for this event to be invoked then the :class:`Client` must have + been part of the guild to begin with. (i.e. it is part of :attr:`Client.guilds`) + + This requires :attr:`Intents.guilds` to be enabled. + + :param guild: The guild that got removed. + :type guild: :class:`Guild` + +.. function:: on_guild_update(before, after) + + Called when a :class:`Guild` updates, for example: + + - Changed name + - Changed AFK channel + - Changed AFK timeout + - etc + + This requires :attr:`Intents.guilds` to be enabled. + + :param before: The guild prior to being updated. + :type before: :class:`Guild` + :param after: The guild after being updated. + :type after: :class:`Guild` + +.. function:: on_guild_emojis_update(guild, before, after) + + Called when a :class:`Guild` adds or removes :class:`Emoji`. + + This requires :attr:`Intents.emojis_and_stickers` to be enabled. + + :param guild: The guild who got their emojis updated. + :type guild: :class:`Guild` + :param before: A list of emojis before the update. + :type before: Sequence[:class:`Emoji`] + :param after: A list of emojis after the update. + :type after: Sequence[:class:`Emoji`] + +.. function:: on_guild_stickers_update(guild, before, after) + + Called when a :class:`Guild` updates its stickers. + + This requires :attr:`Intents.emojis_and_stickers` to be enabled. + + .. versionadded:: 2.0 + + :param guild: The guild who got their stickers updated. + :type guild: :class:`Guild` + :param before: A list of stickers before the update. + :type before: Sequence[:class:`GuildSticker`] + :param after: A list of stickers after the update. + :type after: Sequence[:class:`GuildSticker`] + +integrations +~~~~~~~~~~~~~ + +.. function:: on_integration_create(integration) + + Called when an integration is created. + + This requires :attr:`Intents.integrations` to be enabled. + + .. versionadded:: 2.0 + + :param integration: The integration that was created. + :type integration: :class:`Integration` + +.. function:: on_integration_update(integration) + + Called when an integration is updated. + + This requires :attr:`Intents.integrations` to be enabled. + + .. versionadded:: 2.0 + + :param integration: The integration that was created. + :type integration: :class:`Integration` + +.. function:: on_guild_integrations_update(guild) + + Called whenever an integration is created, modified, or removed from a guild. + + This requires :attr:`Intents.integrations` to be enabled. + + .. versionadded:: 1.4 + + :param guild: The guild that had its integrations updated. + :type guild: :class:`Guild` + +.. function:: on_webhooks_update(channel) + + Called whenever a webhook is created, modified, or removed from a guild channel. + + This requires :attr:`Intents.webhooks` to be enabled. + + :param channel: The channel that had its webhooks updated. + :type channel: :class:`abc.GuildChannel` + +.. function:: on_raw_integration_delete(payload) + + Called when an integration is deleted. + + This requires :attr:`Intents.integrations` to be enabled. + + .. versionadded:: 2.0 + + :param payload: The raw event payload data. + :type payload: :class:`RawIntegrationDeleteEvent` + +Members +~~~~~~~~ + +.. function:: on_member_join(member) + on_member_remove(member) + + Called when a :class:`Member` leaves or joins a :class:`Guild`. + + This requires :attr:`Intents.members` to be enabled. + + :param member: The member who joined or left. + :type member: :class:`Member` + +.. function:: on_member_update(before, after) + + Called when a :class:`Member` updates their profile. + + This is called when one or more of the following things change: + + - nickname + - roles + - pending + + This requires :attr:`Intents.members` to be enabled. + + :param before: The updated member's old info. + :type before: :class:`Member` + :param after: The updated member's updated info. + :type after: :class:`Member` + +.. function:: on_user_update(before, after) + + Called when a :class:`User` updates their profile. + + This is called when one or more of the following things change: + + - avatar + - username + - discriminator + + This requires :attr:`Intents.members` to be enabled. + + :param before: The updated user's old info. + :type before: :class:`User` + :param after: The updated user's updated info. + :type after: :class:`User` + +.. function:: on_member_ban(guild, user) + + Called when user gets banned from a :class:`Guild`. + + This requires :attr:`Intents.bans` to be enabled. + + :param guild: The guild the user got banned from. + :type guild: :class:`Guild` + :param user: The user that got banned. + Can be either :class:`User` or :class:`Member` depending if + the user was in the guild or not at the time of removal. + :type user: Union[:class:`User`, :class:`Member`] + +.. function:: on_member_unban(guild, user) + + Called when a :class:`User` gets unbanned from a :class:`Guild`. + + This requires :attr:`Intents.bans` to be enabled. + + :param guild: The guild the user got unbanned from. + :type guild: :class:`Guild` + :param user: The user that got unbanned. + :type user: :class:`User` + +.. function:: on_presence_update(before, after) + + Called when a :class:`Member` updates their presence. + + This is called when one or more of the following things change: + + - status + - activity + + This requires :attr:`Intents.presences` and :attr:`Intents.members` to be enabled. + + .. versionadded:: 2.0 + + :param before: The updated member's old info. + :type before: :class:`Member` + :param after: The updated member's updated info. + :type after: :class:`Member` + +Messages +~~~~~~~~~ + +.. function:: on_message(message) + + Called when a :class:`Message` is created and sent. + + This requires :attr:`Intents.messages` to be enabled. + + .. warning:: + + Your bot's own messages and private messages are sent through this + event. This can lead cases of 'recursion' depending on how your bot was + programmed. If you want the bot to not reply to itself, consider + checking the user IDs. Note that :class:`~ext.commands.Bot` does not + have this problem. + + :param message: The current message. + :type message: :class:`Message` + +.. function:: on_message_edit(before, after) + + Called when a :class:`Message` receives an update event. If the message is not found + in the internal message cache, then these events will not be called. + Messages might not be in cache if the message is too old + or the client is participating in high traffic guilds. + + If this occurs increase the :class:`max_messages ` parameter + or use the :func:`on_raw_message_edit` event instead. + + The following non-exhaustive cases trigger this event: + + - A message has been pinned or unpinned. + - The message content has been changed. + - The message has received an embed. + + - For performance reasons, the embed server does not do this in a "consistent" manner. + + - The message's embeds were suppressed or unsuppressed. + - A call message has received an update to its participants or ending time. + + This requires :attr:`Intents.messages` to be enabled. + + :param before: The previous version of the message. + :type before: :class:`Message` + :param after: The current version of the message. + :type after: :class:`Message` + +.. function:: on_message_delete(message) + + Called when a message is deleted. If the message is not found in the + internal message cache, then this event will not be called. + Messages might not be in cache if the message is too old + or the client is participating in high traffic guilds. + + If this occurs increase the :class:`max_messages ` parameter + or use the :func:`on_raw_message_delete` event instead. + + This requires :attr:`Intents.messages` to be enabled. + + :param message: The deleted message. + :type message: :class:`Message` + +.. function:: on_bulk_message_delete(messages) + + Called when messages are bulk deleted. If none of the messages deleted + are found in the internal message cache, then this event will not be called. + If individual messages were not found in the internal message cache, + this event will still be called, but the messages not found will not be included in + the messages list. Messages might not be in cache if the message is too old + or the client is participating in high traffic guilds. + + If this occurs increase the :class:`max_messages ` parameter + or use the :func:`on_raw_bulk_message_delete` event instead. + + This requires :attr:`Intents.messages` to be enabled. + + :param messages: The messages that have been deleted. + :type messages: List[:class:`Message`] + +.. function:: on_raw_message_edit(payload) + + Called when a message is edited. Unlike :func:`on_message_edit`, this is called + regardless of the state of the internal message cache. + + If the message is found in the message cache, + it can be accessed via :attr:`RawMessageUpdateEvent.cached_message`. The cached message represents + the message before it has been edited. For example, if the content of a message is modified and + triggers the :func:`on_raw_message_edit` coroutine, the :attr:`RawMessageUpdateEvent.cached_message` + will return a :class:`Message` object that represents the message before the content was modified. + + Due to the inherently raw nature of this event, the data parameter coincides with + the raw data given by the `gateway `_. + + Since the data payload can be partial, care must be taken when accessing stuff in the dictionary. + One example of a common case of partial data is when the ``'content'`` key is inaccessible. This + denotes an "embed" only edit, which is an edit in which only the embeds are updated by the Discord + embed server. + + This requires :attr:`Intents.messages` to be enabled. + + :param payload: The raw event payload data. + :type payload: :class:`RawMessageUpdateEvent` + + +.. function:: on_raw_message_delete(payload) + + Called when a message is deleted. Unlike :func:`on_message_delete`, this is + called regardless of the message being in the internal message cache or not. + + If the message is found in the message cache, + it can be accessed via :attr:`RawMessageDeleteEvent.cached_message` + + This requires :attr:`Intents.messages` to be enabled. + + :param payload: The raw event payload data. + :type payload: :class:`RawMessageDeleteEvent` + +.. function:: on_raw_bulk_message_delete(payload) + + Called when a bulk delete is triggered. Unlike :func:`on_bulk_message_delete`, this is + called regardless of the messages being in the internal message cache or not. + + If the messages are found in the message cache, + they can be accessed via :attr:`RawBulkMessageDeleteEvent.cached_messages` + + This requires :attr:`Intents.messages` to be enabled. + + :param payload: The raw event payload data. + :type payload: :class:`RawBulkMessageDeleteEvent` + +Networking +~~~~~~~~~~~ + .. function:: on_connect() Called when the client has successfully connected to Discord. This is not @@ -204,16 +626,6 @@ to handle it, which defaults to print a traceback and ignoring the exception. The warnings on :func:`on_ready` also apply. -.. function:: on_shard_connect(shard_id) - - Similar to :func:`on_connect` except used by :class:`AutoShardedClient` - to denote when a particular shard ID has connected to Discord. - - .. versionadded:: 1.4 - - :param shard_id: The shard ID that has connected. - :type shard_id: :class:`int` - .. function:: on_disconnect() Called when the client has disconnected from Discord, or a connection attempt to Discord has failed. @@ -222,16 +634,6 @@ to handle it, which defaults to print a traceback and ignoring the exception. This function can be called many times without a corresponding :func:`on_connect` call. -.. function:: on_shard_disconnect(shard_id) - - Similar to :func:`on_disconnect` except used by :class:`AutoShardedClient` - to denote when a particular shard ID has disconnected from Discord. - - .. versionadded:: 1.4 - - :param shard_id: The shard ID that has disconnected. - :type shard_id: :class:`int` - .. function:: on_ready() Called when the client is done preparing the data received from Discord. Usually after login is successful @@ -244,6 +646,31 @@ to handle it, which defaults to print a traceback and ignoring the exception. once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails. +.. function:: on_resumed() + + Called when the client has resumed a session. + +.. function:: on_shard_connect(shard_id) + + Similar to :func:`on_connect` except used by :class:`AutoShardedClient` + to denote when a particular shard ID has connected to Discord. + + .. versionadded:: 1.4 + + :param shard_id: The shard ID that has connected. + :type shard_id: :class:`int` + + +.. function:: on_shard_disconnect(shard_id) + + Similar to :func:`on_disconnect` except used by :class:`AutoShardedClient` + to denote when a particular shard ID has disconnected from Discord. + + .. versionadded:: 1.4 + + :param shard_id: The shard ID that has disconnected. + :type shard_id: :class:`int` + .. function:: on_shard_ready(shard_id) Similar to :func:`on_ready` except used by :class:`AutoShardedClient` @@ -252,9 +679,6 @@ to handle it, which defaults to print a traceback and ignoring the exception. :param shard_id: The shard ID that is ready. :type shard_id: :class:`int` -.. function:: on_resumed() - - Called when the client has resumed a session. .. function:: on_shard_resumed(shard_id) @@ -266,38 +690,6 @@ to handle it, which defaults to print a traceback and ignoring the exception. :param shard_id: The shard ID that has resumed. :type shard_id: :class:`int` -.. function:: on_error(event, *args, **kwargs) - - Usually when an event raises an uncaught exception, a traceback is - printed to stderr and the exception is ignored. If you want to - change this behaviour and handle the exception for whatever reason - yourself, this event can be overridden. Which, when done, will - suppress the default action of printing the traceback. - - The information of the exception raised and the exception itself can - be retrieved with a standard call to :func:`sys.exc_info`. - - If you want exception to propagate out of the :class:`Client` class - you can define an ``on_error`` handler consisting of a single empty - :ref:`raise statement `. Exceptions raised by ``on_error`` will not be - handled in any way by :class:`Client`. - - .. note:: - - ``on_error`` will only be dispatched to :meth:`Client.event`. - - It will not be received by :meth:`Client.wait_for`, or, if used, - :ref:`ext_commands_api_bot` listeners such as - :meth:`~ext.commands.Bot.listen` or :meth:`~ext.commands.Cog.listener`. - - :param event: The name of the event that raised the exception. - :type event: :class:`str` - - :param args: The positional arguments for the event that raised the - exception. - :param kwargs: The keyword arguments for the event that raised the - exception. - .. function:: on_socket_event_type(event_type) Called whenever a websocket event is received from the WebSocket. @@ -349,163 +741,8 @@ to handle it, which defaults to print a traceback and ignoring the exception. WebSocket library. It can be :class:`bytes` to denote a binary message or :class:`str` to denote a regular text message. -.. function:: on_typing(channel, user, when) - - Called when someone begins typing a message. - - The ``channel`` parameter can be a :class:`abc.Messageable` instance. - Which could either be :class:`TextChannel`, :class:`GroupChannel`, or - :class:`DMChannel`. - - If the ``channel`` is a :class:`TextChannel` then the ``user`` parameter - is a :class:`Member`, otherwise it is a :class:`User`. - - This requires :attr:`Intents.typing` to be enabled. - - :param channel: The location where the typing originated from. - :type channel: :class:`abc.Messageable` - :param user: The user that started typing. - :type user: Union[:class:`User`, :class:`Member`] - :param when: When the typing started as an aware datetime in UTC. - :type when: :class:`datetime.datetime` - -.. function:: on_raw_typing(payload) - - Called when someone begins typing a message. Unlike :func:`on_typing`, this is - called regardless if the user can be found or not. This most often happens - when a user types in DMs. - - This requires :attr:`Intents.typing` to be enabled. - - :param payload: The raw typing payload. - :type payload: :class:`RawTypingEvent` - -.. function:: on_message(message) - - Called when a :class:`Message` is created and sent. - - This requires :attr:`Intents.messages` to be enabled. - - .. warning:: - - Your bot's own messages and private messages are sent through this - event. This can lead cases of 'recursion' depending on how your bot was - programmed. If you want the bot to not reply to itself, consider - checking the user IDs. Note that :class:`~ext.commands.Bot` does not - have this problem. - - :param message: The current message. - :type message: :class:`Message` - -.. function:: on_message_delete(message) - - Called when a message is deleted. If the message is not found in the - internal message cache, then this event will not be called. - Messages might not be in cache if the message is too old - or the client is participating in high traffic guilds. - - If this occurs increase the :class:`max_messages ` parameter - or use the :func:`on_raw_message_delete` event instead. - - This requires :attr:`Intents.messages` to be enabled. - - :param message: The deleted message. - :type message: :class:`Message` - -.. function:: on_bulk_message_delete(messages) - - Called when messages are bulk deleted. If none of the messages deleted - are found in the internal message cache, then this event will not be called. - If individual messages were not found in the internal message cache, - this event will still be called, but the messages not found will not be included in - the messages list. Messages might not be in cache if the message is too old - or the client is participating in high traffic guilds. - - If this occurs increase the :class:`max_messages ` parameter - or use the :func:`on_raw_bulk_message_delete` event instead. - - This requires :attr:`Intents.messages` to be enabled. - - :param messages: The messages that have been deleted. - :type messages: List[:class:`Message`] - -.. function:: on_raw_message_delete(payload) - - Called when a message is deleted. Unlike :func:`on_message_delete`, this is - called regardless of the message being in the internal message cache or not. - - If the message is found in the message cache, - it can be accessed via :attr:`RawMessageDeleteEvent.cached_message` - - This requires :attr:`Intents.messages` to be enabled. - - :param payload: The raw event payload data. - :type payload: :class:`RawMessageDeleteEvent` - -.. function:: on_raw_bulk_message_delete(payload) - - Called when a bulk delete is triggered. Unlike :func:`on_bulk_message_delete`, this is - called regardless of the messages being in the internal message cache or not. - - If the messages are found in the message cache, - they can be accessed via :attr:`RawBulkMessageDeleteEvent.cached_messages` - - This requires :attr:`Intents.messages` to be enabled. - - :param payload: The raw event payload data. - :type payload: :class:`RawBulkMessageDeleteEvent` - -.. function:: on_message_edit(before, after) - - Called when a :class:`Message` receives an update event. If the message is not found - in the internal message cache, then these events will not be called. - Messages might not be in cache if the message is too old - or the client is participating in high traffic guilds. - - If this occurs increase the :class:`max_messages ` parameter - or use the :func:`on_raw_message_edit` event instead. - - The following non-exhaustive cases trigger this event: - - - A message has been pinned or unpinned. - - The message content has been changed. - - The message has received an embed. - - - For performance reasons, the embed server does not do this in a "consistent" manner. - - - The message's embeds were suppressed or unsuppressed. - - A call message has received an update to its participants or ending time. - - This requires :attr:`Intents.messages` to be enabled. - - :param before: The previous version of the message. - :type before: :class:`Message` - :param after: The current version of the message. - :type after: :class:`Message` - -.. function:: on_raw_message_edit(payload) - - Called when a message is edited. Unlike :func:`on_message_edit`, this is called - regardless of the state of the internal message cache. - - If the message is found in the message cache, - it can be accessed via :attr:`RawMessageUpdateEvent.cached_message`. The cached message represents - the message before it has been edited. For example, if the content of a message is modified and - triggers the :func:`on_raw_message_edit` coroutine, the :attr:`RawMessageUpdateEvent.cached_message` - will return a :class:`Message` object that represents the message before the content was modified. - - Due to the inherently raw nature of this event, the data parameter coincides with - the raw data given by the `gateway `_. - - Since the data payload can be partial, care must be taken when accessing stuff in the dictionary. - One example of a common case of partial data is when the ``'content'`` key is inaccessible. This - denotes an "embed" only edit, which is an edit in which only the embeds are updated by the Discord - embed server. - - This requires :attr:`Intents.messages` to be enabled. - - :param payload: The raw event payload data. - :type payload: :class:`RawMessageUpdateEvent` +Reactions +~~~~~~~~~~ .. function:: on_reaction_add(reaction, user) @@ -532,16 +769,6 @@ to handle it, which defaults to print a traceback and ignoring the exception. :param user: The user who added the reaction. :type user: Union[:class:`Member`, :class:`User`] -.. function:: on_raw_reaction_add(payload) - - Called when a message has a reaction added. Unlike :func:`on_reaction_add`, this is - called regardless of the state of the internal message cache. - - This requires :attr:`Intents.reactions` to be enabled. - - :param payload: The raw event payload data. - :type payload: :class:`RawReactionActionEvent` - .. function:: on_reaction_remove(reaction, user) Called when a message has a reaction removed from it. Similar to on_message_edit, @@ -564,16 +791,6 @@ to handle it, which defaults to print a traceback and ignoring the exception. :param user: The user who added the reaction. :type user: Union[:class:`Member`, :class:`User`] -.. function:: on_raw_reaction_remove(payload) - - Called when a message has a reaction removed. Unlike :func:`on_reaction_remove`, this is - called regardless of the state of the internal message cache. - - This requires :attr:`Intents.reactions` to be enabled. - - :param payload: The raw event payload data. - :type payload: :class:`RawReactionActionEvent` - .. function:: on_reaction_clear(message, reactions) Called when a message has all its reactions removed from it. Similar to :func:`on_message_edit`, @@ -587,16 +804,6 @@ to handle it, which defaults to print a traceback and ignoring the exception. :param reactions: The reactions that were removed. :type reactions: List[:class:`Reaction`] -.. function:: on_raw_reaction_clear(payload) - - Called when a message has all its reactions removed. Unlike :func:`on_reaction_clear`, - this is called regardless of the state of the internal message cache. - - This requires :attr:`Intents.reactions` to be enabled. - - :param payload: The raw event payload data. - :type payload: :class:`RawReactionClearEvent` - .. function:: on_reaction_clear_emoji(reaction) Called when a message has a specific reaction removed from it. Similar to :func:`on_message_edit`, @@ -610,6 +817,37 @@ to handle it, which defaults to print a traceback and ignoring the exception. :param reaction: The reaction that got cleared. :type reaction: :class:`Reaction` + +.. function:: on_raw_reaction_add(payload) + + Called when a message has a reaction added. Unlike :func:`on_reaction_add`, this is + called regardless of the state of the internal message cache. + + This requires :attr:`Intents.reactions` to be enabled. + + :param payload: The raw event payload data. + :type payload: :class:`RawReactionActionEvent` + +.. function:: on_raw_reaction_remove(payload) + + Called when a message has a reaction removed. Unlike :func:`on_reaction_remove`, this is + called regardless of the state of the internal message cache. + + This requires :attr:`Intents.reactions` to be enabled. + + :param payload: The raw event payload data. + :type payload: :class:`RawReactionActionEvent` + +.. function:: on_raw_reaction_clear(payload) + + Called when a message has all its reactions removed. Unlike :func:`on_reaction_clear`, + this is called regardless of the state of the internal message cache. + + This requires :attr:`Intents.reactions` to be enabled. + + :param payload: The raw event payload data. + :type payload: :class:`RawReactionClearEvent` + .. function:: on_raw_reaction_clear_emoji(payload) Called when a message has a specific reaction removed from it. Unlike :func:`on_reaction_clear_emoji` this is called @@ -622,76 +860,66 @@ to handle it, which defaults to print a traceback and ignoring the exception. :param payload: The raw event payload data. :type payload: :class:`RawReactionClearEmojiEvent` -.. function:: on_interaction(interaction) - Called when an interaction happened. +Roles +~~~~~~ - This currently happens due to slash command invocations or components being used. +.. function:: on_guild_role_create(role) + on_guild_role_delete(role) - .. warning:: + Called when a :class:`Guild` creates or deletes a new :class:`Role`. - This is a low level function that is not generally meant to be used. - If you are working with components, consider using the callbacks associated - with the :class:`~discord.ui.View` instead as it provides a nicer user experience. + To get the guild it belongs to, use :attr:`Role.guild`. + + This requires :attr:`Intents.guilds` to be enabled. + + :param role: The role that was created or deleted. + :type role: :class:`Role` + +.. function:: on_guild_role_update(before, after) + + Called when a :class:`Role` is changed guild-wide. + + This requires :attr:`Intents.guilds` to be enabled. + + :param before: The updated role's old info. + :type before: :class:`Role` + :param after: The updated role's updated info. + :type after: :class:`Role` + + +Stages +~~~~~~~ + +.. function:: on_stage_instance_create(stage_instance) + on_stage_instance_delete(stage_instance) + + Called when a :class:`StageInstance` is created or deleted for a :class:`StageChannel`. .. versionadded:: 2.0 - :param interaction: The interaction data. - :type interaction: :class:`Interaction` + :param stage_instance: The stage instance that was created or deleted. + :type stage_instance: :class:`StageInstance` -.. function:: on_private_channel_update(before, after) +.. function:: on_stage_instance_update(before, after) - Called whenever a private group DM is updated. e.g. changed name or topic. + Called when a :class:`StageInstance` is updated. - This requires :attr:`Intents.messages` to be enabled. + The following, but not limited to, examples illustrate when this event is called: - :param before: The updated group channel's old info. - :type before: :class:`GroupChannel` - :param after: The updated group channel's new info. - :type after: :class:`GroupChannel` + - The topic is changed. + - The privacy level is changed. -.. function:: on_private_channel_pins_update(channel, last_pin) + .. versionadded:: 2.0 - Called whenever a message is pinned or unpinned from a private channel. + :param before: The stage instance before the update. + :type before: :class:`StageInstance` + :param after: The stage instance after the update. + :type after: :class:`StageInstance` - :param channel: The private channel that had its pins updated. - :type channel: :class:`abc.PrivateChannel` - :param last_pin: The latest message that was pinned as an aware datetime in UTC. Could be ``None``. - :type last_pin: Optional[:class:`datetime.datetime`] +Threads +~~~~~~~~ -.. function:: on_guild_channel_delete(channel) - on_guild_channel_create(channel) - - Called whenever a guild channel is deleted or created. - - Note that you can get the guild from :attr:`~abc.GuildChannel.guild`. - - This requires :attr:`Intents.guilds` to be enabled. - - :param channel: The guild channel that got created or deleted. - :type channel: :class:`abc.GuildChannel` - -.. function:: on_guild_channel_update(before, after) - - Called whenever a guild channel is updated. e.g. changed name, topic, permissions. - - This requires :attr:`Intents.guilds` to be enabled. - - :param before: The updated guild channel's old info. - :type before: :class:`abc.GuildChannel` - :param after: The updated guild channel's new info. - :type after: :class:`abc.GuildChannel` - -.. function:: on_guild_channel_pins_update(channel, last_pin) - - Called whenever a message is pinned or unpinned from a guild channel. - - This requires :attr:`Intents.guilds` to be enabled. - - :param channel: The guild channel that had its pins updated. - :type channel: Union[:class:`abc.GuildChannel`, :class:`Thread`] - :param last_pin: The latest message that was pinned as an aware datetime in UTC. Could be ``None``. - :type last_pin: Optional[:class:`datetime.datetime`] .. function:: on_thread_join(thread) @@ -707,6 +935,19 @@ to handle it, which defaults to print a traceback and ignoring the exception. :param thread: The thread that got joined. :type thread: :class:`Thread` +.. function:: on_thread_update(before, after) + + Called whenever a thread is updated. + + This requires :attr:`Intents.guilds` to be enabled. + + .. versionadded:: 2.0 + + :param before: The updated thread's old info. + :type before: :class:`Thread` + :param after: The updated thread's new info. + :type after: :class:`Thread` + .. function:: on_thread_remove(thread) Called whenever a thread is removed. This is different from a thread being deleted. @@ -754,239 +995,8 @@ to handle it, which defaults to print a traceback and ignoring the exception. :param member: The member who joined or left. :type member: :class:`ThreadMember` -.. function:: on_thread_update(before, after) - - Called whenever a thread is updated. - - This requires :attr:`Intents.guilds` to be enabled. - - .. versionadded:: 2.0 - - :param before: The updated thread's old info. - :type before: :class:`Thread` - :param after: The updated thread's new info. - :type after: :class:`Thread` - -.. function:: on_guild_integrations_update(guild) - - Called whenever an integration is created, modified, or removed from a guild. - - This requires :attr:`Intents.integrations` to be enabled. - - .. versionadded:: 1.4 - - :param guild: The guild that had its integrations updated. - :type guild: :class:`Guild` - -.. function:: on_integration_create(integration) - - Called when an integration is created. - - This requires :attr:`Intents.integrations` to be enabled. - - .. versionadded:: 2.0 - - :param integration: The integration that was created. - :type integration: :class:`Integration` - -.. function:: on_integration_update(integration) - - Called when an integration is updated. - - This requires :attr:`Intents.integrations` to be enabled. - - .. versionadded:: 2.0 - - :param integration: The integration that was created. - :type integration: :class:`Integration` - -.. function:: on_raw_integration_delete(payload) - - Called when an integration is deleted. - - This requires :attr:`Intents.integrations` to be enabled. - - .. versionadded:: 2.0 - - :param payload: The raw event payload data. - :type payload: :class:`RawIntegrationDeleteEvent` - -.. function:: on_webhooks_update(channel) - - Called whenever a webhook is created, modified, or removed from a guild channel. - - This requires :attr:`Intents.webhooks` to be enabled. - - :param channel: The channel that had its webhooks updated. - :type channel: :class:`abc.GuildChannel` - -.. function:: on_member_join(member) - on_member_remove(member) - - Called when a :class:`Member` leaves or joins a :class:`Guild`. - - This requires :attr:`Intents.members` to be enabled. - - :param member: The member who joined or left. - :type member: :class:`Member` - -.. function:: on_member_update(before, after) - - Called when a :class:`Member` updates their profile. - - This is called when one or more of the following things change: - - - nickname - - roles - - pending - - This requires :attr:`Intents.members` to be enabled. - - :param before: The updated member's old info. - :type before: :class:`Member` - :param after: The updated member's updated info. - :type after: :class:`Member` - -.. function:: on_presence_update(before, after) - - Called when a :class:`Member` updates their presence. - - This is called when one or more of the following things change: - - - status - - activity - - This requires :attr:`Intents.presences` and :attr:`Intents.members` to be enabled. - - .. versionadded:: 2.0 - - :param before: The updated member's old info. - :type before: :class:`Member` - :param after: The updated member's updated info. - :type after: :class:`Member` - -.. function:: on_user_update(before, after) - - Called when a :class:`User` updates their profile. - - This is called when one or more of the following things change: - - - avatar - - username - - discriminator - - This requires :attr:`Intents.members` to be enabled. - - :param before: The updated user's old info. - :type before: :class:`User` - :param after: The updated user's updated info. - :type after: :class:`User` - -.. function:: on_guild_join(guild) - - Called when a :class:`Guild` is either created by the :class:`Client` or when the - :class:`Client` joins a guild. - - This requires :attr:`Intents.guilds` to be enabled. - - :param guild: The guild that was joined. - :type guild: :class:`Guild` - -.. function:: on_guild_remove(guild) - - Called when a :class:`Guild` is removed from the :class:`Client`. - - This happens through, but not limited to, these circumstances: - - - The client got banned. - - The client got kicked. - - The client left the guild. - - The client or the guild owner deleted the guild. - - In order for this event to be invoked then the :class:`Client` must have - been part of the guild to begin with. (i.e. it is part of :attr:`Client.guilds`) - - This requires :attr:`Intents.guilds` to be enabled. - - :param guild: The guild that got removed. - :type guild: :class:`Guild` - -.. function:: on_guild_update(before, after) - - Called when a :class:`Guild` updates, for example: - - - Changed name - - Changed AFK channel - - Changed AFK timeout - - etc - - This requires :attr:`Intents.guilds` to be enabled. - - :param before: The guild prior to being updated. - :type before: :class:`Guild` - :param after: The guild after being updated. - :type after: :class:`Guild` - -.. function:: on_guild_role_create(role) - on_guild_role_delete(role) - - Called when a :class:`Guild` creates or deletes a new :class:`Role`. - - To get the guild it belongs to, use :attr:`Role.guild`. - - This requires :attr:`Intents.guilds` to be enabled. - - :param role: The role that was created or deleted. - :type role: :class:`Role` - -.. function:: on_guild_role_update(before, after) - - Called when a :class:`Role` is changed guild-wide. - - This requires :attr:`Intents.guilds` to be enabled. - - :param before: The updated role's old info. - :type before: :class:`Role` - :param after: The updated role's updated info. - :type after: :class:`Role` - -.. function:: on_guild_emojis_update(guild, before, after) - - Called when a :class:`Guild` adds or removes :class:`Emoji`. - - This requires :attr:`Intents.emojis_and_stickers` to be enabled. - - :param guild: The guild who got their emojis updated. - :type guild: :class:`Guild` - :param before: A list of emojis before the update. - :type before: Sequence[:class:`Emoji`] - :param after: A list of emojis after the update. - :type after: Sequence[:class:`Emoji`] - -.. function:: on_guild_stickers_update(guild, before, after) - - Called when a :class:`Guild` updates its stickers. - - This requires :attr:`Intents.emojis_and_stickers` to be enabled. - - .. versionadded:: 2.0 - - :param guild: The guild who got their stickers updated. - :type guild: :class:`Guild` - :param before: A list of stickers before the update. - :type before: Sequence[:class:`GuildSticker`] - :param after: A list of stickers after the update. - :type after: Sequence[:class:`GuildSticker`] - -.. function:: on_guild_available(guild) - on_guild_unavailable(guild) - - Called when a guild becomes available or unavailable. The guild must have - existed in the :attr:`Client.guilds` cache. - - This requires :attr:`Intents.guilds` to be enabled. - - :param guild: The :class:`Guild` that has changed availability. +Voice +~~~~~~ .. function:: on_voice_state_update(member, before, after) @@ -1008,56 +1018,70 @@ to handle it, which defaults to print a traceback and ignoring the exception. :param after: The voice state after the changes. :type after: :class:`VoiceState` -.. function:: on_stage_instance_create(stage_instance) - on_stage_instance_delete(stage_instance) - Called when a :class:`StageInstance` is created or deleted for a :class:`StageChannel`. +Others? +~~~~~~~~ - .. versionadded:: 2.0 +.. function:: on_error(event, *args, **kwargs) - :param stage_instance: The stage instance that was created or deleted. - :type stage_instance: :class:`StageInstance` + Usually when an event raises an uncaught exception, a traceback is + printed to stderr and the exception is ignored. If you want to + change this behaviour and handle the exception for whatever reason + yourself, this event can be overridden. Which, when done, will + suppress the default action of printing the traceback. -.. function:: on_stage_instance_update(before, after) + The information of the exception raised and the exception itself can + be retrieved with a standard call to :func:`sys.exc_info`. - Called when a :class:`StageInstance` is updated. + If you want exception to propagate out of the :class:`Client` class + you can define an ``on_error`` handler consisting of a single empty + :ref:`raise statement `. Exceptions raised by ``on_error`` will not be + handled in any way by :class:`Client`. - The following, but not limited to, examples illustrate when this event is called: + .. note:: - - The topic is changed. - - The privacy level is changed. + ``on_error`` will only be dispatched to :meth:`Client.event`. - .. versionadded:: 2.0 + It will not be received by :meth:`Client.wait_for`, or, if used, + :ref:`ext_commands_api_bot` listeners such as + :meth:`~ext.commands.Bot.listen` or :meth:`~ext.commands.Cog.listener`. - :param before: The stage instance before the update. - :type before: :class:`StageInstance` - :param after: The stage instance after the update. - :type after: :class:`StageInstance` + :param event: The name of the event that raised the exception. + :type event: :class:`str` -.. function:: on_member_ban(guild, user) + :param args: The positional arguments for the event that raised the + exception. + :param kwargs: The keyword arguments for the event that raised the + exception. - Called when user gets banned from a :class:`Guild`. - This requires :attr:`Intents.bans` to be enabled. +.. function:: on_group_join(channel, user) + on_group_remove(channel, user) - :param guild: The guild the user got banned from. - :type guild: :class:`Guild` - :param user: The user that got banned. - Can be either :class:`User` or :class:`Member` depending if - the user was in the guild or not at the time of removal. - :type user: Union[:class:`User`, :class:`Member`] + Called when someone joins or leaves a :class:`GroupChannel`. -.. function:: on_member_unban(guild, user) - - Called when a :class:`User` gets unbanned from a :class:`Guild`. - - This requires :attr:`Intents.bans` to be enabled. - - :param guild: The guild the user got unbanned from. - :type guild: :class:`Guild` - :param user: The user that got unbanned. + :param channel: The group that the user joined or left. + :type channel: :class:`GroupChannel` + :param user: The user that joined or left. :type user: :class:`User` +.. function:: on_interaction(interaction) + + Called when an interaction happened. + + This currently happens due to slash command invocations or components being used. + + .. warning:: + + This is a low level function that is not generally meant to be used. + If you are working with components, consider using the callbacks associated + with the :class:`~discord.ui.View` instead as it provides a nicer user experience. + + .. versionadded:: 2.0 + + :param interaction: The interaction data. + :type interaction: :class:`Interaction` + .. function:: on_invite_create(invite) Called when an :class:`Invite` is created. @@ -1095,15 +1119,36 @@ to handle it, which defaults to print a traceback and ignoring the exception. :param invite: The invite that was deleted. :type invite: :class:`Invite` -.. function:: on_group_join(channel, user) - on_group_remove(channel, user) +.. function:: on_typing(channel, user, when) - Called when someone joins or leaves a :class:`GroupChannel`. + Called when someone begins typing a message. - :param channel: The group that the user joined or left. - :type channel: :class:`GroupChannel` - :param user: The user that joined or left. - :type user: :class:`User` + The ``channel`` parameter can be a :class:`abc.Messageable` instance. + Which could either be :class:`TextChannel`, :class:`GroupChannel`, or + :class:`DMChannel`. + + If the ``channel`` is a :class:`TextChannel` then the ``user`` parameter + is a :class:`Member`, otherwise it is a :class:`User`. + + This requires :attr:`Intents.typing` to be enabled. + + :param channel: The location where the typing originated from. + :type channel: :class:`abc.Messageable` + :param user: The user that started typing. + :type user: Union[:class:`User`, :class:`Member`] + :param when: When the typing started as an aware datetime in UTC. + :type when: :class:`datetime.datetime` + +.. function:: on_raw_typing(payload) + + Called when someone begins typing a message. Unlike :func:`on_typing`, this is + called regardless if the user can be found or not. This most often happens + when a user types in DMs. + + This requires :attr:`Intents.typing` to be enabled. + + :param payload: The raw typing payload. + :type payload: :class:`RawTypingEvent` .. _discord-api-utils: