diff --git a/docs/discord.rst b/docs/discord.rst deleted file mode 100644 index ac12417f0..000000000 --- a/docs/discord.rst +++ /dev/null @@ -1,96 +0,0 @@ -: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/faq.rst b/docs/faq.rst index 3f46d2a97..9cf7a2a3f 100644 --- a/docs/faq.rst +++ b/docs/faq.rst @@ -253,7 +253,7 @@ this together we can do the following: :: How do I run something in the background? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -`Check the background_task.py example. `_ +`Check the background_task.py example. `_ How do I get a specific model? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/images/discord_bot_tab.png b/docs/images/discord_bot_tab.png deleted file mode 100644 index 835682448..000000000 Binary files a/docs/images/discord_bot_tab.png and /dev/null differ diff --git a/docs/images/discord_bot_user_options.png b/docs/images/discord_bot_user_options.png deleted file mode 100644 index 4091bd88e..000000000 Binary files a/docs/images/discord_bot_user_options.png and /dev/null differ diff --git a/docs/images/discord_create_app_button.png b/docs/images/discord_create_app_button.png deleted file mode 100644 index e6d06a7a2..000000000 Binary files a/docs/images/discord_create_app_button.png and /dev/null differ diff --git a/docs/images/discord_create_app_form.png b/docs/images/discord_create_app_form.png deleted file mode 100644 index a8afd4fa6..000000000 Binary files a/docs/images/discord_create_app_form.png and /dev/null differ diff --git a/docs/images/discord_create_bot_user.png b/docs/images/discord_create_bot_user.png deleted file mode 100644 index 2d0a3a033..000000000 Binary files a/docs/images/discord_create_bot_user.png and /dev/null differ diff --git a/docs/images/discord_oauth2.png b/docs/images/discord_oauth2.png deleted file mode 100644 index f32fcc7b0..000000000 Binary files a/docs/images/discord_oauth2.png and /dev/null differ diff --git a/docs/images/discord_oauth2_perms.png b/docs/images/discord_oauth2_perms.png deleted file mode 100644 index 0e6df51bd..000000000 Binary files a/docs/images/discord_oauth2_perms.png and /dev/null differ diff --git a/docs/images/discord_oauth2_scope.png b/docs/images/discord_oauth2_scope.png deleted file mode 100644 index 9e2cdeff0..000000000 Binary files a/docs/images/discord_oauth2_scope.png and /dev/null differ diff --git a/docs/images/discord_privileged_intents.png b/docs/images/discord_privileged_intents.png deleted file mode 100644 index 297eabbb5..000000000 Binary files a/docs/images/discord_privileged_intents.png and /dev/null differ diff --git a/docs/index.rst b/docs/index.rst index e1af5163f..34e6e52b1 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,16 +1,11 @@ -.. 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 +Welcome to discord.py-self =========================== .. 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. +discord.py-self is a modern, easy to use, feature-rich, and async ready API wrapper +for the Discord user APIs. **Features:** @@ -26,16 +21,18 @@ 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` +- **Working with Discord:** :doc:`token` - **Examples:** Many examples are available in the :resource:`repository `. +**Obligatory note:** +Automating user accounts is against the Discord ToS. If what you are trying to do is accomplishable with a bot account, please use one. + 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 `. diff --git a/docs/intents.rst b/docs/intents.rst deleted file mode 100644 index a9708aafa..000000000 --- a/docs/intents.rst +++ /dev/null @@ -1,192 +0,0 @@ -: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/intro.rst b/docs/intro.rst index 12a73c70a..1d4b8563e 100644 --- a/docs/intro.rst +++ b/docs/intro.rst @@ -7,14 +7,14 @@ Introduction ============== -This is the documentation for discord.py, a library for Python to aid -in creating applications that utilise the Discord API. +This is the documentation for discord.py-self, a library for Python to aid +in creating self-bots 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. +discord.py-self works with Python 3.8 or higher. Support for earlier versions of Python +is not provided. .. _installing: @@ -24,16 +24,16 @@ Installing You can get the library directly from PyPI: :: - python3 -m pip install -U discord.py + python3 -m pip install -U discord.py-self If you are using Windows, then the following should be used instead: :: - py -3 -m pip install -U discord.py + py -3 -m pip install -U discord.py-self -To get voice support, you should use ``discord.py[voice]`` instead of ``discord.py``, e.g. :: +To get voice support, you should use ``discord.py-self[voice]`` instead of ``discord.py``, e.g. :: - python3 -m pip install -U discord.py[voice] + python3 -m pip install -U discord.py-self[voice] On Linux environments, installing voice requires getting the following dependencies: @@ -84,7 +84,7 @@ However, for the quick and dirty: .. code-block:: shell - $ pip install -U discord.py + $ pip install -U discord.py-self Congratulations. You now have a virtual environment all set up. @@ -109,5 +109,5 @@ A quick example to showcase how events work: print(f'Message from {messsage.author}: {message.content}') client = MyClient() - client.run('my token goes here') + client.run('token') diff --git a/docs/logging.rst b/docs/logging.rst index 535a373f3..27a370cf3 100644 --- a/docs/logging.rst +++ b/docs/logging.rst @@ -6,7 +6,7 @@ Setting Up Logging =================== -*discord.py* logs errors and debug information via the :mod:`logging` python +*discord.py-self* 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:: diff --git a/docs/migrating.rst b/docs/migrating.rst index baf97160f..c7d8c91cf 100644 --- a/docs/migrating.rst +++ b/docs/migrating.rst @@ -1,1172 +1,77 @@ .. currentmodule:: discord -.. _migrating_1_0: +.. _migrating: -Migrating to v1.0 -====================== +Migrating to this library +========================== -v1.0 is one of the biggest breaking changes in the library due to a complete -redesign. +This library is designed to be compatible with discord.py. +However, the user and bot APIs are *not* the same. -The amount of changes are so massive and long that for all intents and purposes, it is a completely -new library. +Most things bots can do, users can (in some capacity) as well. -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. +However, a number of things have been removed. +For example: +- `Intents`: While the gateway technically accepts Intents for user accounts (and even modifies payloads to be a little more like bot payloads), it leads to breakage. Additionally, it's a giant waving red flag to Discord. +- `Shards`: The concept doesn't exist and is unneeded for users. +- `Guild.fetch_members`: The `/guilds/:id/members` and `/guilds/:id/members/search` endpoints instantly phone-lock your account. For more information about guild members, please read their respective section below. -Python Version Change ------------------------ +Additionally, existing payloads and headers have been heavily changed to match the Discord client. -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**. +`guild.members` +---------------- +Since the concept of Intents (mostly) doesn't exist for user accounts; you just get all events, right? +Well, yes but actually no. -Major Model Changes ---------------------- +For 80% of things, events are identical to bot events. However, other than the quite large amount of new events, not all events work the same. -Below are major model changes that have happened in v1.0 +The biggest example of this are the events `on_member_add`, `on_member_update`/`on_user_update`, and `on_member_remove`. -Snowflakes are int -~~~~~~~~~~~~~~~~~~~~ +Bots +~~~~~ +For bots (with the member intent), it's simple. They request all guild members with an OPCode 8 (chunk the guild), and receive respective `GUILD_MEMBER_*` events, that are then parsed by the library and dispatched to users. +If the bot has the presence intent, it even gets an initial member cache in the `GUILD_CREATE` event. -Before v1.0, all snowflakes (the ``id`` attribute) were strings. This has been changed to :class:`int`. +Users +~~~~~~ +Users, however, do not work like this. +If you have one of kick members, ban members, or manage roles, you can request all guild members the same way bots do. The client uses this in various areas of guild settings. -Quick example: :: +But, here's the twist: users do not receive `GUILD_MEMBER_*` reliably. +They receive them in certain circumstances, but they're usually rare and nothing to be relied on. +If the Discord client ever needs member objects for specific users, it sends an OPCode 8 with the specific user IDs/names. This is why this is recommended if you want to fetch specific members (implemented as :func:`Guild.query_members` in the library). The client almost never uses the :func:`Guild.fetch_member` endpoint. +However, the maximum amount of members you can get with this method is 100 per request. - # before - ch = client.get_channel('84319995256905728') - if message.author.id == '80528701850124288': - ... +But, you may be thinking, how does the member list work? Why can't you just utilize that? This is where it gets complicated. +First, let's make sure we understand a few things: +- The API doesn't differentiate between offline and invisible members (for a good reason). +- The concept of a member list is not per-guild, it's per-channel. This makes sense if you think about it, since the member list only shows users that have access to a specific channel. +- The member list is always up-to-date. +- If a server has >1k members, the member list does **not** have offline members. - # after - ch = client.get_channel(84319995256905728) - if message.author.id == 80528701850124288: - ... +The member list uses OPCode 14, and the `GUILD_MEMBER_LIST_UPDATE` event. -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. +One more thing you need to understand, is that the member list is lazily loaded. You subscribe to 100 member ranges, and can subscribe to 2 per-request (needs more testing). So, to subscribe to all available ranges, you need to spam the gateway quite a bit (especially for large guilds). +Once you subscribe to a range, you'll receive `GUILD_MEMBER_LIST_UPDATE`s for it whenever someone is added to it (i.e. someone joined the guild, changed their nickname so they moved in the member list alphabetically, came online, etc.), removed from it (i.e. someone left the guild, went offline, changed their nickname so they moved in the member list alphabetically), or updated in it (i.e. someone got their roles changed, or changed their nickname but remained in the same range). +These can be parsed and dispatched as `on_member_add`, `on_member_update`/`on_user_update`, and `on_member_remove`. -Server is now Guild -~~~~~~~~~~~~~~~~~~~~~ +You may have already noticed a few problems with this: +1. You'll get spammed with `member_add/remove`s whenever someone changes ranges. +2. For guilds with >1k members you don't receive offline members. So, you won't know if an offline member is kicked, or an invisible member joins/leaves. You also won't know if someone came online or joined. Or, if someone went offline or left. -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. +#1 is solveable with a bit of parsing, but #2 is a huge problem. +If you have the permissions to request all guild members, you can combine that with member list scraping and get a *decent* local member cache. However, because of the nature of this (and the fact that you'll have to request all guild membesr again every so often), accurate events are nearly impossible. -A list of changes is as follows: +Additionally, there are more caveats: +1. `GUILD_MEMBER_LIST_UPDATE` removes provide an index, not a user ID. The index starts at 0 from the top of the member list and includes hoisted roles. +2. For large servers, you get ratelimited pretty fast, so scraping can take over half an hour. +3. The scraping has to happen every time the bot starts. This not only slows things down, but *may* make Discord suspicious. +4. Remember that member lists are per-channel? Well, that means you can only subscribe all members that can *see* the channel you're subscribing too. -+-------------------------------+----------------------------------+ -| 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` | -+-------------------------------+----------------------------------+ +#1 is again solveable with a bit of parsing. There's not much you can do about #2 and #3. But, to solve #4, you *can* subscribe to multiple channels. Although, that will probably have problems of its own. -.. _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`. +There are a few more pieces of the puzzle: +- There is a `/guilds/:id/roles/:id/member-ids` endpoint that provides up to 100 member IDs for any role other than the default role. You can use :func:`Guild.query_members` to fetch all these members in one go. +- With OPCode 14, you can subscribe to certain member IDs and receive presence updates for them. The limit of IDs per-request is currently unknown, but I have witnessed the client send over 200/request. This may help with the offline members issue. +- Thread member lists do *not* work the same. You just send an OPCode 14 with the thread IDs and receive a `THREAD_MEMBER_LIST_UPDATE` with all the members. The cache then stays updated with `GUILD_MEMBER_UPDATE` and `THREAD_MEMBERS_UPDATE` events. +- OPCode 14 lets you subscribe to multiple channels at once, and you *might* be able to do more than 2 ranges at once. diff --git a/docs/migrating_to_async.rst b/docs/migrating_to_async.rst deleted file mode 100644 index a705f7239..000000000 --- a/docs/migrating_to_async.rst +++ /dev/null @@ -1,322 +0,0 @@ -: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/token.rst b/docs/token.rst new file mode 100644 index 000000000..8e8a6a44e --- /dev/null +++ b/docs/token.rst @@ -0,0 +1,24 @@ +:orphan: + +.. versionadded:: 2.0 +.. _tokens: + +Tokens +======= + +Tokens are how we authenticate with Discord. + +Regular (and bot) tokens have this format: + +.. image:: /images/token.png + +MFA tokens, however, are just the HMAC prefixed with `mfa.` (as far as I know). + +How to obtain mine +------------------- +To obtain your token from the Discord client, the easiest way is as follows: +1. Open developer tools (CTRL+SHIFT+I). +2. Click the Network tab. +3. Click the XHR tab. +4. Select a request and click the Headers tab. +5. Copy-paste the value in the Authorization header. diff --git a/docs/version_guarantees.rst b/docs/version_guarantees.rst index 7909bd6b5..f4f3738f1 100644 --- a/docs/version_guarantees.rst +++ b/docs/version_guarantees.rst @@ -7,6 +7,8 @@ The library follows a `semantic versioning principle `_ whi 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. +However, the Discord user API is in constant flux, so sometimes breaking changes may creep in. + .. note:: The examples below are non-exhaustive.