diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3d8ef1d270..1a6e159039 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -20,7 +20,7 @@ jobs:
runs-on: ${{ matrix.os }}
steps:
- - name: Checkout repo
+ - name: Checkout repository
uses: actions/checkout@v3
- name: Setup python
@@ -61,7 +61,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- - name: Checkout repo
+ - name: Checkout repository
uses: actions/checkout@v3
- name: Setup python
@@ -92,7 +92,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- - name: Checkout repo
+ - name: Checkout repository
uses: actions/checkout@v3
- name: Setup python
@@ -149,7 +149,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- - name: Checkout repo
+ - name: Checkout repository
uses: actions/checkout@v3
- name: Setup python
@@ -162,11 +162,11 @@ jobs:
pip install -r dev-requirements/nox.txt
nox -s twemoji-test
- pages:
+ docs:
runs-on: ubuntu-latest
steps:
- - name: Checkout repo
+ - name: Checkout repository
uses: actions/checkout@v3
- name: Setup python
@@ -177,24 +177,23 @@ jobs:
- name: Setup node
uses: actions/setup-node@v3
- - name: Build pages
+ - name: Build documentation
run: |
pip install -r dev-requirements/nox.txt
- nox -s pages
+ nox -s sphinx
- name: Upload artifacts
- if: github.event_name != 'release'
+ if: github.event_name == 'pull_request'
uses: actions/upload-artifact@v3
with:
- name: pages
- path: public
+ name: docs
+ path: public/docs
retention-days: 2
if-no-files-found: error
- # Allows us to add this as a required check in Github branch rules, as all the
- # other jobs are subject to change
+ # Allows us to add this as a required check in Github branch rules, as all the other jobs are subject to change
ci-done:
- needs: [upload-coverage, linting, twemoji, pages]
+ needs: [upload-coverage, linting, twemoji, docs]
if: always() && !cancelled()
runs-on: ubuntu-latest
diff --git a/.github/workflows/fragments-check.yml b/.github/workflows/fragments-check.yml
index 35eeeebd5f..22a16d277d 100644
--- a/.github/workflows/fragments-check.yml
+++ b/.github/workflows/fragments-check.yml
@@ -16,7 +16,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- - name: Checkout repo
+ - name: Checkout repository
uses: actions/checkout@v3
with:
# `towncrier check` runs `git diff --name-only origin/main...`, which
diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml
index 96da9a7512..839c7d6593 100644
--- a/.github/workflows/prepare-release.yml
+++ b/.github/workflows/prepare-release.yml
@@ -11,31 +11,34 @@ jobs:
prepare-release:
runs-on: ubuntu-latest
+ if: github.ref == 'refs/heads/master'
+
steps:
- - name: Checkout repo
- uses: actions/checkout@v3
+ - name: Generate token
+ id: generate_token
+ uses: tibdex/github-app-token@v1
+ with:
+ app_id: ${{ secrets.APP_ID }}
+ private_key: ${{ secrets.PRIVATE_KEY }}
- - name: Setup python
- uses: actions/setup-python@v4
+ - name: Checkout repository
+ uses: actions/checkout@v3
with:
- python-version: 3.8
+ token: ${{ steps.generate_token.outputs.token }}
- name: Setup git config
run: |
git config --global user.name "hikari-bot"
git config --global user.email "90276125+hikari-bot[bot]@users.noreply.github.com"
- - name: Generate token
- id: generate_token
- uses: tibdex/github-app-token@v1
+ - name: Setup python
+ uses: actions/setup-python@v4
with:
- app_id: ${{ secrets.APP_ID }}
- private_key: ${{ secrets.PRIVATE_KEY }}
+ python-version: 3.8
- name: Run prepare script
env:
- VERSION: ${{ github.event.inputs.version }}
- GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }}
+ VERSION: ${{ inputs.version }}
run: bash scripts/prepare-release.sh
- name: Create pull request
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 45678b1f2d..b3909b90c4 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -9,41 +9,45 @@ jobs:
runs-on: ubuntu-latest
steps:
- - name: Checkout repo
- uses: actions/checkout@v3
+ - name: Generate token
+ id: generate_token
+ uses: tibdex/github-app-token@v1
with:
- token: ${{ secrets.PAT_TOKEN }}
+ app_id: ${{ secrets.APP_ID }}
+ private_key: ${{ secrets.PRIVATE_KEY }}
- - name: Setup python
- uses: actions/setup-python@v4
+ - name: Checkout repository
+ uses: actions/checkout@v3
with:
- python-version: 3.8
+ token: ${{ steps.generate_token.outputs.token }}
- name: Setup git config
run: |
git config --global user.name "hikari-bot"
git config --global user.email "90276125+hikari-bot[bot]@users.noreply.github.com"
+ - name: Setup python
+ uses: actions/setup-python@v4
+ with:
+ python-version: 3.8
+
- name: Temporarily disable "include administrators" branch protection
- uses: benjefferies/branch-protection-bot@master
+ uses: benjefferies/branch-protection-bot@1.0.7
with:
- access_token: ${{ secrets.PAT_TOKEN }}
+ access_token: ${{ steps.generate_token.outputs.token }}
enforce_admins: false
- - name: Deploy
+ - name: Release
env:
- GITHUB_TOKEN: ${{ secrets.PAT_TOKEN }}
VERSION: ${{ github.event.release.tag_name }}
- REF: ${{ github.sha }}
- GITHUB_REPO_SLUG: ${{ github.repository }}
DEPLOY_WEBHOOK_URL: ${{ secrets.DEPLOY_WEBHOOK_URL }}
TWINE_USERNAME: ${{ secrets.TWINE_USERNAME }}
TWINE_PASSWORD: ${{ secrets.TWINE_PASSWORD }}
- run: bash scripts/deploy.sh
+ run: bash scripts/release.sh
- name: Re-enable "include administrators" branch protection
- uses: benjefferies/branch-protection-bot@master
+ uses: benjefferies/branch-protection-bot@1.0.7
if: always()
with:
- access_token: ${{ secrets.PAT_TOKEN }}
+ access_token: ${{ steps.generate_token.outputs.token }}
enforce_admins: true
diff --git a/.idea/fileTemplates/JS Script.js b/.idea/fileTemplates/JS Script.js
deleted file mode 100644
index 993b512a9f..0000000000
--- a/.idea/fileTemplates/JS Script.js
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright (c) 2020 Nekokatt
-// Copyright (c) 2021-present davfsa
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in all
-// copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-// SOFTWARE.
diff --git a/.idea/fileTemplates/Mako Template.mako b/.idea/fileTemplates/Mako Template.mako
deleted file mode 100644
index e9bfded947..0000000000
--- a/.idea/fileTemplates/Mako Template.mako
+++ /dev/null
@@ -1,34 +0,0 @@
-## Copyright (c) 2020 Nekokatt
-## Copyright (c) 2021-present davfsa
-##
-## Permission is hereby granted, free of charge, to any person obtaining a copy
-## of this software and associated documentation files (the "Software"), to deal
-## in the Software without restriction, including without limitation the rights
-## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-## copies of the Software, and to permit persons to whom the Software is
-## furnished to do so, subject to the following conditions:
-##
-## The above copyright notice and this permission notice shall be included in all
-## copies or substantial portions of the Software.
-##
-## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-## SOFTWARE.
-
-<%
- title = "Hello, World!"
-%>
-
-
-
- ${title}
-
-
- ${title}
- ${title}
-
-
\ No newline at end of file
diff --git a/.readthedocs.yml b/.readthedocs.yml
new file mode 100644
index 0000000000..2d49d78493
--- /dev/null
+++ b/.readthedocs.yml
@@ -0,0 +1,28 @@
+version: 2
+
+build:
+ os: ubuntu-22.04
+ tools:
+ python: "3.8"
+
+sphinx:
+ configuration: docs/conf.py
+ builder: dirhtml
+
+python:
+ install:
+ - requirements: dev-requirements/sphinx.txt
+ - method: pip
+ path: .
+
+search:
+ ignore:
+ # Defaults
+ - search.html
+ - search/index.html
+ - 404.html
+ - 404/index.html
+
+ # Custom
+ - index.html
+ - changelog/index.html
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 320447cab0..935d6f0bd5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,16 +1,6 @@
-# Changelog
+## 2.0.0.dev112 (2022-11-06)
-All notable changes to this project will be documented in this file.
-
-This file is updated every release with the use of `towncrier` from the fragments found under `changes/`.
-
-.. towncrier release notes start
-
-Hikari 2.0.0.dev112 (2022-11-06)
-================================
-
-Breaking Changes
-----------------
+### Breaking Changes
- Moved permission overwrite mapping and permission related methods from `GuildChannel` to `PermissibleGuildChannel`. ([#811](https://github.com/hikari-py/hikari/issues/811))
- Support v10 attachments edits
@@ -23,9 +13,7 @@ Breaking Changes
- `attachment` and `attachments` now supports `None` to replicate the behaviour of fully removing all attachments.
- `InteractionMessageBuilder.clear_attachments` has been implemented to remove existing attachments from messages. ([#1260](https://github.com/hikari-py/hikari/issues/1260))
-
-Features
---------
+### Features
- Thread support for REST requests and gateway events. ([#811](https://github.com/hikari-py/hikari/issues/811))
- Startup and shutdown callbacks for the RESTBot interface/impl. ([#999](https://github.com/hikari-py/hikari/issues/999))
@@ -33,21 +21,19 @@ Features
- Support for including the `SUPPRESS_EMBEDS` flag while creating a message. ([#1331](https://github.com/hikari-py/hikari/issues/1331))
- Add `MANAGE_EVENTS` permission to `hikari.Permissions` ([#1334](https://github.com/hikari-py/hikari/issues/1334))
-
-Bugfixes
---------
+### Bugfixes
- Wrong typehint for `InviteGuild.features`. ([#1307](https://github.com/hikari-py/hikari/issues/1307))
- Fix aiohttp error "charset must not be in content type" when using `InteractionServer` ([#1320](https://github.com/hikari-py/hikari/issues/1320))
- The REST list methods (e.g. `fetch_channels`) no-longer raise `hikari.errors.UnrecognisedEntityError` when they encounter an unknown type. ([#1337](https://github.com/hikari-py/hikari/issues/1337))
- Fix deprecation warnings in CPython3.11 in `hikari.internal.ux`. ([#1344](https://github.com/hikari-py/hikari/issues/1344))
+---
-Hikari 2.0.0.dev111 (2022-09-26)
-================================
-Breaking Changes
-----------------
+## 2.0.0.dev111 (2022-09-26)
+
+### Breaking Changes
- Lifetime improvements breaking changes:
- `GatewayBot.join`'s `until_close` argument removed.
@@ -57,15 +43,11 @@ Breaking Changes
- It is much more efficient to use a threadpool executor for I/O actions like this one
- Due to the nature of process pool, we were also not able to perform proper chunking when reading off the file ([#1273](https://github.com/hikari-py/hikari/issues/1273))
-
-Deprecation
------------
+### Deprecation
- Deprecate `CacheView.iterator` in favour of using the `itertools` module. ([#1289](https://github.com/hikari-py/hikari/issues/1289))
-
-Features
---------
+### Features
- Add python 3.11-dev support. ([#847](https://github.com/hikari-py/hikari/issues/847))
- Support for Application Command Localizations. ([#1141](https://github.com/hikari-py/hikari/issues/1141))
@@ -92,9 +74,7 @@ Features
- Add `mention` property to `PartialChannel`. ([#1221](https://github.com/hikari-py/hikari/issues/1221))
- Implement new Gateway reconnect logic enforced by Discord. ([#1245](https://github.com/hikari-py/hikari/issues/1245))
-
-Bugfixes
---------
+### Bugfixes
- Lifetime improvements bugfixes:
- `GatewayShardImpl` can now be instantiated out of an async environment for consistency with other components.
@@ -107,24 +87,20 @@ Bugfixes
- Allow for `replace_attachments` kwarg to be used in `RESTClient.create_initial_response`. ([#1266](https://github.com/hikari-py/hikari/issues/1266))
- Ignore guild create events which contain unavailable guilds ([#1284](https://github.com/hikari-py/hikari/issues/1284))
+---
-Hikari 2.0.0.dev110 (2022-08-08)
-================================
-Breaking Changes
-----------------
+## 2.0.0.dev110 (2022-08-08)
-- Removed case of `Member.mention` returning bang (`!`) mention, as it is deprecated by Discord. ([#1207](https://github.com/hikari-py/hikari/issues/1207))
+### Breaking Changes
+- Removed case of `Member.mention` returning bang (`!`) mention, as it is deprecated by Discord. ([#1207](https://github.com/hikari-py/hikari/issues/1207))
-Deprecation
------------
+### Deprecation
- `RESTClient.edit_permission_overwrites` renamed to `RESTClient.edit_permission_overwrite` ([#1195](https://github.com/hikari-py/hikari/issues/1195))
-
-Features
---------
+### Features
- Add `hikari.events.StickersUpdateEvent` and relevant cache internals.
Add sticker related public methods onto `hikari.impl.CacheImpl` and `hikari.guilds.Guild`. ([#1126](https://github.com/hikari-py/hikari/issues/1126))
@@ -132,18 +108,16 @@ Features
- Add the `app_permissions` field to command and component interactions. ([#1201](https://github.com/hikari-py/hikari/issues/1201))
- Add application command badge ([#1225](https://github.com/hikari-py/hikari/issues/1225))
-
-Bugfixes
---------
+### Bugfixes
- Fix how CommandBuilder handles `default_member_permissions` to match the behaviour on PartialCommand. ([#1212](https://github.com/hikari-py/hikari/issues/1212))
+---
-Hikari 2.0.0.dev109 (2022-06-26)
-================================
-Breaking Changes
-----------------
+## 2.0.0.dev109 (2022-06-26)
+
+### Breaking Changes
- Removal of all application commands v1 related fields and endpoints.
- Discord has completely disabled some endpoints, so we unfortunately can't
@@ -151,16 +125,12 @@ Breaking Changes
- Removed the `resolved` attribute from `AutocompleteInteraction` as autocomplete interactions never have resolved objects. ([#1152](https://github.com/hikari-py/hikari/issues/1152))
- `build` methods are now typed as returning `MutableMapping[str, typing.Any]`. ([#1164](https://github.com/hikari-py/hikari/issues/1164))
-
-Deprecation
------------
+### Deprecation
- `messages.Mentions` object deprecated
- Alternatives can be found in the base message object ([#1149](https://github.com/hikari-py/hikari/issues/1149))
-
-Features
---------
+### Features
- Add `create` method to `CommandBuilder`. ([#1016](https://github.com/hikari-py/hikari/issues/1016))
- Support for attachments in REST-based interaction responses. ([#1048](https://github.com/hikari-py/hikari/issues/1048))
@@ -174,9 +144,7 @@ Features
- Added `hikari.events.application_events.ApplicationCommandPermissionsUpdate`.
- Added `APPLICATION_COMMAND_PERMISSION_UPDATE` audit log entry ([#1148](https://github.com/hikari-py/hikari/issues/1148))
-
-Bugfixes
---------
+### Bugfixes
- Improved pyright support. ([#1108](https://github.com/hikari-py/hikari/issues/1108))
- `RESTClientImpl.fetch_bans` now return a `LazyIterator` to allow pagination of values. ([#1119](https://github.com/hikari-py/hikari/issues/1119))
@@ -187,12 +155,12 @@ Bugfixes
- Properly garbage collect message references in the cache
- Properly deserialize `PartialMessage.referenced_message` as a partial message ([#1192](https://github.com/hikari-py/hikari/issues/1192))
+---
+
-Hikari 2.0.0.dev108 (2022-03-27)
-================================
+## 2.0.0.dev108 (2022-03-27)
-Breaking Changes
-----------------
+### Breaking Changes
- `hikari.config` has now been split up to `hikari.api.config` and `hikari.impl.config` to avoid leaking impl detail.
This also means that config types are no-longer accessible at the top level (directly on `hikari`). ([#1067](https://github.com/hikari-py/hikari/issues/1067))
@@ -202,15 +170,11 @@ Breaking Changes
- Remove `VoiceRegion.is_vip` due to Discord no longer sending it. ([#1086](https://github.com/hikari-py/hikari/issues/1086))
- Remove store sku related application fields and store channels. ([#1092](https://github.com/hikari-py/hikari/issues/1092))
-
-Deprecation
------------
+### Deprecation
- Renamed `nick` argument to `nickname` for edit member and add user to guild REST methods. ([#1095](https://github.com/hikari-py/hikari/issues/1095))
-
-Features
---------
+### Features
- Scheduled event support. ([#1056](https://github.com/hikari-py/hikari/issues/1056))
- `get_guild()` is now available on `hikari.GuildChannel`. ([#1057](https://github.com/hikari-py/hikari/issues/1057))
@@ -219,9 +183,7 @@ Features
- Optimize event dispatching by only deserializing events when they are needed. ([#1094](https://github.com/hikari-py/hikari/issues/1094))
- Add `hikari.locales.Locale` to help with Discord locale strings. ([#1090](https://github.com/hikari-py/hikari/issues/1090))
-
-Bugfixes
---------
+### Bugfixes
- `fetch_my_guilds` no-longer returns duplicate guilds nor makes unnecessary (duplicated) requests when `newest_first` is set to `True`. ([#1059](https://github.com/hikari-py/hikari/issues/1059))
- Add `InviteEvent` to `hikari.events.channel_events.__all__`, `hikari.events.__all__` and `hikari.__all__`. ([#1065](https://github.com/hikari-py/hikari/issues/1065))
@@ -230,12 +192,12 @@ Bugfixes
- Take the major param for webhook without token endpoints when handling bucket ratelimits. ([#1102](https://github.com/hikari-py/hikari/issues/1102))
- Fix incorrect value for `GuildFeature.MORE_STICKERS`. ([#1989](https://github.com/hikari-py/hikari/issues/1989))
+---
-Hikari 2.0.0.dev107 (2022-03-04)
-================================
-Features
---------
+## 2.0.0.dev107 (2022-03-04)
+
+### Features
- Added a `total_length` function to `hikari.embeds.Embed`
- Takes into account the character length of the embed's title, description, fields (all field names and values), footer, and author combined.
@@ -247,9 +209,7 @@ Features
- The notorious "failed to communicate with server" log message is now a warning rather than an error. ([#1041](https://github.com/hikari-py/hikari/issues/1041))
- `hikari.applications`, `hikari.files`, `hikari.snowflakes` and `hikari.undefined` are now all explicitly exported by `hikari.__init__`, allowing pyright to see them without a direct import. ([#1042](https://github.com/hikari-py/hikari/issues/1042))
-
-Bugfixes
---------
+### Bugfixes
- Fix bucket lock not being released on errors while being acquired, which locked the bucket infinitely ([#841](https://github.com/hikari-py/hikari/issues/841))
- `enable_signal_handlers` now only defaults to `True` when the run/start method is called in the main thread.
@@ -261,28 +221,24 @@ Bugfixes
The multiprocessing file reader strategy now expands user relative (`~`) links (like the threaded strategy). ([#1046](https://github.com/hikari-py/hikari/issues/1046))
+---
+
-Hikari 2.0.0.dev106 (2022-02-03)
-================================
+## 2.0.0.dev106 (2022-02-03)
-Breaking Changes
-----------------
+### Breaking Changes
- Running the standard interaction server implementation now requires a `hikari[server]` install.
This matches a switch over to PyNacl for the cryptographic payload validation. ([#986](https://github.com/hikari-py/hikari/issues/986))
-
-Deprecation
------------
+### Deprecation
- Deprecated `RESTClient.command_builder` and `RESTClient.create_application_command`.
You should switch to `RESTClient.slash_command_builder`and `RESTClient.create_slash_command` respectively. ([#924](https://github.com/hikari-py/hikari/issues/924))
-
-Features
---------
+### Features
- Add context menu commands and command autocomplete. ([#924](https://github.com/hikari-py/hikari/issues/924))
- Added support for GET /users/@me/guilds/{guild}/member. ([#955](https://github.com/hikari-py/hikari/issues/955))
@@ -299,21 +255,19 @@ Features
This helps avoids a common mistake with trailing new-lines which leads to confusing errors on request. ([#989](https://github.com/hikari-py/hikari/issues/989))
-
-Bugfixes
---------
+### Bugfixes
- Relaxed typing of methods with union entry specific specialisations through overloads. ([#876](https://github.com/hikari-py/hikari/issues/876))
- Fix deprecation warnings raised by usage of `asyncio.gather` outside of an active event loop in `GatewayBot.run`. ([#954](https://github.com/hikari-py/hikari/issues/954))
- UTF-8 characters are now properly handled for audit-log reasons in REST requests. ([#963](https://github.com/hikari-py/hikari/issues/963))
- Fix magic methods for `UserImpl` and its subclasses. ([#982](https://github.com/hikari-py/hikari/issues/982))
+---
-Hikari 2.0.0.dev105 (2022-01-01)
-================================
-Features
---------
+## 2.0.0.dev105 (2022-01-01)
+
+### Features
- Add min_value and max_value to `CommandOption` ([#920](https://github.com/hikari-py/hikari/issues/920))
- Add `flags` attribute to Application ([#939](https://github.com/hikari-py/hikari/issues/939))
@@ -322,9 +276,7 @@ Features
- Add `MODERATE_MEMBERS` to `Permission`
- Add `communication_disabled_until` attribute to `edit_member` ([#940](https://github.com/hikari-py/hikari/issues/940))
-
-Bugfixes
---------
+### Bugfixes
- Improved pyright compatibility and introduced pyright "type-completeness" checking. ([#916](https://github.com/hikari-py/hikari/issues/916))
- Add EventStream.filter specialisation to the abc. ([#917](https://github.com/hikari-py/hikari/issues/917))
@@ -336,28 +288,24 @@ Bugfixes
- Remove case for setting `member` and `reference_message` to `undefined.Undefined` in full message deserialization
- Don't set `message.member` to `undefined.UNDEFINED` on partial message deserialization if message was sent by a webhook ([#933](https://github.com/hikari-py/hikari/issues/933))
+---
+
-Hikari 2.0.0.dev104 (2021-11-22)
-================================
+## 2.0.0.dev104 (2021-11-22)
-Breaking Changes
-----------------
+### Breaking Changes
- Remove the redundant `ChannelCreateEvent`, `ChannelUpdateEvent` and `ChannelDeleteEvent` base classes.
`GuildChannelCreateEvent`, `GuildChannelUpdateEvent` and `GuildChannelDeleteEvent` should now be used. ([#862](https://github.com/hikari-py/hikari/issues/862))
- Split bulk message delete from normal delete
- The new event is now `hikari.events.message_events.GuildBulkMessageDeleteEvent` ([#897](https://github.com/hikari-py/hikari/issues/897))
-
-Deprecation
------------
+### Deprecation
- `edit_my_nick` rest method. ([#827](https://github.com/hikari-py/hikari/issues/827))
- EventStream is now a sync context manager, not async. ([#864](https://github.com/hikari-py/hikari/issues/864))
-
-Features
---------
+### Features
- User banners and accent colors to user models. ([#811](https://github.com/hikari-py/hikari/issues/811))
- Add attachment "is_ephemeral" field ([#824](https://github.com/hikari-py/hikari/issues/824))
@@ -371,9 +319,7 @@ Features
- Add `old_message` attribute to `hikari.events.message_events.MessageDelete` ([#897](https://github.com/hikari-py/hikari/issues/897))
- Switch to more relaxed requirements. ([#906](https://github.com/hikari-py/hikari/issues/906))
-
-Bugfixes
---------
+### Bugfixes
- Don't raise in bulk delete when message not found by delete single message endpoint ([#828](https://github.com/hikari-py/hikari/issues/828))
- Setup basic handler if no handlers are defined in favour passed to `logging.config.dictConfig` ([#832](https://github.com/hikari-py/hikari/issues/832))
@@ -382,12 +328,12 @@ Bugfixes
- Fix logic for asserting listeners to not error when using defaults for other arguments ([#911](https://github.com/hikari-py/hikari/issues/911))
- Fix error message given by action row when a conflicted type is added. ([#912](https://github.com/hikari-py/hikari/issues/912))
+---
+
-Hikari 2.0.0.dev103 (2021-10-06)
-================================
+## 2.0.0.dev103 (2021-10-06)
-Breaking Changes
-----------------
+### Breaking Changes
- `USE_PUBLIC_THREADS` and `USE_PRIVATE_THREADS` permissions have been removed in favour of new threads permission
- New permissions are split into `CREATE_PUBLIC_THREADS`, `CREATE_PRIVATE_THREADS` and `SEND_MESSAGES_IN_THREADS` ([#799](https://github.com/hikari-py/hikari/issues/799))
@@ -397,9 +343,7 @@ Breaking Changes
- The message that is sent with the error code is the info that the enum contained ([#816](https://github.com/hikari-py/hikari/issues/816))
- PermissionOverwrite doesn't inherit from Unique anymore and isn't hashable. Equality checks now consider all its fields. ([#820](https://github.com/hikari-py/hikari/issues/820))
-
-Features
---------
+### Features
- Add new `START_EMBEDDED_ACTIVITIES` permission ([#798](https://github.com/hikari-py/hikari/issues/798))
- Support new `channel_types` field in `CommandOption` ([#800](https://github.com/hikari-py/hikari/issues/800))
@@ -407,9 +351,7 @@ Features
- Add `old_guild` attribute to `GuildLeaveEvent`. ([#806](https://github.com/hikari-py/hikari/issues/806))
- Add `GuildJoinEvent` that will fire when the bot joins new guilds ([#809](https://github.com/hikari-py/hikari/issues/809))
-
-Bugfixes
---------
+### Bugfixes
- Fix re-uploading forms with resources ([#787](https://github.com/hikari-py/hikari/issues/787))
- Prevent double linking embed resources, which causes them to upload twice
@@ -417,26 +359,22 @@ Bugfixes
- Fix `BulkDeleteError` returning incorrect values for `messages_skipped`
- This affected the `__str__` and `percentage_completion`, which also returned incorrect values ([#817](https://github.com/hikari-py/hikari/issues/817))
-
-Documentation Improvements
---------------------------
+### Documentation Improvements
- Add docstrings to the remaining undocumented `GatewayBot` methods ([#804](https://github.com/hikari-py/hikari/issues/804))
+---
-Hikari 2.0.0.dev102 (2021-09-19)
-================================
-Deprecations and Removals
--------------------------
+## 2.0.0.dev102 (2021-09-19)
+
+### Deprecations and Removals
- `MessageType.APPLICATION_COMMAND` renamed to `MessageType.CHAT_INPUT` ([#775](https://github.com/hikari-py/hikari/issues/775))
- Removal of deprecated `hikari.impl.bot.BotApp` and `hikari.traits.BotAware`
- Use `hikari.impl.bot.GatewayBot` and `hikari.traits.GatewayBotAware` respectively instead ([#778](https://github.com/hikari-py/hikari/issues/778))
-
-Features
---------
+### Features
- Message components support ([#684](https://github.com/hikari-py/hikari/issues/684))
- Web dashboard example with `rillrate` ([#752](https://github.com/hikari-py/hikari/issues/752))
@@ -451,9 +389,7 @@ Features
- Add `MessageType.CONTEXT_MENU_COMMAND` message type ([#775](https://github.com/hikari-py/hikari/issues/775))
- Add `ApplicationCommand.version` ([#776](https://github.com/hikari-py/hikari/issues/776))
-
-Bugfixes
---------
+### Bugfixes
- Handling of interaction models passed to the webhook message endpoints as the "webhook" field ([#759](https://github.com/hikari-py/hikari/issues/759))
- Fix passing `embeds` arguments in `create_interaction_response` and `edit_initial_response` endpoints
@@ -468,13 +404,13 @@ Bugfixes
- Set `PartialMessage.member` to `undefined.UNDEFINED` when Discord edit the message to display an embed/attachment ([#783](https://github.com/hikari-py/hikari/issues/783))
- `CommandInteractionOption.value` will now be cast to a `Snowflake` for types 6-9 ([#785](https://github.com/hikari-py/hikari/issues/785))
-
-Improved Documentation
-----------------------
+### Documentation Improvements
- Fix typo in Colorish docstring ([#755](https://github.com/hikari-py/hikari/issues/755))
- Remove duplicate raise type in REST and guilds docstrings ([#768](https://github.com/hikari-py/hikari/issues/768))
- Fix various spelling mistakes ([#773](https://github.com/hikari-py/hikari/issues/773))
+---
+
-*This file was added during the development of version 2.0.0.dev102, so nothing before that is documented.*
+*The changelog was added during the development of version 2.0.0.dev102, so nothing prior is documented here.*
diff --git a/README.md b/README.md
index 2b6629eb56..51cc3e159f 100644
--- a/README.md
+++ b/README.md
@@ -1,16 +1,16 @@
-hikari
-
-
+
An opinionated, static typed Discord microframework for Python3 and asyncio that supports Discord's v10 REST and
Gateway APIs.
@@ -41,13 +41,15 @@ bot = hikari.GatewayBot(token="...")
@bot.listen()
async def ping(event: hikari.GuildMessageCreateEvent) -> None:
- # If a non-bot user sends a message "hk.ping", respond with "Pong!"
- # We check there is actually content first, if no message content exists,
- # we would get `None' here.
- if event.is_bot or not event.content:
+ """If a non-bot user mentions your bot, respond with 'Pong!'."""
+
+ # Do not respond to bots nor webhooks pinging us, only user accounts
+ if not event.is_human:
return
- if event.content.startswith("hk.ping"):
+ me = bot.get_me()
+
+ if me.id in event.message.user_mentions_ids:
await event.message.respond("Pong!")
bot.run()
@@ -61,20 +63,20 @@ enable it manually. This has been implemented after seeing a large number of new
writing their first bot in other frameworks simply because of working blind after not understanding or knowing how
to set up standard logging messages.
-If you wish to customise the intents being used in order to change which events your bot is notified about, then you
+If you wish to customize the intents being used in order to change which events your bot is notified about, then you
can pass the `intents` kwarg to the `GatewayBot` constructor:
```py
# the default is to enable all unprivileged intents (all events that do not target the
-# presence or activity of a specific member).
+# presence, activity of a specific member nor message content).
bot = hikari.GatewayBot(intents=hikari.Intents.ALL, token="...")
```
The above example would enable all intents, thus enabling events relating to member presences to be received
(you'd need to whitelist your application first to be able to start the bot if you do this).
-[Other options also exist](https://hikari-py.dev/hikari/impl/bot.html#hikari.impl.bot.GatewayBot) such as
-[customising timeouts for requests](https://hikari-py.dev/hikari/config.html#hikari.config.HTTPSettings.timeouts)
-and [enabling a proxy](https://hikari-py.dev/hikari/config.html#hikari.config.ProxySettings).
+[Other options also exist](https://docs.hikari-py.dev/en/stable/reference/hikari/impl/bot/#hikari.impl.bot.GatewayBot)
+such as [customizing timeouts for requests](https://docs.hikari-py.dev/en/stable/reference/hikari/impl/config/#hikari.impl.config.HTTPSettings.timeouts)
+and [enabling a proxy](https://docs.hikari-py.dev/en/stable/reference/hikari/impl/config/#hikari.impl.config.ProxySettings).
Also note that you could pass extra options to `bot.run` during development, for example:
@@ -89,7 +91,7 @@ bot.run(
)
```
-[Many other helpful options](https://hikari-py.dev/hikari/impl/bot.html#hikari.impl.bot.GatewayBot.run)
+[Many other helpful options](https://docs.hikari-py.dev/en/stable/reference/hikari/impl/bot/#hikari.impl.bot.GatewayBot.run)
exist for you to take advantage of if you wish.
Events are determined by the type annotation on the event parameter, or alternatively as a type passed to the
@@ -125,15 +127,27 @@ async def print_my_user(token):
my_user = await client.fetch_my_user()
print(my_user)
-asyncio.run(print_my_user("user token here"))
+asyncio.run(print_my_user("user token acquired through OAuth here"))
```
---
## Optional Features
-* `hikari[server]` - Install dependencies required to enable Hikari's standard interaction server (RESTBot) functionality.
-* `hikari[speedups]` - Detailed in [`hikari[speedups]`](#hikarispeedups).
+Optional features can be specified when installing hikari:
+
+* `server` - Install dependencies required to enable Hikari's standard interaction server (RESTBot) functionality.
+* `speedups` - Detailed in [`hikari[speedups]`](#hikarispeedups).
+
+Example:
+
+```bash
+# To install hikari with the speedups feature:
+python -m pip install -U hikari[speedups]
+
+# To install hikari with both the speedups and server features:
+python -m pip install -U hikari[speedups, server]
+```
## Additional resources
@@ -152,24 +166,23 @@ Hikari does not include a command framework by default, so you will want to pick
As your application scales, you may need to adjust some things to keep it performing nicely.
-### Python optimisation flags
+### Python optimization flags
-CPython provides two optimisation flags that remove internal safety checks that are useful for development, and change
+CPython provides two optimization flags that remove internal safety checks that are useful for development, and change
other internal settings in the interpreter.
-- `python bot.py` - no optimisation - this is the default.
-- `python -O bot.py` - first level optimisation - features such as internal
- assertions will be disabled.
-- `python -OO bot.py` - second level optimisation - more features (**including
- all docstrings**) will be removed from the loaded code at runtime.
+- `python bot.py` - no optimization - this is the default.
+- `python -O bot.py` - first level optimization - features such as internal assertions will be disabled.
+- `python -OO bot.py` - second level optimization - more features (**including all docstrings**) will be removed from
+ the loaded code at runtime.
-**A minimum of first level of optimizations** is recommended when running bots in a production environment.
+**A minimum of first level of optimization** is recommended when running bots in a production environment.
### `hikari[speedups]`
-If you have a C compiler (Microsoft VC++ Redistributable 14.0 or newer, or a modern copy of GCC/G++, Clang, etc), you
-can install Hikari using `pip install -U hikari[speedups]`. This will install `aiohttp` with its available speedups, and
-`ciso8601` which will provide you with a small performance boost.
+If you have a C compiler (Microsoft VC++ Redistributable 14.0 or newer, or a modern copy of GCC/G++, Clang, etc), it is
+recommended you install Hikari using `pip install -U hikari[speedups]`. This will install `aiohttp` with its available
+speedups, and `ciso8601` which will provide you with a small performance boost.
### `uvloop`
@@ -221,3 +234,6 @@ Check out the issues tab on GitHub. If you are nervous, look for issues marked a
easy to start with!
[![good-first-issues](https://img.shields.io/github/issues/hikari-py/hikari/good%20first%20issue)](https://github.com/hikari-py/hikari/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)
+
+Feel free to also join our [Discord](https://discord.gg/Jx4cNGG) to directly ask questions to the maintainers! They will
+be glad to help you out and point you in the right direction.
diff --git a/changes/.template.rst b/changes/.template.rst
new file mode 100644
index 0000000000..1940463947
--- /dev/null
+++ b/changes/.template.rst
@@ -0,0 +1,32 @@
+## {{ versiondata.version }} ({{ versiondata.date }})
+{% for section, _ in sections.items() %}
+{% set anchor = "#" * underlines[0] %}{% if section %}{{ anchor }} {{section}}
+{% set anchor = "#" * underlines[1] %}
+
+{% endif %}
+
+{% if sections[section] %}
+{% for category, val in definitions.items() if category in sections[section]%}
+{{ anchor }} {{ definitions[category]['name'] }}
+
+{% if definitions[category]['showcontent'] %}
+{% for text, values in sections[section][category].items() %}
+- {{ text }} ({{ values|join(', ') }})
+{% endfor %}
+
+{% else %}
+- {{ sections[section][category]['']|join(', ') }}
+
+{% endif %}
+{% if sections[section][category]|length == 0 %}
+No significant changes.
+
+{% else %}
+{% endif %}
+{% endfor %}
+{% else %}
+No significant changes.
+
+{% endif %}
+{% endfor %}
+---
diff --git a/changes/1118.documentation.md b/changes/1118.documentation.md
new file mode 100644
index 0000000000..c335d5d680
--- /dev/null
+++ b/changes/1118.documentation.md
@@ -0,0 +1 @@
+Documentation overhaul and move to docs.hikari-py.dev domain.
diff --git a/dev-requirements/sphinx.txt b/dev-requirements/sphinx.txt
new file mode 100644
index 0000000000..c579ab5eeb
--- /dev/null
+++ b/dev-requirements/sphinx.txt
@@ -0,0 +1,17 @@
+sphinx==5.3.0
+
+# Theme
+furo==2022.9.29
+
+# Autodocumentation
+#sphinx-autoapi==2.0.0
+git+https://github.com/readthedocs/sphinx-autoapi.git@94295a48cdcec75a057b50d1c3d2ced21f10f2a6
+numpydoc==1.5.0
+
+# Static files
+myst-parser==0.18.1
+
+# Misc extensions
+sphinxext.opengraph==0.7.3
+sphinx-copybutton==0.5.1
+sphinxcontrib-towncrier==0.3.1a3
diff --git a/docs/.gitignore b/docs/.gitignore
new file mode 100644
index 0000000000..feead5b1fb
--- /dev/null
+++ b/docs/.gitignore
@@ -0,0 +1 @@
+reference/
diff --git a/docs/_static/extra.css b/docs/_static/extra.css
new file mode 100644
index 0000000000..1a93b4b4f2
--- /dev/null
+++ b/docs/_static/extra.css
@@ -0,0 +1,15 @@
+html {
+ word-wrap: anywhere;
+}
+
+/* Fit all the long names in the TOC drawer */
+.toc-drawer {
+ width: initial;
+ padding-right: 0;
+}
+
+@media (max-width: 82em) {
+ .toc-drawer {
+ right: -20em;
+ }
+}
diff --git a/docs/_templates/numpydoc_docstring.rst b/docs/_templates/numpydoc_docstring.rst
new file mode 100644
index 0000000000..c3d3f7e317
--- /dev/null
+++ b/docs/_templates/numpydoc_docstring.rst
@@ -0,0 +1,17 @@
+{{index}}
+{{summary}}
+{{extended_summary}}
+{{warns}}
+{{warnings}}
+{{notes}}
+{{parameters}}
+{{other_parameters}}
+{{returns}}
+{{yields}}
+{{receives}}
+{{raises}}
+{{see_also}}
+{{references}}
+{{examples}}
+{{attributes}}
+{{methods}}
diff --git a/docs/_templates/python/data.rst b/docs/_templates/python/data.rst
new file mode 100644
index 0000000000..cae882be1b
--- /dev/null
+++ b/docs/_templates/python/data.rst
@@ -0,0 +1,39 @@
+.. TODO: Remove once https://github.com/readthedocs/sphinx-autoapi/pull/353 is merged
+
+{% if obj.display %}
+.. py:{{ obj.type }}:: {{ obj.name }}
+ {%- if obj.annotation is not none %}
+
+ :type: {%- if obj.annotation %} {{ obj.annotation }}{%- endif %}
+
+ {%- endif %}
+
+ {%- if obj.value is not none %}
+
+ :value: {% if obj.value is string and obj.value.splitlines()|count > 1 -%}
+ Multiline-String
+
+ .. raw:: html
+
+ Show Value
+
+ .. code-block:: python
+
+ """{{ obj.value|indent(width=8,blank=true) }}"""
+
+ .. raw:: html
+
+
+
+ {%- else -%}
+ {%- if obj.value is string -%}
+ {{ "%r" % obj.value|string|truncate(100) }}
+ {%- else -%}
+ {{ obj.value|string|truncate(100) }}
+ {%- endif -%}
+ {%- endif %}
+ {%- endif %}
+
+
+ {{ obj.docstring|indent(3) }}
+{% endif %}
diff --git a/docs/_templates/python/module.rst b/docs/_templates/python/module.rst
new file mode 100644
index 0000000000..085f0f91c5
--- /dev/null
+++ b/docs/_templates/python/module.rst
@@ -0,0 +1,116 @@
+.. modified version of https://github.com/readthedocs/sphinx-autoapi/blob/master/autoapi/templates/python/module.rst
+
+{% if not obj.display %}
+:orphan:
+
+{% endif %}
+{{ obj.name }}
+{{ "=" * obj.name|length }}
+
+.. py:module:: {{ obj.name }}
+
+{% if obj.docstring %}
+.. autoapi-nested-parse::
+
+ {{ obj.docstring|indent(3) }}
+
+{% endif %}
+
+{% block subpackages %}
+{% set visible_subpackages = obj.subpackages|selectattr("display")|list %}
+{% if visible_subpackages %}
+Subpackages
+-----------
+.. toctree::
+ :titlesonly:
+ :maxdepth: 1
+
+{% for subpackage in visible_subpackages %}
+ {{ subpackage.short_name }}/index.rst
+{% endfor %}
+
+
+{% endif %}
+{% endblock %}
+{% block submodules %}
+{% set visible_submodules = obj.submodules|selectattr("display")|list %}
+{% if visible_submodules %}
+Submodules
+----------
+.. toctree::
+ :titlesonly:
+ :maxdepth: 1
+
+{% for submodule in visible_submodules %}
+ {{ submodule.short_name }}/index.rst
+{% endfor %}
+
+
+{% endif %}
+{% endblock %}
+{% block content %}
+{% if obj.all is not none %}
+{% set visible_children = obj.children|selectattr("short_name", "in", obj.all)|list %}
+{% elif obj.type is equalto("package") %}
+{% set visible_children = obj.children|selectattr("display")|list %}
+{% else %}
+{% set visible_children = obj.children|selectattr("display")|rejectattr("imported")|list %}
+{% endif %}
+{% if visible_children %}
+{{ obj.type|title }} Contents
+{{ "-" * obj.type|length }}---------
+
+{% set visible_classes = visible_children|selectattr("type", "equalto", "class")|list %}
+{% set visible_functions = visible_children|selectattr("type", "equalto", "function")|list %}
+{% set visible_attributes = visible_children|selectattr("type", "equalto", "data")|list %}
+{% if "show-module-summary" in autoapi_options and (visible_classes or visible_functions) %}
+{% block classes scoped %}
+{% if visible_classes %}
+Classes
+~~~~~~~
+
+.. autoapisummary::
+
+{% for klass in visible_classes %}
+ {{ klass.id }}
+{% endfor %}
+
+
+{% endif %}
+{% endblock %}
+
+{% block functions scoped %}
+{% if visible_functions %}
+Functions
+~~~~~~~~~
+
+.. autoapisummary::
+
+{% for function in visible_functions %}
+ {{ function.id }}
+{% endfor %}
+
+
+{% endif %}
+{% endblock %}
+
+{% block attributes scoped %}
+{% if visible_attributes %}
+Attributes
+~~~~~~~~~~
+
+.. autoapisummary::
+
+{% for attribute in visible_attributes %}
+ {{ attribute.id }}
+{% endfor %}
+
+
+{% endif %}
+{% endblock %}
+{% endif %}
+{% for obj_item in visible_children %}
+{{ obj_item.render()|indent(0) }}
+{% endfor %}
+{% endif %}
+{% endblock %}
diff --git a/docs/body.mako b/docs/body.mako
deleted file mode 100644
index 130099a8d1..0000000000
--- a/docs/body.mako
+++ /dev/null
@@ -1,23 +0,0 @@
-## Copyright (c) 2020 Nekokatt
-## Copyright (c) 2021-present davfsa
-##
-## Permission is hereby granted, free of charge, to any person obtaining a copy
-## of this software and associated documentation files (the "Software"), to deal
-## in the Software without restriction, including without limitation the rights
-## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-## copies of the Software, and to permit persons to whom the Software is
-## furnished to do so, subject to the following conditions:
-##
-## The above copyright notice and this permission notice shall be included in all
-## copies or substantial portions of the Software.
-##
-## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-## SOFTWARE.
-<%include file="head.mako"/>
-<%include file="documentation.mako"/>
-<%include file="footer.mako"/>
diff --git a/docs/changelog/index.md b/docs/changelog/index.md
new file mode 100644
index 0000000000..45822fff0a
--- /dev/null
+++ b/docs/changelog/index.md
@@ -0,0 +1,11 @@
+# Changelog
+
+```{attention}
+Major and minor releases also include the changes specified in prior development releases.
+```
+
+```{towncrier-draft-entries} Unreleased changes
+```
+
+```{include} ../../CHANGELOG.md
+```
diff --git a/docs/conf.py b/docs/conf.py
new file mode 100644
index 0000000000..de81a24c10
--- /dev/null
+++ b/docs/conf.py
@@ -0,0 +1,142 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) 2020 Nekokatt
+# Copyright (c) 2021-present davfsa
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in all
+# copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+"""Configuration file for the Sphinx documentation builder."""
+import os
+import pathlib
+import re
+import types
+
+# -- Project information -----------------------------------------------------
+
+with open(os.path.join("..", "hikari", "_about.py")) as fp:
+ code = fp.read()
+
+token_pattern = re.compile(r"^__(?P\w+)?__.*=\s*(?P(?:'{3}|\"{3}|'|\"))(?P.*?)(?P=quote)", re.M)
+
+groups = {}
+
+for match in token_pattern.finditer(code):
+ group = match.groupdict()
+ groups[group["key"]] = group["value"]
+
+metadata = types.SimpleNamespace(**groups)
+
+project = "hikari"
+copyright = metadata.copyright
+author = metadata.author
+release = version = metadata.version
+
+PROJECT_ROOT_DIR = pathlib.Path(__file__).parents[1].resolve()
+
+
+# -- General configuration ---------------------------------------------------
+
+extensions = [
+ # Sphinx own extensions
+ "sphinx.ext.autosummary",
+ "sphinx.ext.autodoc",
+ "sphinx.ext.intersphinx",
+ "sphinx.ext.viewcode",
+ "sphinx.ext.mathjax",
+ # Docs generation
+ "autoapi.extension",
+ "numpydoc",
+ "myst_parser",
+ # Misc
+ "sphinxext.opengraph",
+ "sphinx_copybutton",
+ "sphinxcontrib.towncrier.ext",
+]
+
+templates_path = ["_templates"]
+exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
+
+default_role = "py:obj"
+
+# -- HTML output --------------------------------------------------------------
+
+html_theme = "furo"
+html_favicon = "https://www.hikari-py.dev/logo.png"
+# html_theme_options = {
+# "top_of_page_button": None,
+# }
+html_static_path = ["_static"]
+html_css_files = ["extra.css"]
+
+# -- OpenGraph ----------------------------------------------------------------
+
+ogp_site_url = "https://docs.hikari-py.dev"
+ogp_image = "https://www.hikari-py.dev/logo.png"
+
+ogp_custom_meta_tags = [
+ ' ',
+]
+
+# -- AutoAPI options ----------------------------------------------------------
+
+autoapi_root = "reference"
+autoapi_dirs = ["../hikari"]
+autoapi_ignore = ["__main__.py"]
+
+autoapi_options = ["members", "show-inheritance"]
+autoapi_template_dir = "_templates"
+
+autoapi_add_toctree_entry = False
+autoapi_add_objects_to_toctree = False
+autoapi_keep_files = True
+
+# -- AutoDoc options ----------------------------------------------------------
+
+autodoc_typehints = "none" # NumpyDoc will do it for us. We just want to remove them from the signature too
+autodoc_preserve_defaults = True
+
+# -- NumpyDoc options ---------------------------------------------------------
+
+numpydoc_class_members_toctree = True
+numpydoc_show_class_members = False
+numpydoc_xref_param_type = True
+numpydoc_validation_checks = {
+ "all",
+ # Under here are all disabled checks
+ "GL08", # Missing docstring
+ "GL06", # Unknown section
+}
+
+# -- Intersphinx options ------------------------------------------------------
+
+intersphinx_mapping = {
+ "python": ("https://docs.python.org/3", None),
+ "aiohttp": ("https://docs.aiohttp.org/en/stable", None),
+ "attrs": ("https://www.attrs.org/en/stable/", None),
+ "multidict": ("https://multidict.aio-libs.org/en/stable/", None),
+ "yarl": ("https://yarl.aio-libs.org/en/stable/", None),
+}
+
+# -- MyST ---------------------------------------------------------------------
+
+myst_heading_anchors = 3
+
+# -- Towncrier ----------------------------------------------------------------
+
+towncrier_draft_autoversion_mode = "draft"
+towncrier_draft_include_empty = True
+towncrier_draft_working_directory = PROJECT_ROOT_DIR
diff --git a/docs/config.mako b/docs/config.mako
deleted file mode 100644
index 054b3b8bf9..0000000000
--- a/docs/config.mako
+++ /dev/null
@@ -1,54 +0,0 @@
-## Copyright (c) 2020 Nekokatt
-## Copyright (c) 2021-present davfsa
-##
-## Permission is hereby granted, free of charge, to any person obtaining a copy
-## of this software and associated documentation files (the "Software"), to deal
-## in the Software without restriction, including without limitation the rights
-## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-## copies of the Software, and to permit persons to whom the Software is
-## furnished to do so, subject to the following conditions:
-##
-## The above copyright notice and this permission notice shall be included in all
-## copies or substantial portions of the Software.
-##
-## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-## SOFTWARE.
-<%!
- import hikari as _hikari
-
- show_inherited_members = True
- extract_module_toc_into_sidebar = True
- list_class_variables_in_index = True
- sort_identifiers = True
- show_type_annotations = True
-
- show_source_code = True
-
- git_link_template = "https://github.com/hikari-py/hikari/blob/{commit}/{path}#L{start_line}-L{end_line}"
-
- link_prefix = ""
-
- hljs_style = "atom-one-dark"
-
- # Doesn't really do anything, just enables lurn_search
- lunr_search = {"fuzziness": 0}
-
- site_accent = "#ff029a"
- site_logo_name = "logo.png"
- site_logo_url = "https://hikari-py.dev/logo.png"
- site_description = "A Discord Bot framework for modern Python and asyncio built on good intentions"
-
- # Versions of stuff
- mathjax_version = "2.7.5"
- bootstrap_version = "4.5.0"
- highlightjs_version = "9.12.0"
- jquery_version = "3.5.1"
- popperjs_version = "1.16.0"
-
- root_url = "https://github.com/hikari-py/hikari"
-%>
diff --git a/docs/css.mako b/docs/css.mako
deleted file mode 100644
index d347912521..0000000000
--- a/docs/css.mako
+++ /dev/null
@@ -1,290 +0,0 @@
-## Copyright (c) 2020 Nekokatt
-## Copyright (c) 2021-present davfsa
-##
-## Permission is hereby granted, free of charge, to any person obtaining a copy
-## of this software and associated documentation files (the "Software"), to deal
-## in the Software without restriction, including without limitation the rights
-## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-## copies of the Software, and to permit persons to whom the Software is
-## furnished to do so, subject to the following conditions:
-##
-## The above copyright notice and this permission notice shall be included in all
-## copies or substantial portions of the Software.
-##
-## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-## SOFTWARE.
-
-img#logo {
- border-radius: 15px;
- width: 30px;
- height: 30px;
- margin-right: 0.5em;
- ## Hide alt when image is not there
- text-indent: 100%;
- white-space: nowrap;
- overflow: hidden;
-}
-
-small.smaller {
- font-size: 0.50em;
-}
-
-html {
- height: 100%;
- scroll-behavior: smooth;
- scrollbar-color: #202324 #454a4d;
-}
-
-body {
- background-color: #181A1B;
- color: #C9C5C0;
- height: fit-content;
-}
-
-h1 {
- margin-top: 3rem;
-}
-
-h2 {
- margin-top: 1.75rem;
- margin-bottom: 1em;
-}
-
-h3 {
- margin-top: 1.25rem;
-}
-
-h4 {
- margin-top: 1rem;
-}
-
-.nav-section {
- margin-top: 2em;
-}
-
-.monospaced {
- font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
-}
-
-a.sidebar-nav-pill,
-a.sidebar-nav-pill:active,
-a.sidebar-nav-pill:hover {
- color: #BDB7AF;
-}
-
-.module-source > details > pre {
- display: block;
- overflow-x: auto;
- overflow-y: auto;
- max-height: 600px;
- font-size: 0.8em;
-}
-
-a {
- color: #DE4F91;
-}
-
-a:hover {
- color: #64B1F2;
-}
-
-.container > li {
- margin-left: 1em;
- margin-top: 2.5em;
-}
-
-.jumbotron {
- background-color: #232627;
-}
-
-.breadcrumb-item.inactive > a {
- color: #d264d0 !important;
-}
-
-.breadcrumb-item.active > a {
- color: #de4f91 !important;
-}
-
-.breadcrumb-item+.breadcrumb-item::before {
- content: ".";
-}
-
-.module-breadcrumb {
- padding-left: 0 !important;
- background-color: #232627;
-}
-
-ul.nested {
- margin-left: 1em;
-}
-
-h2#parameters::after {
- margin-left: 2em;
-}
-
-.anchor:target {
- background-color: var(--dark);
-}
-
-@media screen and (max-width: 990px) {
- .anchor:target {
- margin-left: -2em;
- padding-left: 2em;
- }
-}
-
-@media screen and (min-width: 990px) {
- .anchor:target {
- border-radius: 0.5em; !important
- margin-right: -2em;
- padding-right: 2em;
- margin-top: -1em;
- padding-top: 1em;
- }
-}
-
-dt {
- margin-left: 2em;
-}
-
-dd {
- margin-left: 4em;
-}
-
-dl.no-nest > dt {
- margin-left: 0em;
-}
-
-dl.no-nest > dd {
- margin-left: 2em;
-}
-
-dl.root {
- margin-bottom: 2em;
-}
-
-.definition {
- display: block;
- margin-bottom: 8em !important;
-}
-
-.definition .row {
- display: block;
- margin-bottom: 4em !important;
-}
-
-.definition h2 {
- font-size: 1em;
- font-weight: bolder;
-}
-
-.sep {
- height: 2em;
-}
-
-code {
- color: #DB61D9;
-}
-
-## Check this to change it
-code .active {
- color: #e83e8c;
-}
-
-code a {
- color: #E94A93;
-}
-
-a.dotted:hover, abbr:hover {
- text-decoration: underline #9E9689 dotted !important;
-}
-
-a.dotted, abbr {
- text-decoration: none !important;
-}
-
-## Custom search formatting to look somewhat bootstrap-py
-.gsc-search-box, .gsc-search-box-tools, .gsc-control-cse {
- background: none !important;
- border: none !important;
-}
-
-.gsc-search-button-v2, .gsc-search-button-v2:hover, .gsc-search-button-v2:focus {
- color: var(--success) !important;
- border-color: var(--success) !important;
- background: none !important;
- padding: 6px 32px !important;
- font-size: inherit !important;
-}
-
-.gsc-search-button-v2 > svg {
- fill: var(--success) !important;
-}
-
-.gsc-input-box {
- border-radius: 3px;
-}
-
-.gsc-control-cse {
- width: 300px !important;
- margin-top: 0 !important;
-}
-
-.gsc-control-cse .gsc-control-cse-en {
- margin-top: 0 !important;
-}
-
-.bg-dark {
- background-color: #2C2F31 !important;
-}
-
-.text-muted {
- color: #9E9689 !important;
-}
-
-.alert-primary {
- color: #7CC3FF;
- background-color: #262A2B;
- border-color: #003B7B;
-}
-
-.alert-secondary {
- color: #C2BCB4;
- background-color: #282B2C;
- border-color: #3B4042;
-}
-
-.alert-success {
- color: #99E6AB;
- background-color: #1A3E29;
- border-color: #255A32;
-}
-
-.alert-info {
- color: #8EE3F1;
- background-color: #143B43;
- border-color: #1E5961;
-}
-
-.alert-warning {
- color: #FBD770;
- background-color: #513E00;
- border-color: #7B5C00;
-}
-
-.alert-danger {
- color: rgb(225, 134, 143);
- background-color: rgb(67, 12, 17);
- border-color: rgb(104, 18, 27);
-}
-
-mark {
- background-color: #333333;
- border-radius: 0.1em;
- color: #DB61D9;
-}
diff --git a/docs/documentation.mako b/docs/documentation.mako
deleted file mode 100644
index d90ad8c6b4..0000000000
--- a/docs/documentation.mako
+++ /dev/null
@@ -1,957 +0,0 @@
-## Copyright (c) 2020 Nekokatt
-## Copyright (c) 2021-present davfsa
-##
-## Permission is hereby granted, free of charge, to any person obtaining a copy
-## of this software and associated documentation files (the "Software"), to deal
-## in the Software without restriction, including without limitation the rights
-## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-## copies of the Software, and to permit persons to whom the Software is
-## furnished to do so, subject to the following conditions:
-##
-## The above copyright notice and this permission notice shall be included in all
-## copies or substantial portions of the Software.
-##
-## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-## SOFTWARE.
-<%!
- import os
- import typing
- import builtins
- import importlib
- import inspect
- import re
- import sphobjinv
- import urllib.error
-
- inventory_urls = [
- "https://docs.python.org/3/objects.inv",
- "https://docs.aiohttp.org/en/stable/objects.inv",
- "https://www.attrs.org/en/stable/objects.inv",
- "https://multidict.readthedocs.io/en/latest/objects.inv",
- "https://yarl.readthedocs.io/en/latest/objects.inv",
- ]
-
- inventories = {}
-
- for i in inventory_urls:
- try:
- print("Prefetching", i)
- inv = sphobjinv.Inventory(url=i)
- url, _, _ = i.partition("objects.inv")
- inventories[url] = inv.json_dict()
- except urllib.error.URLError as ex:
- # Ignore not being able to fetch inventory when not on CI
- if "CI" not in os.environ:
- print(f"Not able to prefetch {i}. Will continue without it")
- continue
-
- raise
-
- # Remove the `about` section from all the inventories
- for inv in inventories.values():
- to_delete = []
- for n, obj in inv.items():
- if isinstance(obj, dict) and obj["name"] == "about":
- to_delete.append(n)
-
- for n in to_delete:
- del inv[n]
-
-
- located_external_refs = {}
- unlocatable_external_refs = set()
-
- def discover_source(fqn):
- if fqn in unlocatable_external_refs:
- return
-
- if fqn.startswith("builtins."):
- fqn = fqn.replace("builtins.", "")
-
- if fqn not in located_external_refs:
- # print("attempting to find intersphinx reference for", fqn)
- for base_url, inv in inventories.items():
- for obj in inv.values():
- if isinstance(obj, dict) and obj["name"] == fqn:
- uri_frag = obj["uri"]
- if uri_frag.endswith("$"):
- uri_frag = uri_frag[:-1] + fqn
-
- url = base_url + uri_frag
- # print("discovered", fqn, "at", url)
- located_external_refs[fqn] = url
- break
- try:
- return located_external_refs[fqn]
- except KeyError:
- # print("blacklisting", fqn, "as it cannot be dereferenced from external documentation")
- unlocatable_external_refs.add(fqn)
-
- project_inventory = sphobjinv.Inventory()
-
- import atexit
-
- @atexit.register
- def dump_inventory():
- import hikari
-
- project_inventory.project = "hikari"
- project_inventory.version = hikari.__version__
-
- text = project_inventory.data_file(contract=True)
- ztext = sphobjinv.compress(text)
- sphobjinv.writebytes('public/objects.inv', ztext)
-
-
- # To get links to work in type hints to builtins, we do a bit of hacky search-replace using regex.
- # This generates regex to match general builtins in typehints.
- builtin_patterns = [
- re.compile(f"(?
-<%
- import abc
- import ast
- import enum
- import functools
- import inspect
- import re
- import textwrap
-
- import pdoc
-
- from pdoc.html_helpers import extract_toc, glimpse, to_html as _to_html, format_git_link
-
- # Hikari Enum hack
- from hikari.internal import enums
-
- # Allow imports to resolve properly.
- typing.TYPE_CHECKING = True
-
-
- QUAL_ABC = "abstract "
- QUAL_ABSTRACT = "abstract "
- QUAL_ASYNC_DEF = "async def "
- QUAL_CLASS = "class "
- QUAL_DATACLASS = "dataclass "
- QUAL_CACHED_PROPERTY = "cached property "
- QUAL_CONST = "const "
- QUAL_DEF = "def "
- QUAL_ENUM = "enum "
- QUAL_ENUM_FLAG = "enum flag "
- QUAL_EXCEPTION = "exception "
- QUAL_EXTERNAL = "extern "
- QUAL_INTERFACE = "abstract trait "
- QUAL_METACLASS = "meta "
- QUAL_MODULE = "module "
- QUAL_NAMESPACE = "namespace "
- QUAL_PACKAGE = "package "
- QUAL_PROPERTY = "property "
- QUAL_PROTOCOL = "trait "
- QUAL_TYPEHINT = "type hint "
- QUAL_VAR = "var "
- QUAL_WARNING = "warning "
-
- def get_url_for_object_from_imports(name, dobj):
- if dobj.module:
- fqn = dobj.module.obj.__name__ + "." + dobj.obj.__qualname__
- elif hasattr(dobj.obj, "__module__"):
- fqn = dobj.obj.__module__ + "." + dobj.obj.__qualname__
- else:
- fqn = dobj.name
-
- url = discover_source(fqn)
- if url is None:
- url = discover_source(name)
-
- if url is None:
- url = get_url_from_imports(fqn)
-
- return url
-
- def get_url_from_imports(fqn):
- if fqn_match := re.match(r"([a-z_]+)\.((?:[^\.]|^\s)+)", fqn):
- if import_match := re.search(f"from (.*) import (.*) as {fqn_match.group(1)}", module.source):
- fqn = import_match.group(1) + "." + import_match.group(2) + "." + fqn_match.group(2)
- try:
- return pdoc._global_context[fqn].url(relative_to=module, link_prefix=link_prefix, top_ancestor=not show_inherited_members)
- # print(old_fqn, "->", fqn, "via", url)
- except KeyError:
- # print("maybe", fqn, "is external but aliased?")
- return discover_source(fqn)
- elif import_match := re.search(f"from (.*) import {fqn_match.group(1)}", module.source):
- old_fqn = fqn
- fqn = import_match.group(1) + "." + fqn_match.group(1) + "." + fqn_match.group(2)
- try:
- return pdoc._global_context[fqn].url(relative_to=module, link_prefix=link_prefix, top_ancestor=not show_inherited_members)
- # print(old_fqn, "->", fqn, "via", url)
- except KeyError:
- # print("maybe", fqn, "is external but aliased?")
- return discover_source(fqn)
- elif import_match := re.search(f"import (.*) as {fqn_match.group(1)}", module.source):
- old_fqn = fqn
- fqn = import_match.group(1) + "." + fqn_match.group(2)
- try:
- return pdoc._global_context[fqn].url(relative_to=module, link_prefix=link_prefix, top_ancestor=not show_inherited_members)
- # print(old_fqn, "->", fqn, "via", url)
- except KeyError:
- # print("maybe", fqn, "is external but aliased?")
- return discover_source(fqn)
- else:
- return None
-
- def get_url_to_object_maybe_module(dobj):
- try:
- # ref = dobj if not hasattr(dobj.obj, "__module__") else pdoc._global_context[dobj.obj.__module__ + "." + dobj.obj.__qualname__]
- ref = pdoc._global_context[dobj.obj.__module__ + "." + dobj.obj.__qualname__]
- return ref.url(relative_to=module, link_prefix=link_prefix, top_ancestor=not show_inherited_members)
- except Exception:
- return dobj.url(relative_to=module, link_prefix=link_prefix, top_ancestor=not show_inherited_members)
-
- def debuiltinify(phrase: str):
- if phrase.startswith("builtins."):
- phrase = phrase[len("builtins."):]
- elif phrase.startswith("typing."):
- phrase = phrase[len("typing."):]
- elif phrase.startswith("asyncio."):
- phrase = phrase[len("asyncio."):]
- return phrase
-
- # Fixed Linkify that works with nested type hints...
- def _fixed_linkify(match: typing.Match, *, link: typing.Callable[..., str], module: pdoc.Module, wrap_code=False):
- #print("matched", match.groups(), match.group())
-
- try:
- code_span = match.group('code')
- except IndexError:
- code_span = match.group()
-
- if code_span.startswith("`") and code_span.endswith("`"):
- code_span = codespan[1:-1]
-
- # Extract identifiers.
- items = list(re.finditer(r"(\w|\.)+", code_span))[::-1]
-
- # For each identifier, replace it with a link.
- for match in items:
- phrase = match.group()
-
- ident = module.find_ident(phrase)
-
- if isinstance(ident, pdoc.External):
- phrase = debuiltinify(ident.name)
-
- url = get_url_for_object_from_imports(phrase, ident)
-
- if url is None:
- module_part = module.find_ident(phrase.split('.')[0])
- if not isinstance(module_part, pdoc.External):
- print(f"Code reference `{phrase}` in module '{module.refname}' does not match any documented object.")
- print("Type", module_part.__class__, module_part)
-
- bits = ident.name.split(".")[:-1]
-
- while bits:
- partial_phrase = ".".join(bits)
- if partial_phrase in pdoc._global_context:
- url = pdoc._global_context[partial_phrase].url(relative_to=module, link_prefix=link_prefix, top_ancestor=not show_inherited_members)
- a_tag = f"{repr(phrase)[1:-1]} "
- break
-
- bits = bits[:-1]
- else:
- a_tag = phrase
- else:
- a_tag = f"{repr(phrase)[1:-1]} "
-
-
- else:
- url = ident.url(relative_to=module, link_prefix=link_prefix, top_ancestor=not show_inherited_members)
- a_tag = f"{repr(ident.name)[1:-1]} "
-
- chunk = slice(*match.span())
- code_span = "".join((
- code_span[:chunk.start],
- a_tag,
- code_span[chunk.stop:],
- ))
-
- if wrap_code:
- code_span = code_span.replace('[', '\\[')
-
- # Wrapping in HTML as opposed to backticks evaluates markdown */_ markers,
- # so let's escape them in text (but not in HTML tag attributes).
- # Backticks also cannot be used because html returned from `link()`
- # would then become escaped.
- # This finds overlapping matches, https://stackoverflow.com/a/5616910/1090455
- cleaned = re.sub(r'(_(?=[^>]*?(?:<|$)))', r'\\\1', code_span)
- return '{}
'.format(cleaned)
- return code_span
-
-
- from pdoc import html_helpers
- html_helpers._linkify = _fixed_linkify
-
- # Help, it is a monster!
- def link(
- dobj: pdoc.Doc,
- *,
- with_prefixes=False,
- simple_names=False,
- css_classes="",
- name=None,
- default_type="",
- dotted=True,
- anchor=False,
- fully_qualified=False,
- hide_ref=False,
- recurse=True,
- ):
- prefix = ""
- name = name or dobj.name
-
- name = debuiltinify(name)
-
- show_object = False
- if with_prefixes:
- if isinstance(dobj, pdoc.Function):
- qual = QUAL_ASYNC_DEF if dobj._is_async else QUAL_DEF
-
- if not simple_names:
- if getattr(dobj.obj, "__isabstractmethod__", False):
- prefix = f"{QUAL_ABSTRACT} "
-
- prefix = "" + prefix + qual + " "
-
- elif isinstance(dobj, pdoc.Variable):
- if getattr(dobj.obj, "__isabstractmethod__", False) and not simple_names:
- prefix = f"{QUAL_ABSTRACT} "
-
- descriptor = None
- is_descriptor = False
-
- if hasattr(dobj.cls, "obj"):
- for cls in dobj.cls.obj.mro():
- if (descriptor := cls.__dict__.get(dobj.name)) is not None:
- is_descriptor = hasattr(descriptor, "__get__")
- break
-
- if all(not c.isalpha() or c.isupper() for c in dobj.name):
- prefix = f"{prefix}{QUAL_CONST} "
- elif is_descriptor:
- qual = QUAL_CACHED_PROPERTY if isinstance(descriptor, functools.cached_property) else QUAL_PROPERTY
- prefix = f"{prefix}{qual} "
- elif dobj.module.name == "typing" or dobj.docstring and dobj.docstring.casefold().startswith(("type hint", "typehint", "type alias")):
- show_object = not simple_names
- prefix = f"{prefix}{QUAL_TYPEHINT} "
- else:
- prefix = f"{prefix}{QUAL_VAR} "
-
- elif isinstance(dobj, pdoc.Class):
- qual = ""
-
- if getattr(dobj.obj, "_is_protocol", False):
- qual += QUAL_PROTOCOL
- elif issubclass(dobj.obj, type):
- qual += QUAL_METACLASS
- else:
- if enums.Flag in dobj.obj.mro() or enum.Flag in dobj.obj.mro():
- qual += QUAL_ENUM_FLAG
- elif enums.Enum in dobj.obj.mro() or enum.Enum in dobj.obj.mro():
- qual += QUAL_ENUM
- elif hasattr(dobj.obj, "__attrs_attrs__"):
- qual += QUAL_DATACLASS
- elif issubclass(dobj.obj, Warning):
- qual += QUAL_WARNING
- elif issubclass(dobj.obj, BaseException):
- qual += QUAL_EXCEPTION
- else:
- qual += QUAL_CLASS
-
- if not simple_names:
- if inspect.isabstract(dobj.obj):
- if re.match(r"^I[A-Za-z]", dobj.name):
- qual = f"{QUAL_INTERFACE} {qual}"
- else:
- qual = f"{QUAL_ABC} {qual}"
-
- prefix = f"{qual} "
-
- elif isinstance(dobj, pdoc.Module):
- qual = QUAL_PACKAGE if dobj.is_package else QUAL_NAMESPACE if dobj.is_namespace else QUAL_MODULE
- prefix = f"{qual} "
-
- else:
- if isinstance(dobj, pdoc.External):
- prefix = f"{QUAL_EXTERNAL} {default_type} "
- else:
- prefix = f"{default_type} "
- else:
- name = name or dobj.name or ""
-
- if fully_qualified and not simple_names:
- name = dobj.module.name + "." + dobj.obj.__qualname__
-
- if isinstance(dobj, pdoc.External):
- url = get_url_for_object_from_imports(name, dobj)
-
- if url is None:
- # print("Could not resolve where", fqn, "came from :(")
- return name
- else:
- url = get_url_to_object_maybe_module(dobj)
-
- if simple_names:
- name = simple_name(name)
-
- extra = ""
- if show_object:
- extra = f" = {dobj.obj}"
-
- classes = []
- class_str = " ".join(classes)
-
- if class_str.strip():
- class_str = f"class={class_str!r}"
-
- anchor = "" if not anchor else f'id="{dobj.refname}"'
-
- return '{}{} {}'.format(prefix, dobj.name + " -- " + glimpse(dobj.docstring), url, anchor, class_str, name, extra)
-
- def simple_name(s):
- _, _, name = s.rpartition(".")
- return name
-
- def get_annotation(bound_method, sep=':'):
- annot = bound_method(link=link)
-
- annot = annot.replace("NoneType", "None")
- # Remove quotes.
- if annot.startswith("'") and annot.endswith("'"):
- annot = annot[1:-1]
-
- if annot.startswith("builtins."):
- annot = annot[len("builtins."):]
-
- if annot:
- annot = ' ' + sep + '\N{NBSP}' + annot
-
- # for pattern in builtin_patterns:
- # annot = pattern.sub(r"builtins.\1", annot)
-
- return annot
-
- def to_html(text):
- text = _to_html(text, module=module, link=link, latex_math=latex_math)
- replacements = [
- ('class="admonition info"', 'class="alert alert-primary"'),
- ('class="admonition warning"', 'class="alert alert-warning"'),
- ('class="admonition danger"', 'class="alert alert-danger"'),
- ('class="admonition note"', 'class="alert alert-success"')
- ]
-
- for before, after in replacements:
- text = text.replace(before, after)
-
- return text
-%>
-<%def name="ident(name)">${name} %def>
-<%def name="breadcrumb()">
- <%
- module_breadcrumb = []
-
- sm = module
- while sm is not None:
- module_breadcrumb.append(sm)
- sm = sm.supermodule
-
- module_breadcrumb.reverse()
- %>
-
-
-
- % for m in module_breadcrumb:
- % if m is module:
- ${m.name | simple_name}
- % else:
- <% url = link(m) %>
- ${link(m, with_prefixes=False, simple_names=True)}
- % endif
- % endfor
-
-
-%def>
-<%def name="show_var(v)">
- <%
- return_type = get_annotation(v.type_annotation)
- parent = v.cls.obj if v.cls is not None else v.module.obj
- if return_type == "":
-
- if hasattr(parent, "mro"):
- for cls in parent.mro():
- if hasattr(cls, "__annotations__") and v.name in cls.__annotations__:
- return_type = get_annotation(lambda *_, **__: cls.__annotations__[v.name])
- if return_type != "":
- break
-
- if hasattr(parent, "__annotations__") and v.name in parent.__annotations__:
- return_type = get_annotation(lambda *_, **__: parent.__annotations__[v.name])
-
- return_type = re.sub(r'[\w\.]+', functools.partial(_fixed_linkify, link=link, module=v.module), return_type)
-
- value = None
- if v.cls is not None:
- try:
- obj = getattr(v.cls.obj, v.name)
-
- simple_bases = (
- bytes, int, bool, str, float, complex, list, set, frozenset, dict, tuple, type(None),
- enum.Enum, typing.Container
- )
-
- if isinstance(obj, simple_bases):
- value = str(obj)
-
- # Combined enum tidyup
- if value.count("|") > 3 and isinstance(obj, enum.Enum):
- start = "\n\N{EM SPACE}\N{EM SPACE}\N{EM SPACE}"
- value = f"({start} " + f"{start} | ".join(value.split(" | ")) + "\n)"
-
- except Exception as ex:
- print(v.name, type(ex).__name__, ex)
-
- if value:
- for enum_mapping in ("_value2member_map_", "_value_to_member_map_"):
- if mapping := getattr(v.cls.obj, enum_mapping, None):
- try:
- real_value = getattr(v.cls.obj, v.name)
- if real_value in mapping.values():
- return_type += f" = {real_value.value!r}"
- break
- except AttributeError:
- pass
- else:
- return_type += f" = {value}"
-
- if hasattr(parent, "mro"):
- name = f"{parent.__module__}.{parent.__qualname__}.{v.name}"
- else:
- name = f"{parent.__name__}.{v.qualname}"
-
- project_inventory.objects.append(
- sphobjinv.DataObjStr(
- name = name,
- domain = "py",
- role = "variable",
- uri = v.url(),
- priority = "1",
- dispname = "-",
- )
- )
- %>
-
-
- ${link(v, with_prefixes=True)}${return_type}
-
-
${v.docstring | to_html}
-
-%def>
-<%def name="show_func(f)">
- <%
- params = f.params(annotate=show_type_annotations, link=link)
- return_type = get_annotation(f.return_annotation, '->')
- qual = QUAL_ASYNC_DEF if f._is_async else QUAL_DEF
- anchored_name = f'{f.name} '
-
- example_str = qual + f.name + "(" + ", ".join(params) + ")" + return_type
-
- if params and params[0] in ("self", "mcs", "mcls", "metacls"):
- params = params[1:]
-
- if len(params) > 4 or len(params) > 0 and len(example_str) > 70:
- representation = "\n".join((
- qual + " " + anchored_name + "(",
- *(f" {p}," for p in params),
- ")" + return_type + ": ..."
- ))
-
- elif params:
- representation = f"{qual} {anchored_name}({', '.join(params)}){return_type}: ..."
- else:
- representation = f"{qual} {anchored_name}(){return_type}: ..."
-
- if f.module.name != f.obj.__module__:
- try:
- ref = pdoc._global_context[f.obj.__module__ + "." + f.obj.__qualname__]
- redirect = True
- except KeyError:
- redirect = False
- else:
- redirect = False
-
- if not redirect:
- project_inventory.objects.append(
- sphobjinv.DataObjStr(
- name = f.obj.__module__ + "." + f.obj.__qualname__,
- domain = "py",
- role = "function",
- uri = f.url(),
- priority = "1",
- dispname = "-",
- )
- )
- %>
-
-
- ${representation}
-
-
- % if inspect.isabstract(f.obj):
- This function is abstract!
- % endif
- % if redirect:
- ${show_desc(f, short=True)}
- This function is defined explicitly at ${link(ref, with_prefixes=False, fully_qualified=True)}. Visit that link to view the full documentation!
- % else:
- ${show_desc(f)}
-
- ${show_source(f)}
- % endif
-
-
-
-
-%def>
-<%def name="show_class(c)">
- <%
- variables = c.instance_variables(show_inherited_members, sort=sort_identifiers) + c.class_variables(show_inherited_members, sort=sort_identifiers)
- methods = c.methods(show_inherited_members, sort=sort_identifiers) + c.functions(show_inherited_members, sort=sort_identifiers)
- mro = c.mro()
- subclasses = c.subclasses()
-
- # No clue why I need to do this, and I don't care at this point. This hurts my brain.
- params = [p.replace("builtins.", "") for p in c.params(annotate=show_type_annotations, link=link)]
-
- example_str = f"{QUAL_CLASS} " + c.name + "(" + ", ".join(params) + ")"
-
- suppress_params = getattr(c.obj, "_is_protocol", False)
-
- if not suppress_params and (len(params) > 4 or len(example_str) > 70 and len(params) > 0):
- representation = "\n".join((
- f"{QUAL_CLASS} {c.name} (",
- *(f" {p}," for p in params),
- "): ..."
- ))
- elif params and not suppress_params:
- representation = f"{QUAL_CLASS} {c.name} (" + ", ".join(params) + "): ..."
- else:
- representation = f"{QUAL_CLASS} {c.name}: ..."
-
- if c.module.name != c.obj.__module__:
- try:
- ref = pdoc._global_context[c.obj.__module__ + "." + c.obj.__qualname__]
- redirect = True
- except KeyError:
- redirect = False
- else:
- redirect = False
-
- if not redirect:
- project_inventory.objects.append(
- sphobjinv.DataObjStr(
- name = c.obj.__module__ + "." + c.obj.__qualname__,
- domain = "py",
- role = "class",
- uri = c.url(),
- priority = "1",
- dispname = "-",
- )
- )
- %>
-
-
- % if redirect:
- reference to ${link(c, with_prefixes=True)}
- % else:
- ${link(c, with_prefixes=True, simple_names=True)}
- % endif
-
-
- % if redirect:
- ${show_desc(c, short=True)}
- % else:
- ${representation}
-
- ${show_desc(c)}
-
- ${show_source(c)}
-
-
- % if subclasses:
- Subclasses
-
- % for sc in subclasses:
- % if not isinstance(sc, pdoc.External):
- ${link(sc, with_prefixes=True, default_type="class")}
- ${sc.docstring or sc.obj.__doc__ or "" | glimpse, to_html}
- % endif
- % endfor
-
-
- % endif
-
- % if mro:
- Method resolution order
-
- ${link(c, with_prefixes=True)}
- That's this class!
- % for mro_c in mro:
- <%
- if mro_c.obj is None:
- module, _, cls = mro_c.qualname.rpartition(".")
- try:
- cls = getattr(importlib.import_module(module), cls)
- mro_c.docstring = cls.__doc__ or ""
- except:
- pass
- %>
-
- ${link(mro_c, with_prefixes=True, default_type="class")}
- ${mro_c.docstring | glimpse, to_html}
- % endfor
-
-
- % endif
-
- % if variables:
- Variables and properties
-
- % for i in variables:
- ${show_var(i)}
- % endfor
-
-
- % endif
-
- % if methods:
- Methods
-
- % for m in methods:
- ${show_func(m)}
- % endfor
-
-
- % endif
- % endif
-
-
-%def>
-<%def name="show_desc(d, short=False)">
- <%
- inherits = ' inherited' if d.inherits else ''
- docstring = d.docstring or d.obj.__doc__ or ""
- %>
- % if not short:
- % if inherits:
-
- Inherited from:
- % if hasattr(d.inherits, 'cls'):
- ${link(d.inherits.cls, with_prefixes=False)}
.${link(d.inherits, name=d.name, with_prefixes=False)}
- % else:
- ${link(d.inherits, with_prefixes=False)}
- % endif
-
- % endif
-
- ${docstring | to_html}
- % else:
- ${docstring | glimpse, to_html}
- % endif
-%def>
-<%def name="show_source(d)">
- % if (show_source_code or git_link_template) and d.source and d.obj is not getattr(d.inherits, 'obj', None):
- <% git_link = format_git_link(git_link_template, d) %>
- % if show_source_code:
-
-
- Expand source code
- % if git_link:
-
- Browse git
- %endif
-
- ${d.source | h}
-
- % elif git_link:
-
- %endif
- %endif
-%def>
-
-
-
-
${breadcrumb()}
-
${module.docstring | to_html}
-
-
-
-
-
- <%
- variables = module.variables(sort=sort_identifiers and module.name != "hikari")
- classes = module.classes(sort=sort_identifiers and module.name != "hikari")
- functions = module.functions(sort=sort_identifiers and module.name != "hikari")
- submodules = module.submodules()
- supermodule = module.supermodule
-
- project_inventory.objects.append(
- sphobjinv.DataObjStr(
- name = module.name,
- domain = "py",
- role = "module",
- uri = module.url(),
- priority = "1",
- dispname = "-",
- )
- )
- %>
-
-
-
- % if submodules:
-
- % for child_module in submodules:
- ${link(child_module, with_prefixes=True, css_classes="sidebar-nav-pill", dotted=False, simple_names=True)}
- % endfor
-
- % endif
-
- % if variables or functions or classes:
-
This module
- % endif
-
- % if variables:
-
- % for variable in variables:
- ${link(variable, with_prefixes=True, css_classes="sidebar-nav-pill", dotted=False, simple_names=True)}
- % endfor
-
- % endif
-
- % if functions:
-
- % for function in functions:
- ${link(function, with_prefixes=True, css_classes="sidebar-nav-pill", dotted=False, simple_names=True)}
- % endfor
-
- % endif
-
- % if classes:
-
- % for c in classes:
- <%
- if c.module.name != c.obj.__module__:
- try:
- ref = pdoc._global_context[c.obj.__module__ + "." + c.obj.__qualname__]
- redirect = True
- except KeyError:
- redirect = False
- else:
- redirect = False
-
- members = c.functions(sort=sort_identifiers) + c.methods(sort=sort_identifiers)
-
- if list_class_variables_in_index:
- members += (c.instance_variables(sort=sort_identifiers) + c.class_variables(sort=sort_identifiers))
-
- if not show_inherited_members:
- members = [i for i in members if not i.inherits]
-
- if sort_identifiers:
- members = sorted(members)
- %>
-
- ## Purposely using one item per list for layout reasons.
-
- ${link(c, with_prefixes=True, css_classes="sidebar-nav-pill", dotted=False, simple_names=True)}
-
-
- % if members and not redirect:
- % for member in members:
-
- ${link(member, with_prefixes=True, css_classes="sidebar-nav-pill", dotted=False, simple_names=True)}
-
- % endfor
- % endif
-
-
-
- % endfor
-
- % endif
-
-
-
-
-
-
- ${show_source(module)}
-
-
-
-
- % if submodules:
-
Child Modules
-
-
- % for m in submodules:
- ${link(m, simple_names=True, with_prefixes=True)}
- ${m.docstring | glimpse, to_html}
- % endfor
-
-
- % endif
-
- % if variables:
-
Variables and Type Hints
-
-
- % for v in variables:
- ${show_var(v)}
- % endfor
-
-
- % endif
-
- % if functions:
-
Functions
-
-
- % for f in functions:
- ${show_func(f)}
- % endfor
-
-
- % endif
-
- % if classes:
-
Classes
-
-
- % for c in classes:
- ${show_class(c)}
- % endfor
-
-
- % endif
-
-
-
diff --git a/docs/footer.mako b/docs/footer.mako
deleted file mode 100644
index 53872eab27..0000000000
--- a/docs/footer.mako
+++ /dev/null
@@ -1,20 +0,0 @@
-## Copyright (c) 2020 Nekokatt
-## Copyright (c) 2021-present davfsa
-##
-## Permission is hereby granted, free of charge, to any person obtaining a copy
-## of this software and associated documentation files (the "Software"), to deal
-## in the Software without restriction, including without limitation the rights
-## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-## copies of the Software, and to permit persons to whom the Software is
-## furnished to do so, subject to the following conditions:
-##
-## The above copyright notice and this permission notice shall be included in all
-## copies or substantial portions of the Software.
-##
-## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-## SOFTWARE.
diff --git a/docs/head.mako b/docs/head.mako
deleted file mode 100644
index 7c538976fe..0000000000
--- a/docs/head.mako
+++ /dev/null
@@ -1,47 +0,0 @@
-## Copyright (c) 2020 Nekokatt
-## Copyright (c) 2021-present davfsa
-##
-## Permission is hereby granted, free of charge, to any person obtaining a copy
-## of this software and associated documentation files (the "Software"), to deal
-## in the Software without restriction, including without limitation the rights
-## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-## copies of the Software, and to permit persons to whom the Software is
-## furnished to do so, subject to the following conditions:
-##
-## The above copyright notice and this permission notice shall be included in all
-## copies or substantial portions of the Software.
-##
-## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-## SOFTWARE.
-<%
- import hikari
-
- DEPTH = '../' * module.url().count('/')
-%>
-
-
-
-
-
- Hikari ${hikari.__version__}
-
-
-
diff --git a/docs/html.mako b/docs/html.mako
deleted file mode 100644
index aa9a30392c..0000000000
--- a/docs/html.mako
+++ /dev/null
@@ -1,83 +0,0 @@
-## Copyright (c) 2020 Nekokatt
-## Copyright (c) 2021-present davfsa
-##
-## Permission is hereby granted, free of charge, to any person obtaining a copy
-## of this software and associated documentation files (the "Software"), to deal
-## in the Software without restriction, including without limitation the rights
-## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-## copies of the Software, and to permit persons to whom the Software is
-## furnished to do so, subject to the following conditions:
-##
-## The above copyright notice and this permission notice shall be included in all
-## copies or substantial portions of the Software.
-##
-## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-## SOFTWARE.
-############################# IMPORTS ##############################
-<%!
- import os
- from pdoc import html_helpers
-%>
-########################### CONFIGURATION ##########################
-<%include file="config.mako"/>
-############################ COMPONENTS ############################
-
-
-
-
-
-
- % if module_list:
- ${module.name} module list
-
- % else:
- ${module.name} API documentation
-
- % endif
-
- ## Determine how to name the page.
- % if "." in module.name:
-
- % else:
-
- % endif
-
-
-
-
-
-
-
- ## Google Search Engine integration
-
-
- ## Bootstrap 4 stylesheet
-
- ## Highlight.js stylesheet
-
- ## Custom stylesheets
-
-
- ## Provide LaTeX math support
-
-
-
-
- <%include file="body.mako"/>
- ## Script dependencies for Bootstrap.
-
-
-
- ## Highlightjs stuff
-
-
-
-
diff --git a/docs/index.md b/docs/index.md
new file mode 100644
index 0000000000..62e7c6438d
--- /dev/null
+++ b/docs/index.md
@@ -0,0 +1,12 @@
+# Welcome!
+
+```{include} ../README.md
+```
+
+```{toctree}
+:titlesonly:
+:maxdepth: 1
+
+API Reference
+/changelog/index
+```
diff --git a/docs/patched_pdoc.py b/docs/patched_pdoc.py
deleted file mode 100644
index b0e5f2d6c2..0000000000
--- a/docs/patched_pdoc.py
+++ /dev/null
@@ -1,112 +0,0 @@
-# -*- coding: utf-8 -*-
-# cython: language_level=3
-# Copyright (c) 2020 Nekokatt
-# Copyright (c) 2021-present davfsa
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in all
-# copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-# SOFTWARE.
-
-import json
-import os.path as path
-import re
-
-import pdoc
-from pdoc import cli
-
-
-def _patched_generate_lunr_search(modules, index_docstrings, template_config):
- # This will only be called once due to how we generate the documentation, so we can ignore the rest
- assert len(modules) == 1, "expected only 1 module to be generated, got more"
- top_module = modules[0]
-
- def trim_docstring(docstring):
- return re.sub(
- r"""
- \s+[-=~]{3,}\s+| # title underlines
- ^[ \t]*[`~]{3,}\w*$| # code blocks
- \s*[`#*]+\s*| # common markdown chars
- \s*([^\w\d_>])\1\s*| # sequences of punct of the same kind
- \s*?\w*[^>]*>\s* # simple HTML tags
- \s+ # whitespace sequences
- """,
- " ",
- docstring,
- flags=re.VERBOSE | re.MULTILINE,
- )
-
- def recursive_add_to_index(dobj):
- if dobj.module.name != "hikari": # Do not index root
- url = to_url_id(dobj)
- # r: ref
- # u: url
- # d: docstring
- # f: function
- info = {"r": dobj.refname, "u": url}
- if index_docstrings:
- info["d"] = trim_docstring(dobj.docstring)
- if isinstance(dobj, pdoc.Function):
- info["f"] = 1
-
- index.append(info)
-
- for member_dobj in getattr(dobj, "doc", {}).values():
- if dobj.module.name == "hikari" and not isinstance(member_dobj, pdoc.Module):
- continue
-
- recursive_add_to_index(member_dobj)
-
- def to_url_id(dobj):
- # pdocs' .url() doesn't take in account that some attributes are inherited,
- # which generates an invalid url. Because of this, we need to take matter
- # into our own hands.
- url = dobj.refname.replace(".", "/")
- if not isinstance(dobj, pdoc.Module):
- depth = 1
- obj = getattr(dobj, "cls", None)
- while obj:
- depth += 1
- obj = getattr(obj, "cls", None)
-
- url = "/".join(url.split("/")[:-depth])
-
- if top_module.is_package: # Reference from subfolder if its a package
- _, url = url.split("/", maxsplit=1)
- if url not in url_cache:
- url_cache[url] = len(url_cache)
- return url_cache[url]
-
- index = []
- url_cache = {}
- recursive_add_to_index(top_module)
- urls = sorted(url_cache.keys(), key=url_cache.__getitem__)
-
- # If top module is a package, output the index in its subfolder, else, in the output dir
- main_path = path.join(cli.args.output_dir, *top_module.name.split(".") if top_module.is_package else "")
- with cli._open_write_file(path.join(main_path, "index.json")) as f:
- json.dump({"urls": urls, "index": index}, f)
-
- # Generate search.html
- with cli._open_write_file(path.join(main_path, "search.html")) as f:
- rendered_template = pdoc._render_template("/search.mako", module=top_module, **template_config)
- f.write(rendered_template)
-
-
-if __name__ == "__main__":
- cli._generate_lunr_search = _patched_generate_lunr_search
-
- cli.main()
diff --git a/docs/search.mako b/docs/search.mako
deleted file mode 100644
index ce5f4a7067..0000000000
--- a/docs/search.mako
+++ /dev/null
@@ -1,233 +0,0 @@
-## Copyright (c) 2020 Nekokatt
-## Copyright (c) 2021-present davfsa
-##
-## Permission is hereby granted, free of charge, to any person obtaining a copy
-## of this software and associated documentation files (the "Software"), to deal
-## in the Software without restriction, including without limitation the rights
-## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-## copies of the Software, and to permit persons to whom the Software is
-## furnished to do so, subject to the following conditions:
-##
-## The above copyright notice and this permission notice shall be included in all
-## copies or substantial portions of the Software.
-##
-## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-## SOFTWARE.
-########################### CONFIGURATION ##########################
-<%include file="config.mako"/>
-############################ COMPONENTS ############################
-
-
-
-
-
-
- Search documentation - ${module.name.capitalize()}
-
-
-
-
-
-
-
-
-
-
- ## Bootstrap 4 stylesheet
-
- ## Custom stylesheets
-
-
-
-
- <%include file="head.mako"/>
-
-
-
-
-
-
-
- JavaScript is disabled, so search functionality is not available!
-
-
-
-
-
-
-
-
-
-
-
diff --git a/hikari/__init__.py b/hikari/__init__.py
index 10b95e050a..566b3a7daa 100644
--- a/hikari/__init__.py
+++ b/hikari/__init__.py
@@ -22,14 +22,13 @@
# SOFTWARE.
"""A sane Python framework for writing modern Discord bots.
-To get started, you will want to initialize an instance of `GatewayBot`
-for writing a bot, or `RESTApp` if you only need to use the REST API.
+To get started, you will want to initialize an instance of `hikari.impl.bot.GatewayBot`
+for writing a gateway based bot, `hikari.impl.rest_bot.RESTBot` for a REST based bot,
+or `hikari.impl.rest.RESTApp` if you only need to use the REST API.
"""
from __future__ import annotations
-import os as _os
-
from hikari import api
from hikari import applications
from hikari import events
@@ -132,9 +131,3 @@
from hikari.users import *
from hikari.voices import *
from hikari.webhooks import *
-
-# Only expose this during documentation, as we need it to make anything visible.
-if _os.getenv("PDOC3_GENERATING") == "1": # pragma: no cover
- __all__ = [name for name in dir() if not name.startswith("_")]
-
-del _os
diff --git a/hikari/__init__.pyi b/hikari/__init__.pyi
index 3d59a211ff..81ae74e07e 100644
--- a/hikari/__init__.pyi
+++ b/hikari/__init__.pyi
@@ -1,8 +1,6 @@
# DO NOT MANUALLY EDIT THIS FILE!
# This file was automatically generated by `nox -s generate-stubs`
-from _typeshed import Incomplete
-
from hikari import api as api
from hikari import applications as applications
from hikari import events as events
@@ -105,5 +103,3 @@ from hikari.undefined import UndefinedType as UndefinedType
from hikari.users import *
from hikari.voices import *
from hikari.webhooks import *
-
-__all__: Incomplete
diff --git a/hikari/_about.py b/hikari/_about.py
index f53f780dd7..bcce3487bd 100644
--- a/hikari/_about.py
+++ b/hikari/_about.py
@@ -26,15 +26,15 @@
import typing
# DO NOT CHANGE THE TYPE HINTS FOR THESE FIELDS. THESE ARE AUTOMATICALLY UPDATED
-# FROM THE CI SCRIPT AND DOING THIS MAY LEAD TO THE DEPLOY PROCESS FAILING.
+# FROM THE CI SCRIPT AND DOING THIS MAY LEAD TO THE RELEASE PROCESS FAILING.
__author__: typing.Final[str] = "Nekokatt"
__maintainer__: typing.Final[str] = "davfsa"
__ci__: typing.Final[str] = "https://github.com/hikari-py/hikari/actions"
-__copyright__: typing.Final[str] = "© 2021-present davfsa"
+__copyright__: typing.Final[str] = "2021-present, davfsa"
__coverage__: typing.Final[str] = "https://codeclimate.com/github/hikari-py/hikari"
__discord_invite__: typing.Final[str] = "https://discord.gg/Jx4cNGG"
-__docs__: typing.Final[str] = "https://hikari-py.dev/hikari"
+__docs__: typing.Final[str] = "https://docs.hikari-py.dev/en/master"
__email__: typing.Final[str] = "davfsa@gmail.com"
__issue_tracker__: typing.Final[str] = "https://github.com/hikari-py/hikari/issues"
__license__: typing.Final[str] = "MIT"
diff --git a/hikari/api/cache.py b/hikari/api/cache.py
index edca63a09c..49555adda7 100644
--- a/hikari/api/cache.py
+++ b/hikari/api/cache.py
@@ -65,7 +65,7 @@ def get_item_at(self, index: slice, /) -> typing.Sequence[_ValueT]:
@abc.abstractmethod
def get_item_at(self, index: typing.Union[slice, int], /) -> typing.Union[_ValueT, typing.Sequence[_ValueT]]:
- ...
+ """Get an item at a specific position or slice."""
class Cache(abc.ABC):
@@ -104,7 +104,7 @@ def get_dm_channel_id(
-------
typing.Optional[hikari.snowflakes.Snowflake]
ID of the DM channel which was found cached for the supplied user or
- `builtins.None`.
+ `None`.
"""
@abc.abstractmethod
@@ -131,7 +131,7 @@ def get_emoji(
Returns
-------
typing.Optional[hikari.emojis.KnownCustomEmoji]
- The object of the emoji that was found in the cache or `builtins.None`.
+ The object of the emoji that was found in the cache or `None`.
"""
@abc.abstractmethod
@@ -177,7 +177,7 @@ def get_sticker(
Returns
-------
typing.Optional[hikari.stickers.GuildSticker]
- The object of the sticker that was found in the cache or `builtins.None`.
+ The object of the sticker that was found in the cache or `None`.
"""
@abc.abstractmethod
@@ -214,7 +214,7 @@ def get_guild(
) -> typing.Optional[guilds.GatewayGuild]:
"""Get a guild from the cache.
- !!! warning
+ .. warning::
This will return a guild regardless of whether it is available or
not. To only query available guilds, use `get_available_guild`
instead. Likewise, to only query unavailable guilds, use
@@ -228,7 +228,7 @@ def get_guild(
Returns
-------
typing.Optional[hikari.guilds.GatewayGuild]
- The object of the guild if found, else `builtins.None`.
+ The object of the guild if found, else `None`.
"""
@abc.abstractmethod
@@ -245,7 +245,7 @@ def get_available_guild(
Returns
-------
typing.Optional[hikari.guilds.GatewayGuild]
- The object of the guild if found, else `builtins.None`.
+ The object of the guild if found, else `None`.
"""
@abc.abstractmethod
@@ -254,7 +254,7 @@ def get_unavailable_guild(
) -> typing.Optional[guilds.GatewayGuild]:
"""Get the object of a unavailable guild from the cache.
- !!! note
+ .. note::
Unlike `Cache.get_available_guild`, the objects returned by this
method will likely be out of date and inaccurate as they are
considered unavailable, meaning that we are not receiving gateway
@@ -268,7 +268,7 @@ def get_unavailable_guild(
Returns
-------
typing.Optional[hikari.guilds.GatewayGuild]
- The object of the guild if found, else `builtins.None`.
+ The object of the guild if found, else `None`.
"""
@abc.abstractmethod
@@ -295,7 +295,7 @@ def get_available_guilds_view(self) -> CacheView[snowflakes.Snowflake, guilds.Ga
def get_unavailable_guilds_view(self) -> CacheView[snowflakes.Snowflake, guilds.GatewayGuild]:
"""Get a view of the unavailable guild objects in the cache.
- !!! note
+ .. note::
Unlike `Cache.get_available_guilds_view`, the objects returned by
this method will likely be out of date and inaccurate as they are
considered unavailable, meaning that we are not receiving gateway
@@ -322,7 +322,7 @@ def get_guild_channel(
-------
typing.Optional[hikari.channels.PermissibleGuildChannel]
The object of the guild channel that was found in the cache or
- `builtins.None`.
+ `None`.
"""
@abc.abstractmethod
@@ -430,13 +430,13 @@ def get_invite(self, code: typing.Union[invites.InviteCode, str], /) -> typing.O
Parameters
----------
- code : typing.Union[hikari.invites.InviteCode, builtins.str]
+ code : typing.Union[hikari.invites.InviteCode, str]
The object or string code of the invite to get from the cache.
Returns
-------
typing.Optional[hikari.invites.InviteWithMetadata]
- The object of the invite that was found in the cache or `builtins.None`.
+ The object of the invite that was found in the cache or `None`.
"""
@abc.abstractmethod
@@ -445,7 +445,7 @@ def get_invites_view(self) -> CacheView[str, invites.InviteWithMetadata]:
Returns
-------
- CacheView[builtins.str, hikari.invites.InviteWithMetadata]
+ CacheView[str, hikari.invites.InviteWithMetadata]
A view of string codes to objects of the invites that were found in
the cache.
"""
@@ -463,7 +463,7 @@ def get_invites_view_for_guild(
Returns
-------
- CacheView[builtins.str, hikari.invites.InviteWithMetadata]
+ CacheView[str, hikari.invites.InviteWithMetadata]
A view of string code to objects of the invites that were found in
the cache for the specified guild.
"""
@@ -498,7 +498,7 @@ def get_me(self) -> typing.Optional[users.OwnUser]:
Returns
-------
typing.Optional[hikari.users.OwnUser]
- The own user object that was found in the cache, else `builtins.None`.
+ The own user object that was found in the cache, else `None`.
"""
@abc.abstractmethod
@@ -520,7 +520,7 @@ def get_member(
Returns
-------
typing.Optional[hikari.guilds.Member]
- The object of the member found in the cache, else `builtins.None`.
+ The object of the member found in the cache, else `None`.
"""
@abc.abstractmethod
@@ -565,7 +565,7 @@ def get_message(
Returns
-------
typing.Optional[hikari.messages.Message]
- The object of the message found in the cache or `builtins.None`.
+ The object of the message found in the cache or `None`.
"""
@abc.abstractmethod
@@ -598,7 +598,7 @@ def get_presence(
-------
typing.Optional[hikari.presences.MemberPresence]
The object of the presence that was found in the cache or
- `builtins.None`.
+ `None`.
"""
@abc.abstractmethod
@@ -644,7 +644,7 @@ def get_role(self, role: snowflakes.SnowflakeishOr[guilds.PartialRole], /) -> ty
Returns
-------
typing.Optional[hikari.guilds.Role]
- The object of the role found in the cache or `builtins.None`.
+ The object of the role found in the cache or `None`.
"""
@abc.abstractmethod
@@ -688,7 +688,7 @@ def get_user(self, user: snowflakes.SnowflakeishOr[users.PartialUser], /) -> typ
-------
typing.Optional[hikari.users.User]
The object of the user that was found in the cache, else
- `builtins.None`.
+ `None`.
"""
@abc.abstractmethod
@@ -721,7 +721,7 @@ def get_voice_state(
-------
typing.Optional[hikari.voices.VoiceState]
The object of the voice state that was found in the cache, or
- `builtins.None`.
+ `None`.
"""
@abc.abstractmethod
@@ -734,7 +734,7 @@ def get_voice_states_view(
-------
CacheView[hikari.snowflakes.Snowflake, CacheView[hikari.snowflakes.Snowflake, hikari.voices.VoiceState]]
A view of guild IDs to views of user IDs to objects of the voice
- states that were found in the cache,
+ states that were found in the cache.
"""
@abc.abstractmethod
@@ -818,7 +818,7 @@ def delete_dm_channel_id(
-------
typing.Optional[hikari.snowflakes.Snowflake]
The DM channel ID which was removed from the cache if found, else
- `builtins.None`.
+ `None`.
"""
@abc.abstractmethod
@@ -842,7 +842,7 @@ def set_dm_channel_id(
def clear_emojis(self) -> CacheView[snowflakes.Snowflake, emojis.KnownCustomEmoji]:
"""Remove all the known custom emoji objects from the cache.
- !!! note
+ .. note::
This will skip emojis that are being kept alive by a reference
on a presence entry.
@@ -859,15 +859,15 @@ def clear_emojis_for_guild(
) -> CacheView[snowflakes.Snowflake, emojis.KnownCustomEmoji]:
"""Remove the known custom emoji objects cached for a specific guild.
+ .. note::
+ This will skip emojis that are being kept alive by a reference
+ on a presence entry.
+
Parameters
----------
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
Object or ID of the guild to remove the cached emoji objects for.
- !!! note
- This will skip emojis that are being kept alive by a reference
- on a presence entry.
-
Returns
-------
CacheView[hikari.snowflakes.Snowflake, hikari.emojis.KnownCustomEmoji]
@@ -881,20 +881,20 @@ def delete_emoji(
) -> typing.Optional[emojis.KnownCustomEmoji]:
"""Remove a known custom emoji from the cache.
+ .. note::
+ This will not delete emojis that are being kept alive by a reference
+ on a presence entry.
+
Parameters
----------
emoji : hikari.snowflakes.SnowflakeishOr[hikari.emojis.CustomEmoji]
Object or ID of the emoji to remove from the cache.
- !!! note
- This will not delete emojis that are being kept alive by a reference
- on a presence entry.
-
Returns
-------
typing.Optional[hikari.emojis.KnownCustomEmoji]
The object of the emoji that was removed from the cache or
- `builtins.None`.
+ `None`.
"""
@abc.abstractmethod
@@ -921,16 +921,16 @@ def update_emoji(
Returns
-------
typing.Tuple[typing.Optional[hikari.emojis.KnownCustomEmoji], typing.Optional[hikari.emojis.KnownCustomEmoji]]
- A tuple of the old cached emoji object if found (else `builtins.None`)
+ A tuple of the old cached emoji object if found (else `None`)
and the new cached emoji object if it could be cached (else
- `builtins.None`).
+ `None`).
"""
@abc.abstractmethod
def clear_stickers(self) -> CacheView[snowflakes.Snowflake, stickers.GuildSticker]:
"""Remove all the sticker objects from the cache.
- !!! note
+ .. note::
This will skip stickers that are being kept alive by a reference.
Returns
@@ -951,7 +951,7 @@ def clear_stickers_for_guild(
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
Object or ID of the guild to remove the cached sticker objects for.
- !!! note
+ .. note::
This will skip stickers that are being kept alive by a reference.
Returns
@@ -967,19 +967,19 @@ def delete_sticker(
) -> typing.Optional[stickers.GuildSticker]:
"""Remove a sticker from the cache.
+ .. note::
+ This will not delete stickers that are being kept alive by a reference.
+
Parameters
----------
sticker : hikari.snowflakes.SnowflakeishOr[hikari.stickers.GuildSticker]
Object or ID of the sticker to remove from the cache.
- !!! note
- This will not delete stickers that are being kept alive by a reference.
-
Returns
-------
typing.Optional[hikari.stickers.GuildSticker]
The object of the sticker that was removed from the cache or
- `builtins.None`.
+ `None`.
"""
@abc.abstractmethod
@@ -1018,7 +1018,7 @@ def delete_guild(
-------
typing.Optional[hikari.guilds.GatewayGuild]
The object of the guild that was removed from the cache, will be
- `builtins.None` if not found.
+ `None` if not found.
"""
@abc.abstractmethod
@@ -1041,7 +1041,7 @@ def set_guild_availability(
----------
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
Object or ID of the guild to set the availability for.
- is_available : builtins.bool
+ is_available : bool
The availability to set for the guild.
"""
@@ -1059,9 +1059,9 @@ def update_guild(
Returns
-------
typing.Tuple[typing.Optional[hikari.guilds.GatewayGuild], typing.Optional[hikari.guilds.GatewayGuild]]
- A tuple of the old cached guild object if found (else `builtins.None`)
+ A tuple of the old cached guild object if found (else `None`)
and the object of the guild that was added to the cache if it could
- be added (else `builtins.None`).
+ be added (else `None`).
"""
@abc.abstractmethod
@@ -1108,7 +1108,7 @@ def delete_guild_channel(
-------
typing.Optional[hikari.channels.PermissibleGuildChannel]
The object of the guild channel that was removed from the cache if
- found, else `builtins.None`.
+ found, else `None`.
"""
@abc.abstractmethod
@@ -1137,9 +1137,9 @@ def update_guild_channel(
Returns
-------
typing.Tuple[typing.Optional[hikari.channels.PermissibleGuildChannel], typing.Optional[hikari.channels.PermissibleGuildChannel]]
- A tuple of the old cached guild channel if found (else `builtins.None`)
+ A tuple of the old cached guild channel if found (else `None`)
and the new cached guild channel if it could be cached
- (else `builtins.None`).
+ (else `None`).
""" # noqa: E501 - Line too long
@abc.abstractmethod
@@ -1247,7 +1247,7 @@ def clear_invites(self) -> CacheView[str, invites.InviteWithMetadata]:
Returns
-------
- CacheView[builtins.str, hikari.invites.InviteWithMetadata]
+ CacheView[str, hikari.invites.InviteWithMetadata]
A view of invite code strings to objects of the invites that were
removed from the cache.
"""
@@ -1265,7 +1265,7 @@ def clear_invites_for_guild(
Returns
-------
- CacheView[builtins.str, hikari.invites.InviteWithMetadata]
+ CacheView[str, hikari.invites.InviteWithMetadata]
A view of invite code strings to objects of the invites that were
removed from the cache for the specified guild.
"""
@@ -1288,7 +1288,7 @@ def clear_invites_for_channel(
Returns
-------
- CacheView[builtins.str, hikari.invites.InviteWithMetadata]
+ CacheView[str, hikari.invites.InviteWithMetadata]
A view of invite code strings to objects of the invites that were
removed from the cache for the specified channel.
"""
@@ -1301,14 +1301,14 @@ def delete_invite(
Parameters
----------
- code : typing.Union[hikari.invites.InviteCode, builtins.str]
+ code : typing.Union[hikari.invites.InviteCode, str]
Object or string code of the invite to remove from the cache.
Returns
-------
typing.Optional[hikari.invites.InviteWithMetadata]
The object of the invite that was removed from the cache if found,
- else `builtins.None`.
+ else `None`.
"""
@abc.abstractmethod
@@ -1336,8 +1336,8 @@ def update_invite(
-------
typing.Tuple[typing.Optional[hikari.invites.InviteWithMetadata], typing.Optional[hikari.invites.InviteWithMetadata]]
A tuple of the old cached invite object if found (else
- `builtins.None`) and the new cached invite object if it could be
- cached (else `builtins.None`).
+ `None`) and the new cached invite object if it could be
+ cached (else `None`).
"""
@abc.abstractmethod
@@ -1348,7 +1348,7 @@ def delete_me(self) -> typing.Optional[users.OwnUser]:
-------
typing.Optional[hikari.users.OwnUser]
The own user object that was removed from the cache if found,
- else `builtins.None`.
+ else `None`.
"""
@abc.abstractmethod
@@ -1376,8 +1376,8 @@ def update_me(
-------
typing.Tuple[typing.Optional[hikari.users.OwnUser], typing.Optional[hikari.users.OwnUser]]
A tuple of the old cached own user object if found (else
- `builtins.None`) and the new cached own user object if it could be
- cached, else `builtins.None`.
+ `None`) and the new cached own user object if it could be
+ cached, else `None`.
"""
@abc.abstractmethod
@@ -1397,15 +1397,15 @@ def clear_members_for_guild(
) -> CacheView[snowflakes.Snowflake, guilds.Member]:
"""Remove the members for a specific guild from the cache.
+ .. note::
+ This will skip members that are being referenced by other entries in
+ the cache; a matching voice state will keep a member entry alive.
+
Parameters
----------
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
Object or ID of the guild to remove cached members for.
- !!! note
- This will skip members that are being referenced by other entries in
- the cache; a matching voice state will keep a member entry alive.
-
Returns
-------
CacheView[hikari.snowflakes.Snowflake, hikari.guilds.Member]
@@ -1422,6 +1422,11 @@ def delete_member(
) -> typing.Optional[guilds.Member]:
"""Remove a member object from the cache.
+ .. note::
+ You cannot delete a member entry that's being referenced by other
+ entries in the cache; a matching voice state will keep a member
+ entry alive.
+
Parameters
----------
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
@@ -1429,16 +1434,11 @@ def delete_member(
user : hikari.snowflakes.SnowflakeishOr[hikari.users.PartialUser]
Object or ID of the user to remove a member from the cache for.
- !!! note
- You cannot delete a member entry that's being referenced by other
- entries in the cache; a matching voice state will keep a member
- entry alive.
-
Returns
-------
typing.Optional[hikari.guilds.Member]
The object of the member that was removed from the cache if found,
- else `builtins.None`.
+ else `None`.
"""
@abc.abstractmethod
@@ -1465,9 +1465,9 @@ def update_member(
Returns
-------
typing.Tuple[typing.Optional[hikari.guilds.Member], typing.Optional[hikari.guilds.Member]]
- A tuple of the old cached member object if found (else `builtins.None`)
+ A tuple of the old cached member object if found (else `None`)
and the new cached member object if it could be cached (else
- `builtins.None`)
+ `None`).
"""
@abc.abstractmethod
@@ -1521,7 +1521,7 @@ def delete_presence(
-------
typing.Optional[hikari.presences.MemberPresence]
The object of the presence that was removed from the cache if found,
- else `builtins.None`.
+ else `None`.
"""
@abc.abstractmethod
@@ -1548,9 +1548,9 @@ def update_presence(
Returns
-------
typing.Tuple[typing.Optional[hikari.presences.MemberPresence], typing.Optional[hikari.presences.MemberPresence]]
- A tuple of the old cached invite object if found (else `builtins.None`
+ A tuple of the old cached invite object if found (else `None`
and the new cached invite object if it could be cached ( else
- `builtins.None`).
+ `None`).
"""
@abc.abstractmethod
@@ -1595,7 +1595,7 @@ def delete_role(self, role: snowflakes.SnowflakeishOr[guilds.PartialRole], /) ->
-------
typing.Optional[hikari.guilds.Role]
The object of the role that was removed from the cache if found,
- else `builtins.None`.
+ else `None`.
"""
@abc.abstractmethod
@@ -1622,9 +1622,9 @@ def update_role(
Returns
-------
typing.Tuple[typing.Optional[hikari.guilds.Role], typing.Optional[hikari.guilds.Role]]
- A tuple of the old cached role object if found (else `builtins.None`
+ A tuple of the old cached role object if found (else `None`
and the new cached role object if it could be cached (else
- `builtins.None`).
+ `None`).
"""
@abc.abstractmethod
@@ -1699,7 +1699,7 @@ def delete_voice_state(
-------
typing.Optional[hikari.voices.VoiceState]
The object of the voice state that was removed from the cache if
- found, else `builtins.None`.
+ found, else `None`.
"""
@abc.abstractmethod
@@ -1726,9 +1726,9 @@ def update_voice_state(
Returns
-------
typing.Tuple[typing.Optional[hikari.voices.VoiceState], typing.Optional[hikari.voices.VoiceState]]
- A tuple of the old cached voice state if found (else `builtins.None`)
+ A tuple of the old cached voice state if found (else `None`)
and the new cached voice state object if it could be cached
- (else `builtins.None`).
+ (else `None`).
"""
@abc.abstractmethod
@@ -1756,7 +1756,7 @@ def delete_message(
-------
typing.Optional[hikari.messages.Message]
The object of the message that was removed from the cache if found,
- else `builtins.None`.
+ else `None`.
"""
@abc.abstractmethod
@@ -1783,7 +1783,7 @@ def update_message(
Returns
-------
typing.Tuple[typing.Optional[hikari.messages.Message], typing.Optional[hikari.messages.Message]]
- A tuple of the old cached message object if found (else `builtins.None`)
+ A tuple of the old cached message object if found (else `None`)
and the new cached message object if it could be cached (else
- `builtins.None`).
+ `None`).
"""
diff --git a/hikari/api/config.py b/hikari/api/config.py
index 9dba677ecf..ef6b05b738 100644
--- a/hikari/api/config.py
+++ b/hikari/api/config.py
@@ -107,7 +107,7 @@ class ProxySettings(abc.ABC):
def url(self) -> typing.Union[None, str]:
"""Proxy URL to use.
- If this is `builtins.None` then no explicit proxy is being used.
+ If this is `None` then no explicit proxy is being used.
"""
@property
@@ -115,13 +115,13 @@ def url(self) -> typing.Union[None, str]:
def trust_env(self) -> bool:
"""Toggle whether to look for a `netrc` file or environment variables.
- If `builtins.True`, and no `url` is given on this object, then
+ If `True`, and no `url` is given on this object, then
`HTTP_PROXY` and `HTTPS_PROXY` will be used from the environment
variables, or a `netrc` file may be read to determine credentials.
- If `builtins.False`, then this information is instead ignored.
+ If `False`, then this information is instead ignored.
- !!! note
+ .. note::
For more details of using `netrc`, visit:
https://www.gnu.org/software/inetutils/manual/html_node/The-_002enetrc-file.html
"""
@@ -137,11 +137,11 @@ class HTTPSettings(abc.ABC):
def max_redirects(self) -> typing.Optional[int]:
"""Behavior for handling redirect HTTP responses.
- If a `builtins.int`, allow following redirects from `3xx` HTTP responses
+ If a `int`, allow following redirects from `3xx` HTTP responses
for up to this many redirects. Exceeding this value will raise an
exception.
- If `builtins.None`, then disallow any redirects.
+ If `None`, then disallow any redirects.
The default is to disallow this behavior for security reasons.
@@ -149,7 +149,7 @@ def max_redirects(self) -> typing.Optional[int]:
future where you need to enable this if Discord change their URL without
warning.
- !!! note
+ .. note::
This will only apply to the REST API. WebSockets remain unaffected
by any value set here.
"""
@@ -159,24 +159,24 @@ def max_redirects(self) -> typing.Optional[int]:
def ssl(self) -> ssl_.SSLContext:
"""SSL context to use.
- This may be __assigned__ a `builtins.bool` or an `ssl.SSLContext` object.
+ This may be assigned a `bool` or an `ssl.SSLContext` object.
- If assigned to `builtins.True`, a default SSL context is generated by
+ If assigned to `True`, a default SSL context is generated by
this class that will enforce SSL verification. This is then stored in
this field.
- If `builtins.False`, then a default SSL context is generated by this
+ If `False`, then a default SSL context is generated by this
class that will **NOT** enforce SSL verification. This is then stored
in this field.
If an instance of `ssl.SSLContext`, then this context will be used.
- !!! warning
+ .. warning::
Setting a custom value here may have security implications, or
may result in the application being unable to connect to Discord
at all.
- !!! warning
+ .. warning::
Disabling SSL verification is almost always unadvised. This
is because your application will no longer check whether you are
connecting to Discord, or to some third party spoof designed
diff --git a/hikari/api/entity_factory.py b/hikari/api/entity_factory.py
index 2c21303fed..90e2e46d7f 100644
--- a/hikari/api/entity_factory.py
+++ b/hikari/api/entity_factory.py
@@ -60,8 +60,8 @@
class GatewayGuildDefinition(abc.ABC):
"""Structure for handling entities within guild create and update events.
- !!! warning
- The methods on this class may raise `builtins.LookupError` if called
+ .. warning::
+ The methods on this class may raise `LookupError` if called
when the relevant resource isn't available in the inner payload.
"""
@@ -92,7 +92,7 @@ def guild(self) -> guild_models.GatewayGuild:
def members(self) -> typing.Mapping[snowflakes.Snowflake, guild_models.Member]:
"""Get a mapping of user IDs to the members that belong to the guild.
- !!! note
+ .. note::
This may be a partial mapping of members in the guild.
"""
@@ -100,7 +100,7 @@ def members(self) -> typing.Mapping[snowflakes.Snowflake, guild_models.Member]:
def presences(self) -> typing.Mapping[snowflakes.Snowflake, presence_models.MemberPresence]:
"""Get a mapping of user IDs to the presences that are active in the guild.
- !!! note
+ .. note::
This may be a partial mapping of presences active in the guild.
"""
@@ -368,9 +368,8 @@ def deserialize_guild_category(
The ID of the guild this channel belongs to. If passed then this
will be prioritised over `"guild_id"` in the payload.
- !!! note
- `guild_id` currently only covers the gateway GUILD_CREATE event
- where `"guild_id"` is not included in the channel's payload.
+ This currently only covers the gateway `GUILD_CREATE` event,
+ where it is not included in the channel's payload.
Returns
-------
@@ -379,7 +378,7 @@ def deserialize_guild_category(
Raises
------
- builtins.KeyError
+ KeyError
If `guild_id` is left as `hikari.undefined.UNDEFINED` when
`"guild_id"` is not present in the passed payload.
"""
@@ -404,9 +403,8 @@ def deserialize_guild_text_channel(
The ID of the guild this channel belongs to. If passed then this
will be prioritised over `"guild_id"` in the payload.
- !!! note
- `guild_id` currently only covers the gateway GUILD_CREATE event
- where `"guild_id"` is not included in the channel's payload.
+ This currently only covers the gateway `GUILD_CREATE` event,
+ where it is not included in the channel's payload.
Returns
-------
@@ -415,7 +413,7 @@ def deserialize_guild_text_channel(
Raises
------
- builtins.KeyError
+ KeyError
If `guild_id` is left as `hikari.undefined.UNDEFINED` when
`"guild_id"` is not present in the passed payload.
"""
@@ -440,9 +438,8 @@ def deserialize_guild_news_channel(
The ID of the guild this channel belongs to. If passed then this
will be prioritised over `"guild_id"` in the payload.
- !!! note
- `guild_id` currently only covers the gateway GUILD_CREATE event
- where `"guild_id"` is not included in the channel's payload.
+ This currently only covers the gateway `GUILD_CREATE` event,
+ where it is not included in the channel's payload.
Returns
-------
@@ -451,7 +448,7 @@ def deserialize_guild_news_channel(
Raises
------
- builtins.KeyError
+ KeyError
If `guild_id` is left as `hikari.undefined.UNDEFINED` when
`"guild_id"` is not present in the passed payload.
"""
@@ -476,9 +473,8 @@ def deserialize_guild_voice_channel(
The ID of the guild this channel belongs to. If passed then this
will be prioritised over `"guild_id"` in the payload.
- !!! note
- `guild_id` currently only covers the gateway GUILD_CREATE event
- where `"guild_id"` is not included in the channel's payload.
+ This currently only covers the gateway `GUILD_CREATE` event,
+ where it is not included in the channel's payload.
Returns
-------
@@ -487,7 +483,7 @@ def deserialize_guild_voice_channel(
Raises
------
- builtins.KeyError
+ KeyError
If `guild_id` is left as `hikari.undefined.UNDEFINED` when
`"guild_id"` is not present in the passed payload.
"""
@@ -512,9 +508,8 @@ def deserialize_guild_stage_channel(
The ID of the guild this channel belongs to. If passed then this
will be prioritised over `"guild_id"` in the payload.
- !!! note
- `guild_id` currently only covers the gateway GUILD_CREATE event
- where `"guild_id"` is not included in the channel's payload.
+ This currently only covers the gateway `GUILD_CREATE` event,
+ where it is not included in the channel's payload.
Returns
-------
@@ -523,7 +518,7 @@ def deserialize_guild_stage_channel(
Raises
------
- builtins.KeyError
+ KeyError
If `guild_id` is left as `hikari.undefined.UNDEFINED` when
`"guild_id"` is not present in the passed payload.
"""
@@ -548,7 +543,7 @@ def deserialize_thread_member(
ID of the thread this member belongs to. This will be
prioritised over `"id"` in the payload when passed.
- !!! note
+ .. note::
`thread_id` currently only covers the gateway GUILD_CREATE event
where the field are is included in the thread member's payload.
@@ -559,7 +554,7 @@ def deserialize_thread_member(
Raises
------
- builtins.KeyError
+ KeyError
If `thread_id` or `user_id` is left as `hikari.undefined.UNDEFINED`
when the relevant field isn't present in the passed payload.
"""
@@ -580,7 +575,7 @@ def deserialize_guild_thread(
The ID of the guild this channel belongs to. If passed then this
will be prioritised over `"guild_id"` in the payload.
- !!! note
+ .. note::
`guild_id` currently only covers the gateway GUILD_CREATE event
where `"guild_id"` is not included in the channel's payload.
member : hikari.undefined.UndefinedNoneOr[hikari.channels.ThreadMember]
@@ -594,7 +589,7 @@ def deserialize_guild_thread(
Raises
------
- builtins.KeyError
+ KeyError
If `guild_id` is left as `hikari.undefined.UNDEFINED` when
`"guild_id"` is not present in the passed payload.
"""
@@ -620,7 +615,7 @@ def deserialize_guild_news_thread(
The ID of the guild this channel belongs to. This will be
prioritised over `"guild_id"` in the payload when passed.
- !!! note
+ .. note::
`guild_id` currently only covers the gateway GUILD_CREATE event
where `"guild_id"` is not included in the channel's payload.
member : hikari.undefined.UndefinedNoneOr[hikari.channels.ThreadMember]
@@ -634,7 +629,7 @@ def deserialize_guild_news_thread(
Raises
------
- builtins.KeyError
+ KeyError
If `guild_id` is left as `hikari.undefined.UNDEFINED` when
`"guild_id"` is not present in the passed payload.
"""
@@ -660,7 +655,7 @@ def deserialize_guild_public_thread(
The ID of the guild this channel belongs to. This will be
prioritised over `"guild_id"` in the payload when passed.
- !!! note
+ .. note::
`guild_id` currently only covers the gateway GUILD_CREATE event
where `"guild_id"` is not included in the channel's payload.
member : hikari.undefined.UndefinedNoneOr[hikari.channels.ThreadMember]
@@ -674,7 +669,7 @@ def deserialize_guild_public_thread(
Raises
------
- builtins.KeyError
+ KeyError
If `guild_id` is left as `hikari.undefined.UNDEFINED` when
`"guild_id"` is not present in the passed payload.
"""
@@ -700,7 +695,7 @@ def deserialize_guild_private_thread(
The ID of the guild this channel belongs to. This will be
prioritised over `"guild_id"` in the payload when passed.
- !!! note
+ .. note::
`guild_id` currently only covers the gateway GUILD_CREATE event
where `"guild_id"` is not included in the channel's payload.
member : hikari.undefined.UndefinedNoneOr[hikari.channels.ThreadMember]
@@ -714,7 +709,7 @@ def deserialize_guild_private_thread(
Raises
------
- builtins.KeyError
+ KeyError
If `guild_id` is left as `hikari.undefined.UNDEFINED` when
`"guild_id"` is not present in the passed payload.
"""
@@ -728,7 +723,7 @@ def deserialize_channel(
) -> channel_models.PartialChannel:
"""Parse a raw payload from Discord into a channel object.
- !!! note
+ .. note::
This also deserializes to thread channels.
Parameters
@@ -743,9 +738,8 @@ def deserialize_channel(
for DM and group DM channels and will be prioritised over
`"guild_id"` in the payload when passed.
- !!! note
- `guild_id` currently only covers the gateway GUILD_CREATE event
- where `"guild_id"` is not included in the channel's payload.
+ This is necessary in GUILD_CREATE events, where `"guild_id"` is not
+ included in the channel's payload
Returns
-------
@@ -754,7 +748,7 @@ def deserialize_channel(
Raises
------
- builtins.KeyError
+ KeyError
If `guild_id` is left as `hikari.undefined.UNDEFINED` when
`"guild_id"` is not present in the passed payload of a guild
channel.
@@ -950,6 +944,11 @@ def deserialize_member(
) -> guild_models.Member:
"""Parse a raw payload from Discord into a member object.
+ .. note::
+ `guild_id` covers cases such as the GUILD_CREATE gateway event and
+ GET Guild Member where `"guild_id"` is not included in the returned
+ payload.
+
Parameters
----------
payload : hikari.internal.data_binding.JSONObject
@@ -964,11 +963,6 @@ def deserialize_member(
The ID of the guild this member belongs to. If this is specified
then this will be prioritised over `"guild_id"` in the payload.
- !!! note
- `guild_id` covers cases such as the GUILD_CREATE gateway event and
- GET Guild Member where `"guild_id"` is not included in the returned
- payload.
-
Returns
-------
hikari.guilds.Member
@@ -976,7 +970,7 @@ def deserialize_member(
Raises
------
- builtins.KeyError
+ KeyError
If `guild_id` is left as `hikari.undefined.UNDEFINED` when
`"guild_id"` is not present in the passed payload.
"""
@@ -1047,7 +1041,7 @@ def deserialize_integration(
Raises
------
- builtins.KeyError
+ KeyError
If `guild_id` is left as `hikari.undefined.UNDEFINED` when
`"guild_id"` is not present in the passed payload for the payload of
the integration.
@@ -1158,7 +1152,7 @@ def deserialize_slash_command(
Raises
------
- builtins.KeyError
+ KeyError
If `guild_id` is left as `hikari.undefined.UNDEFINED` when
`"guild_id"` is not present in the passed payload for the payload of
the integration.
@@ -1191,7 +1185,7 @@ def deserialize_context_menu_command(
Raises
------
- builtins.KeyError
+ KeyError
If `guild_id` is left as `hikari.undefined.UNDEFINED` when
`"guild_id"` is not present in the passed payload for the payload of
the integration.
@@ -1224,13 +1218,10 @@ def deserialize_command(
Raises
------
- builtins.KeyError
+ KeyError
If `guild_id` is left as `hikari.undefined.UNDEFINED` when
`"guild_id"` is not present in the passed payload for the payload of
the integration.
-
- Raises
- ------
hikari.errors.UnrecognisedEntityError
If the command type is unknown.
"""
@@ -1258,7 +1249,7 @@ def serialize_command_permission(self, permission: commands.CommandPermission) -
Parameters
----------
- permission: hikari.commands.CommandPermission
+ permission : hikari.commands.CommandPermission
The command permission object to serialize.
Returns
@@ -1299,6 +1290,23 @@ def deserialize_command_interaction(
The deserialized command interaction object.
"""
+ @abc.abstractmethod
+ def deserialize_autocomplete_interaction(
+ self, payload: data_binding.JSONObject
+ ) -> command_interactions.AutocompleteInteraction:
+ """Parse a raw payload from Discord into an autocomplete interaction object.
+
+ Parameters
+ ----------
+ payload : hikari.internal.data_binding.JSONObject
+ The JSON payload to deserialize.
+
+ Returns
+ -------
+ hikari.interactions.command_interactions.AutocompleteInteraction
+ The deserialized autocomplete interaction object.
+ """
+
@abc.abstractmethod
def deserialize_modal_interaction(self, payload: data_binding.JSONObject) -> modal_interactions.ModalInteraction:
"""Parse a raw payload from Discord into a modal interaction object.
@@ -1316,9 +1324,9 @@ def deserialize_modal_interaction(self, payload: data_binding.JSONObject) -> mod
@abc.abstractmethod
def deserialize_interaction(self, payload: data_binding.JSONObject) -> base_interactions.PartialInteraction:
- """Parse a raw payload from Discord into a interaction object.
+ """Parse a raw payload from Discord into an interaction object.
- !!! note
+ .. note::
This isn't required to implement logic for deserializing
PING interactions and if you want to unmarshal those
`EntityFactory.deserialize_partial_interaction` should be compatible.
@@ -1345,7 +1353,7 @@ def serialize_command_option(self, option: commands.CommandOption) -> data_bindi
Parameters
----------
- option: hikari.commands.CommandOption
+ option : hikari.commands.CommandOption
The command option object to serialize.
Returns
@@ -1531,6 +1539,12 @@ def deserialize_member_presence(
) -> presence_models.MemberPresence:
"""Parse a raw payload from Discord into a member presence object.
+ .. note::
+ At the time of writing, the only place where `guild_id` will be
+ mandatory is when parsing presences sent in a `GUILD_CREATE` event
+ from Discord, since the `guild_id` attribute in the payload will
+ have been omitted for redundancy.
+
Parameters
----------
payload : hikari.internal.data_binding.JSONObject
@@ -1542,12 +1556,6 @@ def deserialize_member_presence(
The ID of the guild the presence belongs to. If this is specified
then it is prioritised over `guild_id` in the payload.
- !!! note
- At the time of writing, the only place where `guild_id` will be
- mandatory is when parsing presences sent in a `GUILD_CREATE` event
- from Discord, since the `guild_id` attribute in the payload will
- have been omitted for redundancy.
-
Returns
-------
hikari.presences.MemberPresence
@@ -1555,7 +1563,7 @@ def deserialize_member_presence(
Raises
------
- builtins.KeyError
+ KeyError
If `guild_id` is not an attribute of the `payload` dict, and no
guild ID was passed for the `guild_id` parameter.
@@ -1730,6 +1738,12 @@ def deserialize_voice_state(
) -> voice_models.VoiceState:
"""Parse a raw payload from Discord into a voice state object.
+ .. note::
+ At the time of writing, `GUILD_CREATE` events are the only known
+ place where neither `guild_id` nor `member` will be keys on the
+ payload. In this case, you will need to provide the former
+ parameters explicitly.
+
Parameters
----------
payload : hikari.internal.data_binding.JSONObject
@@ -1745,12 +1759,6 @@ def deserialize_voice_state(
specified then this will be prioritised over `"member"` in the
payload.
- !!! note
- At the time of writing, `GUILD_CREATE` events are the only known
- place where neither `guild_id` nor `member` will be keys on the
- payload. In this case, you will need to provide the former
- parameters explicitly.
-
Returns
-------
hikari.voices.VoiceState
@@ -1758,7 +1766,7 @@ def deserialize_voice_state(
Raises
------
- builtins.KeyError
+ KeyError
If `guild_id` is left as `hikari.undefined.UNDEFINED` when
`"guild_id"` is not present in the passed payload for the payload of
the voice state.
diff --git a/hikari/api/event_factory.py b/hikari/api/event_factory.py
index 97bfa81109..955fe9f30a 100644
--- a/hikari/api/event_factory.py
+++ b/hikari/api/event_factory.py
@@ -129,7 +129,7 @@ def deserialize_guild_channel_update_event(
Other Parameters
----------------
old_channel : typing.Optional[hikari.channels.PermissibleGuildChannel]
- The guild channel object or `builtins.None`.
+ The guild channel object or `None`.
Returns
-------
@@ -346,8 +346,8 @@ def deserialize_invite_delete_event(
Other Parameters
----------------
- old_invite: typing.Optional[hikari.invites.InviteWithMetadata]
- The invite object or `builtins.None`.
+ old_invite : typing.Optional[hikari.invites.InviteWithMetadata]
+ The invite object or `None`.
Returns
-------
@@ -440,7 +440,7 @@ def deserialize_guild_update_event(
Other Parameters
----------------
old_guild : typing.Optional[hikari.guilds.GatewayGuild]
- The guild object or `builtins.None`.
+ The guild object or `None`.
Returns
-------
@@ -468,7 +468,7 @@ def deserialize_guild_leave_event(
Other Parameters
----------------
old_guild : typing.Optional[hikari.guilds.GatewayGuild]
- The guild object or `builtins.None`.
+ The guild object or `None`.
Returns
-------
@@ -553,7 +553,7 @@ def deserialize_guild_emojis_update_event(
Other Parameters
----------------
old_emojis : typing.Optional[typing.Sequence[hikari.emojis.KnownCustomEmoji]]
- The sequence of emojis or `builtins.None`.
+ The sequence of emojis or `None`.
Returns
-------
@@ -581,7 +581,7 @@ def deserialize_guild_stickers_update_event(
Other Parameters
----------------
old_stickers : typing.Optional[typing.Sequence[hikari.stickers.GuildSticker]]
- The sequence of stickers or `builtins.None`.
+ The sequence of stickers or `None`.
Returns
-------
@@ -665,8 +665,8 @@ def deserialize_presence_update_event(
Other Parameters
----------------
- old_presence: typing.Optional[hikari.presences.MemberPresence]
- The presence object or `builtins.None`.
+ old_presence : typing.Optional[hikari.presences.MemberPresence]
+ The presence object or `None`.
Returns
-------
@@ -741,8 +741,8 @@ def deserialize_guild_member_update_event(
Other Parameters
----------------
- old_member: typing.Optional[hikari.guilds.Member]
- The member object or `builtins.None`.
+ old_member : typing.Optional[hikari.guilds.Member]
+ The member object or `None`.
Returns
-------
@@ -769,8 +769,8 @@ def deserialize_guild_member_remove_event(
Other Parameters
----------------
- old_member: typing.Optional[hikari.guilds.Member]
- The member object or `builtins.None`.
+ old_member : typing.Optional[hikari.guilds.Member]
+ The member object or `None`.
Returns
-------
@@ -820,8 +820,8 @@ def deserialize_guild_role_update_event(
Other Parameters
----------------
- old_role: typing.Optional[hikari.guilds.Role]
- The role object or `builtins.None`.
+ old_role : typing.Optional[hikari.guilds.Role]
+ The role object or `None`.
Returns
-------
@@ -848,8 +848,8 @@ def deserialize_guild_role_delete_event(
Other Parameters
----------------
- old_role: typing.Optional[hikari.guilds.Role]
- The role object or `builtins.None`.
+ old_role : typing.Optional[hikari.guilds.Role]
+ The role object or `None`.
Returns
-------
@@ -1052,8 +1052,8 @@ def deserialize_message_update_event(
Other Parameters
----------------
- old_message: typing.Optional[hikari.messages.PartialMessage]
- The message object or `builtins.None`.
+ old_message : typing.Optional[hikari.messages.PartialMessage]
+ The message object or `None`.
Returns
-------
@@ -1213,7 +1213,7 @@ def deserialize_shard_payload_event(
The shard that emitted this event.
payload : hikari.internal.data_binding.JSONObject
The dict payload to parse.
- name : builtins.str
+ name : str
Name of the event.
Returns
@@ -1330,8 +1330,8 @@ def deserialize_own_user_update_event(
Other Parameters
----------------
- old_user: typing.Optional[hikari.users.OwnUser]
- The OwnUser object or `builtins.None`.
+ old_user : typing.Optional[hikari.users.OwnUser]
+ The OwnUser object or `None`.
Returns
-------
@@ -1362,8 +1362,8 @@ def deserialize_voice_state_update_event(
Other Parameters
----------------
- old_state: typing.Optional[hikari.voices.VoiceState]
- The VoiceState object or `builtins.None`.
+ old_state : typing.Optional[hikari.voices.VoiceState]
+ The VoiceState object or `None`.
Returns
-------
diff --git a/hikari/api/event_manager.py b/hikari/api/event_manager.py
index 05ac7ea44a..797fe3cc4a 100644
--- a/hikari/api/event_manager.py
+++ b/hikari/api/event_manager.py
@@ -59,29 +59,29 @@ class EventStream(iterators.LazyIterator[base_events.EventT], abc.ABC):
where `EventStream.open` and `EventStream.close` are implicitly called based on
context.
- ```py
- with EventStream(app, EventType, timeout=50) as stream:
- async for entry in stream:
- ...
- ```
+ .. code-block:: python
+
+ with EventStream(app, EventType, timeout=50) as stream:
+ async for entry in stream:
+ ...
A streamer may also be directly started and closed using the `EventStream.close`
and `EventStream.open`. Note that if you don't call `EventStream.close` after
opening a streamer when you're finished with it then it may queue events
events in memory indefinitely.
- ```py
- stream = EventStream(app, EventType, timeout=50)
- await stream.open()
- async for event in stream:
- ...
+ .. code-block:: python
+
+ stream = EventStream(app, EventType, timeout=50)
+ await stream.open()
+ async for event in stream:
+ ...
- await stream.close()
- ```
+ await stream.close()
See Also
--------
- LazyIterator: `hikari.iterators.LazyIterator`
+ LazyIterator : `hikari.iterators.LazyIterator`.
"""
__slots__: typing.Sequence[str] = ()
@@ -92,7 +92,7 @@ def close(self) -> None:
If called on an already closed streamer then this will do nothing.
- !!! note
+ .. note::
`with streamer` may be used as a short-cut for opening and
closing a streamer.
"""
@@ -103,7 +103,7 @@ def open(self) -> None:
If called on an already started streamer then this will do nothing.
- !!! note
+ .. note::
`with streamer` may be used as a short-cut for opening and
closing a stream.
"""
@@ -119,17 +119,17 @@ def filter(
Each condition is treated as a predicate, being called with each item
that this iterator would return when it is requested.
- All conditions must evaluate to `builtins.True` for the item to be
+ All conditions must evaluate to `True` for the item to be
returned. If this is not met, then the item is discarded and ignored,
the next matching item will be returned instead, if there is one.
Parameters
----------
- *predicates : typing.Union[typing.Callable[[ValueT], builtins.bool], typing.Tuple[builtins.str, typing.Any]]
+ *predicates : typing.Union[typing.Callable[[ValueT], bool], typing.Tuple[str, typing.Any]]
Predicates to invoke. These are functions that take a value and
- return `builtins.True` if it is of interest, or `builtins.False`
- otherwise. These may instead include 2-`builtins.tuple` objects
- consisting of a `builtins.str` attribute name (nested attributes
+ return `True` if it is of interest, or `False`
+ otherwise. These may instead include 2-`tuple` objects
+ consisting of a `str` attribute name (nested attributes
are referred to using the `.` operator), and values to compare for
equality. This allows you to specify conditions such as
`members.filter(("user.bot", True))`.
@@ -184,7 +184,7 @@ def consume_raw_event(
Raises
------
- builtins.LookupError
+ LookupError
If there is no consumer for the event.
"""
@@ -197,62 +197,62 @@ def dispatch(self, event: base_events.Event) -> asyncio.Future[typing.Any]:
event : hikari.events.base_events.Event
The event to dispatch.
- Example
- -------
+ Examples
+ --------
We can dispatch custom events by first defining a class that
derives from `hikari.events.base_events.Event`.
- ```py
- import attr
+ .. code-block:: python
- from hikari.traits import RESTAware
- from hikari.events.base_events import Event
- from hikari.users import User
- from hikari.snowflakes import Snowflake
+ import attr
- @attr.define()
- class EveryoneMentionedEvent(Event):
- app: RESTAware = attr.field()
+ from hikari.traits import RESTAware
+ from hikari.events.base_events import Event
+ from hikari.users import User
+ from hikari.snowflakes import Snowflake
- author: User = attr.field()
- '''The user who mentioned everyone.'''
+ @attr.define()
+ class EveryoneMentionedEvent(Event):
+ app: RESTAware = attr.field()
- content: str = attr.field()
- '''The message that was sent.'''
+ author: User = attr.field()
+ '''The user who mentioned everyone.'''
- message_id: Snowflake = attr.field()
- '''The message ID.'''
+ content: str = attr.field()
+ '''The message that was sent.'''
- channel_id: Snowflake = attr.field()
- '''The channel ID.'''
- ```
+ message_id: Snowflake = attr.field()
+ '''The message ID.'''
+
+ channel_id: Snowflake = attr.field()
+ '''The channel ID.'''
We can then dispatch our event as we see fit.
- ```py
- from hikari.events.messages import MessageCreateEvent
+ .. code-block:: python
+
+ from hikari.events.messages import MessageCreateEvent
- @bot.listen(MessageCreateEvent)
- async def on_message(event):
- if "@everyone" in event.content or "@here" in event.content:
- event = EveryoneMentionedEvent(
- author=event.author,
- content=event.content,
- message_id=event.id,
- channel_id=event.channel_id,
- )
+ @bot.listen(MessageCreateEvent)
+ async def on_message(event):
+ if "@everyone" in event.content or "@here" in event.content:
+ event = EveryoneMentionedEvent(
+ author=event.author,
+ content=event.content,
+ message_id=event.id,
+ channel_id=event.channel_id,
+ )
- bot.dispatch(event)
- ```
+ bot.dispatch(event)
This event can be listened to elsewhere by subscribing to it with
`EventManager.subscribe`.
- ```py
- @bot.listen(EveryoneMentionedEvent)
- async def on_everyone_mentioned(event):
- print(event.user, "just pinged everyone in", event.channel_id)
- ```
+ .. code-block:: python
+
+ @bot.listen(EveryoneMentionedEvent)
+ async def on_everyone_mentioned(event):
+ print(event.user, "just pinged everyone in", event.channel_id)
Returns
-------
@@ -264,11 +264,11 @@ async def on_everyone_mentioned(event):
See Also
--------
- Listen: `hikari.api.event_manager.EventManager.listen`
- Stream: `hikari.api.event_manager.EventManager.stream`
- Subscribe: `hikari.api.event_manager.EventManager.subscribe`
- Unsubscribe: `hikari.api.event_manager.EventManager.unsubscribe`
- Wait_for: `hikari.api.event_manager.EventManager.wait_for`
+ Listen : `hikari.api.event_manager.EventManager.listen`.
+ Stream : `hikari.api.event_manager.EventManager.stream`.
+ Subscribe : `hikari.api.event_manager.EventManager.subscribe`.
+ Unsubscribe : `hikari.api.event_manager.EventManager.unsubscribe`.
+ Wait_for: `hikari.api.event_manager.EventManager.wait_for`.
"""
# Yes, this is not generic. The reason for this is MyPy complains about
@@ -290,27 +290,27 @@ def subscribe(self, event_type: typing.Type[typing.Any], callback: CallbackT[typ
consume an instance of the given event, or an instance of a valid
subclass if one exists. Any result is discarded.
- Example
- -------
+ Examples
+ --------
The following demonstrates subscribing a callback to message creation
events.
- ```py
- from hikari.events.messages import MessageCreateEvent
+ .. code-block:: python
- async def on_message(event):
- ...
+ from hikari.events.messages import MessageCreateEvent
- bot.subscribe(MessageCreateEvent, on_message)
- ```
+ async def on_message(event):
+ ...
+
+ bot.subscribe(MessageCreateEvent, on_message)
See Also
--------
- Dispatch: `hikari.api.event_manager.EventManager.dispatch`
- Listen: `hikari.api.event_manager.EventManager.listen`
- Stream: `hikari.api.event_manager.EventManager.stream`
- Unsubscribe: `hikari.api.event_manager.EventManager.unsubscribe`
- Wait_for: `hikari.api.event_manager.EventManager.wait_for`
+ Dispatch : `hikari.api.event_manager.EventManager.dispatch`.
+ Listen : `hikari.api.event_manager.EventManager.listen`.
+ Stream : `hikari.api.event_manager.EventManager.stream`.
+ Unsubscribe : `hikari.api.event_manager.EventManager.unsubscribe`.
+ Wait_for : `hikari.api.event_manager.EventManager.wait_for`.
"""
# Yes, this is not generic. The reason for this is MyPy complains about
@@ -330,27 +330,27 @@ def unsubscribe(self, event_type: typing.Type[typing.Any], callback: CallbackT[t
callback
The callback to unsubscribe.
- Example
- -------
+ Examples
+ --------
The following demonstrates unsubscribing a callback from a message
creation event.
- ```py
- from hikari.events.messages import MessageCreateEvent
+ .. code-block:: python
- async def on_message(event):
- ...
+ from hikari.events.messages import MessageCreateEvent
+
+ async def on_message(event):
+ ...
- bot.unsubscribe(MessageCreateEvent, on_message)
- ```
+ bot.unsubscribe(MessageCreateEvent, on_message)
See Also
--------
- Dispatch: `hikari.api.event_manager.EventManager.dispatch`
- Listen: `hikari.api.event_manager.EventManager.listen`
- Stream: `hikari.api.event_manager.EventManager.stream`
- Subscribe: `hikari.api.event_manager.EventManager.subscribe`
- Wait_for: `hikari.api.event_manager.EventManager.wait_for`
+ Dispatch : `hikari.api.event_manager.EventManager.dispatch`.
+ Listen : `hikari.api.event_manager.EventManager.listen`.
+ Stream : `hikari.api.event_manager.EventManager.stream`.
+ Subscribe : `hikari.api.event_manager.EventManager.subscribe`.
+ Wait_for : `hikari.api.event_manager.EventManager.wait_for`.
"""
@abc.abstractmethod
@@ -368,23 +368,17 @@ def get_listeners(
event_type : typing.Type[T]
The event type to look for.
`T` must be a subclass of `hikari.events.base_events.Event`.
- polymorphic : builtins.bool
- If `builtins.True`, this will also return the listeners for all the
- event types `event_type` will dispatch. If `builtins.False`, then
+ polymorphic : bool
+ If `True`, this will also return the listeners for all the
+ event types `event_type` will dispatch. If `False`, then
only listeners for this class specifically are returned. The
- default is `builtins.True`.
+ default is `True`.
Returns
-------
- typing.Collection[typing.Callable[[T], typing.Coroutine[typing.Any, typing.Any, builtins.None]]]
+ typing.Collection[typing.Callable[[T], typing.Coroutine[typing.Any, typing.Any, None]]]
A copy of the collection of listeners for the event. Will return
an empty collection if nothing is registered.
-
- `T` must be a subclass of `hikari.events.base_events.Event`.
-
- See Also
- --------
- Has listener: `hikari.api.event_manager.EventManager.has_listener`
"""
@abc.abstractmethod
@@ -402,7 +396,6 @@ def listen(
The event types to subscribe to. The implementation may allow this
to be undefined. If this is the case, the event type will be inferred
instead from the type hints on the function signature.
-
`T` must be a subclass of `hikari.events.base_events.Event`.
Returns
@@ -414,11 +407,11 @@ def listen(
See Also
--------
- Dispatch: `hikari.api.event_manager.EventManager.dispatch`
- Stream: `hikari.api.event_manager.EventManager.stream`
- Subscribe: `hikari.api.event_manager.EventManager.subscribe`
- Unsubscribe: `hikari.api.event_manager.EventManager.unsubscribe`
- Wait_for: `hikari.api.event_manager.EventManager.wait_for`
+ Dispatch : `hikari.api.event_manager.EventManager.dispatch`.
+ Stream : `hikari.api.event_manager.EventManager.stream`.
+ Subscribe : `hikari.api.event_manager.EventManager.subscribe`.
+ Unsubscribe : `hikari.api.event_manager.EventManager.unsubscribe`.
+ Wait_for : `hikari.api.event_manager.EventManager.wait_for`.
"""
@abc.abstractmethod
@@ -431,18 +424,23 @@ def stream(
) -> EventStream[base_events.EventT]:
"""Return a stream iterator for the given event and sub-events.
+ .. warning::
+ If you use `await stream.open()` to start the stream then you must
+ also close it with `await stream.close()` otherwise it may queue
+ events in memory indefinitely.
+
Parameters
----------
event_type : typing.Type[hikari.events.base_events.Event]
The event type to listen for. This will listen for subclasses of
this type additionally.
- timeout : typing.Optional[builtins.int, builtins.float]
+ timeout : typing.Optional[int, float]
How long this streamer should wait for the next event before
- ending the iteration. If `builtins.None` then this will continue
+ ending the iteration. If `None` then this will continue
until explicitly broken from.
- limit : typing.Optional[builtins.int]
+ limit : typing.Optional[int]
The limit for how many events this should queue at one time before
- dropping extra incoming events, leave this as `builtins.None` for
+ dropping extra incoming events, leave this as `None` for
the cache size to be unlimited.
Returns
@@ -452,39 +450,33 @@ def stream(
with `with stream:` or `stream.open()` before
asynchronously iterating over it.
- !!! warning
- If you use `stream.open()` to start the stream then you must
- also close it with `stream.close()` otherwise it may queue
- events in memory indefinitely.
-
Examples
--------
+ .. code-block:: python
- ```py
- with bot.stream(events.ReactionAddEvent, timeout=30).filter(("message_id", message.id)) as stream:
- async for user_id in stream.map("user_id").limit(50):
- ...
- ```
+ with bot.stream(events.ReactionAddEvent, timeout=30).filter(("message_id", message.id)) as stream:
+ async for user_id in stream.map("user_id").limit(50):
+ ...
or using `open()` and `close()`
- ```py
- stream = bot.stream(events.ReactionAddEvent, timeout=30).filter(("message_id", message.id))
- stream.open()
+ .. code-block:: python
- async for user_id in stream.map("user_id").limit(50)
- ...
+ stream = bot.stream(events.ReactionAddEvent, timeout=30).filter(("message_id", message.id))
+ stream.open()
- stream.close()
- ```
+ async for user_id in stream.map("user_id").limit(50)
+ ...
+
+ stream.close()
See Also
--------
- Dispatch: `hikari.api.event_manager.EventManager.dispatch`
- Listen: `hikari.api.event_manager.EventManager.listen`
- Subscribe: `hikari.api.event_manager.EventManager.subscribe`
- Unsubscribe: `hikari.api.event_manager.EventManager.unsubscribe`
- Wait_for: `hikari.api.event_manager.EventManager.wait_for`
+ Dispatch : `hikari.api.event_manager.EventManager.dispatch`.
+ Listen : `hikari.api.event_manager.EventManager.listen`.
+ Subscribe : `hikari.api.event_manager.EventManager.subscribe`.
+ Unsubscribe : `hikari.api.event_manager.EventManager.unsubscribe`.
+ Wait_for : `hikari.api.event_manager.EventManager.wait_for`.
"""
@abc.abstractmethod
@@ -497,6 +489,9 @@ async def wait_for(
) -> base_events.EventT:
"""Wait for a given event to occur once, then return the event.
+ .. warning::
+ Async predicates are not supported.
+
Parameters
----------
event_type : typing.Type[hikari.events.base_events.Event]
@@ -504,17 +499,14 @@ async def wait_for(
this type additionally.
predicate
A function taking the event as the single parameter.
- This should return `builtins.True` if the event is one you want to
- return, or `builtins.False` if the event should not be returned.
+ This should return `True` if the event is one you want to
+ return, or `False` if the event should not be returned.
If left as `None` (the default), then the first matching event type
that the bot receives (or any subtype) will be the one returned.
-
- !!! warning
- Async predicates are not supported.
- timeout : typing.Union[builtins.float, builtins.int, builtins.None]
+ timeout : typing.Union[float, int, None]
The amount of time to wait before raising an `asyncio.TimeoutError`
and giving up instead. This is measured in seconds. If
- `builtins.None`, then no timeout will be waited for (no timeout can
+ `None`, then no timeout will be waited for (no timeout can
result in "leaking" of coroutines that never complete if called in
an uncontrolled way, so is not recommended).
@@ -526,14 +518,14 @@ async def wait_for(
Raises
------
asyncio.TimeoutError
- If the timeout is not `builtins.None` and is reached before an
- event is received that the predicate returns `builtins.True` for.
+ If the timeout is not `None` and is reached before an
+ event is received that the predicate returns `True` for.
See Also
--------
- Dispatch: `hikari.api.event_manager.EventManager.dispatch`
- Listen: `hikari.api.event_manager.EventManager.listen`
- Stream: `hikari.api.event_manager.EventManager.stream`
- Subscribe: `hikari.api.event_manager.EventManager.subscribe`
- Unsubscribe: `hikari.api.event_manager.EventManager.unsubscribe`
+ Dispatch : `hikari.api.event_manager.EventManager.dispatch`.
+ Listen : `hikari.api.event_manager.EventManager.listen`.
+ Stream : `hikari.api.event_manager.EventManager.stream`.
+ Subscribe : `hikari.api.event_manager.EventManager.subscribe`.
+ Unsubscribe : `hikari.api.event_manager.EventManager.unsubscribe`.
"""
diff --git a/hikari/api/interaction_server.py b/hikari/api/interaction_server.py
index 7e122e4701..4bf328e420 100644
--- a/hikari/api/interaction_server.py
+++ b/hikari/api/interaction_server.py
@@ -57,7 +57,7 @@
subclass for the provided interaction type which will instruct the server on how
to respond.
-!!! note
+.. note::
For the standard implementations of
`hikari.api.special_endpoints.InteractionResponseBuilder` see
`hikari.impl.special_endpoints`.
@@ -95,31 +95,20 @@ def headers(self) -> typing.Optional[typing.MutableMapping[str, str]]:
@property
def payload(self) -> typing.Optional[bytes]:
- """Payload to provide in the response.
-
- Returns
- -------
- typing.Optional[builtins.bytes]
- The bytes payload to respond with if applicable else `builtins.None`.
- """
+ """Payload to provide in the response."""
raise NotImplementedError
@property
def status_code(self) -> int:
"""Status code that should be used to respond.
- Returns
- -------
- builtins.int
- The response code to use for the response. This should be a valid
- HTTP status code, for more information see
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Status.
+ For more information see .
"""
raise NotImplementedError
class InteractionServer(abc.ABC):
- """Interface for an implementation of a Interactions compatible REST server."""
+ """Interface for an implementation of an interactions compatible REST server."""
__slots__: typing.Sequence[str] = ()
@@ -129,11 +118,11 @@ async def on_interaction(self, body: bytes, signature: bytes, timestamp: bytes)
Parameters
----------
- body : builtins.bytes
+ body : bytes
The interaction payload.
- signature : builtins.bytes
+ signature : bytes
Value of the `"X-Signature-Ed25519"` header used to verify the body.
- timestamp : builtins.bytes
+ timestamp : bytes
Value of the `"X-Signature-Timestamp"` header used to verify the body.
Returns
@@ -195,7 +184,7 @@ def get_listener(
-------
typing.Optional[ListenersT[hikari.interactions.base_interactions.PartialInteraction, hikari.api.special_endpoints.InteractionResponseBuilder]
The callback registered for the provided interaction type if found,
- else `builtins.None`.
+ else `None`.
""" # noqa: E501 - Line too long
@typing.overload
@@ -266,18 +255,18 @@ def set_listener(
interaction_type : typing.Type[hikari.interactions.base_interactions.PartialInteraction]
The type of interaction this listener should be registered for.
listener : typing.Optional[ListenerT[hikari.interactions.base_interactions.PartialInteraction, hikari.api.special_endpoints.InteractionResponseBuilder]]
- The asynchronous listener callback to set or `builtins.None` to
+ The asynchronous listener callback to set or `None` to
unset the previous listener.
Other Parameters
----------------
- replace : builtins.bool
+ replace : bool
Whether this call should replace the previously set listener or not.
- This call will raise a `builtins.ValueError` if set to `builtins.False`
+ This call will raise a `ValueError` if set to `False`
when a listener is already set.
Raises
------
- builtins.TypeError
- If `replace` is `builtins.False` when a listener is already set.
+ TypeError
+ If `replace` is `False` when a listener is already set.
""" # noqa: E501 - Line too long
diff --git a/hikari/api/rest.py b/hikari/api/rest.py
index fa45fb8c5a..6c19e6e9c9 100644
--- a/hikari/api/rest.py
+++ b/hikari/api/rest.py
@@ -69,21 +69,20 @@ class TokenStrategy(abc.ABC):
@property
@abc.abstractmethod
def token_type(self) -> typing.Union[applications.TokenType, str]:
- """Type of token this strategy returns.
-
- Returns
- -------
- typing.Union[hikari.applications.TokenType, builtins.str]
- The type of token this strategy returns.
- """
+ """Type of token this strategy returns."""
@abc.abstractmethod
async def acquire(self, client: RESTClient) -> str:
"""Acquire an authorization token (including the prefix).
+ Parameters
+ ----------
+ client : hikari.api.rest.RESTClient
+ The rest client to use to acquire the token.
+
Returns
-------
- builtins.str
+ str
The current authorization token to use for this client and it's
prefix.
"""
@@ -92,14 +91,14 @@ async def acquire(self, client: RESTClient) -> str:
def invalidate(self, token: typing.Optional[str]) -> None:
"""Invalidate the cached token in this handler.
- !!! note
+ .. note::
`token` may be provided in-order to avoid newly generated tokens
from being invalidated due to multiple calls being made by separate
subroutines which are handling the same token.
Parameters
----------
- token : typing.Optional[builtins.str]
+ token : typing.Optional[str]
The token to specifically invalidate. If provided then this will only
invalidate the cached token if it matches this, otherwise it'll be
invalidated regardless.
@@ -126,13 +125,8 @@ def entity_factory(self) -> entity_factory_.EntityFactory:
def token_type(self) -> typing.Union[str, applications.TokenType, None]:
"""Type of token this client is using for most requests.
- Returns
- -------
- typing.Union[builtins.str, hikari.applications.TokenType, builtins.None]
- The type of token this client is using for most requests.
-
- If this is `builtins.None` then this client will likely only work
- for some endpoints such as public and webhook ones.
+ If this is `None` then this client will likely only work
+ for some endpoints such as public and webhook ones.
"""
@abc.abstractmethod
@@ -171,7 +165,7 @@ async def fetch_channel(
`hikari.channels.TextableChannel` can be used to determine
if the channel provides textual functionality to the application.
- You can check for these using the `builtins.isinstance`
+ You can check for these using the `isinstance`
builtin function.
Raises
@@ -235,25 +229,25 @@ async def edit_channel(
Other Parameters
----------------
- name : hikari.undefined.UndefinedOr[[builtins.str]
+ name : hikari.undefined.UndefinedOr[str]
If provided, the new name for the channel.
- position : hikari.undefined.UndefinedOr[[builtins.int]
+ position : hikari.undefined.UndefinedOr[int]
If provided, the new position for the channel.
- topic : hikari.undefined.UndefinedOr[builtins.str]
+ topic : hikari.undefined.UndefinedOr[str]
If provided, the new topic for the channel.
- nsfw : hikari.undefined.UndefinedOr[builtins.bool]
+ nsfw : hikari.undefined.UndefinedOr[bool]
If provided, whether the channel should be marked as NSFW or not.
- bitrate : hikari.undefined.UndefinedOr[builtins.int]
+ bitrate : hikari.undefined.UndefinedOr[int]
If provided, the new bitrate for the channel.
- video_quality_mode: hikari.undefined.UndefinedOr[typing.Union[hikari.channels.VideoQualityMode, builtins.int]]
+ video_quality_mode : hikari.undefined.UndefinedOr[typing.Union[hikari.channels.VideoQualityMode, int]]
If provided, the new video quality mode for the channel.
- user_limit : hikari.undefined.UndefinedOr[builtins.int]
+ user_limit : hikari.undefined.UndefinedOr[int]
If provided, the new user limit in the channel.
rate_limit_per_user : hikari.undefined.UndefinedOr[hikari.internal.time.Intervalish]
If provided, the new rate limit per user in the channel.
- region : hikari.undefined.UndefinedOr[typing.Union[builtins.str, hikari.voices.VoiceRegion]]
+ region : hikari.undefined.UndefinedOr[typing.Union[str, hikari.voices.VoiceRegion]]
If provided, the voice region to set for this channel. Passing
- `builtins.None` here will set it to "auto" mode where the used
+ `None` here will set it to "auto" mode where the used
region will be decided based on the first person who connects to it
when it's empty.
permission_overwrites : hikari.undefined.UndefinedOr[typing.Sequence[hikari.channels.PermissionOverwrite]]
@@ -267,13 +261,13 @@ async def edit_channel(
This should be either 60, 1440, 4320 or 10080 seconds and, as of
writing, ignores the parent channel's set default_auto_archive_duration
when passed as `hikari.undefined.UNDEFINED`.
- archived : hikari.undefined.UndefinedOr[builtins.bool]
+ archived : hikari.undefined.UndefinedOr[bool]
If provided, whether to archive or unarchive this thread channel.
- locked : hikari.undefined.UndefinedOr[builtins.bool]
+ locked : hikari.undefined.UndefinedOr[bool]
If provided, whether to lock or unlock this thread channel.
If it's locked then only people with `MANAGE_THREADS` can unarchive it.
- invitable : undefined.UndefinedOr[builtins.bool]
+ invitable : undefined.UndefinedOr[bool]
If provided, whether non-moderators should be able to add other non-moderators to the thread.
This only applies to private threads.
@@ -283,7 +277,7 @@ async def edit_channel(
This should be either 60, 1440, 4320 or 10080 seconds and, as of
writing, ignores the parent channel's set default_auto_archive_duration
when passed as `hikari.undefined.UNDEFINED`.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -372,6 +366,10 @@ async def delete_channel(
) -> channels_.PartialChannel:
"""Delete a channel in a guild, or close a DM.
+ .. note::
+ For Public servers, the set 'Rules' or 'Guidelines' channels and the
+ 'Public Server Updates' channel cannot be deleted.
+
Parameters
----------
channel : hikari.snowflakes.SnowflakeishOr[hikari.channels.PartialChannel]
@@ -404,10 +402,6 @@ async def delete_channel(
nature, and will trigger this exception if they occur.
hikari.errors.InternalServerError
If an internal error occurs on Discord while handling the request.
-
- !!! note
- For Public servers, the set 'Rules' or 'Guidelines' channels and the
- 'Public Server Updates' channel cannot be deleted.
"""
@abc.abstractmethod
@@ -421,7 +415,7 @@ async def edit_my_voice_state(
) -> None:
"""Edit the current user's voice state in a stage channel.
- !!! note
+ .. note::
The current user has to have already joined the target stage channel
before any calls can be made to this endpoint.
@@ -434,21 +428,18 @@ async def edit_my_voice_state(
Other Parameters
----------------
- suppress : hikari.undefined.UndefinedOr[builtins.bool]
+ suppress : hikari.undefined.UndefinedOr[bool]
If specified, whether the user should be allowed to become a speaker
in the target stage channel with `builtin.True` suppressing them from
becoming one.
- request_to_speak : typing.Union[hikari.undefined.UndefinedType, builtins.bool, datetime.datetime]
+ request_to_speak : typing.Union[hikari.undefined.UndefinedType, bool, datetime.datetime]
Whether to request to speak. This may be one of the following:
* `True` to indicate that the bot wants to speak.
* `False` to remove any previously set request to speak.
* `datetime.datetime` to specify when they want their request to
- speak timestamp to be set to.
-
- !!! note
- If a datetime from the past is passed then Discord will use the
- current time instead.
+ speak timestamp to be set to. If a datetime from the past is
+ passed then Discord will use the current time instead.
Raises
------
@@ -486,6 +477,10 @@ async def edit_voice_state(
) -> None:
"""Edit an existing voice state in a stage channel.
+ .. note::
+ The target user must already be present in the stage channel before
+ any calls are made to this endpoint.
+
Parameters
----------
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
@@ -497,14 +492,10 @@ async def edit_voice_state(
Other Parameters
----------------
- suppress : hikari.undefined.UndefinedOr[builtins.bool]
+ suppress : hikari.undefined.UndefinedOr[bool]
If defined, whether the user should be allowed to become a speaker
in the target stage channel.
- !!! note
- The target user must already be present in the stage channel before
- any calls are made to this endpoint.
-
Raises
------
hikari.errors.BadRequestError
@@ -590,13 +581,13 @@ async def edit_permission_overwrite(
If provided, the new value of all allowed permissions.
deny : hikari.undefined.UndefinedOr[hikari.permissions.Permissions]
If provided, the new value of all disallowed permissions.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
Raises
------
- builtins.TypeError
+ TypeError
If `target_type` is unset and we were unable to determine the type
from `target`.
hikari.errors.BadRequestError
@@ -730,13 +721,13 @@ async def create_invite(
Other Parameters
----------------
- max_age : hikari.undefined.UndefinedOr[typing.Union[datetime.timedelta, builtins.float, builtins.int]]
+ max_age : hikari.undefined.UndefinedOr[typing.Union[datetime.timedelta, float, int]]
If provided, the duration of the invite before expiry.
- max_uses : hikari.undefined.UndefinedOr[builtins.int]
+ max_uses : hikari.undefined.UndefinedOr[int]
If provided, the max uses the invite can have.
- temporary : hikari.undefined.UndefinedOr[builtins.bool]
+ temporary : hikari.undefined.UndefinedOr[bool]
If provided, whether the invite only grants temporary membership.
- unique : hikari.undefined.UndefinedOr[builtins.bool]
+ unique : hikari.undefined.UndefinedOr[bool]
If provided, whether the invite should be unique.
target_type : hikari.undefined.UndefinedOr[hikari.invites.TargetType]
If provided, the target type of this invite.
@@ -744,17 +735,17 @@ async def create_invite(
If provided, the target user id for this invite. This may be the
object or the ID of an existing user.
- !!! note
+ .. note::
This is required if `target_type` is `STREAM` and the targeted
user must be streaming into the channel.
target_application : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]]
If provided, the target application id for this invite. This may be
the object or the ID of an existing application.
- !!! note
+ .. note::
This is required if `target_type` is `EMBEDDED_APPLICATION` and
the targeted application must have the `EMBEDDED` flag.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -795,22 +786,23 @@ def trigger_typing(
) -> special_endpoints.TypingIndicator:
"""Trigger typing in a text channel.
- The result of this call can be awaited to trigger typing once, or
- can be used as an async context manager to continually type until the
- context manager is left.
+ .. note::
+ The result of this call can be awaited to trigger typing once, or
+ can be used as an async context manager to continually type until the
+ context manager is left. Any errors documented below will happen then.
Examples
--------
- ```py
- # Trigger typing just once.
- await rest.trigger_typing(channel)
+ .. code-block:: python
+
+ # Trigger typing just once.
+ await rest.trigger_typing(channel)
- # Trigger typing repeatedly for 1 minute.
- async with rest.trigger_typing(channel):
- await asyncio.sleep(60)
- ```
+ # Trigger typing repeatedly for 1 minute.
+ async with rest.trigger_typing(channel):
+ await asyncio.sleep(60)
- !!! warning
+ .. warning::
Sending a message to the channel will cause the typing indicator
to disappear until it is re-triggered.
@@ -846,11 +838,6 @@ def trigger_typing(
nature, and will trigger this exception if they occur.
hikari.errors.InternalServerError
If an internal error occurs on Discord while handling the request.
-
- !!! note
- The exceptions on this endpoint will only be raised once the result
- is awaited or iterated over. Invoking this function itself will
- not raise any of the above types.
"""
@abc.abstractmethod
@@ -986,6 +973,13 @@ def fetch_messages(
) -> iterators.LazyIterator[messages_.Message]:
"""Browse the message history for a given text channel.
+ .. note::
+ This call is not a coroutine function, it returns a special type of
+ lazy iterator that will perform API calls as you iterate across it,
+ thus any errors documented below will happen then.
+
+ See `hikari.iterators` for the full API for this iterator type.
+
Parameters
----------
channel : hikari.snowflakes.SnowflakeishOr[hikari.channels.TextableChannel]
@@ -1015,14 +1009,9 @@ def fetch_messages(
hikari.iterators.LazyIterator[hikari.messages.Message]
An iterator to fetch the messages.
- !!! note
- This call is not a coroutine function, it returns a special type of
- lazy iterator that will perform API calls as you iterate across it.
- See `hikari.iterators` for the full API for this iterator type.
-
Raises
------
- builtins.TypeError
+ TypeError
If you specify more than one of `before`, `after`, `about`.
hikari.errors.UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
@@ -1043,12 +1032,6 @@ def fetch_messages(
nature, and will trigger this exception if they occur.
hikari.errors.InternalServerError
If an internal error occurs on Discord while handling the request.
-
- !!! note
- The exceptions on this endpoint (other than `builtins.TypeError`) will only
- be raised once the result is awaited or iterated over. Invoking
- this function itself will not raise anything (other than
- `builtins.TypeError`).
"""
@abc.abstractmethod
@@ -1131,7 +1114,7 @@ async def create_message(
If provided, the message contents. If
`hikari.undefined.UNDEFINED`, then nothing will be sent
in the content. Any other value here will be cast to a
- `builtins.str`.
+ `str`.
If this is a `hikari.embeds.Embed` and no `embed` nor `embeds` kwarg
is provided, then this will instead update the embed. This allows
@@ -1146,6 +1129,32 @@ async def create_message(
attachment : hikari.undefined.UndefinedOr[hikari.files.Resourceish]
If provided, the message attachment. This can be a resource,
or string of a path on your computer or a URL.
+
+ Attachments can be passed as many different things, to aid in
+ convenience.
+
+ - If a `pathlib.PurePath` or `str` to a valid URL, the
+ resource at the given URL will be streamed to Discord when
+ sending the message. Subclasses of
+ `hikari.files.WebResource` such as
+ `hikari.files.URL`,
+ `hikari.messages.Attachment`,
+ `hikari.emojis.Emoji`,
+ `EmbedResource`, etc will also be uploaded this way.
+ This will use bit-inception, so only a small percentage of the
+ resource will remain in memory at any one time, thus aiding in
+ scalability.
+ - If a `hikari.files.Bytes` is passed, or a `str`
+ that contains a valid data URI is passed, then this is uploaded
+ with a randomized file name if not provided.
+ - If a `hikari.files.File`, `pathlib.PurePath` or
+ `str` that is an absolute or relative path to a file
+ on your file system is passed, then this resource is uploaded
+ as an attachment using non-blocking code internally and streamed
+ using bit-inception where possible. This depends on the
+ type of `concurrent.futures.Executor` that is being used for
+ the application (default is a thread pool which supports this
+ behaviour).
attachments : hikari.undefined.UndefinedOr[typing.Sequence[hikari.files.Resourceish]]
If provided, the message attachments. These can be resources, or
strings consisting of paths on your computer or URLs.
@@ -1158,30 +1167,30 @@ async def create_message(
If provided, the message embed.
embeds : hikari.undefined.UndefinedOr[typing.Sequence[hikari.embeds.Embed]]
If provided, the message embeds.
- tts : hikari.undefined.UndefinedOr[builtins.bool]
+ tts : hikari.undefined.UndefinedOr[bool]
If provided, whether the message will be read out by a screen
reader using Discord's TTS (text-to-speech) system.
reply : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage]]
If provided, the message to reply to.
- mentions_everyone : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_everyone : hikari.undefined.UndefinedOr[bool]
If provided, whether the message should parse @everyone/@here
mentions.
- mentions_reply : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_reply : hikari.undefined.UndefinedOr[bool]
If provided, whether to mention the author of the message
that is being replied to.
This will not do anything if not being used with `reply`.
- user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
- If provided, and `builtins.True`, all user mentions will be detected.
- If provided, and `builtins.False`, all user mentions will be ignored
+ user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], bool]]
+ If provided, and `True`, all user mentions will be detected.
+ If provided, and `False`, all user mentions will be ignored
if appearing in the message body.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.users.PartialUser` derivatives to enforce mentioning
specific users.
- role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], builtins.bool]]
- If provided, and `builtins.True`, all role mentions will be detected.
- If provided, and `builtins.False`, all role mentions will be ignored
+ role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], bool]]
+ If provided, and `True`, all role mentions will be detected.
+ If provided, and `False`, all role mentions will be ignored
if appearing in the message body.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
@@ -1194,33 +1203,6 @@ async def create_message(
Note that some flags may not be able to be set. Currently the only
flags that can be set are `NONE` and `SUPPRESS_EMBEDS`.
- !!! note
- Attachments can be passed as many different things, to aid in
- convenience.
-
- - If a `pathlib.PurePath` or `builtins.str` to a valid URL, the
- resource at the given URL will be streamed to Discord when
- sending the message. Subclasses of
- `hikari.files.WebResource` such as
- `hikari.files.URL`,
- `hikari.messages.Attachment`,
- `hikari.emojis.Emoji`,
- `EmbedResource`, etc will also be uploaded this way.
- This will use bit-inception, so only a small percentage of the
- resource will remain in memory at any one time, thus aiding in
- scalability.
- - If a `hikari.files.Bytes` is passed, or a `builtins.str`
- that contains a valid data URI is passed, then this is uploaded
- with a randomized file name if not provided.
- - If a `hikari.files.File`, `pathlib.PurePath` or
- `builtins.str` that is an absolute or relative path to a file
- on your file system is passed, then this resource is uploaded
- as an attachment using non-blocking code internally and streamed
- using bit-inception where possible. This depends on the
- type of `concurrent.futures.Executor` that is being used for
- the application (default is a thread pool which supports this
- behaviour).
-
Returns
-------
hikari.messages.Message
@@ -1228,7 +1210,7 @@ async def create_message(
Raises
------
- builtins.ValueError
+ ValueError
If more than 100 unique objects/entities are passed for
`role_mentions` or `user_mentions` or if both `attachment` and
`attachments`, `component` and `components` or `embed` and `embeds`
@@ -1341,6 +1323,25 @@ async def edit_message(
) -> messages_.Message:
"""Edit an existing message in a given channel.
+ .. warning::
+ If the message was not sent by your user, the only parameter
+ you may provide to this call is the `flags` parameter. Anything
+ else will result in a `hikari.errors.ForbiddenError` being raised.
+
+ .. note::
+ Mentioning everyone, roles, or users in message edits currently
+ will not send a push notification showing a new mention to people
+ on Discord. It will still highlight in their chat as if they
+ were mentioned, however.
+
+ Also important to note that if you specify a text `content`, `mentions_everyone`,
+ `mentions_reply`, `user_mentions`, and `role_mentions` will default
+ to `False` as the message will be re-parsed for mentions. This will
+ also occur if only one of the four are specified
+
+ This is a limitation of Discord's design. If in doubt, specify all
+ four of them each time.
+
Parameters
----------
channel : hikari.snowflakes.SnowflakeishOr[hikari.channels.TextableChannel]
@@ -1352,9 +1353,9 @@ async def edit_message(
content : hikari.undefined.UndefinedOr[typing.Any]
If provided, the message content to update with. If
`hikari.undefined.UNDEFINED`, then the content will not
- be changed. If `builtins.None`, then the content will be removed.
+ be changed. If `None`, then the content will be removed.
- Any other value will be cast to a `builtins.str` before sending.
+ Any other value will be cast to a `str` before sending.
If this is a `hikari.embeds.Embed` and neither the `embed` or
`embeds` kwargs are provided or if this is a
@@ -1368,62 +1369,62 @@ async def edit_message(
attachment : hikari.undefined.UndefinedNoneOr[typing.Union[hikari.files.Resourceish, hikari.messages.Attachment]]
If provided, the attachment to set on the message. If
`hikari.undefined.UNDEFINED`, the previous attachment, if
- present, is not changed. If this is `builtins.None`, then the
+ present, is not changed. If this is `None`, then the
attachment is removed, if present. Otherwise, the new attachment
that was provided will be attached.
attachments : hikari.undefined.UndefinedNoneOr[typing.Sequence[typing.Union[hikari.files.Resourceish, hikari.messages.Attachment]]]
If provided, the attachments to set on the message. If
`hikari.undefined.UNDEFINED`, the previous attachments, if
- present, are not changed. If this is `builtins.None`, then the
+ present, are not changed. If this is `None`, then the
attachments is removed, if present. Otherwise, the new attachments
that were provided will be attached.
component : hikari.undefined.UndefinedNoneOr[hikari.api.special_endpoints.ComponentBuilder]
If provided, builder object of the component to set for this message.
This component will replace any previously set components and passing
- `builtins.None` will remove all components.
+ `None` will remove all components.
components : hikari.undefined.UndefinedNoneOr[typing.Sequence[hikari.api.special_endpoints.ComponentBuilder]]
If provided, a sequence of the component builder objects set for
this message. These components will replace any previously set
- components and passing `builtins.None` or an empty sequence will
+ components and passing `None` or an empty sequence will
remove all components.
embed : hikari.undefined.UndefinedNoneOr[hikari.embeds.Embed]
If provided, the embed to set on the message. If
`hikari.undefined.UNDEFINED`, the previous embed(s) are not changed.
- If this is `builtins.None` then any present embeds are removed.
+ If this is `None` then any present embeds are removed.
Otherwise, the new embed that was provided will be used as the
replacement.
embeds : hikari.undefined.UndefinedNoneOr[typing.Sequence[hikari.embeds.Embed]]
If provided, the embeds to set on the message. If
`hikari.undefined.UNDEFINED`, the previous embed(s) are not changed.
- If this is `builtins.None` then any present embeds are removed.
+ If this is `None` then any present embeds are removed.
Otherwise, the new embeds that were provided will be used as the
replacement.
- mentions_everyone : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_everyone : hikari.undefined.UndefinedOr[bool]
If provided, sanitation for `@everyone` mentions. If
`hikari.undefined.UNDEFINED`, then the previous setting is
- not changed. If `builtins.True`, then `@everyone`/`@here` mentions
+ not changed. If `True`, then `@everyone`/`@here` mentions
in the message content will show up as mentioning everyone that can
view the chat.
- mentions_reply : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_reply : hikari.undefined.UndefinedOr[bool]
If provided, whether to mention the author of the message
that is being replied to.
This will not do anything if `message` is not a reply message.
- user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
+ user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], bool]]
If provided, sanitation for user mentions. If
`hikari.undefined.UNDEFINED`, then the previous setting is
- not changed. If `builtins.True`, all valid user mentions will behave
- as mentions. If `builtins.False`, all valid user mentions will not
+ not changed. If `True`, all valid user mentions will behave
+ as mentions. If `False`, all valid user mentions will not
behave as mentions.
You may alternatively pass a collection of
`hikari.snowflakes.Snowflake` user IDs, or
`hikari.users.PartialUser`-derived objects.
- role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], builtins.bool]]
+ role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], bool]]
If provided, sanitation for role mentions. If
`hikari.undefined.UNDEFINED`, then the previous setting is
- not changed. If `builtins.True`, all valid role mentions will behave
- as mentions. If `builtins.False`, all valid role mentions will not
+ not changed. If `True`, all valid role mentions will behave
+ as mentions. If `False`, all valid role mentions will not
behave as mentions.
You may alternatively pass a collection of
@@ -1438,33 +1439,6 @@ async def edit_message(
have `MANAGE_MESSAGES` permissions, you can use this call to
suppress embeds on another user's message.
- !!! note
- Mentioning everyone, roles, or users in message edits currently
- will not send a push notification showing a new mention to people
- on Discord. It will still highlight in their chat as if they
- were mentioned, however.
-
- !!! warning
- If you specify a non-embed `content`, `mentions_everyone`,
- `mentions_reply`, `user_mentions`, and `role_mentions` will default
- to `builtins.False` as the message will be re-parsed for mentions.
-
- This is a limitation of Discord's design. If in doubt, specify all
- four of them each time.
-
- !!! warning
- If you specify one of `mentions_everyone`, `mentions_reply`,
- `user_mentions`, or `role_mentions`, then all others will default to
- `builtins.False`, even if they were enabled previously.
-
- This is a limitation of Discord's design. If in doubt, specify all
- four of them each time.
-
- !!! warning
- If the message was not sent by your user, the only parameter
- you may provide to this call is the `flags` parameter. Anything
- else will result in a `hikari.errors.ForbiddenError` being raised.
-
Returns
-------
hikari.messages.Message
@@ -1472,7 +1446,7 @@ async def edit_message(
Raises
------
- builtins.ValueError
+ ValueError
If both `attachment` and `attachments`, `component` and `components`
or `embed` and `embeds` are specified.
hikari.errors.BadRequestError
@@ -1558,21 +1532,7 @@ async def delete_messages(
) -> None:
"""Bulk-delete messages from the channel.
- Parameters
- ----------
- channel : hikari.snowflakes.SnowflakeishOr[hikari.channels.TextableChannel]
- The channel to bulk delete the messages in. This may be
- the object or the ID of an existing channel.
- messages : typing.Union[hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage], hikari.snowflakes.SnowflakeishIterable[hikari.messages.PartialMessage]]
- Either the object/ID of an existing message to delete or an iterable
- of the objects and/or IDs of existing messages to delete.
-
- Other Parameters
- ----------------
- *other_messages : hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage]
- The objects and/or IDs of other existing messages to delete.
-
- !!! note
+ .. note::
This API endpoint will only be able to delete 100 messages
at a time. For anything more than this, multiple requests will
be executed one-after-the-other, since the rate limits for this
@@ -1581,24 +1541,38 @@ async def delete_messages(
If one message is left over from chunking per 100 messages, or
only one message is passed to this coroutine function, then the
logic is expected to defer to `delete_message`. The implication
- of this is that the `delete_message` endpoint is ratelimited
+ of this is that the `delete_message` endpoint is rate limited
by a different bucket with different usage rates.
- !!! warning
+ .. warning::
This endpoint is not atomic. If an error occurs midway through
a bulk delete, you will **not** be able to revert any changes made
up to this point.
- !!! warning
+ .. warning::
Specifying any messages more than 14 days old will cause the call
to fail, potentially with partial completion.
+ Parameters
+ ----------
+ channel : hikari.snowflakes.SnowflakeishOr[hikari.channels.TextableChannel]
+ The channel to bulk delete the messages in. This may be
+ the object or the ID of an existing channel.
+ messages : typing.Union[hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage], hikari.snowflakes.SnowflakeishIterable[hikari.messages.PartialMessage]]
+ Either the object/ID of an existing message to delete or an iterable
+ of the objects and/or IDs of existing messages to delete.
+
+ Other Parameters
+ ----------------
+ *other_messages : hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage]
+ The objects and/or IDs of other existing messages to delete.
+
Raises
------
hikari.errors.BulkDeleteError
An error containing the messages successfully deleted, and the
messages that were not removed. The
- `builtins.BaseException.__cause__` of the exception will be the
+ `BaseException.__cause__` of the exception will be the
original error that terminated this process.
""" # noqa: E501 - Line too long
@@ -1621,7 +1595,7 @@ async def add_reaction(
message : hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage]
The message to add a reaction to. This may be the
object or the ID of an existing message.
- emoji : typing.Union[builtins.str, hikari.emojis.Emoji]
+ emoji : typing.Union[str, hikari.emojis.Emoji]
Object or name of the emoji to react with.
Other Parameters
@@ -1676,7 +1650,7 @@ async def delete_my_reaction(
message : hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage]
The message to delete a reaction from. This may be the
object or the ID of an existing message.
- emoji : typing.Union[builtins.str, hikari.emojis.Emoji]
+ emoji : typing.Union[str, hikari.emojis.Emoji]
Object or name of the emoji to remove your reaction for.
Other Parameters
@@ -1728,7 +1702,7 @@ async def delete_all_reactions_for_emoji(
message : hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage]
The message to delete a reactions from. This may be the
object or the ID of an existing message.
- emoji : typing.Union[builtins.str, hikari.emojis.Emoji]
+ emoji : typing.Union[str, hikari.emojis.Emoji]
Object or name of the emoji to remove all the reactions for.
Other Parameters
@@ -1786,9 +1760,9 @@ async def delete_reaction(
message : hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage]
The message to delete a reaction from. This may be the
object or the ID of an existing message.
- user: hikari.snowflakes.SnowflakeishOr[hikari.users.PartialUser]
+ user : hikari.snowflakes.SnowflakeishOr[hikari.users.PartialUser]
Object or ID of the user to remove the reaction of.
- emoji : typing.Union[builtins.str, hikari.emojis.Emoji]
+ emoji : typing.Union[str, hikari.emojis.Emoji]
Object or name of the emoji to react with.
Other Parameters
@@ -1877,6 +1851,13 @@ def fetch_reactions_for_emoji(
) -> iterators.LazyIterator[users.User]:
"""Fetch reactions for an emoji from a message.
+ .. note::
+ This call is not a coroutine function, it returns a special type of
+ lazy iterator that will perform API calls as you iterate across it,
+ thus any errors documented below will happen then.
+
+ See `hikari.iterators` for the full API for this iterator type.
+
Parameters
----------
channel : hikari.snowflakes.SnowflakeishOr[hikari.channels.TextableChannel]
@@ -1885,7 +1866,7 @@ def fetch_reactions_for_emoji(
message : hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage]
The message to delete all reaction from. This may be the
object or the ID of an existing message.
- emoji : typing.Union[builtins.str, hikari.emojis.Emoji]
+ emoji : typing.Union[str, hikari.emojis.Emoji]
Object or name of the emoji to get the reactions for.
Other Parameters
@@ -1900,11 +1881,6 @@ def fetch_reactions_for_emoji(
hikari.iterators.LazyIterator[hikari.users.User]
An iterator to fetch the users.
- !!! note
- This call is not a coroutine function, it returns a special type of
- lazy iterator that will perform API calls as you iterate across it.
- See `hikari.iterators` for the full API for this iterator type.
-
Raises
------
hikari.errors.BadRequestError
@@ -1927,11 +1903,6 @@ def fetch_reactions_for_emoji(
nature, and will trigger this exception if they occur.
hikari.errors.InternalServerError
If an internal error occurs on Discord while handling the request.
-
- !!! note
- The exceptions on this endpoint will only be raised once the
- result is awaited or iterated over. Invoking this function
- itself will not raise anything.
"""
@abc.abstractmethod
@@ -1957,7 +1928,7 @@ async def create_webhook(
----------------
avatar : typing.Optional[hikari.files.Resourceish]
If provided, the avatar for the webhook.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -2008,7 +1979,7 @@ async def fetch_webhook(
Other Parameters
----------------
- token : hikari.undefined.UndefinedOr[builtins.str]
+ token : hikari.undefined.UndefinedOr[str]
If provided, the webhook token that will be used to fetch
the webhook instead of the token the client was initialized with.
@@ -2145,17 +2116,17 @@ async def edit_webhook(
Other Parameters
----------------
- token : hikari.undefined.UndefinedOr[builtins.str]
+ token : hikari.undefined.UndefinedOr[str]
If provided, the webhook token that will be used to edit
the webhook instead of the token the client was initialized with.
- name : hikari.undefined.UndefinedOr[builtins.str]
+ name : hikari.undefined.UndefinedOr[str]
If provided, the new webhook name.
avatar : hikari.undefined.UndefinedNoneOr[hikari.files.Resourceish]
- If provided, the new webhook avatar. If `builtins.None`, will
+ If provided, the new webhook avatar. If `None`, will
remove the webhook avatar.
channel : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.WebhookChannelT]]
If provided, the text channel to move the webhook to.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -2205,7 +2176,7 @@ async def delete_webhook(
Other Parameters
----------------
- token : hikari.undefined.UndefinedOr[builtins.str]
+ token : hikari.undefined.UndefinedOr[str]
If provided, the webhook token that will be used to delete
the webhook instead of the token the client was initialized with.
@@ -2264,18 +2235,22 @@ async def execute_webhook(
) -> messages_.Message:
"""Execute a webhook.
+ .. warning::
+ As of writing, `username` and `avatar_url` are ignored for
+ interaction webhooks.
+
Parameters
----------
webhook : typing.Union[hikari.snowflakes.Snowflakeish, hikari.webhooks.ExecutableWebhook]
The webhook to execute. This may be the object
or the ID of an existing webhook.
- token: builtins.str
+ token : str
The webhook token.
content : hikari.undefined.UndefinedOr[typing.Any]
If provided, the message contents. If
`hikari.undefined.UNDEFINED`, then nothing will be sent
in the content. Any other value here will be cast to a
- `builtins.str`.
+ `str`.
If this is a `hikari.embeds.Embed` and no `embed` nor
no `embeds` kwarg is provided, then this will instead
@@ -2294,15 +2269,41 @@ async def execute_webhook(
the webhook's target channel.
This is required when trying to create a thread message.
- username : hikari.undefined.UndefinedOr[builtins.str]
+ username : hikari.undefined.UndefinedOr[str]
If provided, the username to override the webhook's username
for this request.
- avatar_url : typing.Union[hikari.undefined.UndefinedType, builtins.str, hikari.files.URL]
+ avatar_url : typing.Union[hikari.undefined.UndefinedType, hikari.files.URL, str]
If provided, the url of an image to override the webhook's
avatar with for this request.
attachment : hikari.undefined.UndefinedOr[hikari.files.Resourceish]
If provided, the message attachment. This can be a resource,
or string of a path on your computer or a URL.
+
+ Attachments can be passed as many different things, to aid in
+ convenience.
+
+ - If a `pathlib.PurePath` or `str` to a valid URL, the
+ resource at the given URL will be streamed to Discord when
+ sending the message. Subclasses of
+ `hikari.files.WebResource` such as
+ `hikari.files.URL`,
+ `hikari.messages.Attachment`,
+ `hikari.emojis.Emoji`,
+ `EmbedResource`, etc will also be uploaded this way.
+ This will use bit-inception, so only a small percentage of the
+ resource will remain in memory at any one time, thus aiding in
+ scalability.
+ - If a `hikari.files.Bytes` is passed, or a `str`
+ that contains a valid data URI is passed, then this is uploaded
+ with a randomized file name if not provided.
+ - If a `hikari.files.File`, `pathlib.PurePath` or
+ `str` that is an absolute or relative path to a file
+ on your file system is passed, then this resource is uploaded
+ as an attachment using non-blocking code internally and streamed
+ using bit-inception where possible. This depends on the
+ type of `concurrent.futures.Executor` that is being used for
+ the application (default is a thread pool which supports this
+ behaviour).
attachments : hikari.undefined.UndefinedOr[typing.Sequence[hikari.files.Resourceish]]
If provided, the message attachments. These can be resources, or
strings consisting of paths on your computer or URLs.
@@ -2315,72 +2316,35 @@ async def execute_webhook(
If provided, the message embed.
embeds : hikari.undefined.UndefinedOr[typing.Sequence[hikari.embeds.Embed]]
If provided, the message embeds.
- tts : hikari.undefined.UndefinedOr[builtins.bool]
+ tts : hikari.undefined.UndefinedOr[bool]
If provided, whether the message will be read out by a screen
reader using Discord's TTS (text-to-speech) system.
- nonce : hikari.undefined.UndefinedOr[builtins.str]
- An arbitrary identifier to associate with the message. This
- can be used to identify it later in received events. If provided,
- this must be less than 32 bytes. If not provided, then
- a null value is placed on the message instead. All users can
- see this value.
- mentions_everyone : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_everyone : hikari.undefined.UndefinedOr[bool]
If provided, whether the message should parse @everyone/@here
mentions.
- user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
- If provided, and `builtins.True`, all user mentions will be detected.
- If provided, and `builtins.False`, all user mentions will be ignored
+ user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], bool]]
+ If provided, and `True`, all user mentions will be detected.
+ If provided, and `False`, all user mentions will be ignored
if appearing in the message body.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.users.PartialUser` derivatives to enforce mentioning
specific users.
- role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], builtins.bool]]
- If provided, and `builtins.True`, all role mentions will be detected.
- If provided, and `builtins.False`, all role mentions will be ignored
+ role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], bool]]
+ If provided, and `True`, all role mentions will be detected.
+ If provided, and `False`, all role mentions will be ignored
if appearing in the message body.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.guilds.PartialRole` derivatives to enforce mentioning
specific roles.
- flags : typing.Union[hikari.undefined.UndefinedType, builtins.int, hikari.messages.MessageFlag]
+ flags : typing.Union[hikari.undefined.UndefinedType, int, hikari.messages.MessageFlag]
The flags to set for this webhook message.
- !!! warning
- As of writing the only flags which can be passed here are
- `EPHEMERAL` (if this is an interaction response webhook) and
- `SUPPRESS_EMBEDS`.
-
- !!! warning
- As of writing, `username` and `avatar_url` are ignored for
- interaction webhooks.
-
- !!! note
- Attachments can be passed as many different things, to aid in
- convenience.
-
- - If a `pathlib.PurePath` or `builtins.str` to a valid URL, the
- resource at the given URL will be streamed to Discord when
- sending the message. Subclasses of
- `hikari.files.WebResource` such as
- `hikari.files.URL`,
- `hikari.messages.Attachment`,
- `hikari.emojis.Emoji`,
- `EmbedResource`, etc will also be uploaded this way.
- This will use bit-inception, so only a small percentage of the
- resource will remain in memory at any one time, thus aiding in
- scalability.
- - If a `hikari.files.Bytes` is passed, or a `builtins.str`
- that contains a valid data URI is passed, then this is uploaded
- with a randomized file name if not provided.
- - If a `hikari.files.File`, `pathlib.PurePath` or
- `builtins.str` that is an absolute or relative path to a file
- on your file system is passed, then this resource is uploaded
- as an attachment using non-blocking code internally and streamed
- using bit-inception where possible. This depends on the
- type of `concurrent.futures.Executor` that is being used for
- the application (default is a thread pool which supports this
- behaviour).
+ .. warning::
+ As of writing this can only be set for interaction webhooks
+ and the only settable flag is `EPHEMERAL`; this field is just
+ ignored for non-interaction webhooks.
Returns
-------
@@ -2389,7 +2353,7 @@ async def execute_webhook(
Raises
------
- builtins.ValueError
+ ValueError
If more than 100 unique objects/entities are passed for
`role_mentions` or `user_mentions` or if both `attachment` and
`attachments` or `embed` and `embeds` are specified.
@@ -2437,7 +2401,7 @@ async def fetch_webhook_message(
webhook : typing.Union[hikari.snowflakes.Snowflakeish, hikari.webhooks.ExecutableWebhook]
The webhook to execute. This may be the object
or the ID of an existing webhook.
- token: builtins.str
+ token : str
The webhook token.
message : hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage]
The message to fetch. This may be the object or the ID of an
@@ -2512,12 +2476,26 @@ async def edit_webhook_message(
) -> messages_.Message:
"""Edit a message sent by a webhook.
+ .. note::
+ Mentioning everyone, roles, or users in message edits currently
+ will not send a push notification showing a new mention to people
+ on Discord. It will still highlight in their chat as if they
+ were mentioned, however.
+
+ Also important to note that if you specify a text `content`, `mentions_everyone`,
+ `mentions_reply`, `user_mentions`, and `role_mentions` will default
+ to `False` as the message will be re-parsed for mentions. This will
+ also occur if only one of the four are specified
+
+ This is a limitation of Discord's design. If in doubt, specify all
+ four of them each time.
+
Parameters
----------
webhook : typing.Union[hikari.snowflakes.Snowflakeish, hikari.webhooks.ExecutableWebhook]
The webhook to execute. This may be the object
or the ID of an existing webhook.
- token: builtins.str
+ token : str
The webhook token.
message : hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage]
The message to delete. This may be the object or the ID of
@@ -2525,9 +2503,9 @@ async def edit_webhook_message(
content : hikari.undefined.UndefinedOr[typing.Any]
If provided, the message content to update with. If
`hikari.undefined.UNDEFINED`, then the content will not
- be changed. If `builtins.None`, then the content will be removed.
+ be changed. If `None`, then the content will be removed.
- Any other value will be cast to a `builtins.str` before sending.
+ Any other value will be cast to a `str` before sending.
If this is a `hikari.embeds.Embed` and neither the
`embed` or `embeds` kwargs are provided or if this is a
@@ -2547,81 +2525,59 @@ async def edit_webhook_message(
attachment : hikari.undefined.UndefinedNoneOr[typing.Union[hikari.files.Resourceish, hikari.messages.Attachment]]
If provided, the attachment to set on the message. If
`hikari.undefined.UNDEFINED`, the previous attachment, if
- present, is not changed. If this is `builtins.None`, then the
+ present, is not changed. If this is `None`, then the
attachment is removed, if present. Otherwise, the new attachment
that was provided will be attached.
attachments : hikari.undefined.UndefinedNoneOr[typing.Sequence[typing.Union[hikari.files.Resourceish, hikari.messages.Attachment]]]
If provided, the attachments to set on the message. If
`hikari.undefined.UNDEFINED`, the previous attachments, if
- present, are not changed. If this is `builtins.None`, then the
+ present, are not changed. If this is `None`, then the
attachments is removed, if present. Otherwise, the new attachments
that were provided will be attached.
component : hikari.undefined.UndefinedNoneOr[hikari.api.special_endpoints.ComponentBuilder]
If provided, builder object of the component to set for this message.
This component will replace any previously set components and passing
- `builtins.None` will remove all components.
+ `None` will remove all components.
components : hikari.undefined.UndefinedNoneOr[typing.Sequence[hikari.api.special_endpoints.ComponentBuilder]]
If provided, a sequence of the component builder objects set for
this message. These components will replace any previously set
- components and passing `builtins.None` or an empty sequence will
+ components and passing `None` or an empty sequence will
remove all components.
embed : hikari.undefined.UndefinedNoneOr[hikari.embeds.Embed]
If provided, the embed to set on the message. If
`hikari.undefined.UNDEFINED`, the previous embed(s) are not changed.
- If this is `builtins.None` then any present embeds are removed.
+ If this is `None` then any present embeds are removed.
Otherwise, the new embed that was provided will be used as the
replacement.
embeds : hikari.undefined.UndefinedNoneOr[typing.Sequence[hikari.embeds.Embed]]
If provided, the embeds to set on the message. If
`hikari.undefined.UNDEFINED`, the previous embed(s) are not changed.
- If this is `builtins.None` then any present embeds are removed.
+ If this is `None` then any present embeds are removed.
Otherwise, the new embeds that were provided will be used as the
replacement.
- mentions_everyone : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_everyone : hikari.undefined.UndefinedOr[bool]
If provided, sanitation for `@everyone` mentions. If
`hikari.undefined.UNDEFINED`, then the previous setting is
- not changed. If `builtins.True`, then `@everyone`/`@here` mentions
+ not changed. If `True`, then `@everyone`/`@here` mentions
in the message content will show up as mentioning everyone that can
view the chat.
- user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
- If provided, and `builtins.True`, all user mentions will be detected.
- If provided, and `builtins.False`, all user mentions will be ignored
+ user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], bool]]
+ If provided, and `True`, all user mentions will be detected.
+ If provided, and `False`, all user mentions will be ignored
if appearing in the message body.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.users.PartialUser` derivatives to enforce mentioning
specific users.
- role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], builtins.bool]]
- If provided, and `builtins.True`, all role mentions will be detected.
- If provided, and `builtins.False`, all role mentions will be ignored
+ role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], bool]]
+ If provided, and `True`, all role mentions will be detected.
+ If provided, and `False`, all role mentions will be ignored
if appearing in the message body.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.guilds.PartialRole` derivatives to enforce mentioning
specific roles.
- !!! note
- Mentioning everyone, roles, or users in message edits currently
- will not send a push notification showing a new mention to people
- on Discord. It will still highlight in their chat as if they
- were mentioned, however.
-
- !!! warning
- If you specify a non-embed `content`, `mentions_everyone`,
- `mentions_reply`, `user_mentions`, and `role_mentions` will default
- to `builtins.False` as the message will be re-parsed for mentions.
-
- This is a limitation of Discord's design. If in doubt, specify all
- three of them each time.
-
- !!! warning
- If you specify one of `mentions_everyone`, `mentions_reply`,
- `user_mentions`, or `role_mentions`, then all others will default to
- `builtins.False`, even if they were enabled previously.
-
- This is a limitation of Discord's design. If in doubt, specify all
- three of them each time.
-
Returns
-------
hikari.messages.Message
@@ -2629,7 +2585,7 @@ async def edit_webhook_message(
Raises
------
- builtins.ValueError
+ ValueError
If both `attachment` and `attachments`, `component` and `components`
or `embed` and `embeds` are specified.
hikari.errors.BadRequestError
@@ -2676,7 +2632,7 @@ async def delete_webhook_message(
webhook : typing.Union[hikari.snowflakes.Snowflakeish, hikari.webhooks.ExecutableWebhook]
The webhook to execute. This may be the object
or the ID of an existing webhook.
- token: builtins.str
+ token : str
The webhook token.
message : hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage]
The message to delete. This may be the object or the ID of
@@ -2716,7 +2672,7 @@ async def delete_webhook_message(
async def fetch_gateway_url(self) -> str:
"""Fetch the gateway url.
- !!! note
+ .. note::
This endpoint does not require any valid authorization.
Raises
@@ -2738,7 +2694,7 @@ async def fetch_gateway_url(self) -> str:
@abc.abstractmethod
async def fetch_gateway_bot_info(self) -> sessions.GatewayBotInfo:
- """Fetch the gateway gateway info for the bot.
+ """Fetch the gateway info for the bot.
Returns
-------
@@ -2772,7 +2728,7 @@ async def fetch_invite(
Parameters
----------
- invite : typing.Union[hikari.invites.InviteCode, builtins.str]
+ invite : typing.Union[hikari.invites.InviteCode, str]
The invite to fetch. This may be an invite object or
the code of an existing invite.
with_counts : builtins.bool
@@ -2816,7 +2772,7 @@ async def delete_invite(self, invite: typing.Union[invites.InviteCode, str]) ->
Parameters
----------
- invite : typing.Union[hikari.invites.InviteCode, builtins.str]
+ invite : typing.Union[hikari.invites.InviteCode, str]
The invite to delete. This may be an invite object or
the code of an existing invite.
@@ -2889,10 +2845,10 @@ async def edit_my_user(
Other Parameters
----------------
- username : undefined.UndefinedOr[builtins.str]
+ username : undefined.UndefinedOr[str]
If provided, the new username.
avatar : undefined.UndefinedNoneOr[hikari.files.Resourceish]
- If provided, the new avatar. If `builtins.None`,
+ If provided, the new avatar. If `None`,
the avatar will be removed.
Returns
@@ -2905,8 +2861,8 @@ async def edit_my_user(
hikari.errors.BadRequestError
If any of the fields that are passed have an invalid value.
- Discord also returns this on a ratelimit:
- https://github.com/discord/discord-api-docs/issues/1462
+ Discord also returns this on a rate limit:
+
hikari.errors.UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
hikari.errors.InternalServerError
@@ -2950,11 +2906,18 @@ def fetch_my_guilds(
) -> iterators.LazyIterator[applications.OwnGuild]:
"""Fetch the token's associated guilds.
+ .. note::
+ This call is not a coroutine function, it returns a special type of
+ lazy iterator that will perform API calls as you iterate across it,
+ thus any errors documented below will happen then.
+
+ See `hikari.iterators` for the full API for this iterator type.
+
Other Parameters
----------------
- newest_first : builtins.bool
+ newest_first : bool
Whether to fetch the newest first or the oldest first.
- Defaults to `builtins.False`.
+ Defaults to `False`.
start_at : hikari.undefined.UndefinedOr[hikari.snowflakes.SearchableSnowflakeishOr[hikari.guilds.PartialGuild]]
If provided, will start at this snowflake. If you provide
a datetime object, it will be transformed into a snowflake. This
@@ -2966,11 +2929,6 @@ def fetch_my_guilds(
hikari.iterators.LazyIterator[hikari.applications.OwnGuild]
The token's associated guilds.
- !!! note
- This call is not a coroutine function, it returns a special type of
- lazy iterator that will perform API calls as you iterate across it.
- See `hikari.iterators` for the full API for this iterator type.
-
Raises
------
hikari.errors.BadRequestError
@@ -2990,11 +2948,6 @@ def fetch_my_guilds(
nature, and will trigger this exception if they occur.
hikari.errors.InternalServerError
If an internal error occurs on Discord while handling the request.
-
- !!! note
- The exceptions on this endpoint will only be raised once the
- result is awaited or iterated over. Invoking this function
- itself will not raise anything.
"""
@abc.abstractmethod
@@ -3064,12 +3017,12 @@ async def create_dm_channel(self, user: snowflakes.SnowflakeishOr[users.PartialU
If an internal error occurs on Discord while handling the request.
"""
- # THIS IS AN OAUTH2 FLOW BUT CAN BE USED BY BOTS ALSO
+ # THIS IS AN OAUTH2 FLOW BUT CAN ALSO BE USED BY BOTS
@abc.abstractmethod
async def fetch_application(self) -> applications.Application:
"""Fetch the token's associated application.
- !!! warning
+ .. warning::
This endpoint can only be used with a Bot token. Using this with a
Bearer token will result in a `hikari.errors.UnauthorizedError`.
@@ -3102,7 +3055,7 @@ async def fetch_application(self) -> applications.Application:
async def fetch_authorization(self) -> applications.AuthorizationInformation:
"""Fetch the token's authorization information.
- !!! warning
+ .. warning::
This endpoint can only be used with a Bearer token. Using this
with a Bot token will result in a `hikari.errors.UnauthorizedError`.
@@ -3144,9 +3097,9 @@ async def authorize_client_credentials_token(
----------
client : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
Object or ID of the application to authorize as.
- client_secret : builtins.str
+ client_secret : str
Secret of the application to authorize as.
- scopes : typing.Sequence[typing.Union[hikari.applications.OAuth2Scope, builtins.str]]
+ scopes : typing.Sequence[typing.Union[hikari.applications.OAuth2Scope, str]]
The scopes to authorize for.
Returns
@@ -3189,11 +3142,11 @@ async def authorize_access_token(
----------
client : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
Object or ID of the application to authorize with.
- client_secret : builtins.str
+ client_secret : str
Secret of the application to authorize with.
- code : builtins.str
+ code : str
The authorization code to exchange for an OAuth2 access token.
- redirect_uri : builtins.str
+ redirect_uri : str
The redirect uri that was included in the authorization request.
Returns
@@ -3235,7 +3188,7 @@ async def refresh_access_token(
) -> applications.OAuth2AuthorizationToken:
"""Refresh an access token.
- !!! warning
+ .. warning::
As of writing this Discord currently ignores any passed scopes,
therefore you should use
`hikari.applications.OAuth2AuthorizationToken.scopes` to validate
@@ -3245,14 +3198,14 @@ async def refresh_access_token(
----------
client : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
Object or ID of the application to authorize with.
- client_secret : builtins.str
+ client_secret : str
Secret of the application to authorize with.
- refresh_token : builtins.str
+ refresh_token : str
The refresh token to use.
Other Parameters
----------------
- scopes : typing.Sequence[typing.Union[hikari.applications.OAuth2Scope, builtins.str]]
+ scopes : typing.Sequence[typing.Union[hikari.applications.OAuth2Scope, str]]
The scope of the access request.
Returns
@@ -3294,9 +3247,9 @@ async def revoke_access_token(
----------
client : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
Object or ID of the application to authorize with.
- client_secret : builtins.str
+ client_secret : str
Secret of the application to authorize with.
- token : typing.Union[builtins.str, hikari.applications.PartialOAuth2Token]
+ token : typing.Union[str, hikari.applications.PartialOAuth2Token]
Object or string of the access token to revoke.
Raises
@@ -3333,7 +3286,7 @@ async def add_user_to_guild(
) -> typing.Optional[guilds.Member]:
"""Add a user to a guild.
- !!! note
+ .. note::
This requires the `access_token` to have the
`hikari.applications.OAuth2Scope.GUILDS_JOIN` scope enabled along
with the authorization of a Bot which has `MANAGE_INVITES`
@@ -3341,7 +3294,7 @@ async def add_user_to_guild(
Parameters
----------
- access_token : typing.Union[builtins.str, hikari.applications.PartialOAuth2Token]
+ access_token : typing.Union[str, hikari.applications.PartialOAuth2Token]
Object or string of the access token to use for this request.
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
The guild to add the user to. This may be the object
@@ -3352,7 +3305,7 @@ async def add_user_to_guild(
Other Parameters
----------------
- nickname : hikari.undefined.UndefinedOr[builtins.str]
+ nickname : hikari.undefined.UndefinedOr[str]
If provided, the nick to add to the user when he joins the guild.
Requires the `MANAGE_NICKNAMES` permission on the guild.
@@ -3361,11 +3314,11 @@ async def add_user_to_guild(
This may be a collection objects or IDs of existing roles.
Requires the `MANAGE_ROLES` permission on the guild.
- mute : hikari.undefined.UndefinedOr[builtins.bool]
+ mute : hikari.undefined.UndefinedOr[bool]
If provided, the mute state to add the user when he joins the guild.
Requires the `MUTE_MEMBERS` permission on the guild.
- deaf : hikari.undefined.UndefinedOr[builtins.bool]
+ deaf : hikari.undefined.UndefinedOr[bool]
If provided, the deaf state to add the user when he joins the guild.
Requires the `DEAFEN_MEMBERS` permission on the guild.
@@ -3373,7 +3326,7 @@ async def add_user_to_guild(
Returns
-------
typing.Optional[hikari.guilds.Member]
- `builtins.None` if the user was already part of the guild, else
+ `None` if the user was already part of the guild, else
`hikari.guilds.Member`.
Raises
@@ -3446,7 +3399,7 @@ async def fetch_user(self, user: snowflakes.SnowflakeishOr[users.PartialUser]) -
Returns
-------
hikari.users.User
- The requested user
+ The requested user.
Raises
------
@@ -3480,6 +3433,13 @@ def fetch_audit_log(
) -> iterators.LazyIterator[audit_logs.AuditLog]:
"""Fetch pages of the guild's audit log.
+ .. note::
+ This call is not a coroutine function, it returns a special type of
+ lazy iterator that will perform API calls as you iterate across it,
+ thus any errors documented below will happen then.
+
+ See `hikari.iterators` for the full API for this iterator type.
+
Parameters
----------
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
@@ -3489,13 +3449,13 @@ def fetch_audit_log(
Other Parameters
----------------
before : hikari.undefined.UndefinedOr[hikari.snowflakes.SearchableSnowflakeishOr[hikari.snowflakes.Unique]]
- If provided, filter to only actions after this snowflake. If you provide
+ If provided, filter to only actions before this snowflake. If you provide
a datetime object, it will be transformed into a snowflake. This
may be any other Discord entity that has an ID. In this case, the
date the object was first created will be used.
user : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.users.PartialUser]]
If provided, the user to filter for.
- event_type : hikari.undefined.UndefinedOr[typing.Union[hikari.audit_logs.AuditLogEventType, builtins.int]]
+ event_type : hikari.undefined.UndefinedOr[typing.Union[hikari.audit_logs.AuditLogEventType, int]]
If provided, the event type to filter for.
Returns
@@ -3503,11 +3463,6 @@ def fetch_audit_log(
hikari.iterators.LazyIterator[hikari.audit_logs.AuditLog]
The guild's audit log.
- !!! note
- This call is not a coroutine function, it returns a special type of
- lazy iterator that will perform API calls as you iterate across it.
- See `hikari.iterators` for the full API for this iterator type.
-
Raises
------
hikari.errors.BadRequestError
@@ -3529,11 +3484,6 @@ def fetch_audit_log(
nature, and will trigger this exception if they occur.
hikari.errors.InternalServerError
If an internal error occurs on Discord while handling the request.
-
- !!! note
- The exceptions on this endpoint will only be raised once the
- result is awaited or iterated over. Invoking this function
- itself will not raise anything.
"""
@abc.abstractmethod
@@ -3634,7 +3584,7 @@ async def create_emoji(
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
The guild to create the emoji on. This can be a
guild object or the ID of an existing guild.
- name : builtins.str
+ name : str
The name for the emoji.
image : hikari.files.Resourceish
The 128x128 image for the emoji. Maximum upload size is 256kb.
@@ -3646,7 +3596,7 @@ async def create_emoji(
If provided, a collection of the roles that will be able to
use this emoji. This can be a `hikari.guilds.PartialRole` or
the ID of an existing role.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -3704,13 +3654,13 @@ async def edit_emoji(
Other Parameters
----------------
- name : hikari.undefined.UndefinedOr[builtins.str]
+ name : hikari.undefined.UndefinedOr[str]
If provided, the new name for the emoji.
roles : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole]]
If provided, the new collection of roles that will be able to
use this emoji. This can be a `hikari.guilds.PartialRole` or
the ID of an existing role.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -3765,7 +3715,7 @@ async def delete_emoji(
Other Parameters
----------------
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -3960,23 +3910,23 @@ async def create_sticker(
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
The guild to create the sticker on. This can be a guild object or the
ID of an existing guild.
- name : builtins.str
+ name : str
The name for the sticker.
- tag : builtins.str
+ tag : str
The tag for the sticker.
image : hikari.files.Resourceish
The 320x320 image for the sticker. Maximum upload size is 500kb.
This can be a still or an animated PNG or a Lottie.
- !!! note
+ .. note::
Lottie support is only available for verified and partnered
servers.
Other Parameters
----------------
- description: hikari.undefined.UndefinedOr[builtins.str]
+ description : hikari.undefined.UndefinedOr[str]
If provided, the description of the sticker.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -4035,13 +3985,13 @@ async def edit_sticker(
Other Parameters
----------------
- name : hikari.undefined.UndefinedOr[builtins.str]
+ name : hikari.undefined.UndefinedOr[str]
If provided, the new name for the sticker.
- description : hikari.undefined.UndefinedOr[builtins.str]
+ description : hikari.undefined.UndefinedOr[str]
If provided, the new description for the sticker.
- tag : hikari.undefined.UndefinedOr[builtins.str]
+ tag : hikari.undefined.UndefinedOr[str]
If provided, the new sticker tag.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -4096,7 +4046,7 @@ async def delete_sticker(
Other Parameters
----------------
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -4127,9 +4077,19 @@ async def delete_sticker(
def guild_builder(self, name: str, /) -> special_endpoints.GuildBuilder:
"""Make a guild builder to create a guild with.
+ .. note::
+ This endpoint can only be used by bots in less than 10 guilds.
+
+ .. note::
+ This call is not a coroutine function, it returns a special type of
+ lazy iterator that will perform API calls as you iterate across it,
+ thus any errors documented below will happen then.
+
+ See `hikari.iterators` for the full API for this iterator type.
+
Parameters
----------
- name : builtins.str
+ name : str
The new guilds name.
Returns
@@ -4138,9 +4098,6 @@ def guild_builder(self, name: str, /) -> special_endpoints.GuildBuilder:
The guild builder to use. This will allow to create a guild
later with `hikari.api.special_endpoints.GuildBuilder.create`.
- !!! note
- This endpoint can only be used by bots in less than 10 guilds.
-
Raises
------
hikari.errors.BadRequestError
@@ -4162,15 +4119,9 @@ def guild_builder(self, name: str, /) -> special_endpoints.GuildBuilder:
hikari.errors.InternalServerError
If an internal error occurs on Discord while handling the request.
- !!! note
- The exceptions on this endpoint will only be raised once
- `hikari.api.special_endpoints.GuildBuilder.create` is called.
- Invoking this function itself will not raise any of
- the above types.
-
See Also
--------
- Guild builder: `hikari.api.special_endpoints.GuildBuilder`
+ GuildBuilder : `hikari.api.special_endpoints.GuildBuilder`.
"""
@abc.abstractmethod
@@ -4215,6 +4166,9 @@ async def fetch_guild(self, guild: snowflakes.SnowflakeishOr[guilds.PartialGuild
async def fetch_guild_preview(self, guild: snowflakes.SnowflakeishOr[guilds.PartialGuild]) -> guilds.GuildPreview:
"""Fetch a guild preview.
+ .. note::
+ This will only work for guilds you are a part of or are public.
+
Parameters
----------
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
@@ -4226,9 +4180,6 @@ async def fetch_guild_preview(self, guild: snowflakes.SnowflakeishOr[guilds.Part
hikari.guilds.GuildPreview
The requested guild preview.
- !!! note
- This will only work for guilds you are a part of or are public.
-
Raises
------
hikari.errors.NotFoundError
@@ -4293,7 +4244,7 @@ async def edit_guild(
Other Parameters
----------------
- name : hikari.undefined.UndefinedOr[builtins.str]
+ name : hikari.undefined.UndefinedOr[str]
If provided, the new name for the guild.
verification_level : hikari.undefined.UndefinedOr[hikari.guilds.GuildVerificationLevel]
If provided, the new verification level.
@@ -4312,7 +4263,7 @@ async def edit_guild(
owner : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.users.PartialUser]]]
If provided, the new guild owner.
- !!! warning
+ .. warning::
You need to be the owner of the server to use this.
splash : hikari.undefined.UndefinedNoneOr[hikari.files.Resourceish]
If provided, the new guild splash. Must be a 16:9 image and the
@@ -4326,9 +4277,9 @@ async def edit_guild(
If provided, the new rules channel.
public_updates_channel : hikari.undefined.UndefinedNoneOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildTextChannel]]
If provided, the new public updates channel.
- preferred_locale : hikari.undefined.UndefinedNoneOr[builtins.str]
+ preferred_locale : hikari.undefined.UndefinedNoneOr[str]
If provided, the new preferred locale.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -4459,17 +4410,17 @@ async def create_guild_text_channel(
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
The guild to create the channel in. This may be the
object or the ID of an existing guild.
- name : builtins.str
+ name : str
The channels name. Must be between 2 and 1000 characters.
Other Parameters
----------------
- position : hikari.undefined.UndefinedOr[builtins.int]
+ position : hikari.undefined.UndefinedOr[int]
If provided, the position of the channel (relative to the
category, if any).
- topic : hikari.undefined.UndefinedOr[builtins.str]
+ topic : hikari.undefined.UndefinedOr[str]
If provided, the channels topic. Maximum 1024 characters.
- nsfw : hikari.undefined.UndefinedOr[builtins.bool]
+ nsfw : hikari.undefined.UndefinedOr[bool]
If provided, whether to mark the channel as NSFW.
rate_limit_per_user : hikari.undefined.UndefinedOr[hikari.internal.time.Intervalish]
If provided, the amount of seconds a user has to wait
@@ -4487,7 +4438,7 @@ async def create_guild_text_channel(
This should be either 60, 1440, 4320 or 10080 seconds and, as of
writing, ignores the parent channel's set default_auto_archive_duration
when passed as `hikari.undefined.UNDEFINED`.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -4545,17 +4496,17 @@ async def create_guild_news_channel(
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
The guild to create the channel in. This may be the
object or the ID of an existing guild.
- name : builtins.str
+ name : str
The channels name. Must be between 2 and 1000 characters.
Other Parameters
----------------
- position : hikari.undefined.UndefinedOr[builtins.int]
+ position : hikari.undefined.UndefinedOr[int]
If provided, the position of the channel (relative to the
category, if any).
- topic : hikari.undefined.UndefinedOr[builtins.str]
+ topic : hikari.undefined.UndefinedOr[str]
If provided, the channels topic. Maximum 1024 characters.
- nsfw : hikari.undefined.UndefinedOr[builtins.bool]
+ nsfw : hikari.undefined.UndefinedOr[bool]
If provided, whether to mark the channel as NSFW.
rate_limit_per_user : hikari.undefined.UndefinedOr[hikari.internal.time.Intervalish]
If provided, the amount of seconds a user has to wait
@@ -4573,7 +4524,7 @@ async def create_guild_news_channel(
This should be either 60, 1440, 4320 or 10080 seconds and, as of
writing, ignores the parent channel's set default_auto_archive_duration
when passed as `hikari.undefined.UNDEFINED`.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -4631,34 +4582,34 @@ async def create_guild_voice_channel(
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
The guild to create the channel in. This may be the
object or the ID of an existing guild.
- name : builtins.str
+ name : str
The channels name. Must be between 2 and 1000 characters.
Other Parameters
----------------
- position : hikari.undefined.UndefinedOr[builtins.int]
+ position : hikari.undefined.UndefinedOr[int]
If provided, the position of the channel (relative to the
category, if any).
- user_limit : hikari.undefined.UndefinedOr[builtins.int]
+ user_limit : hikari.undefined.UndefinedOr[int]
If provided, the maximum users in the channel at once.
Must be between 0 and 99 with 0 meaning no limit.
- bitrate : hikari.undefined.UndefinedOr[builtins.int]
+ bitrate : hikari.undefined.UndefinedOr[int]
If provided, the bitrate for the channel. Must be
between 8000 and 96000 or 8000 and 128000 for VIP
servers.
- video_quality_mode: hikari.undefined.UndefinedOr[typing.Union[hikari.channels.VideoQualityMode, builtins.int]]
+ video_quality_mode : hikari.undefined.UndefinedOr[typing.Union[hikari.channels.VideoQualityMode, int]]
If provided, the new video quality mode for the channel.
permission_overwrites : hikari.undefined.UndefinedOr[typing.Sequence[hikari.channels.PermissionOverwrite]]
If provided, the permission overwrites for the channel.
- region : hikari.undefined.UndefinedOr[typing.Union[hikari.voices.VoiceRegion, builtins.str]]
+ region : hikari.undefined.UndefinedOr[typing.Union[hikari.voices.VoiceRegion, str]]
If provided, the voice region to for this channel. Passing
- `builtins.None` here will set it to "auto" mode where the used
+ `None` here will set it to "auto" mode where the used
region will be decided based on the first person who connects to it
when it's empty.
category : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildCategory]]
The category to create the channel under. This may be the
object or the ID of an existing category.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -4715,32 +4666,32 @@ async def create_guild_stage_channel(
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
The guild to create the channel in. This may be the
object or the ID of an existing guild.
- name : builtins.str
+ name : str
The channel's name. Must be between 2 and 1000 characters.
Other Parameters
----------------
- position : hikari.undefined.UndefinedOr[builtins.int]
+ position : hikari.undefined.UndefinedOr[int]
If provided, the position of the channel (relative to the
category, if any).
- user_limit : hikari.undefined.UndefinedOr[builtins.int]
+ user_limit : hikari.undefined.UndefinedOr[int]
If provided, the maximum users in the channel at once.
Must be between 0 and 99 with 0 meaning no limit.
- bitrate : hikari.undefined.UndefinedOr[builtins.int]
+ bitrate : hikari.undefined.UndefinedOr[int]
If provided, the bitrate for the channel. Must be
between 8000 and 96000 or 8000 and 128000 for VIP
servers.
permission_overwrites : hikari.undefined.UndefinedOr[typing.Sequence[hikari.channels.PermissionOverwrite]]
If provided, the permission overwrites for the channel.
- region : hikari.undefined.UndefinedOr[typing.Union[hikari.voices.VoiceRegion, builtins.str]]
+ region : hikari.undefined.UndefinedOr[typing.Union[hikari.voices.VoiceRegion, str]]
If provided, the voice region to for this channel. Passing
- `builtins.None` here will set it to "auto" mode where the used
+ `None` here will set it to "auto" mode where the used
region will be decided based on the first person who connects to it
when it's empty.
category : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildCategory]]
The category to create the channel under. This may be the
object or the ID of an existing category.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -4793,16 +4744,16 @@ async def create_guild_category(
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
The guild to create the channel in. This may be the
object or the ID of an existing guild.
- name : builtins.str
+ name : str
The channels name. Must be between 2 and 1000 characters.
Other Parameters
----------------
- position : hikari.undefined.UndefinedOr[builtins.int]
+ position : hikari.undefined.UndefinedOr[int]
If provided, the position of the category.
permission_overwrites : hikari.undefined.UndefinedOr[typing.Sequence[hikari.channels.PermissionOverwrite]]
If provided, the permission overwrites for the category.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -4852,7 +4803,7 @@ async def create_message_thread(
) -> typing.Union[channels_.GuildPublicThread, channels_.GuildNewsThread]:
"""Create a public or news thread on a message in a guild channel.
- !!! note
+ .. note::
This call may create a public or news thread dependent on the
target channel's type and cannot create private threads.
@@ -4862,7 +4813,7 @@ async def create_message_thread(
Object or ID of the guild news or text channel to create a public thread in.
message : hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage]
Object or ID of the message to attach the created thread to.
- name : builtins.str
+ name : str
Name of the thread channel.
Other Parameters
@@ -4924,7 +4875,7 @@ async def create_thread(
) -> channels_.GuildThreadChannel:
"""Create a thread in a guild channel.
- !!! warning
+ .. warning::
Private and public threads can only be made in guild text channels,
and news threads can only be made in guild news channels.
@@ -4932,7 +4883,7 @@ async def create_thread(
----------
channel : hikari.snowflakes.SnowflakeishOr[hikari.channels.PermissibleGuildChannel]
Object or ID of the guild news or text channel to create a thread in.
- name : builtins.str
+ name : str
Name of the thread channel.
Other Parameters
@@ -4943,7 +4894,7 @@ async def create_thread(
This should be either 60, 1440, 4320 or 10080 seconds and, as of
writing, ignores the parent channel's set default_auto_archive_duration
when passed as `hikari.undefined.UNDEFINED`.
- invitable : undefined.UndefinedOr[builtins.bool]
+ invitable : undefined.UndefinedOr[bool]
If provided, whether non-moderators should be able to add other non-moderators to the thread.
This only applies to private threads.
@@ -5267,7 +5218,7 @@ def fetch_public_archived_threads(
) -> iterators.LazyIterator[typing.Union[channels_.GuildNewsThread, channels_.GuildPublicThread]]:
"""Fetch a channel's public archived threads.
- !!! note
+ .. note::
The exceptions on this endpoint will only be raised once the
result is awaited or iterated over. Invoking this function
itself will not raise anything.
@@ -5289,7 +5240,7 @@ def fetch_public_archived_threads(
hikari.iterators.LazyIterator[typing.Union[hikari.channels.GuildNewsChannel, hikari.channels.GuildPublicThread]]
An iterator to fetch the threads.
- !!! note
+ .. note::
This call is not a coroutine function, it returns a special type of
lazy iterator that will perform API calls as you iterate across it.
See `hikari.iterators` for the full API for this iterator type.
@@ -5327,7 +5278,7 @@ def fetch_private_archived_threads(
) -> iterators.LazyIterator[channels_.GuildPrivateThread]:
"""Fetch a channel's private archived threads.
- !!! note
+ .. note::
The exceptions on this endpoint will only be raised once the
result is awaited or iterated over. Invoking this function
itself will not raise anything.
@@ -5349,7 +5300,7 @@ def fetch_private_archived_threads(
hikari.iterators.LazyIterator[hikari.channels.GuildPrivateThread]
An iterator to fetch the threads.
- !!! note
+ .. note::
This call is not a coroutine function, it returns a special type of
lazy iterator that will perform API calls as you iterate across it.
See `hikari.iterators` for the full API for this iterator type.
@@ -5389,7 +5340,7 @@ def fetch_joined_private_archived_threads(
) -> iterators.LazyIterator[channels_.GuildPrivateThread]:
"""Fetch the private archived threads you have joined in a channel.
- !!! note
+ .. note::
The exceptions on this endpoint will only be raised once the
result is awaited or iterated over. Invoking this function
itself will not raise anything.
@@ -5410,7 +5361,7 @@ def fetch_joined_private_archived_threads(
hikari.iterators.LazyIterator[hikari.channels.GuildPrivateThread]
An iterator to fetch the threads.
- !!! note
+ .. note::
This call is not a coroutine function, it returns a special type of
lazy iterator that will perform API calls as you iterate across it.
See `hikari.iterators` for the full API for this iterator type.
@@ -5451,7 +5402,7 @@ async def reposition_channels(
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
The guild to reposition the channels in. This may be the
object or the ID of an existing guild.
- positions : typing.Mapping[builtins.int, hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildChannel]]
+ positions : typing.Mapping[int, hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildChannel]]
A mapping of of the object or the ID of an existing channel to
the new position, relative to their parent category, if any.
@@ -5527,6 +5478,19 @@ def fetch_members(
) -> iterators.LazyIterator[guilds.Member]:
"""Fetch the members from a guild.
+ .. warning::
+ This endpoint requires the `GUILD_MEMBERS` intent to be enabled in
+ the dashboard, not necessarily authenticated with it if using the
+ gateway. If you don't have the intents you can use `search_members`
+ which doesn't require any intents.
+
+ .. note::
+ This call is not a coroutine function, it returns a special type of
+ lazy iterator that will perform API calls as you iterate across it,
+ thus any errors documented below will happen then.
+
+ See `hikari.iterators` for the full API for this iterator type.
+
Parameters
----------
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
@@ -5538,11 +5502,6 @@ def fetch_members(
hikari.iterators.LazyIterator[hikari.guilds.Member]
An iterator to fetch the members.
- !!! note
- This call is not a coroutine function, it returns a special type of
- lazy iterator that will perform API calls as you iterate across it.
- See `hikari.iterators` for the full API for this iterator type.
-
Raises
------
hikari.errors.UnauthorizedError
@@ -5562,26 +5521,13 @@ def fetch_members(
nature, and will trigger this exception if they occur.
hikari.errors.InternalServerError
If an internal error occurs on Discord while handling the request.
-
- !!! note
- The exceptions on this endpoint will only be raised once the
- result is awaited or iterated over. Invoking this function
- itself will not raise anything.
-
- !!! warning
- This endpoint requires the `GUILD_MEMBERS` intent to be enabled in
- the dashboard, not necessarily authenticated with it if using the
- gateway.
-
- If you don't have the intents you can use `search_members` which
- doesn't require any intents.
"""
@abc.abstractmethod
async def fetch_my_member(self, guild: snowflakes.SnowflakeishOr[guilds.PartialGuild]) -> guilds.Member:
"""Fetch the Oauth token's associated member in a guild.
- !!! warning
+ .. warning::
This endpoint can only be used with a Bearer token. Using this
with a Bot token will result in a `hikari.errors.UnauthorizedError`.
@@ -5619,6 +5565,11 @@ async def search_members(
) -> typing.Sequence[guilds.Member]:
"""Search the members in a guild by nickname and username.
+ .. note::
+ Unlike `RESTClient.fetch_members` this endpoint isn't paginated and
+ therefore will return all the members in one go rather than needing
+ to be asynchronously iterated over.
+
Parameters
----------
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
@@ -5650,11 +5601,6 @@ async def search_members(
nature, and will trigger this exception if they occur.
hikari.errors.InternalServerError
If an internal error occurs on Discord while handling the request.
-
- !!! note
- Unlike `RESTClient.fetch_members` this endpoint isn't paginated and
- therefore will return all the members in one go rather than needing
- to be asynchronously iterated over.
"""
@abc.abstractmethod
@@ -5680,14 +5626,14 @@ async def edit_member(
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
The guild to edit. This may be the object
or the ID of an existing guild.
- user : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
- The guild to edit. This may be the object
- or the ID of an existing guild.
+ user : hikari.snowflakes.SnowflakeishOr[hikari.users.PartialUser]
+ The user to edit. This may be the object
+ or the ID of an existing user.
Other Parameters
----------------
- nickname : hikari.undefined.UndefinedNoneOr[builtins.str]
- If provided, the new nick for the member. If `builtins.None`,
+ nickname : hikari.undefined.UndefinedNoneOr[str]
+ If provided, the new nick for the member. If `None`,
will remove the members nick.
Requires the `MANAGE_NICKNAMES` permission.
@@ -5695,33 +5641,33 @@ async def edit_member(
If provided, the new roles for the member.
Requires the `MANAGE_ROLES` permission.
- mute : hikari.undefined.UndefinedOr[builtins.bool]
+ mute : hikari.undefined.UndefinedOr[bool]
If provided, the new server mute state for the member.
Requires the `MUTE_MEMBERS` permission.
- deaf : hikari.undefined.UndefinedOr[builtins.bool]
+ deaf : hikari.undefined.UndefinedOr[bool]
If provided, the new server deaf state for the member.
Requires the `DEAFEN_MEMBERS` permission.
voice_channel : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildVoiceChannel]]]
- If provided, `builtins.None` or the object or the ID of
+ If provided, `None` or the object or the ID of
an existing voice channel to move the member to.
- If `builtins.None`, will disconnect the member from voice.
+ If `None`, will disconnect the member from voice.
Requires the `MOVE_MEMBERS` permission and the `CONNECT`
permission in the original voice channel and the target
voice channel.
- !!! note
+ .. note::
If the member is not in a voice channel, this will
take no effect.
communication_disabled_until : hikari.undefined.UndefinedNoneOr[datetime.datetime]
If provided, the datetime when the timeout (disable communication)
- of the member expires, up to 28 days in the future, or `builtins.None`
+ of the member expires, up to 28 days in the future, or `None`
to remove the timeout from the member.
Requires the `MODERATE_MEMBERS` permission.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -5773,9 +5719,9 @@ async def edit_my_member(
Other Parameters
----------------
- nickname : hikari.undefined.UndefinedNoneOr[builtins.str]
+ nickname : hikari.undefined.UndefinedNoneOr[str]
If provided, the new nickname for the member. If
- `builtins.None`, will remove the members nickname.
+ `None`, will remove the members nickname.
Requires the `CHANGE_NICKNAME` permission.
If provided, the reason that will be recorded in the audit logs.
@@ -5836,7 +5782,7 @@ async def add_role_to_member(
Other Parameters
----------------
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -5888,7 +5834,7 @@ async def remove_role_from_member(
Other Parameters
----------------
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -5936,7 +5882,7 @@ async def kick_user(
Other Parameters
----------------
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -5971,7 +5917,7 @@ async def kick_member(
*,
reason: undefined.UndefinedOr[str] = undefined.UNDEFINED,
) -> None:
- """Alias of `RESTClient.kick_user`."""
+ """Alias of `kick_user`."""
@abc.abstractmethod
async def ban_user(
@@ -5995,10 +5941,10 @@ async def ban_user(
Other Parameters
----------------
- delete_message_days : hikari.undefined.UndefinedNoneOr[builtins.int]
+ delete_message_days : hikari.undefined.UndefinedOr[int]
If provided, the number of days to delete messages for.
This must be between 0 and 7.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -6036,7 +5982,7 @@ async def ban_member(
delete_message_days: undefined.UndefinedOr[int] = undefined.UNDEFINED,
reason: undefined.UndefinedOr[str] = undefined.UNDEFINED,
) -> None:
- """Alias of `RESTClient.ban_user`."""
+ """Alias of `ban_user`."""
@abc.abstractmethod
async def unban_user(
@@ -6059,7 +6005,7 @@ async def unban_user(
Other Parameters
----------------
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -6094,7 +6040,7 @@ async def unban_member(
*,
reason: undefined.UndefinedOr[str] = undefined.UNDEFINED,
) -> None:
- """Alias of `RESTClient.unban_user`."""
+ """Alias of `unban_user`."""
@abc.abstractmethod
async def fetch_ban(
@@ -6153,7 +6099,7 @@ def fetch_bans(
) -> iterators.LazyIterator[guilds.GuildBan]:
"""Fetch the bans of a guild.
- !!! note
+ .. note::
This call is not a coroutine function, it returns a special type of
lazy iterator that will perform API calls as you iterate across it.
See `hikari.iterators` for the full API for this iterator type.
@@ -6166,10 +6112,10 @@ def fetch_bans(
Other Parameters
----------------
- newest_first : builtins.bool
+ newest_first : bool
Whether to fetch the newest first or the oldest first.
- Defaults to `builtins.False`.
+ Defaults to `False`.
start_at : undefined.UndefinedOr[snowflakes.SearchableSnowflakeishOr[users.PartialUser]]
If provided, will start at this snowflake. If you provide
a datetime object, it will be transformed into a snowflake. This
@@ -6268,7 +6214,7 @@ async def create_role(
Other Parameters
----------------
- name : hikari.undefined.UndefinedOr[builtins.str]
+ name : hikari.undefined.UndefinedOr[str]
If provided, the name for the role.
permissions : hikari.undefined.UndefinedOr[hikari.permissions.Permissions]
The permissions to give the role. This will default to setting
@@ -6279,15 +6225,15 @@ async def create_role(
If provided, the role's color.
colour : hikari.undefined.UndefinedOr[hikari.colors.Colorish]
An alias for `color`.
- hoist : hikari.undefined.UndefinedOr[builtins.bool]
+ hoist : hikari.undefined.UndefinedOr[bool]
If provided, whether to hoist the role.
icon : hikari.undefined.UndefinedOr[hikari.files.Resourceish]
If provided, the role icon. Must be a 64x64 image under 256kb.
- unicode_emoji : hikari.undefined.UndefinedOr[builtins.str]
+ unicode_emoji : hikari.undefined.UndefinedOr[str]
If provided, the standard emoji to set as the role icon.
- mentionable : hikari.undefined.UndefinedOr[builtins.bool]
+ mentionable : hikari.undefined.UndefinedOr[bool]
If provided, whether to make the role mentionable.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -6298,7 +6244,7 @@ async def create_role(
Raises
------
- builtins.TypeError
+ TypeError
If both `color` and `colour` are specified or if both `icon` and
`unicode_emoji` are specified.
hikari.errors.BadRequestError
@@ -6337,7 +6283,7 @@ async def reposition_roles(
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
The guild to reposition the roles in. This may be
the object or the ID of an existing guild.
- positions : typing.Mapping[builtins.int, hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialRole]]
+ positions : typing.Mapping[int, hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialRole]]
A mapping of the position to the role.
Raises
@@ -6392,7 +6338,7 @@ async def edit_role(
Other Parameters
----------------
- name : hikari.undefined.UndefinedOr[builtins.str]
+ name : hikari.undefined.UndefinedOr[str]
If provided, the new name for the role.
permissions : hikari.undefined.UndefinedOr[hikari.permissions.Permissions]
If provided, the new permissions for the role.
@@ -6400,16 +6346,16 @@ async def edit_role(
If provided, the new color for the role.
colour : hikari.undefined.UndefinedOr[hikari.colors.Colorish]
An alias for `color`.
- hoist : hikari.undefined.UndefinedOr[builtins.bool]
+ hoist : hikari.undefined.UndefinedOr[bool]
If provided, whether to hoist the role.
icon : hikari.undefined.UndefinedNoneOr[hikari.files.Resourceish]
If provided, the new role icon. Must be a 64x64 image
under 256kb.
- unicode_emoji : hikari.undefined.UndefinedNoneOr[builtins.str]
+ unicode_emoji : hikari.undefined.UndefinedNoneOr[str]
If provided, the new unicode emoji to set as the role icon.
- mentionable : hikari.undefined.UndefinedOr[builtins.bool]
+ mentionable : hikari.undefined.UndefinedOr[bool]
If provided, whether to make the role mentionable.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -6420,7 +6366,7 @@ async def edit_role(
Raises
------
- builtins.TypeError
+ TypeError
If both `color` and `colour` are specified or if both `icon` and
`unicode_emoji` are specified.
hikari.errors.BadRequestError
@@ -6504,7 +6450,7 @@ async def estimate_guild_prune_count(
Other Parameters
----------------
- days : hikari.undefined.UndefinedOr[builtins.int]
+ days : hikari.undefined.UndefinedOr[int]
If provided, number of days to count prune for.
include_roles : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole]]]
If provided, the role(s) to include. By default, this endpoint will
@@ -6514,7 +6460,7 @@ async def estimate_guild_prune_count(
Returns
-------
- builtins.int
+ int
The estimated guild prune count.
Raises
@@ -6562,9 +6508,9 @@ async def begin_guild_prune(
Other Parameters
----------------
- days : hikari.undefined.UndefinedOr[builtins.int]
+ days : hikari.undefined.UndefinedOr[int]
If provided, number of days to count prune for.
- compute_prune_count: hikari.snowflakes.SnowflakeishOr[builtins.bool]
+ compute_prune_count : hikari.snowflakes.SnowflakeishOr[bool]
If provided, whether to return the prune count. This is discouraged
for large guilds.
include_roles : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole]]
@@ -6572,15 +6518,15 @@ async def begin_guild_prune(
not count users with roles. Providing roles using this attribute
will make members with the specified roles also get included into
the count.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
Returns
-------
- typing.Optional[builtins.int]
- If `compute_prune_count` is not provided or `builtins.True`, the
- number of members pruned. Else `builtins.None`.
+ typing.Optional[int]
+ If `compute_prune_count` is not provided or `True`, the
+ number of members pruned. Else `None`.
Raises
------
@@ -6786,11 +6732,11 @@ async def edit_widget(
Other Parameters
----------------
channel : hikari.undefined.UndefinedNoneOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildChannel]]
- If provided, the channel to set the widget to. If `builtins.None`,
+ If provided, the channel to set the widget to. If `None`,
will not set to any.
- enabled : hikari.undefined.UndefinedOr[builtins.bool]
+ enabled : hikari.undefined.UndefinedOr[bool]
If provided, whether to enable the widget.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -6877,17 +6823,17 @@ async def edit_welcome_screen(
Other Parameters
----------------
- description : undefined.UndefinedNoneOr[builtins.str]
+ description : undefined.UndefinedNoneOr[str]
If provided, the description to set for the guild's welcome screen.
- This may be `builtins.None` to unset the description.
- enabled : undefined.UndefinedOr[builtins.bool]
+ This may be `None` to unset the description.
+ enabled : undefined.UndefinedOr[bool]
If provided, Whether the guild's welcome screen should be enabled.
channels : hikari.undefined.UndefinedNoneOr[typing.Sequence[hikari.guilds.WelcomeChannel]]
If provided, a sequence of up to 5 public channels to set in this
- guild's welcome screen. This may be passed as `builtins.None` to
+ guild's welcome screen. This may be passed as `None` to
remove all welcome channels
- !!! note
+ .. note::
Custom emojis may only be included in a guild's welcome channels
if it's boost status is tier 2 or above.
@@ -6983,7 +6929,7 @@ async def create_template(
Other Parameters
----------------
- description : hikari.undefined.UndefinedNoneOr[builtins.str]
+ description : hikari.undefined.UndefinedNoneOr[str]
The description to set for the template.
Returns
@@ -7025,11 +6971,14 @@ async def create_guild_from_template(
) -> guilds.RESTGuild:
"""Make a guild from a template.
+ .. note::
+ This endpoint can only be used by bots in less than 10 guilds.
+
Parameters
----------
- template : typing.Union[builtins.str, hikari.templates.Template]
+ template : typing.Union[str, hikari.templates.Template]
The object or string code of the template to create a guild based on.
- name : builtins.str
+ name : str
The new guilds name.
Other Parameters
@@ -7043,9 +6992,6 @@ async def create_guild_from_template(
hikari.guilds.RESTGuild
Object of the created guild.
- !!! note
- This endpoint can only be used by bots in less than 10 guilds.
-
Raises
------
hikari.errors.BadRequestError
@@ -7127,14 +7073,14 @@ async def edit_template(
----------
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
The guild to edit a template in.
- template : typing.Union[builtins.str, hikari.templates.Template]
+ template : typing.Union[str, hikari.templates.Template]
Object or string code of the template to modify.
Other Parameters
----------------
- name : hikari.undefined.UndefinedOr[builtins.str]
+ name : hikari.undefined.UndefinedOr[str]
The name to set for this template.
- description : hikari.undefined.UndefinedNoneOr[builtins.str]
+ description : hikari.undefined.UndefinedNoneOr[str]
The description to set for the template.
Returns
@@ -7172,7 +7118,7 @@ async def fetch_template(self, template: typing.Union[str, templates.Template])
Parameters
----------
- template : typing.Union[builtins.str, hikari.templates.Template]
+ template : typing.Union[str, hikari.templates.Template]
The object or string code of the template to fetch.
Returns
@@ -7253,7 +7199,7 @@ async def sync_guild_template(
----------
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
The guild to sync a template in.
- template : typing.Union[builtins.str, hikari.templates.Template]
+ template : typing.Union[str, hikari.templates.Template]
Object or code of the template to sync.
Returns
@@ -7295,10 +7241,10 @@ def slash_command_builder(
Parameters
----------
- name : builtins.str
+ name : str
The command's name. This should match the regex `^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$` in
Unicode mode and be lowercase.
- description : builtins.str
+ description : str
The description to set for the command if this is a slash command.
This should be inclusively between 1-100 characters in length.
@@ -7320,7 +7266,7 @@ def context_menu_command_builder(
----------
type : commands.CommandType
The commands's type.
- name : builtins.str
+ name : str
The command's name.
Returns
@@ -7340,9 +7286,9 @@ async def fetch_application_command(
Parameters
----------
- application: hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
+ application : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
Object or ID of the application to fetch a command for.
- command: hikari.snowflakes.SnowflakeishOr[hikari.commands.PartialCommand]
+ command : hikari.snowflakes.SnowflakeishOr[hikari.commands.PartialCommand]
Object or ID of the command to fetch.
Other Parameters
@@ -7390,7 +7336,7 @@ async def fetch_application_commands(
Parameters
----------
- application: hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
+ application : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
Object or ID of the application to fetch the commands for.
Other Parameters
@@ -7456,12 +7402,12 @@ async def create_slash_command(
Parameters
----------
- application: hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
+ application : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
Object or ID of the application to create a command for.
- name : builtins.str
- The command's name. This should match the regex `^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$` in
+ name : str
+ The command's name. This should match the regex `^[\w-]{1,32}$` in
Unicode mode and be lowercase.
- description : builtins.str
+ description : str
The description to set for the command.
This should be inclusively between 1-100 characters in length.
@@ -7482,7 +7428,7 @@ async def create_slash_command(
If `0`, then it will be available for all members. Note that this doesn't affect
administrators of the guild and overwrites.
- dm_enabled : hikari.undefined.UndefinedOr[builtins.bool]
+ dm_enabled : hikari.undefined.UndefinedOr[bool]
Whether this command is enabled in DMs with the bot.
This can only be applied to non-guild commands.
@@ -7540,13 +7486,13 @@ async def create_context_menu_command(
Parameters
----------
- application: hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
+ application : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
Object or ID of the application to create a command for.
- type : typing.Union[hikari.commands.CommandType, builtins.int]
+ type : typing.Union[hikari.commands.CommandType, int]
The type of menu command to make.
Only USER and MESSAGE are valid here.
- name : builtins.str
+ name : str
The command's name. This should match the regex `^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$` in
Unicode mode and be lowercase.
@@ -7563,7 +7509,7 @@ async def create_context_menu_command(
If `0`, then it will be available for all members. Note that this doesn't affect
administrators of the guild and overwrites.
- dm_enabled : hikari.undefined.UndefinedOr[builtins.bool]
+ dm_enabled : hikari.undefined.UndefinedOr[bool]
Whether this command is enabled in DMs with the bot.
This can only be applied to non-guild commands.
@@ -7609,15 +7555,15 @@ async def set_application_commands(
) -> typing.Sequence[commands.PartialCommand]:
"""Set the commands for an application.
- !!! warning
+ .. warning::
Any existing commands not included in the provided commands array
will be deleted.
Parameters
----------
- application: hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
+ application : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
Object or ID of the application to create a command for.
- commands: typing.Sequence[hikari.api.special_endpoints.CommandBuilder]
+ commands : typing.Sequence[hikari.api.special_endpoints.CommandBuilder]
A sequence of up to 100 initialised command builder objects of the
commands to set for this the application.
@@ -7677,7 +7623,7 @@ async def edit_application_command(
Parameters
----------
- application: hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
+ application : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
Object or ID of the application to edit a command for.
command : hikari.snowflakes.SnowflakeishOr[hikari.commands.PartialCommand]
Object or ID of the command to modify.
@@ -7688,10 +7634,10 @@ async def edit_application_command(
Object or ID of the guild to edit a command for if this is a guild
specific command. Leave this as `hikari.undefined.UNDEFINED` to delete
a global command.
- name : hikari.undefined.UndefinedOr[builtins.str]
+ name : hikari.undefined.UndefinedOr[str]
The name to set for the command. Leave as `hikari.undefined.UNDEFINED`
to not change.
- description : hikari.undefined.UndefinedOr[builtins.str]
+ description : hikari.undefined.UndefinedOr[str]
The description to set for the command. Leave as `hikari.undefined.UNDEFINED`
to not change.
options : hikari.undefined.UndefinedOr[typing.Sequence[hikari.commands.CommandOption]]
@@ -7702,7 +7648,7 @@ async def edit_application_command(
If `0`, then it will be available for all members. Note that this doesn't affect
administrators of the guild and overwrites.
- dm_enabled : hikari.undefined.UndefinedOr[builtins.bool]
+ dm_enabled : hikari.undefined.UndefinedOr[bool]
Whether this command is enabled in DMs with the bot.
This can only be applied to non-guild commands.
@@ -7748,7 +7694,7 @@ async def delete_application_command(
Parameters
----------
- application: hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
+ application : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
Object or ID of the application to delete a command for.
command : hikari.snowflakes.SnowflakeishOr[hikari.commands.PartialCommand]
Object or ID of the command to delete.
@@ -7793,7 +7739,7 @@ async def fetch_application_guild_commands_permissions(
Parameters
----------
- application: hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
+ application : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
Object or ID of the application to fetch the command permissions for.
guild : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]]
Object or ID of the guild to fetch the command permissions for.
@@ -7837,11 +7783,11 @@ async def fetch_application_command_permissions(
Parameters
----------
- application: hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
+ application : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
Object or ID of the application to fetch the command permissions for.
guild : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]]
Object or ID of the guild to fetch the command permissions for.
- command: hikari.snowflakes.SnowflakeishOr[hikari.commands.PartialCommand]
+ command : hikari.snowflakes.SnowflakeishOr[hikari.commands.PartialCommand]
Object or ID of the command to fetch the command permissions for.
Returns
@@ -7883,18 +7829,18 @@ async def set_application_command_permissions(
) -> commands.GuildCommandPermissions:
"""Set permissions for a specific command.
- !!! note
+ .. note::
This requires the `access_token` to have the
`hikari.applications.OAuth2Scope.APPLICATIONS_COMMANDS_PERMISSION_UPDATE`
scope enabled along with the authorization of a Bot which has `MANAGE_INVITES`
permission within the target guild.
- !!! note
+ .. note::
This overwrites any previously set permissions.
Parameters
----------
- application: hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
+ application : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
Object or ID of the application to set the command permissions for.
guild : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]]
Object or ID of the guild to set the command permissions for.
@@ -7939,7 +7885,7 @@ def interaction_deferred_builder(
Parameters
----------
- type: typing.Union[hikari.interactions.base_interactions.ResponseType, builtins.int]
+ type : typing.Union[hikari.interactions.base_interactions.ResponseType, int]
The type of deferred message response this builder is for.
Returns
@@ -7968,7 +7914,7 @@ def interaction_message_builder(
Parameters
----------
- type : typing.Union[hikari.interactions.base_interactions.ResponseType, builtins.int]
+ type : typing.Union[hikari.interactions.base_interactions.ResponseType, int]
The type of message response this builder is for.
Returns
@@ -8002,9 +7948,9 @@ async def fetch_interaction_response(
Parameters
----------
- application: hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
+ application : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
Object or ID of the application to fetch a command for.
- token: builtins.str
+ token : str
Token of the interaction to get the initial response for.
Returns
@@ -8063,7 +8009,7 @@ async def create_interaction_response(
) -> None:
"""Create the initial response for a interaction.
- !!! warning
+ .. warning::
Calling this with an interaction which already has an initial
response will result in this raising a `hikari.errors.NotFoundError`.
This includes if the REST interaction server has already responded
@@ -8073,9 +8019,9 @@ async def create_interaction_response(
----------
interaction : hikari.snowflakes.SnowflakeishOr[hikari.interactions.base_interactions.PartialInteraction]
Object or ID of the interaction this response is for.
- token : builtins.str
+ token : str
The command interaction's token.
- response_type : typing.Union[builtins.int, hikari.interactions.base_interactions.ResponseType]
+ response_type : typing.Union[int, hikari.interactions.base_interactions.ResponseType]
The type of interaction response this is.
Other Parameters
@@ -8084,7 +8030,7 @@ async def create_interaction_response(
If provided, the message contents. If
`hikari.undefined.UNDEFINED`, then nothing will be sent
in the content. Any other value here will be cast to a
- `builtins.str`.
+ `str`.
If this is a `hikari.embeds.Embed` and no `embed` nor
no `embeds` kwarg is provided, then this will instead
@@ -8105,28 +8051,28 @@ async def create_interaction_response(
If provided, the message embed.
embeds : hikari.undefined.UndefinedNoneOr[typing.Sequence[hikari.embeds.Embed]]
If provided, the message embeds.
- flags : typing.Union[builtins.int, hikari.messages.MessageFlag, hikari.undefined.UndefinedType]
+ flags : typing.Union[int, hikari.messages.MessageFlag, hikari.undefined.UndefinedType]
If provided, the message flags this response should have.
As of writing the only message flag which can be set here is
`hikari.messages.MessageFlag.EPHEMERAL`.
- tts : hikari.undefined.UndefinedOr[builtins.bool]
+ tts : hikari.undefined.UndefinedOr[bool]
If provided, whether the message will be read out by a screen
reader using Discord's TTS (text-to-speech) system.
- mentions_everyone : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_everyone : hikari.undefined.UndefinedOr[bool]
If provided, whether the message should parse @everyone/@here
mentions.
- user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
- If provided, and `builtins.True`, all user mentions will be detected.
- If provided, and `builtins.False`, all user mentions will be ignored
+ user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], bool]]
+ If provided, and `True`, all user mentions will be detected.
+ If provided, and `False`, all user mentions will be ignored
if appearing in the message body.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.users.PartialUser` derivatives to enforce mentioning
specific users.
- role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], builtins.bool]]
- If provided, and `builtins.True`, all role mentions will be detected.
- If provided, and `builtins.False`, all role mentions will be ignored
+ role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], bool]]
+ If provided, and `True`, all role mentions will be detected.
+ If provided, and `False`, all role mentions will be ignored
if appearing in the message body.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
@@ -8135,10 +8081,10 @@ async def create_interaction_response(
Raises
------
- builtins.ValueError
+ ValueError
If more than 100 unique objects/entities are passed for
`role_mentions` or `user_mentions`.
- builtins.TypeError
+ TypeError
If both `embed` and `embeds` are specified.
hikari.errors.BadRequestError
This may be raised in several discrete situations, such as messages
@@ -8194,11 +8140,25 @@ async def edit_interaction_response(
) -> messages_.Message:
"""Edit the initial response to a command interaction.
+ .. note::
+ Mentioning everyone, roles, or users in message edits currently
+ will not send a push notification showing a new mention to people
+ on Discord. It will still highlight in their chat as if they
+ were mentioned, however.
+
+ Also important to note that if you specify a text `content`, `mentions_everyone`,
+ `mentions_reply`, `user_mentions`, and `role_mentions` will default
+ to `False` as the message will be re-parsed for mentions. This will
+ also occur if only one of the four are specified
+
+ This is a limitation of Discord's design. If in doubt, specify all
+ four of them each time.
+
Parameters
----------
- application: hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
+ application : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
Object or ID of the application to edit a command response for.
- token : builtins.str
+ token : str
The interaction's token.
Other Parameters
@@ -8206,9 +8166,9 @@ async def edit_interaction_response(
content : hikari.undefined.UndefinedOr[typing.Any]
If provided, the message content to update with. If
`hikari.undefined.UNDEFINED`, then the content will not
- be changed. If `builtins.None`, then the content will be removed.
+ be changed. If `None`, then the content will be removed.
- Any other value will be cast to a `builtins.str` before sending.
+ Any other value will be cast to a `str` before sending.
If this is a `hikari.embeds.Embed` and neither the
`embed` or `embeds` kwargs are provided or if this is a
@@ -8219,70 +8179,56 @@ async def edit_interaction_response(
attachment : hikari.undefined.UndefinedNoneOr[typing.Union[hikari.files.Resourceish, hikari.messages.Attachment]]
If provided, the attachment to set on the message. If
`hikari.undefined.UNDEFINED`, the previous attachment, if
- present, is not changed. If this is `builtins.None`, then the
+ present, is not changed. If this is `None`, then the
attachment is removed, if present. Otherwise, the new attachment
that was provided will be attached.
attachments : hikari.undefined.UndefinedNoneOr[typing.Sequence[typing.Union[hikari.files.Resourceish, hikari.messages.Attachment]]]
If provided, the attachments to set on the message. If
`hikari.undefined.UNDEFINED`, the previous attachments, if
- present, are not changed. If this is `builtins.None`, then the
+ present, are not changed. If this is `None`, then the
attachments is removed, if present. Otherwise, the new attachments
that were provided will be attached.
component : hikari.undefined.UndefinedNoneOr[hikari.api.special_endpoints.ComponentBuilder]
If provided, builder object of the component to set for this message.
This component will replace any previously set components and passing
- `builtins.None` will remove all components.
+ `None` will remove all components.
components : hikari.undefined.UndefinedNoneOr[typing.Sequence[hikari.api.special_endpoints.ComponentBuilder]]
If provided, a sequence of the component builder objects set for
this message. These components will replace any previously set
- components and passing `builtins.None` or an empty sequence will
+ components and passing `None` or an empty sequence will
remove all components.
embed : hikari.undefined.UndefinedNoneOr[hikari.embeds.Embed]
If provided, the embed to set on the message. If
`hikari.undefined.UNDEFINED`, the previous embed(s) are not changed.
- If this is `builtins.None` then any present embeds are removed.
+ If this is `None` then any present embeds are removed.
Otherwise, the new embed that was provided will be used as the
replacement.
embeds : hikari.undefined.UndefinedNoneOr[typing.Sequence[hikari.embeds.Embed]]
If provided, the embeds to set on the message. If
`hikari.undefined.UNDEFINED`, the previous embed(s) are not changed.
- If this is `builtins.None` then any present embeds are removed.
+ If this is `None` then any present embeds are removed.
Otherwise, the new embeds that were provided will be used as the
replacement.
- mentions_everyone : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_everyone : hikari.undefined.UndefinedOr[bool]
If provided, whether the message should parse @everyone/@here
mentions.
- user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
- If provided, and `builtins.True`, all user mentions will be detected.
- If provided, and `builtins.False`, all user mentions will be ignored
+ user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], bool]]
+ If provided, and `True`, all user mentions will be detected.
+ If provided, and `False`, all user mentions will be ignored
if appearing in the message body.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.users.PartialUser` derivatives to enforce mentioning
specific users.
- role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], builtins.bool]]
- If provided, and `builtins.True`, all role mentions will be detected.
- If provided, and `builtins.False`, all role mentions will be ignored
+ role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], bool]]
+ If provided, and `True`, all role mentions will be detected.
+ If provided, and `False`, all role mentions will be ignored
if appearing in the message body.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.guilds.PartialRole` derivatives to enforce mentioning
specific roles.
- !!! note
- Mentioning everyone, roles, or users in message edits currently
- will not send a push notification showing a new mention to people
- on Discord. It will still highlight in their chat as if they
- were mentioned, however.
-
- !!! warning
- If you specify one of `mentions_everyone`, `user_mentions`, or
- `role_mentions`, then all others will default to `builtins.False`,
- even if they were enabled previously.
-
- This is a limitation of Discord's design. If in doubt, specify all three of
- them each time.
-
Returns
-------
hikari.messages.Message
@@ -8290,7 +8236,7 @@ async def edit_interaction_response(
Raises
------
- builtins.ValueError
+ ValueError
If both `attachment` and `attachments`, `component` and `components`
or `embed` and `embeds` are specified.
hikari.errors.BadRequestError
@@ -8326,9 +8272,9 @@ async def delete_interaction_response(
Parameters
----------
- application: hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
+ application : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]
Object or ID of the application to delete a command response for.
- token : builtins.str
+ token : str
The interaction's token.
Raises
@@ -8365,7 +8311,7 @@ async def create_autocomplete_response(
----------
interaction : hikari.snowflakes.SnowflakeishOr[hikari.interactions.base_interactions.PartialInteraction]
Object or ID of the interaction this response is for.
- token : builtins.str
+ token : str
The command interaction's token.
Other Parameters
@@ -8458,18 +8404,21 @@ async def fetch_scheduled_event(
event: snowflakes.SnowflakeishOr[scheduled_events.ScheduledEvent],
/,
) -> scheduled_events.ScheduledEvent:
- """Fetch a channel.
+ """Fetch a scheduled event.
Parameters
----------
- channel : hikari.snowflakes.SnowflakeishOr[hikari.channels.PartialChannel]
- The channel to fetch. This may be the object or the ID of an
- existing channel.
+ guild : hikari.snowflakes.SnowflakeishOr[hikari.channels.PartialGuild]
+ The guild the event bellongs to. This may be the object or the
+ ID of an existing guild.
+ event : hikari.snowflakes.SnowflakeishOr[hikari.scheduled_events.ScheduledEvent]
+ The event to fetch. This may be the object or the
+ ID of an existing event.
Returns
-------
hikari.scheduled_events.ScheduledEvent
- The scheduled event
+ The scheduled event.
Raises
------
@@ -8503,7 +8452,7 @@ async def fetch_scheduled_events(
) -> typing.Sequence[scheduled_events.ScheduledEvent]:
"""Fetch the scheduled events for a guild.
- !!! note
+ .. note::
`VOICE` and `STAGE_CHANNEL` events are only included if the bot has
`VOICE` or `STAGE_CHANNEL` permissions in the associated channel.
@@ -8580,7 +8529,7 @@ async def create_stage_event(
The event's privacy level.
This effects who can view and subscribe to the event.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -8659,7 +8608,7 @@ async def create_voice_event(
The event's privacy level.
This effects who can view and subscribe to the event.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -8738,7 +8687,7 @@ async def create_external_event(
The event's privacy level.
This effects who can view and subscribe to the event.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -8836,7 +8785,7 @@ async def edit_scheduled_event(
`SCHEDULED` events can be set to `ACTIVE` and `CANCELED`.
`ACTIVE` events can only be set to `COMPLETED`.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -8927,6 +8876,13 @@ def fetch_scheduled_event_users(
) -> iterators.LazyIterator[scheduled_events.ScheduledEventUser]:
"""Asynchronously iterate over the users who're subscribed to a scheduled event.
+ .. note::
+ This call is not a coroutine function, it returns a special type of
+ lazy iterator that will perform API calls as you iterate across it,
+ thus any errors documented below will happen then.
+
+ See `hikari.iterators` for the full API for this iterator type.
+
Parameters
----------
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
@@ -8936,10 +8892,10 @@ def fetch_scheduled_event_users(
Other Parameters
----------------
- newest_first : builtins.bool
+ newest_first : bool
Whether to fetch the newest first or the oldest first.
- Defaults to `builtins.False`.
+ Defaults to `False`.
start_at : hikari.undefined.UndefinedOr[hikari.snowflakes.SearchableSnowflakeishOr[hikari.guilds.PartialGuild]]
If provided, will start at this snowflake. If you provide
a datetime object, it will be transformed into a snowflake. This
@@ -8951,11 +8907,6 @@ def fetch_scheduled_event_users(
hikari.iterators.LazyIterator[hikari.scheduled_events.ScheduledEventUser]
The token's associated guilds.
- !!! note
- This call is not a coroutine function, it returns a special type of
- lazy iterator that will perform API calls as you iterate across it.
- See `hikari.iterators` for the full API for this iterator type.
-
Raises
------
hikari.errors.BadRequestError
@@ -8977,9 +8928,4 @@ def fetch_scheduled_event_users(
nature, and will trigger this exception if they occur.
hikari.errors.InternalServerError
If an internal error occurs on Discord while handling the request.
-
- !!! note
- The exceptions on this endpoint will only be raised once the
- result is awaited or iterated over. Invoking this function
- itself will not raise anything.
"""
diff --git a/hikari/api/shard.py b/hikari/api/shard.py
index 4c72174fe3..b0378a880c 100644
--- a/hikari/api/shard.py
+++ b/hikari/api/shard.py
@@ -73,36 +73,21 @@ class GatewayShard(abc.ABC):
@property
@abc.abstractmethod
def heartbeat_latency(self) -> float:
- """Return the shard's most recent heartbeat latency.
+ """Shard's most recent heartbeat latency.
- Returns
- -------
- builtins.float
- Heartbeat latency measured in seconds. If the information is
- not yet available, then this will be `float('nan')` instead.
+ If the information is not yet available, then this will be
+ `float('nan')` instead.
"""
@property
@abc.abstractmethod
def id(self) -> int:
- """Return the shard ID for this shard.
-
- Returns
- -------
- builtins.int
- The integer 0-based shard ID.
- """
+ """0-based shard ID for this shard."""
@property
@abc.abstractmethod
def intents(self) -> intents_.Intents:
- """Return the intents set on this shard.
-
- Returns
- -------
- hikari.intents.Intents
- The intents being used on this shard.
- """
+ """Intents set on this shard."""
@property
@abc.abstractmethod
@@ -117,13 +102,7 @@ def is_connected(self) -> bool:
@property
@abc.abstractmethod
def shard_count(self) -> int:
- """Return the total number of shards expected in the entire application.
-
- Returns
- -------
- builtins.int
- A number of shards greater than or equal to 1.
- """
+ """Return the total number of shards expected in the entire application."""
@abc.abstractmethod
def get_user_id(self) -> snowflakes.Snowflake:
@@ -171,8 +150,8 @@ async def update_presence(
idle_since : hikari.undefined.UndefinedNoneOr[datetime.datetime]
The datetime that the user started being idle. If undefined, this
will not be changed.
- afk : hikari.undefined.UndefinedOr[builtins.bool]
- If `builtins.True`, the user is marked as AFK. If `builtins.False`,
+ afk : hikari.undefined.UndefinedOr[bool]
+ If `True`, the user is marked as AFK. If `False`,
the user is marked as being active. If undefined, this will not be
changed.
activity : hikari.undefined.UndefinedNoneOr[hikari.presences.Activity]
@@ -198,15 +177,15 @@ async def update_voice_state(
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
The guild or guild ID to update the voice state for.
channel : typing.Optional[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildVoiceChannel]]
- The channel or channel ID to update the voice state for. If `builtins.None`
+ The channel or channel ID to update the voice state for. If `None`
then the bot will leave the voice channel that it is in for the
given guild.
- self_mute : builtins.bool
- If specified and `builtins.True`, the bot will mute itself in that
- voice channel. If `builtins.False`, then it will unmute itself.
- self_deaf : builtins.bool
- If specified and `builtins.True`, the bot will deafen itself in that
- voice channel. If `builtins.False`, then it will undeafen itself.
+ self_mute : bool
+ If specified and `True`, the bot will mute itself in that
+ voice channel. If `False`, then it will unmute itself.
+ self_deaf : bool
+ If specified and `True`, the bot will deafen itself in that
+ voice channel. If `False`, then it will undeafen itself.
"""
@abc.abstractmethod
@@ -222,28 +201,28 @@ async def request_guild_members(
) -> None:
"""Request for a guild chunk.
+ .. note::
+ To request the full list of members, set `query` to `""` (empty
+ string) and `limit` to `0`.
+
Parameters
----------
- guild: hikari.guilds.Guild
+ guild : hikari.guilds.Guild
The guild to request chunk for.
Other Parameters
----------------
- include_presences: hikari.undefined.UndefinedOr[builtins.bool]
+ include_presences : hikari.undefined.UndefinedOr[bool]
If provided, whether to request presences.
- query: builtins.str
+ query : str
If not `""`, request the members which username starts with the string.
- limit: builtins.int
+ limit : int
Maximum number of members to send matching the query.
- users: hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishSequence[hikari.users.User]]
+ users : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishSequence[hikari.users.User]]
If provided, the users to request for.
- nonce: hikari.undefined.UndefinedOr[builtins.str]
+ nonce : hikari.undefined.UndefinedOr[str]
If provided, the nonce to be sent with guild chunks.
- !!! note
- To request the full list of members, set `query` to `""` (empty
- string) and `limit` to `0`.
-
Raises
------
ValueError
diff --git a/hikari/api/special_endpoints.py b/hikari/api/special_endpoints.py
index 24bb97a841..bb8fb13d2b 100644
--- a/hikari/api/special_endpoints.py
+++ b/hikari/api/special_endpoints.py
@@ -85,7 +85,7 @@ class TypingIndicator(abc.ABC):
the typing indicator once, or an async context manager to keep triggering
the typing indicator repeatedly until the context finishes.
- !!! note
+ .. note::
This is a helper class that is used by `hikari.api.rest.RESTClient`.
You should only ever need to use instances of this class that are
produced by that API.
@@ -118,70 +118,63 @@ class GuildBuilder(abc.ABC):
the logic behind creating a guild on an API level is somewhat confusing
and detailed.
- !!! note
- This is a helper class that is used by `hikari.api.rest.RESTClient`.
- You should only ever need to use instances of this class that are
- produced by that API, thus, any details about the constructor are
- omitted from the following examples for brevity.
+ .. note::
+ If you call `add_role`, the default roles provided by Discord will
+ be created. This also applies to the `add_` functions for
+ text channels/voice channels/categories.
+
+ .. note::
+ Functions that return a `hikari.snowflakes.Snowflake` do
+ **not** provide the final ID that the object will have once the
+ API call is made. The returned IDs are only able to be used to
+ re-reference particular objects while building the guild format
+ to allow for the creation of channels within categories,
+ and to provide permission overwrites.
Examples
--------
- Creating an empty guild.
+ Creating an empty guild:
- ```py
- guild = await rest.guild_builder("My Server!").create()
- ```
+ .. code-block:: python
- Creating a guild with an icon
+ guild = await rest.guild_builder("My Server!").create()
- ```py
- from hikari.files import WebResourceStream
+ Creating a guild with an icon:
- guild_builder = rest.guild_builder("My Server!")
- guild_builder.icon = WebResourceStream("cat.png", "http://...")
- guild = await guild_builder.create()
- ```
+ .. code-block:: python
- Adding roles to your guild.
+ from hikari.files import WebResourceStream
- ```py
- from hikari.permissions import Permissions
+ guild_builder = rest.guild_builder("My Server!")
+ guild_builder.icon = WebResourceStream("cat.png", "http://...")
+ guild = await guild_builder.create()
- guild_builder = rest.guild_builder("My Server!")
+ Adding roles to your guild:
- everyone_role_id = guild_builder.add_role("@everyone")
- admin_role_id = guild_builder.add_role("Admins", permissions=Permissions.ADMINISTRATOR)
+ .. code-block:: python
- await guild_builder.create()
- ```
+ from hikari.permissions import Permissions
- !!! warning
- The first role must always be the `@everyone` role.
+ guild_builder = rest.guild_builder("My Server!")
- !!! note
- If you call `add_role`, the default roles provided by discord will
- be created. This also applies to the `add_` functions for
- text channels/voice channels/categories.
+ everyone_role_id = guild_builder.add_role("@everyone")
+ admin_role_id = guild_builder.add_role("Admins", permissions=Permissions.ADMINISTRATOR)
- !!! note
- Functions that return a `hikari.snowflakes.Snowflake` do
- **not** provide the final ID that the object will have once the
- API call is made. The returned IDs are only able to be used to
- re-reference particular objects while building the guild format.
+ await guild_builder.create()
- This is provided to allow creation of channels within categories,
- and to provide permission overwrites.
+ .. warning::
+ The first role must always be the `@everyone` role.
- Adding a text channel to your guild.
+ Adding a text channel to your guild:
- ```py
- guild_builder = rest.guild_builder("My Server!")
+ .. code-block:: python
- category_id = guild_builder.add_category("My safe place")
- channel_id = guild_builder.add_text_channel("general", parent_id=category_id)
+ guild_builder = rest.guild_builder("My Server!")
- await guild_builder.create()
- ```
+ category_id = guild_builder.add_category("My safe place")
+ channel_id = guild_builder.add_text_channel("general", parent_id=category_id)
+
+ await guild_builder.create()
"""
__slots__: typing.Sequence[str] = ()
@@ -234,10 +227,7 @@ def icon(self, icon: undefined.UndefinedOr[files.Resourceish], /) -> None:
@property
@abc.abstractmethod
def verification_level(self) -> undefined.UndefinedOr[typing.Union[guilds.GuildVerificationLevel, int]]:
- """Verification level required to join the guild that can be overwritten.
-
- If not overridden, the guild will use the default verification level for
- """
+ """Verification level required to join the guild."""
@verification_level.setter
def verification_level(
@@ -285,12 +275,12 @@ def add_role(
) -> snowflakes.Snowflake:
"""Create a role.
- !!! warning
+ .. warning::
The first role you create must always be the `@everyone` role.
Parameters
----------
- name : builtins.str
+ name : str
The role's name.
Other Parameters
@@ -301,13 +291,10 @@ def add_role(
If provided, the role's color.
colour : hikari.undefined.UndefinedOr[hikari.colors.Colorish]
An alias for `color`.
- hoist : hikari.undefined.UndefinedOr[builtins.bool]
+ hoist : hikari.undefined.UndefinedOr[bool]
If provided, whether to hoist the role.
- mentionable : hikari.undefined.UndefinedOr[builtins.bool]
+ mentionable : hikari.undefined.UndefinedOr[bool]
If provided, whether to make the role mentionable.
- reason : hikari.undefined.UndefinedOr[builtins.str]
- If provided, the reason that will be recorded in the audit logs.
- Maximum of 512 characters.
Returns
-------
@@ -320,9 +307,9 @@ def add_role(
Raises
------
- builtins.ValueError
+ ValueError
If you are defining the first role, but did not name it `@everyone`.
- builtins.TypeError
+ TypeError
If you specify both `color` and `colour` together or if you try to
specify `color`, `colour`, `hoisted`, `mentionable` or `position` for
the `@everyone` role.
@@ -343,12 +330,12 @@ def add_category(
Parameters
----------
- name : builtins.str
+ name : str
The channels name. Must be between 2 and 1000 characters.
Other Parameters
----------------
- position : hikari.undefined.UndefinedOr[builtins.int]
+ position : hikari.undefined.UndefinedOr[int]
If provided, the position of the category.
permission_overwrites : hikari.undefined.UndefinedOr[typing.Sequence[hikari.channels.PermissionOverwrite]]
If provided, the permission overwrites for the category.
@@ -382,27 +369,26 @@ def add_text_channel(
Parameters
----------
- name : builtins.str
+ name : str
The channels name. Must be between 2 and 1000 characters.
Other Parameters
----------------
- position : hikari.undefined.UndefinedOr[builtins.int]
+ position : hikari.undefined.UndefinedOr[int]
If provided, the position of the channel (relative to the
category, if any).
- topic : hikari.undefined.UndefinedOr[builtins.str]
+ topic : hikari.undefined.UndefinedOr[str]
If provided, the channels topic. Maximum 1024 characters.
- nsfw : hikari.undefined.UndefinedOr[builtins.bool]
+ nsfw : hikari.undefined.UndefinedOr[bool]
If provided, whether to mark the channel as NSFW.
- rate_limit_per_user : hikari.undefined.UndefinedOr[builtins.int]
+ rate_limit_per_user : hikari.undefined.UndefinedOr[int]
If provided, the amount of seconds a user has to wait
before being able to send another message in the channel.
Maximum 21600 seconds.
permission_overwrites : hikari.undefined.UndefinedOr[typing.Sequence[hikari.channels.PermissionOverwrite]]
If provided, the permission overwrites for the channel.
- category : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildCategory]]
- The category to create the channel under. This may be the
- object or the ID of an existing category.
+ parent_id : hikari.undefined.UndefinedOr[hikari.snowflakes.Snowflake]
+ The ID of the category to create the channel under.
Returns
-------
@@ -434,33 +420,32 @@ def add_voice_channel(
Parameters
----------
- name : builtins.str
+ name : str
The channels name. Must be between 2 and 1000 characters.
Other Parameters
----------------
- position : hikari.undefined.UndefinedOr[builtins.int]
+ position : hikari.undefined.UndefinedOr[int]
If provided, the position of the channel (relative to the
category, if any).
- user_limit : hikari.undefined.UndefinedOr[builtins.int]
+ user_limit : hikari.undefined.UndefinedOr[int]
If provided, the maximum users in the channel at once.
Must be between 0 and 99 with 0 meaning no limit.
- bitrate : hikari.undefined.UndefinedOr[builtins.int]
+ bitrate : hikari.undefined.UndefinedOr[int]
If provided, the bitrate for the channel. Must be
between 8000 and 96000 or 8000 and 128000 for VIP
servers.
- video_quality_mode: hikari.undefined.UndefinedOr[typing.Union[hikari.channels.VideoQualityMode, builtins.int]]
+ video_quality_mode : hikari.undefined.UndefinedOr[typing.Union[hikari.channels.VideoQualityMode, int]]
If provided, the new video quality mode for the channel.
permission_overwrites : hikari.undefined.UndefinedOr[typing.Sequence[hikari.channels.PermissionOverwrite]]
If provided, the permission overwrites for the channel.
- region : hikari.undefined.UndefinedOr[typing.Union[hikari.voices.VoiceRegion, builtins.str]]
+ region : hikari.undefined.UndefinedOr[typing.Union[hikari.voices.VoiceRegion, str]]
If provided, the voice region to for this channel. Passing
- `builtins.None` here will set it to "auto" mode where the used
+ `None` here will set it to "auto" mode where the used
region will be decided based on the first person who connects to it
when it's empty.
- category : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildCategory]]
- The category to create the channel under. This may be the
- object or the ID of an existing category.
+ parent_id : hikari.undefined.UndefinedOr[hikari.snowflakes.Snowflake]
+ The ID of the category to create the channel under.
Returns
-------
@@ -491,31 +476,30 @@ def add_stage_channel(
Parameters
----------
- name : builtins.str
+ name : str
The channels name. Must be between 2 and 1000 characters.
Other Parameters
----------------
- position : hikari.undefined.UndefinedOr[builtins.int]
+ position : hikari.undefined.UndefinedOr[int]
If provided, the position of the channel (relative to the
category, if any).
- user_limit : hikari.undefined.UndefinedOr[builtins.int]
+ user_limit : hikari.undefined.UndefinedOr[int]
If provided, the maximum users in the channel at once.
Must be between 0 and 99 with 0 meaning no limit.
- bitrate : hikari.undefined.UndefinedOr[builtins.int]
+ bitrate : hikari.undefined.UndefinedOr[int]
If provided, the bitrate for the channel. Must be
between 8000 and 96000 or 8000 and 128000 for VIP
servers.
permission_overwrites : hikari.undefined.UndefinedOr[typing.Sequence[hikari.channels.PermissionOverwrite]]
If provided, the permission overwrites for the channel.
- region : hikari.undefined.UndefinedOr[typing.Union[hikari.voices.VoiceRegion, builtins.str]]
+ region : hikari.undefined.UndefinedOr[typing.Union[hikari.voices.VoiceRegion, str]]
If provided, the voice region to for this channel. Passing
- `builtins.None` here will set it to "auto" mode where the used
+ `None` here will set it to "auto" mode where the used
region will be decided based on the first person who connects to it
when it's empty.
- category : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildCategory]]
- The category to create the channel under. This may be the
- object or the ID of an existing category.
+ parent_id : hikari.undefined.UndefinedOr[hikari.snowflakes.Snowflake]
+ The ID of the category to create the channel under.
Returns
-------
@@ -572,7 +556,7 @@ def type(self) -> base_interactions.DeferredResponseTypesT:
def flags(self) -> typing.Union[undefined.UndefinedType, int, messages.MessageFlag]:
"""Message flags this response should have.
- !!! note
+ .. note::
As of writing the only message flag which can be set here is
`hikari.messages.MessageFlag.EPHEMERAL`.
"""
@@ -581,12 +565,12 @@ def flags(self) -> typing.Union[undefined.UndefinedType, int, messages.MessageFl
def set_flags(self: _T, flags: typing.Union[undefined.UndefinedType, int, messages.MessageFlag], /) -> _T:
"""Set message flags for this response.
- !!! note
- As of writing, the only message flag which can be set is EPHEMERAL.
+ .. note::
+ As of writing, the only message flag which can be set is `hikari.messages.MessageFlag.EPHEMERAL`.
Parameters
----------
- flags : typing.Union[hikari.undefined.UndefinedType, builtins.int, hikari.messages.MessageFlag]
+ flags : typing.Union[hikari.undefined.UndefinedType, int, hikari.messages.MessageFlag]
The message flags to set for this response.
Returns
@@ -663,7 +647,7 @@ def content(self) -> undefined.UndefinedOr[str]:
def flags(self) -> typing.Union[undefined.UndefinedType, int, messages.MessageFlag]:
"""Message flags this response should have.
- !!! note
+ .. note::
As of writing the only message flag which can be set here is
`hikari.messages.MessageFlag.EPHEMERAL`.
"""
@@ -685,13 +669,10 @@ def role_mentions(
) -> undefined.UndefinedOr[typing.Union[snowflakes.SnowflakeishSequence[guilds.PartialRole], bool]]:
"""Whether and what role mentions should be enabled for this response.
- Returns
- -------
- hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
- Either a sequence of object/IDs of the roles mentions should be enabled for,
- `builtins.False` or `hikari.undefined.UNDEFINED` to disallow any role
- mentions or `True` to allow all role mentions.
- """ # noqa: E501 - Line too long
+ Either a sequence of object/IDs of the roles mentions should be enabled
+ for, `False` or `hikari.undefined.UNDEFINED` to disallow any
+ role mentions or `True` to allow all role mentions.
+ """
@property
@abc.abstractmethod
@@ -700,13 +681,10 @@ def user_mentions(
) -> undefined.UndefinedOr[typing.Union[snowflakes.SnowflakeishSequence[users.PartialUser], bool]]:
"""Whether and what user mentions should be enabled for this response.
- Returns
- -------
- hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
- Either a sequence of object/IDs of the users mentions should be enabled for,
- `builtins.False` or `hikari.undefined.UNDEFINED` to disallow any user
- mentions or `True` to allow all user mentions.
- """ # noqa: E501 - Line too long
+ Either a sequence of object/IDs of the users mentions should be enabled
+ for, `False` or `hikari.undefined.UNDEFINED` to disallow any
+ user mentions or `True` to allow all user mentions.
+ """
@abc.abstractmethod
def clear_attachments(self: _T, /) -> _T:
@@ -763,7 +741,7 @@ def add_embed(self: _T, embed: embeds_.Embed, /) -> _T:
Returns
-------
InteractionMessageBuilder
- Object of this builder.
+ Object of this builder to allow for chained calls.
"""
@abc.abstractmethod
@@ -772,31 +750,32 @@ def set_content(self: _T, content: undefined.UndefinedOr[str], /) -> _T:
Parameters
----------
- content : hikari.undefined.UndefinedOr[builtins.str]
+ content : hikari.undefined.UndefinedOr[str]
The message content to set for this response.
Returns
-------
InteractionMessageBuilder
- Object of this builder.
+ Object of this builder to allow for chained calls.
"""
@abc.abstractmethod
def set_flags(self: _T, flags: typing.Union[undefined.UndefinedType, int, messages.MessageFlag], /) -> _T:
"""Set message flags for this response.
- !!! note
- As of writing, the only message flag which can be set is EPHEMERAL.
+ .. note::
+ As of writing, the only message flag which can be set is
+ `hikari.messages.MessageFlag.EPHEMERAL`..
Parameters
----------
- flags : typing.Union[hikari.undefined.UndefinedType, builtins.int, hikari.messages.MessageFlag]
+ flags : typing.Union[hikari.undefined.UndefinedType, int, hikari.messages.MessageFlag]
The message flags to set for this response.
Returns
-------
InteractionMessageBuilder
- Object of this builder.
+ Object of this builder to allow for chained calls.
"""
@abc.abstractmethod
@@ -805,12 +784,13 @@ def set_tts(self: _T, tts: undefined.UndefinedOr[bool], /) -> _T:
Parameters
----------
- tts : Whether this response should trigger text-to-speech processing.
+ tts : bool
+ Whether this response should trigger text-to-speech processing.
Returns
-------
InteractionMessageBuilder
- Object of this builder.
+ Object of this builder to allow for chained calls.
"""
@abc.abstractmethod
@@ -819,13 +799,13 @@ def set_mentions_everyone(self: _T, mentions: undefined.UndefinedOr[bool] = unde
Parameters
----------
- mentions : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions : hikari.undefined.UndefinedOr[bool]
Whether this response should be able to mention @everyone/@here.
Returns
-------
InteractionMessageBuilder
- Object of this builder.
+ Object of this builder to allow for chained calls.
"""
@abc.abstractmethod
@@ -840,15 +820,15 @@ def set_role_mentions(
Parameters
----------
- mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
+ mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], bool]]
Either a sequence of object/IDs of the roles mentions should be enabled for,
- `builtins.False` or `hikari.undefined.UNDEFINED` to disallow any role
+ `False` or `hikari.undefined.UNDEFINED` to disallow any role
mentions or `True` to allow all role mentions.
Returns
-------
InteractionMessageBuilder
- Object of this builder.
+ Object of this builder to allow for chained calls.
""" # noqa: E501 - Line too long
@abc.abstractmethod
@@ -863,15 +843,15 @@ def set_user_mentions(
Parameters
----------
- mentions: hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
+ mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], bool]]
Either a sequence of object/IDs of the users mentions should be enabled for,
- `builtins.False` or `hikari.undefined.UNDEFINED` to disallow any user
+ `False` or `hikari.undefined.UNDEFINED` to disallow any user
mentions or `True` to allow all user mentions.
Returns
-------
InteractionMessageBuilder
- Object of this builder.
+ Object of this builder to allow for chained calls.
""" # noqa: E501 - Line too long
@@ -946,14 +926,9 @@ class CommandBuilder(abc.ABC):
def name(self) -> str:
r"""Name to set for this command.
- !!! warning
+ .. warning::
This should match the regex `^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$` in Unicode mode
and must be lowercase.
-
- Returns
- -------
- builtins.str
- The name to set for this command.
"""
@property
@@ -1005,7 +980,7 @@ def set_id(self: _T, id_: undefined.UndefinedOr[snowflakes.Snowflakeish], /) ->
Returns
-------
CommandBuilder
- Object of this command builder.
+ Object of this command builder to allow for chained calls.
"""
@abc.abstractmethod
@@ -1016,7 +991,7 @@ def set_default_member_permissions(
Parameters
----------
- default_member_permissions : hikari.undefined.UndefinedOr[builtins.bool]
+ default_member_permissions : hikari.undefined.UndefinedOr[bool]
The default member permissions to utilize this command by default.
If `0`, then it will be available for all members. Note that this doesn't affect
@@ -1034,13 +1009,13 @@ def set_is_dm_enabled(self: _T, state: undefined.UndefinedOr[bool], /) -> _T:
Parameters
----------
- state : hikari.undefined.UndefinedOr[builtins.bool]
+ state : hikari.undefined.UndefinedOr[bool]
Whether this command is enabled in DMs with the bot.
Returns
-------
CommandBuilder
- Object of this command builder for chained calls.
+ Object of this command builder to allow for chained calls.
"""
@abc.abstractmethod
@@ -1130,11 +1105,11 @@ class SlashCommandBuilder(CommandBuilder):
@property
@abc.abstractmethod
def description(self) -> str:
- """Description to set for this command.
+ """Command's description.
- !!! warning
+ .. warning::
This should be inclusively between 1-100 characters in length.
- """ # noqa: D401 - Imperative mood
+ """
@property
@abc.abstractmethod
@@ -1171,7 +1146,7 @@ def options(self) -> typing.Sequence[commands.CommandOption]:
def add_option(self: _T, option: commands.CommandOption) -> _T:
"""Add an option to this command.
- !!! note
+ .. note::
A command can have up to 25 options.
Parameters
@@ -1182,7 +1157,7 @@ def add_option(self: _T, option: commands.CommandOption) -> _T:
Returns
-------
CommandBuilder
- Object of this command builder.
+ Object of this command builder to allow for chained calls.
"""
@abc.abstractmethod
@@ -1297,7 +1272,7 @@ def emoji(self) -> typing.Union[snowflakes.Snowflakeish, emojis.Emoji, str, unde
def label(self) -> undefined.UndefinedOr[str]:
"""Text label which should appear on this button.
- !!! note
+ .. note::
The text label to that should appear on this button. This may be
up to 80 characters long.
"""
@@ -1305,11 +1280,7 @@ def label(self) -> undefined.UndefinedOr[str]:
@property
@abc.abstractmethod
def is_disabled(self) -> bool:
- """Whether the button should be marked as disabled.
-
- !!! note
- Defaults to `builtins.False`.
- """
+ """Whether the button should be marked as disabled."""
@abc.abstractmethod
def set_emoji(
@@ -1319,7 +1290,7 @@ def set_emoji(
Parameters
----------
- emoji : typing.Union[hikari.snowflakes.Snowflakeish, hikari.emojis.Emoji, builtins.str, hikari.undefined.UndefinedType]
+ emoji : typing.Union[hikari.snowflakes.Snowflakeish, hikari.emojis.Emoji, str, hikari.undefined.UndefinedType]
Object, ID or raw string of the emoji which should be displayed on
this button.
@@ -1335,7 +1306,7 @@ def set_label(self: _T, label: undefined.UndefinedOr[str], /) -> _T:
Parameters
----------
- label : hikari.undefined.UndefinedOr[builtins.str]
+ label : hikari.undefined.UndefinedOr[str]
The text label to show on this button.
This may be up to 80 characters long.
@@ -1382,7 +1353,7 @@ class LinkButtonBuilder(ButtonBuilder[_ContainerT], abc.ABC):
@property
@abc.abstractmethod
def url(self) -> str:
- """Url this button should link to when pressed."""
+ """URL this button should link to when pressed."""
class InteractiveButtonBuilder(ButtonBuilder[_ContainerT], abc.ABC):
@@ -1424,10 +1395,7 @@ def emoji(self) -> typing.Union[snowflakes.Snowflakeish, emojis.Emoji, str, unde
@property
@abc.abstractmethod
def is_default(self) -> bool:
- """Whether this option should be marked as selected by default.
-
- Defaults to `builtins.False`.
- """
+ """Whether this option should be marked as selected by default."""
@abc.abstractmethod
def set_description(self: _T, value: undefined.UndefinedOr[str], /) -> _T:
@@ -1435,7 +1403,7 @@ def set_description(self: _T, value: undefined.UndefinedOr[str], /) -> _T:
Parameters
----------
- value : hikari.undefined.UndefinedOr[builtins.str]
+ value : hikari.undefined.UndefinedOr[str]
Description to set for this option. This can be up to 100 characters
long.
@@ -1453,7 +1421,7 @@ def set_emoji(
Parameters
----------
- emoji : typing.Union[hikari.snowflakes.Snowflakeish, hikari.emojis.Emoji, builtins.str, hikari.undefined.UndefinedType]
+ emoji : typing.Union[hikari.snowflakes.Snowflakeish, hikari.emojis.Emoji, str, hikari.undefined.UndefinedType]
Object, ID or raw string of the emoji which should be displayed on
this option.
@@ -1469,7 +1437,7 @@ def set_is_default(self: _T, state: bool, /) -> _T:
Parameters
----------
- state : builtins.bool
+ state : bool
Whether this option should be selected by default.
Returns
@@ -1504,11 +1472,7 @@ def custom_id(self) -> str:
@property
@abc.abstractmethod
def is_disabled(self) -> bool:
- """Whether the select menu should be marked as disabled.
-
- !!! note
- Defaults to `builtins.False`.
- """
+ """Whether the select menu should be marked as disabled."""
@property
@abc.abstractmethod
@@ -1544,29 +1508,32 @@ def max_values(self) -> int:
def add_option(self: _SelectMenuBuilderT, label: str, value: str, /) -> SelectOptionBuilder[_SelectMenuBuilderT]:
"""Add an option to this menu.
+ .. note::
+ Setup should be finalised by calling `add_to_menu` in the builder
+ returned.
+
Parameters
----------
- label : builtins.str
+ label : str
The user-facing name of this option, max 100 characters.
- value : builtins.str
+ value : str
The developer defined value of this option, max 100 characters.
Returns
-------
- SelectOptionBuilder[Self]
+ SelectOptionBuilder[SelectMenuBuilder]
Option builder object.
- This should be finalised by calling `SelectOptionBuilder.add_to_menu`.
"""
@abc.abstractmethod
def set_is_disabled(self: _T, state: bool, /) -> _T:
"""Set whether this option is disabled.
- Defaults to `builtins.False`.
+ Defaults to `False`.
Parameters
----------
- state : builtins.bool
+ state : bool
Whether this option is disabled.
Returns
@@ -1581,7 +1548,7 @@ def set_placeholder(self: _T, value: undefined.UndefinedOr[str], /) -> _T:
Parameters
----------
- value : hikari.undefined.UndefinedOr[builtins.str]
+ value : hikari.undefined.UndefinedOr[str]
Place-holder text to be displayed when no option is selected.
Max 100 characters.
@@ -1595,13 +1562,13 @@ def set_placeholder(self: _T, value: undefined.UndefinedOr[str], /) -> _T:
def set_min_values(self: _T, value: int, /) -> _T:
"""Set the minimum amount of options which need to be selected for this menu.
- !!! note
+ .. note::
This defaults to 1 if not set and must be greater than or equal to 0
and less than or equal to `SelectMenuBuilder.max_values`.
Parameters
----------
- value : builtins.int
+ value : int
The minimum amount of options which need to be selected for this menu.
Returns
@@ -1614,13 +1581,13 @@ def set_min_values(self: _T, value: int, /) -> _T:
def set_max_values(self: _T, value: int, /) -> _T:
"""Set the maximum amount of options which can be selected for this menu.
- !!! note
+ .. note::
This defaults to 1 if not set and must be less than or equal to 25
and greater than or equal to `SelectMenuBuilder.min_values`.
Parameters
----------
- value : builtins.int
+ value : int
The maximum amount of options which can selected for this menu.
Returns
@@ -1650,7 +1617,7 @@ class TextInputBuilder(ComponentBuilder, abc.ABC, typing.Generic[_ContainerT]):
def custom_id(self) -> str:
"""Developer set custom ID used for identifying this text input.
- !!! note
+ .. note::
This custom_id is never used in component interaction events.
It is meant to be used purely for resolving components modal interactions.
"""
@@ -1839,7 +1806,7 @@ def add_component(
) -> _T:
"""Add a component to this action row builder.
- !!! warning
+ .. warning::
It is generally better to use `ActionRowBuilder.add_button`
and `ActionRowBuilder.add_select_menu` to add your
component to the builder. Those methods utilize this one.
@@ -1884,9 +1851,9 @@ def add_button(
Parameters
----------
- style : typing.Union[builtins.int, hikari.messages.ButtonStyle]
+ style : typing.Union[int, hikari.messages.ButtonStyle]
The button's style.
- url_or_custom_id : builtins.str
+ url_or_custom_id : str
For interactive button styles this is a developer-defined custom
identifier used to identify which button triggered component interactions.
@@ -1907,7 +1874,7 @@ def add_select_menu(self: _T, custom_id: str, /) -> SelectMenuBuilder[_T]:
Parameters
----------
- custom_id : builtins.str
+ custom_id : str
A developer-defined custom identifier used to identify which menu
triggered component interactions.
@@ -1938,7 +1905,7 @@ def add_component(
) -> _T:
"""Add a component to this action row builder.
- !!! warning
+ .. warning::
It is generally better to use `ActionRowBuilder.add_button`
and `ActionRowBuilder.add_select_menu` to add your
component to the builder. Those methods utilize this one.
diff --git a/hikari/api/voice.py b/hikari/api/voice.py
index e36d80fd53..d158ff5977 100644
--- a/hikari/api/voice.py
+++ b/hikari/api/voice.py
@@ -35,7 +35,9 @@
from hikari import guilds
from hikari import snowflakes
-_VoiceConnectionT = typing.TypeVar("_VoiceConnectionT", bound="VoiceConnection")
+ _T = typing.TypeVar("_T")
+
+ _VoiceConnectionT = typing.TypeVar("_VoiceConnectionT", bound="VoiceConnection")
class VoiceComponent(abc.ABC):
@@ -100,19 +102,19 @@ async def connect_to(
voice_connection_type : typing.Type[VoiceConnection]
The type of voice connection to use. This should be initialized
internally using the `VoiceConnection.initialize`
- `builtins.classmethod`.
- deaf : builtins.bool
- Defaulting to `builtins.False`, if `builtins.True`, the client will
+ `classmethod`.
+ deaf : bool
+ Defaulting to `False`, if `True`, the client will
enter the voice channel deafened (thus unable to hear other users).
- mute : builtins.bool
- Defaulting to `builtins.False`, if `builtins.True`, the client will
+ mute : bool
+ Defaulting to `False`, if `True`, the client will
enter the voice channel muted (thus unable to send audio).
- timeout: typing.Optional[builtins.int]
+ timeout : typing.Optional[int]
Defaulting to `5`, The amount of time to wait before erroring when
connecting to the voice channel. If timeout is `None` there will be
no timeout.
- !!! warning
+ .. warning::
If timeout is `None`, this function will be awaited forever if an
invalid `guild_id` or `channel_id` is provided.
@@ -120,7 +122,6 @@ async def connect_to(
Any arguments to provide to the `VoiceConnection.initialize`
method.
-
Returns
-------
VoiceConnection
@@ -145,9 +146,6 @@ class VoiceConnection(abc.ABC):
__slots__: typing.Sequence[str] = ()
- if typing.TYPE_CHECKING:
- _T = typing.TypeVar("_T")
-
@classmethod
@abc.abstractmethod
async def initialize(
@@ -181,12 +179,12 @@ async def initialize(
connection is unregistered from the voice component safely.
owner : VoiceComponent
The component that made this connection object.
- session_id : builtins.str
+ session_id : str
The voice session ID to use.
- shard_id : builtins.int
+ shard_id : int
The associated shard ID that the voice connection was generated
from.
- token : builtins.str
+ token : str
The voice token to use.
user_id : hikari.snowflakes.Snowflake
The user ID of the account that just joined the voice channel.
@@ -203,22 +201,22 @@ async def initialize(
@property
@abc.abstractmethod
def channel_id(self) -> snowflakes.Snowflake:
- """Return the ID of the voice channel this voice connection is in."""
+ """ID of the voice channel this voice connection is in."""
@property
@abc.abstractmethod
def guild_id(self) -> snowflakes.Snowflake:
- """Return the ID of the guild this voice connection is in."""
+ """ID of the guild this voice connection is in."""
@property
@abc.abstractmethod
def is_alive(self) -> bool:
- """Return `builtins.True` if the connection is alive."""
+ """Whether the connection is alive."""
@property
@abc.abstractmethod
def shard_id(self) -> int:
- """Return the ID of the shard that requested the connection."""
+ """ID of the shard that requested the connection."""
@property
@abc.abstractmethod
diff --git a/hikari/applications.py b/hikari/applications.py
index 7ac3d2e23c..50329802b8 100644
--- a/hikari/applications.py
+++ b/hikari/applications.py
@@ -111,31 +111,31 @@ class OAuth2Scope(str, enums.Enum):
ACTIVITIES_READ = "activities.read"
"""Enables fetching the "Now Playing/Recently Played" list.
- !!! note
+ .. note::
You must be whitelisted to use this scope.
"""
ACTIVITIES_WRITE = "activities.write"
"""Enables updating a user's activity.
- !!! note
+ .. note::
You must be whitelisted to use this scope.
- !!! note
+ .. note::
This is not required to use the GameSDK activity manager.
"""
APPLICATIONS_BUILDS_READ = "applications.builds.read"
"""Enables reading build data for a user's applications.
- !!! note
+ .. note::
You must be whitelisted to use this scope.
"""
APPLICATIONS_BUILDS_UPLOAD = "applications.builds.upload"
"""Enables uploading/updating builds for a user's applications.
- !!! note
+ .. note::
You must be whitelisted to use this scope.
"""
@@ -161,14 +161,14 @@ class OAuth2Scope(str, enums.Enum):
This includes store listings, achievements, SKU's, etc.
- !!! note
+ .. note::
The store API is deprecated and may be removed in the future.
"""
BOT = "bot"
"""Enables adding a bot application to a guild.
- !!! note
+ .. note::
This requires you to have set up a bot account for your application.
"""
@@ -181,7 +181,7 @@ class OAuth2Scope(str, enums.Enum):
GROUP_DM_JOIN = "gdm.join"
"""Enables joining users into a group DM.
- !!! warning
+ .. warning::
This cannot add the bot to a group DM.
"""
@@ -191,14 +191,14 @@ class OAuth2Scope(str, enums.Enum):
GUILDS_JOIN = "guilds.join"
"""Enables adding the user to a specific guild.
- !!! note
+ .. note::
This requires you to have set up a bot account for your application.
"""
IDENTIFY = "identify"
"""Enables viewing info about itself.
- !!! note
+ .. note::
This does not include email address info. Use the `EMAIL` scope instead
to retrieve this information.
"""
@@ -206,14 +206,14 @@ class OAuth2Scope(str, enums.Enum):
RELATIONSHIPS_READ = "relationships.read"
"""Enables viewing a user's friend list.
- !!! note
+ .. note::
You must be whitelisted to use this scope.
"""
RPC = "rpc"
"""Enables the RPC application to control the local user's Discord client.
- !!! note
+ .. note::
You must be whitelisted to use this scope.
"""
@@ -223,7 +223,7 @@ class OAuth2Scope(str, enums.Enum):
RPC_NOTIFICATIONS_READ = "rpc.notifications.read"
"""Enables the RPC application to read from all channels the user is in.
- !!! note
+ .. note::
You must be whitelisted to use this scope.
"""
@@ -259,7 +259,7 @@ class OwnConnection:
id: str = attr.field(hash=True, repr=True)
"""The string ID of the third party connected account.
- !!! warning
+ .. warning::
Seeing as this is a third party ID, it will not be a snowflakes.
"""
@@ -270,19 +270,19 @@ class OwnConnection:
"""The type of service this connection is for."""
is_revoked: bool = attr.field(eq=False, hash=False, repr=False)
- """`builtins.True` if the connection has been revoked."""
+ """`True` if the connection has been revoked."""
integrations: typing.Sequence[guilds.PartialIntegration] = attr.field(eq=False, hash=False, repr=False)
"""A sequence of the partial guild integration objects this connection has."""
is_verified: bool = attr.field(eq=False, hash=False, repr=False)
- """`builtins.True` if the connection has been verified."""
+ """`True` if the connection has been verified."""
is_friend_sync_enabled: bool = attr.field(eq=False, hash=False, repr=False)
- """`builtins.True` if friends should be added based on this connection."""
+ """`True` if friends should be added based on this connection."""
is_activity_visible: bool = attr.field(eq=False, hash=False, repr=False)
- """`builtins.True` if this connection's activities are shown in the user's presence."""
+ """`True` if this connection's activities are shown in the user's presence."""
visibility: typing.Union[ConnectionVisibility, int] = attr.field(eq=False, hash=False, repr=True)
"""The visibility of the connection."""
@@ -296,7 +296,7 @@ class OwnGuild(guilds.PartialGuild):
"""A list of the features in this guild."""
is_owner: bool = attr.field(eq=False, hash=False, repr=True)
- """`builtins.True` when the current user owns this guild."""
+ """`True` when the current user owns this guild."""
my_permissions: permissions_.Permissions = attr.field(eq=False, hash=False, repr=False)
"""The guild-level permissions that apply to the current user or bot."""
@@ -324,7 +324,7 @@ class TeamMember(users.User):
permissions: typing.Sequence[str] = attr.field(repr=False)
"""This member's permissions within a team.
- At the time of writing, this will always be a sequence of one `builtins.str`,
+ At the time of writing, this will always be a sequence of one `str`,
which will always be `"*"`. This may change in the future, however.
"""
@@ -409,7 +409,7 @@ class Team(snowflakes.Unique):
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
id: snowflakes.Snowflake = attr.field(hash=True, repr=True)
"""The ID of this entity."""
@@ -420,7 +420,7 @@ class Team(snowflakes.Unique):
icon_hash: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
"""The CDN hash of this team's icon.
- If no icon is provided, this will be `builtins.None`.
+ If no icon is provided, this will be `None`.
"""
members: typing.Mapping[snowflakes.Snowflake, TeamMember] = attr.field(eq=False, hash=False, repr=False)
@@ -438,13 +438,7 @@ def __str__(self) -> str:
@property
def icon_url(self) -> typing.Optional[files.URL]:
- """Team icon URL.
-
- Returns
- -------
- typing.Optional[hikari.files.URL]
- The URL, or `builtins.None` if no icon exists.
- """
+ """Icon URL, or `None` if no icon exists."""
return self.make_icon_url()
def make_icon_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
@@ -452,21 +446,21 @@ def make_icon_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optiona
Parameters
----------
- ext : builtins.str
+ ext : str
The extension to use for this URL, defaults to `png`.
Supports `png`, `jpeg`, `jpg` and `webp`.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`. Can be any power
of two between `16` and `4096` inclusive.
Returns
-------
typing.Optional[hikari.files.URL]
- The URL, or `builtins.None` if no icon exists.
+ The URL, or `None` if no icon exists.
Raises
------
- builtins.ValueError
+ ValueError
If the size is not an integer power of 2 between 16 and 4096
(inclusive).
"""
@@ -490,7 +484,7 @@ class InviteApplication(guilds.PartialApplication):
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
cover_image_hash: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
"""The CDN's hash of this application's default rich presence invite cover image."""
@@ -500,13 +494,7 @@ class InviteApplication(guilds.PartialApplication):
@property
def cover_image_url(self) -> typing.Optional[files.URL]:
- """Rich presence cover image URL for this application, if set.
-
- Returns
- -------
- typing.Optional[hikari.files.URL]
- The URL, or `builtins.None` if no cover image exists.
- """
+ """Rich presence cover image URL for this application, if set."""
return self.make_cover_image_url()
def make_cover_image_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
@@ -514,21 +502,21 @@ def make_cover_image_url(self, *, ext: str = "png", size: int = 4096) -> typing.
Parameters
----------
- ext : builtins.str
+ ext : str
The extension to use for this URL, defaults to `png`.
Supports `png`, `jpeg`, `jpg` and `webp`.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Returns
-------
typing.Optional[hikari.files.URL]
- The URL, or `builtins.None` if no cover image exists.
+ The URL, or `None` if no cover image exists.
Raises
------
- builtins.ValueError
+ ValueError
If the size is not an integer power of 2 between 16 and 4096
(inclusive).
"""
@@ -552,13 +540,13 @@ class Application(guilds.PartialApplication):
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
is_bot_public: bool = attr.field(eq=False, hash=False, repr=True)
- """`builtins.True` if the bot associated with this application is public."""
+ """`True` if the bot associated with this application is public."""
is_bot_code_grant_required: bool = attr.field(eq=False, hash=False, repr=False)
- """`builtins.True` if this application's bot is requiring code grant for invites."""
+ """`True` if this application's bot is requiring code grant for invites."""
owner: users.User = attr.field(eq=False, hash=False, repr=True)
"""The application's owner."""
@@ -575,7 +563,7 @@ class Application(guilds.PartialApplication):
team: typing.Optional[Team] = attr.field(eq=False, hash=False, repr=False)
"""The team this application belongs to.
- If the application is not part of a team, this will be `builtins.None`.
+ If the application is not part of a team, this will be `None`.
"""
cover_image_hash: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
@@ -589,13 +577,7 @@ class Application(guilds.PartialApplication):
@property
def cover_image_url(self) -> typing.Optional[files.URL]:
- """Rich presence cover image URL for this application, if set.
-
- Returns
- -------
- typing.Optional[hikari.files.URL]
- The URL, or `builtins.None` if no cover image exists.
- """
+ """Rich presence cover image URL for this application, if set."""
return self.make_cover_image_url()
def make_cover_image_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
@@ -603,21 +585,21 @@ def make_cover_image_url(self, *, ext: str = "png", size: int = 4096) -> typing.
Parameters
----------
- ext : builtins.str
+ ext : str
The extension to use for this URL, defaults to `png`.
Supports `png`, `jpeg`, `jpg` and `webp`.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Returns
-------
typing.Optional[hikari.files.URL]
- The URL, or `builtins.None` if no cover image exists.
+ The URL, or `None` if no cover image exists.
Raises
------
- builtins.ValueError
+ ValueError
If the size is not an integer power of 2 between 16 and 4096
(inclusive).
"""
@@ -642,15 +624,15 @@ class AuthorizationApplication(guilds.PartialApplication):
"""The key used for verifying interaction and GameSDK payload signatures."""
is_bot_public: typing.Optional[bool] = attr.field(eq=False, hash=False, repr=True)
- """`builtins.True` if the bot associated with this application is public.
+ """`True` if the bot associated with this application is public.
- Will be `builtins.None` if this application doesn't have an associated bot.
+ Will be `None` if this application doesn't have an associated bot.
"""
is_bot_code_grant_required: typing.Optional[bool] = attr.field(eq=False, hash=False, repr=False)
- """`builtins.True` if this application's bot is requiring code grant for invites.
+ """`True` if this application's bot is requiring code grant for invites.
- Will be `builtins.None` if this application doesn't have a bot.
+ Will be `None` if this application doesn't have a bot.
"""
terms_of_service_url: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
@@ -715,14 +697,14 @@ class OAuth2AuthorizationToken(PartialOAuth2Token):
"""Object of the webhook that was created.
This will only be present if this token was authorized with the
- `webhooks.incoming` scope, otherwise this will be `builtins.None`.
+ `webhooks.incoming` scope, otherwise this will be `None`.
"""
guild: typing.Optional[guilds.RESTGuild] = attr.field(eq=False, hash=False, repr=True)
"""Object of the guild the user was added to.
This will only be present if this token was authorized with the
- `bot` scope, otherwise this will be `builtins.None`.
+ `bot` scope, otherwise this will be `None`.
"""
@@ -759,7 +741,7 @@ def get_token_id(token: str) -> snowflakes.Snowflake:
Raises
------
- builtins.ValueError
+ ValueError
If the passed token has an unexpected format.
"""
try:
diff --git a/hikari/audit_logs.py b/hikari/audit_logs.py
index 5bc4bdb67f..2d001bcb53 100644
--- a/hikari/audit_logs.py
+++ b/hikari/audit_logs.py
@@ -140,7 +140,7 @@ class AuditLogChangeKey(str, enums.Enum):
REMOVE_ROLE_FROM_MEMBER = "$remove"
COLOUR = COLOR
- """Alias for "COLOR"""
+ """Alias for `COLOR`."""
@attr_extensions.with_copy
@@ -211,7 +211,7 @@ class BaseAuditLogEntryInfo(abc.ABC):
"""A base object that all audit log entry info objects will inherit from."""
app: traits.RESTAware = attr.field(repr=False, eq=False, metadata={attr_extensions.SKIP_DEEP_COPY: True})
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
@attr_extensions.with_copy
@@ -393,7 +393,7 @@ class MemberMoveEntryInfo(MemberDisconnectEntryInfo):
"""Extra information for the voice chat based member move entry."""
channel_id: snowflakes.Snowflake = attr.field(repr=True)
- """The channel that the member(s) have been moved to"""
+ """The channel that the member(s) have been moved to."""
async def fetch_channel(self) -> channels.GuildVoiceChannel:
"""Fetch the guild voice based channel where the member(s) have been moved to.
@@ -438,7 +438,7 @@ class AuditLogEntry(snowflakes.Unique):
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
id: snowflakes.Snowflake = attr.field(hash=True, repr=True)
"""The ID of this entity."""
diff --git a/hikari/banner.txt b/hikari/banner.txt
index 577f7b1920..d7de2238d6 100644
--- a/hikari/banner.txt
+++ b/hikari/banner.txt
@@ -1,6 +1,6 @@
${bold_red}oooo o8o oooo o8o ${reset}${bold_white} 光 ${hikari_version} ${thin_white}[${hikari_git_sha1}]${reset}
- ${red}`888 `"' `888 `"' ${reset}${bold_white}${hikari_copyright}${thin_white} - ${hikari_license} license${reset}
+ ${red}`888 `"' `888 `"' ${reset}${bold_white}© ${hikari_copyright}${thin_white} - ${hikari_license} license${reset}
${yellow} 888 .oo. oooo 888 oooo .oooo. oooo d8b oooo ${reset}${bold_white}interpreter: ${thin_white}${python_implementation} ${python_version}${reset}
${green} 888P"Y88b `888 888 .8P' `P )88b `888""8P `888 ${reset}${bold_white}running on: ${thin_white}${system_description}${reset}
${blue} 888 888 888 888888. .oP"888 888 888 ${reset}${bold_white}installed at: ${thin_white}${hikari_install_location}${reset}
diff --git a/hikari/channels.py b/hikari/channels.py
index 6ef00f332e..38bc3abb8f 100644
--- a/hikari/channels.py
+++ b/hikari/channels.py
@@ -143,31 +143,13 @@ class ChannelFollow:
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """Return the client application that models may use for procedures.
-
- Returns
- -------
- hikari.traits.RESTAware
- The REST-aware application object.
- """
+ """Client application that models may use for procedures."""
channel_id: snowflakes.Snowflake = attr.field(hash=True, repr=True)
- """Return the channel ID of the channel being followed.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The channel ID for the channel being followed.
- """
+ """Return the channel ID of the channel being followed."""
webhook_id: snowflakes.Snowflake = attr.field(hash=True, repr=True)
- """Return the ID of the webhook for this follow.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the webhook that was created for this follow.
- """
+ """Return the ID of the webhook for this follow."""
async def fetch_channel(self) -> typing.Union[GuildNewsChannel, GuildTextChannel]:
"""Fetch the object of the guild channel being followed.
@@ -175,9 +157,10 @@ async def fetch_channel(self) -> typing.Union[GuildNewsChannel, GuildTextChannel
Returns
-------
typing.Union[hikari.channels.GuildNewsChannel, hikari.channels.GuildTextChannel]
- The channel being followed. While this will usually be
- `GuildNewsChannel`, if the channel's news status has been removed
- then this will be a `GuildTextChannel`
+ The channel being followed.
+
+ While this will usually be `GuildNewsChannel`, if the channel's
+ news status has been removed then this will be a `GuildTextChannel`.
Raises
------
@@ -243,16 +226,16 @@ async def fetch_webhook(self) -> webhooks.ChannelFollowerWebhook:
def get_channel(self) -> typing.Union[GuildNewsChannel, GuildTextChannel, None]:
"""Get the channel being followed from the cache.
- !!! warning
- This will always be `builtins.None` if you are not
+ .. warning::
+ This will always be `None` if you are not
in the guild that this channel exists in.
Returns
-------
- typing.Union[hikari.channels.GuildNewsChannel, hikari.channels.GuildTextChannel, builtins.None]
+ typing.Union[hikari.channels.GuildNewsChannel, hikari.channels.GuildTextChannel, None]
The object of the guild channel that was found in the cache or
- `builtins.None`. While this will usually be `GuildNewsChannel` or
- `builtins.None`, if the channel referenced has since lost it's news
+ `None`. While this will usually be `GuildNewsChannel` or
+ `None`, if the channel referenced has since lost it's news
status then this will return a `GuildTextChannel`.
"""
if not isinstance(self.app, traits.CacheAware):
@@ -282,25 +265,25 @@ class PermissionOverwrite:
You may sometimes need to make instances of this object to add/edit
permission overwrites on channels.
- Example
- -------
+ Examples
+ --------
Creating a permission overwrite.
- ```py
- overwrite = PermissionOverwrite(
- id=163979124820541440,
- type=PermissionOverwriteType.MEMBER,
- allow=(
- Permissions.VIEW_CHANNEL
- | Permissions.READ_MESSAGE_HISTORY
- | Permissions.SEND_MESSAGES
- ),
- deny=(
- Permissions.MANAGE_MESSAGES
- | Permissions.SPEAK
- ),
- )
- ```
+ .. code-block:: python
+
+ overwrite = PermissionOverwrite(
+ id=163979124820541440,
+ type=PermissionOverwriteType.MEMBER,
+ allow=(
+ Permissions.VIEW_CHANNEL
+ | Permissions.READ_MESSAGE_HISTORY
+ | Permissions.SEND_MESSAGES
+ ),
+ deny=(
+ Permissions.MANAGE_MESSAGES
+ | Permissions.SPEAK
+ ),
+ )
"""
id: snowflakes.Snowflake = attr.field(converter=snowflakes.Snowflake, repr=True)
@@ -337,7 +320,7 @@ class PartialChannel(snowflakes.Unique):
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
id: snowflakes.Snowflake = attr.field(hash=True, repr=True)
"""The ID of this entity."""
@@ -352,14 +335,14 @@ class PartialChannel(snowflakes.Unique):
def mention(self) -> str:
"""Return a raw mention string for the channel.
- !!! note
+ .. note::
There are platform specific inconsistencies with mentions of
GuildCategories, GroupDMChannels and DMChannels showing
the correct name but not being interactable.
Returns
-------
- builtins.str
+ str
The mention string to use.
"""
return f"<#{self.id}>"
@@ -370,6 +353,10 @@ def __str__(self) -> str:
async def delete(self) -> PartialChannel:
"""Delete a channel in a guild, or close a DM.
+ .. note::
+ For Public servers, the set 'Rules' or 'Guidelines' channels and the
+ 'Public Server Updates' channel cannot be deleted.
+
Returns
-------
hikari.channels.PartialChannel
@@ -396,10 +383,6 @@ async def delete(self) -> PartialChannel:
nature, and will trigger this exception if they occur.
hikari.errors.InternalServerError
If an internal error occurs on Discord while handling the request.
-
- !!! note
- For Public servers, the set 'Rules' or 'Guidelines' channels and the
- 'Public Server Updates' channel cannot be deleted.
"""
return await self.app.rest.delete_channel(self.id)
@@ -420,6 +403,12 @@ def fetch_history(
) -> iterators.LazyIterator[messages.Message]:
"""Browse the message history for a given text channel.
+ .. note::
+ This call is not a coroutine function, it returns a special type of
+ lazy iterator that will perform API calls as you iterate across it,
+ thus any errors documented below will happen then.
+ See `hikari.iterators` for the full API for this iterator type.
+
Other Parameters
----------------
before : hikari.undefined.UndefinedOr[snowflakes.SearchableSnowflakeishOr[hikari.snowflakes.Unique]]
@@ -445,7 +434,7 @@ def fetch_history(
Raises
------
- builtins.TypeError
+ TypeError
If you specify more than one of `before`, `after`, `about`.
hikari.errors.UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
@@ -456,12 +445,6 @@ def fetch_history(
If the channel is not found.
hikari.errors.InternalServerError
If an internal error occurs on Discord while handling the request.
-
- !!! note
- The exceptions on this endpoint (other than `builtins.TypeError`) will only
- be raised once the result is awaited or interacted with. Invoking
- this function itself will not raise anything (other than
- `builtins.TypeError`).
"""
return self.app.rest.fetch_messages(self.id, before=before, after=after, around=around)
@@ -534,7 +517,7 @@ async def send(
If provided, the message contents. If
`hikari.undefined.UNDEFINED`, then nothing will be sent
in the content. Any other value here will be cast to a
- `builtins.str`.
+ `str`.
If this is a `hikari.embeds.Embed` and no `embed` nor `embeds` kwarg
is provided, then this will instead update the embed. This allows
@@ -549,6 +532,32 @@ async def send(
attachment : hikari.undefined.UndefinedOr[hikari.files.Resourceish]
If provided, the message attachment. This can be a resource,
or string of a path on your computer or a URL.
+
+ Attachments can be passed as many different things, to aid in
+ convenience.
+
+ - If a `pathlib.PurePath` or `str` to a valid URL, the
+ resource at the given URL will be streamed to Discord when
+ sending the message. Subclasses of
+ `hikari.files.WebResource` such as
+ `hikari.files.URL`,
+ `hikari.messages.Attachment`,
+ `hikari.emojis.Emoji`,
+ `EmbedResource`, etc will also be uploaded this way.
+ This will use bit-inception, so only a small percentage of the
+ resource will remain in memory at any one time, thus aiding in
+ scalability.
+ - If a `hikari.files.Bytes` is passed, or a `str`
+ that contains a valid data URI is passed, then this is uploaded
+ with a randomized file name if not provided.
+ - If a `hikari.files.File`, `pathlib.PurePath` or
+ `str` that is an absolute or relative path to a file
+ on your file system is passed, then this resource is uploaded
+ as an attachment using non-blocking code internally and streamed
+ using bit-inception where possible. This depends on the
+ type of `concurrent.futures.Executor` that is being used for
+ the application (default is a thread pool which supports this
+ behaviour).
attachments : hikari.undefined.UndefinedOr[typing.Sequence[hikari.files.Resourceish]]
If provided, the message attachments. These can be resources, or
strings consisting of paths on your computer or URLs.
@@ -561,28 +570,28 @@ async def send(
If provided, the message embed.
embeds : hikari.undefined.UndefinedOr[typing.Sequence[hikari.embeds.Embed]]
If provided, the message embeds.
- tts : hikari.undefined.UndefinedOr[builtins.bool]
+ tts : hikari.undefined.UndefinedOr[bool]
If provided, whether the message will be TTS (Text To Speech).
reply : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage]]
If provided, the message to reply to.
- mentions_everyone : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_everyone : hikari.undefined.UndefinedOr[bool]
If provided, whether the message should parse @everyone/@here
mentions.
- mentions_reply : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_reply : hikari.undefined.UndefinedOr[bool]
If provided, whether to mention the author of the message
that is being replied to.
This will not do anything if not being used with `reply`.
- user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
- If provided, and `builtins.True`, all mentions will be parsed.
- If provided, and `builtins.False`, no mentions will be parsed.
+ user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], bool]]
+ If provided, and `True`, all mentions will be parsed.
+ If provided, and `False`, no mentions will be parsed.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.users.PartialUser` derivatives to enforce mentioning
specific users.
- role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], builtins.bool]]
- If provided, and `builtins.True`, all mentions will be parsed.
- If provided, and `builtins.False`, no mentions will be parsed.
+ role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], bool]]
+ If provided, and `True`, all mentions will be parsed.
+ If provided, and `False`, no mentions will be parsed.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.guilds.PartialRole` derivatives to enforce mentioning
@@ -594,33 +603,6 @@ async def send(
Note that some flags may not be able to be set. Currently the only
flags that can be set are `NONE` and `SUPPRESS_EMBEDS`.
- !!! note
- Attachments can be passed as many different things, to aid in
- convenience.
-
- - If a `pathlib.PurePath` or `builtins.str` to a valid URL, the
- resource at the given URL will be streamed to Discord when
- sending the message. Subclasses of
- `hikari.files.WebResource` such as
- `hikari.files.URL`,
- `hikari.messages.Attachment`,
- `hikari.emojis.Emoji`,
- `EmbedResource`, etc will also be uploaded this way.
- This will use bit-inception, so only a small percentage of the
- resource will remain in memory at any one time, thus aiding in
- scalability.
- - If a `hikari.files.Bytes` is passed, or a `builtins.str`
- that contains a valid data URI is passed, then this is uploaded
- with a randomized file name if not provided.
- - If a `hikari.files.File`, `pathlib.PurePath` or
- `builtins.str` that is an absolute or relative path to a file
- on your file system is passed, then this resource is uploaded
- as an attachment using non-blocking code internally and streamed
- using bit-inception where possible. This depends on the
- type of `concurrent.futures.Executor` that is being used for
- the application (default is a thread pool which supports this
- behaviour).
-
Returns
-------
hikari.messages.Message
@@ -643,10 +625,10 @@ async def send(
If the channel is not found.
hikari.errors.InternalServerError
If an internal error occurs on Discord while handling the request.
- builtins.ValueError
+ ValueError
If more than 100 unique objects/entities are passed for
`role_mentions` or `user_mentions`.
- builtins.TypeError
+ TypeError
If both `attachment` and `attachments` are specified.
""" # noqa: E501 - Line too long
return await self.app.rest.create_message(
@@ -670,18 +652,18 @@ async def send(
def trigger_typing(self) -> special_endpoints.TypingIndicator:
"""Trigger typing in a given channel.
- This returns an object that can either be `await`ed to trigger typing
+ This returns an object that can either be awaited to trigger typing
once, or used as an async context manager to keep typing until the
block completes.
- ```py
- await channel.trigger_typing() # type for 10s
+ .. code-block:: python
- async with channel.trigger_typing():
- await asyncio.sleep(35) # keep typing until this finishes
- ```
+ await channel.trigger_typing() # type for 10s
- !!! note
+ async with channel.trigger_typing():
+ await asyncio.sleep(35) # keep typing until this finishes
+
+ .. note::
Sending a message to this channel will stop the typing indicator. If
using an `async with`, it will start up again after a few seconds.
This is a limitation of Discord's API.
@@ -804,18 +786,7 @@ async def delete_messages(
) -> None:
"""Bulk-delete messages from the channel.
- Parameters
- ----------
- messages : typing.Union[hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage], hikari.snowflakes.SnowflakeishIterable[hikari.messages.PartialMessage]]
- Either the object/ID of an existing message to delete or an iterable
- of the objects and/or IDs of existing messages to delete.
-
- Other Parameters
- ----------------
- *other_messages : hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage]
- The objects and/or IDs of other existing messages to delete.
-
- !!! note
+ .. note::
This API endpoint will only be able to delete 100 messages
at a time. For anything more than this, multiple requests will
be executed one-after-the-other, since the rate limits for this
@@ -827,21 +798,32 @@ async def delete_messages(
of this is that the `delete_message` endpoint is ratelimited
by a different bucket with different usage rates.
- !!! warning
+ .. warning::
This endpoint is not atomic. If an error occurs midway through
a bulk delete, you will **not** be able to revert any changes made
up to this point.
- !!! warning
+ .. warning::
Specifying any messages more than 14 days old will cause the call
to fail, potentially with partial completion.
+ Parameters
+ ----------
+ messages : typing.Union[hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage], hikari.snowflakes.SnowflakeishIterable[hikari.messages.PartialMessage]]
+ Either the object/ID of an existing message to delete or an iterable
+ of the objects and/or IDs of existing messages to delete.
+
+ Other Parameters
+ ----------------
+ *other_messages : hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage]
+ The objects and/or IDs of other existing messages to delete.
+
Raises
------
hikari.errors.BulkDeleteError
An error containing the messages successfully deleted, and the
messages that were not removed. The
- `builtins.BaseException.__cause__` of the exception will be the
+ `BaseException.__cause__` of the exception will be the
original error that terminated this process.
""" # noqa: E501 - Line too long
return await self.app.rest.delete_messages(self.id, messages, *other_messages)
@@ -854,7 +836,7 @@ class PrivateChannel(PartialChannel):
last_message_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=False)
"""The ID of the last message sent in this channel.
- !!! warning
+ .. warning::
This might point to an invalid or deleted message. Do not assume that
this will always be valid.
"""
@@ -880,7 +862,7 @@ def __str__(self) -> str:
class GroupDMChannel(PrivateChannel):
"""Represents a group direct message channel.
- !!! note
+ .. note::
This doesn't have the methods found on `TextableChannel` as bots cannot
interact with a group DM that they own by sending or seeing messages in
it.
@@ -901,7 +883,7 @@ class GroupDMChannel(PrivateChannel):
application_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=False)
"""The ID of the application that created the group DM.
- If the group DM was not created by a bot, this will be `builtins.None`.
+ If the group DM was not created by a bot, this will be `None`.
"""
def __str__(self) -> str:
@@ -920,21 +902,21 @@ def make_icon_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optiona
Parameters
----------
- ext : builtins.str
+ ext : str
The extension to use for this URL, defaults to `png`.
Supports `png`, `jpeg`, `jpg` and `webp`.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Returns
-------
typing.Optional[hikari.files.URL]
- The URL, or `builtins.None` if no icon is present.
+ The URL, or `None` if no icon is present.
Raises
------
- builtins.ValueError
+ ValueError
If `size` is not a power of two between 16 and 4096 (inclusive).
"""
if self.icon_hash is None:
@@ -961,15 +943,15 @@ class GuildChannel(PartialChannel):
For thread channels this will refer to the parent textable guild channel.
For other guild channel types this will refer to the parent category and
- if no parent category is set for the channel, this will be `builtins.None`.
- For guild categories this will always be `builtins.None`.
+ if no parent category is set for the channel, this will be `None`.
+ For guild categories this will always be `None`.
"""
@property
def shard_id(self) -> typing.Optional[int]:
"""Return the shard ID for the shard.
- This may be `builtins.None` if the shard count is not known.
+ This may be `None` if the shard count is not known.
"""
if isinstance(self.app, traits.ShardAware):
return snowflakes.calculate_shard_id(self.app, self.guild_id)
@@ -982,7 +964,7 @@ def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
Returns
-------
typing.Optional[hikari.guilds.Guild]
- The linked guild object or `builtins.None` if it's not cached.
+ The linked guild object or `None` if it's not cached.
"""
if not isinstance(self.app, traits.CacheAware):
return None
@@ -1042,25 +1024,25 @@ async def edit(
Other Parameters
----------------
- name : hikari.undefined.UndefinedOr[[builtins.str]
+ name : hikari.undefined.UndefinedOr[[str]
If provided, the new name for the channel.
- position : hikari.undefined.UndefinedOr[[builtins.int]
+ position : hikari.undefined.UndefinedOr[[int]
If provided, the new position for the channel.
- topic : hikari.undefined.UndefinedOr[builtins.str]
+ topic : hikari.undefined.UndefinedOr[str]
If provided, the new topic for the channel.
- nsfw : hikari.undefined.UndefinedOr[builtins.bool]
+ nsfw : hikari.undefined.UndefinedOr[bool]
If provided, whether the channel should be marked as NSFW or not.
- bitrate : hikari.undefined.UndefinedOr[builtins.int]
+ bitrate : hikari.undefined.UndefinedOr[int]
If provided, the new bitrate for the channel.
- video_quality_mode: hikari.undefined.UndefinedOr[typing.Union[hikari.channels.VideoQualityMode, builtins.int]]
+ video_quality_mode: hikari.undefined.UndefinedOr[typing.Union[hikari.channels.VideoQualityMode, int]]
If provided, the new video quality mode for the channel.
- user_limit : hikari.undefined.UndefinedOr[builtins.int]
+ user_limit : hikari.undefined.UndefinedOr[int]
If provided, the new user limit in the channel.
rate_limit_per_user : hikari.undefined.UndefinedOr[hikari.internal.time.Intervalish]
If provided, the new rate limit per user in the channel.
- region : hikari.undefined.UndefinedOr[typing.Union[hikari.voices.VoiceRegion, builtins.str]]
+ region : hikari.undefined.UndefinedOr[typing.Union[hikari.voices.VoiceRegion, str]]
If provided, the voice region to set for this channel. Passing
- `builtins.None` here will set it to "auto" mode where the used
+ `None` here will set it to "auto" mode where the used
region will be decided based on the first person who connects to it
when it's empty.
permission_overwrites : hikari.undefined.UndefinedOr[typing.Sequence[hikari.channels.PermissionOverwrite]]
@@ -1073,7 +1055,7 @@ async def edit(
This should be either 60, 1440, 4320 or 10080 seconds and, as of
writing.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -1128,7 +1110,7 @@ async def edit(
class PermissibleGuildChannel(GuildChannel):
"""Base class for all guild channels which have permission overwrites.
- !!! note
+ .. note::
This doesn't apply to thread channels as they implicitly inherit
permissions from their parent channel.
"""
@@ -1178,13 +1160,13 @@ async def edit_overwrite(
If provided, the new value of all allowed permissions.
deny : hikari.undefined.UndefinedOr[hikari.permissions.Permissions]
If provided, the new value of all disallowed permissions.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
Raises
------
- builtins.TypeError
+ TypeError
If `target_type` is unset and we were unable to determine the type
from `target`.
hikari.errors.BadRequestError
@@ -1274,7 +1256,7 @@ class GuildCategory(PermissibleGuildChannel):
parent_id: None = attr.field(eq=False, hash=False, repr=True)
"""The ID of the parent channel the channel belongs to.
- This is always `builtins.None` for categories.
+ This is always `None` for categories.
"""
@@ -1288,7 +1270,7 @@ class GuildTextChannel(PermissibleGuildChannel, TextableGuildChannel):
last_message_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=False)
"""The ID of the last message sent in this channel.
- !!! warning
+ .. warning::
This might point to an invalid or deleted message. Do not assume that
this will always be valid.
"""
@@ -1298,7 +1280,7 @@ class GuildTextChannel(PermissibleGuildChannel, TextableGuildChannel):
If there is no rate limit, this will be 0 seconds.
- !!! note
+ .. note::
Any user that has permissions allowing `MANAGE_MESSAGES`,
`MANAGE_CHANNEL`, `ADMINISTRATOR` will not be limited. Likewise, bots
will not be affected by this rate limit.
@@ -1307,8 +1289,8 @@ class GuildTextChannel(PermissibleGuildChannel, TextableGuildChannel):
last_pin_timestamp: typing.Optional[datetime.datetime] = attr.field(eq=False, hash=False, repr=False)
"""The timestamp of the last-pinned message.
- !!! note
- This may be `builtins.None` in several cases; Discord does not document what
+ .. note::
+ This may be `None` in several cases; Discord does not document what
these cases are. Trust no one!
"""
@@ -1329,7 +1311,7 @@ class GuildNewsChannel(PermissibleGuildChannel, TextableGuildChannel):
last_message_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=False)
"""The ID of the last message sent in this channel.
- !!! warning
+ .. warning::
This might point to an invalid or deleted message. Do not assume that
this will always be valid.
"""
@@ -1337,8 +1319,8 @@ class GuildNewsChannel(PermissibleGuildChannel, TextableGuildChannel):
last_pin_timestamp: typing.Optional[datetime.datetime] = attr.field(eq=False, hash=False, repr=False)
"""The timestamp of the last-pinned message.
- !!! note
- This may be `builtins.None` in several cases; Discord does not document what
+ .. note::
+ This may be `None` in several cases; Discord does not document what
these cases are. Trust no one!
"""
@@ -1359,7 +1341,7 @@ class GuildVoiceChannel(PermissibleGuildChannel, TextableGuildChannel):
region: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
"""ID of the voice region for this voice channel.
- If set to `builtins.None` then this is set to "auto" mode where the used
+ If set to `None` then this is set to "auto" mode where the used
region will be decided based on the first person who connects to it when
it's empty.
"""
@@ -1376,7 +1358,7 @@ class GuildVoiceChannel(PermissibleGuildChannel, TextableGuildChannel):
last_message_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=False)
"""The ID of the last message sent in this channel.
- !!! warning
+ .. warning::
This might point to an invalid or deleted message. Do not assume that
this will always be valid.
"""
@@ -1392,7 +1374,7 @@ class GuildStageChannel(PermissibleGuildChannel):
region: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
"""ID of the voice region for this stage channel.
- If set to `builtins.None` then this is set to "auto" mode where the used
+ If set to `None` then this is set to "auto" mode where the used
region will be decided based on the first person who connects to it when
it's empty.
"""
@@ -1436,8 +1418,8 @@ class ThreadMember:
user_id: snowflakes.Snowflake = attr.field(eq=True, repr=True)
"""The member's user ID.
- !!! note
- This will only ever be `builtins.None` on thread members attached to
+ .. note::
+ This will only ever be `None` on thread members attached to
guild create events, where this is the current bot's user.
"""
@@ -1447,7 +1429,7 @@ class ThreadMember:
flags: int = attr.field(eq=True, repr=True)
"""Bitfield flag of the user's settings for the thread.
- !!! note
+ .. note::
As of writing, the values of this field's are undocumented.
"""
@@ -1459,7 +1441,7 @@ class GuildThreadChannel(TextableGuildChannel):
last_message_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=False)
"""The ID of the last message sent in this channel.
- !!! warning
+ .. warning::
This might point to an invalid or deleted message. Do not assume that
this will always be valid.
"""
@@ -1467,8 +1449,8 @@ class GuildThreadChannel(TextableGuildChannel):
last_pin_timestamp: typing.Optional[datetime.datetime] = attr.field(eq=False, hash=False, repr=False)
"""The timestamp of the last-pinned message.
- !!! note
- This may be `builtins.None` in several cases; Discord does not document what
+ .. note::
+ This may be `None` in several cases; Discord does not document what
these cases are. Trust no one!
"""
@@ -1477,7 +1459,7 @@ class GuildThreadChannel(TextableGuildChannel):
If there is no rate limit, this will be 0 seconds.
- !!! note
+ .. note::
Any user that has permissions allowing `MANAGE_MESSAGES`,
`MANAGE_CHANNEL`, `ADMINISTRATOR` will not be limited. Likewise, bots
will not be affected by this rate limit.
@@ -1486,14 +1468,14 @@ class GuildThreadChannel(TextableGuildChannel):
approximate_message_count: int = attr.field(eq=False, hash=False, repr=True)
"""Approximate number of messages in the thread channel.
- !!! warning
+ .. warning::
This stops counting at 50 for threads created before 2022/06/01.
"""
approximate_member_count: int = attr.field(eq=False, hash=False, repr=True)
"""Approximate count of members in the thread channel.
- !!! warning
+ .. warning::
This stop counting at 50.
"""
@@ -1509,7 +1491,7 @@ class GuildThreadChannel(TextableGuildChannel):
archive_timestamp: datetime.datetime = attr.field(eq=False, hash=False, repr=True)
"""When the thread's archived state was last changed.
- !!! note
+ .. note::
If the thread has never been archived then this will be the thread's
creation date and this will be changed when a thread is unarchived.
"""
@@ -1524,7 +1506,7 @@ class GuildThreadChannel(TextableGuildChannel):
member: typing.Optional[ThreadMember] = attr.field(eq=False, hash=False, repr=True)
"""Thread member object for the current user, if they are in the thread.
- !!! note
+ .. note::
This is only returned by some endpoints and on private thread
access events.
"""
diff --git a/hikari/colors.py b/hikari/colors.py
index 7ef7b49859..e566b4efd0 100644
--- a/hikari/colors.py
+++ b/hikari/colors.py
@@ -66,7 +66,7 @@ class Color(int):
This value is immutable.
- This is a specialization of `builtins.int` which provides alternative overrides for
+ This is a specialization of `int` which provides alternative overrides for
common methods and color system conversions.
This currently supports:
@@ -82,80 +82,80 @@ class Color(int):
--------
Examples of conversions to given formats include:
- ```py
- >>> c = Color(0xFF051A)
- Color(r=0xff, g=0x5, b=0x1a)
+ .. code-block:: python
- >>> hex(c)
- 0xff051a
+ >>> c = Color(0xFF051A)
+ Color(r=0xff, g=0x5, b=0x1a)
+
+ >>> hex(c)
+ 0xff051a
- >>> c.hex_code
- #FF051A
+ >>> c.hex_code
+ #FF051A
- >>> str(c)
- #FF051A
+ >>> str(c)
+ #FF051A
- >>> int(c)
- 16712986
+ >>> int(c)
+ 16712986
- >>> c.rgb
- (255, 5, 26)
+ >>> c.rgb
+ (255, 5, 26)
- >>> c.rgb_float
- (1.0, 0.0196078431372549, 0.10196078431372549)
- ```
+ >>> c.rgb_float
+ (1.0, 0.0196078431372549, 0.10196078431372549)
Alternatively, if you have an arbitrary input in one of the above formats
that you wish to become a color, you can use `Color.of` on the class itself
to automatically attempt to resolve the color:
- ```py
- >>> Color.of(0xFF051A)
- Color(r=0xff, g=0x5, b=0x1a)
+ .. code-block:: python
- >>> Color.of(16712986)
- Color(r=0xff, g=0x5, b=0x1a)
+ >>> Color.of(0xFF051A)
+ Color(r=0xff, g=0x5, b=0x1a)
- >>> c = Color.of((255, 5, 26))
- Color(r=0xff, g=0x5, b=1xa)
+ >>> Color.of(16712986)
+ Color(r=0xff, g=0x5, b=0x1a)
- >>> c = Color.of(255, 5, 26)
- Color(r=0xff, g=0x5, b=1xa)
+ >>> c = Color.of((255, 5, 26))
+ Color(r=0xff, g=0x5, b=1xa)
- >>> c = Color.of([0xFF, 0x5, 0x1a])
- Color(r=0xff, g=0x5, b=1xa)
+ >>> c = Color.of(255, 5, 26)
+ Color(r=0xff, g=0x5, b=1xa)
- >>> c = Color.of("#1a2b3c")
- Color(r=0x1a, g=0x2b, b=0x3c)
+ >>> c = Color.of([0xFF, 0x5, 0x1a])
+ Color(r=0xff, g=0x5, b=1xa)
- >>> c = Color.of("#1AB")
- Color(r=0x11, g=0xaa, b=0xbb)
+ >>> c = Color.of("#1a2b3c")
+ Color(r=0x1a, g=0x2b, b=0x3c)
- >>> c = Color.of((1.0, 0.0196078431372549, 0.10196078431372549))
- Color(r=0xff, g=0x5, b=0x1a)
+ >>> c = Color.of("#1AB")
+ Color(r=0x11, g=0xaa, b=0xbb)
- >>> c = Color.of([1.0, 0.0196078431372549, 0.10196078431372549])
- Color(r=0xff, g=0x5, b=0x1a)
- ```
+ >>> c = Color.of((1.0, 0.0196078431372549, 0.10196078431372549))
+ Color(r=0xff, g=0x5, b=0x1a)
+
+ >>> c = Color.of([1.0, 0.0196078431372549, 0.10196078431372549])
+ Color(r=0xff, g=0x5, b=0x1a)
Examples of initialization of Color objects from given formats include:
- ```py
- >>> c = Color(16712986)
- Color(r=0xff, g=0x5, b=0x1a)
+ .. code-block:: python
+
+ >>> c = Color(16712986)
+ Color(r=0xff, g=0x5, b=0x1a)
- >>> c = Color.from_rgb(255, 5, 26)
- Color(r=0xff, g=0x5, b=1xa)
+ >>> c = Color.from_rgb(255, 5, 26)
+ Color(r=0xff, g=0x5, b=1xa)
- >>> c = Color.from_hex_code("#1a2b3c")
- Color(r=0x1a, g=0x2b, b=0x3c)
+ >>> c = Color.from_hex_code("#1a2b3c")
+ Color(r=0x1a, g=0x2b, b=0x3c)
- >>> c = Color.from_hex_code("#1AB")
- Color(r=0x11, g=0xaa, b=0xbb)
+ >>> c = Color.from_hex_code("#1AB")
+ Color(r=0x11, g=0xaa, b=0xbb)
- >>> c = Color.from_rgb_float(1.0, 0.0196078431372549, 0.10196078431372549)
- Color(r=0xff, g=0x5, b=0x1a)
- ```
+ >>> c = Color.from_rgb_float(1.0, 0.0196078431372549, 0.10196078431372549)
+ Color(r=0xff, g=0x5, b=0x1a)
"""
__slots__: typing.Sequence[str] = ()
@@ -163,7 +163,7 @@ class Color(int):
def __init__(self, raw_rgb: typing.SupportsInt) -> None:
if not (0 <= int(raw_rgb) <= 0xFFFFFF):
raise ValueError(f"raw_rgb must be in the exclusive range of 0 and {0xFF_FF_FF}")
- # The __new__ for `builtins.int` initializes the value for us, this super-call does nothing other
+ # The __new__ for `int` initializes the value for us, this super-call does nothing other
# than keeping the linter happy.
super().__init__()
@@ -181,8 +181,8 @@ def rgb(self) -> typing.Tuple[int, int, int]:
Represented as a tuple of R, G, B. Each value is
in the range [0, 0xFF].
- Example
- -------
+ Examples
+ --------
`(123, 234, 47)`
""" # noqa: D401 - Imperative mood
return (self >> 16) & 0xFF, (self >> 8) & 0xFF, self & 0xFF
@@ -193,8 +193,8 @@ def rgb_float(self) -> typing.Tuple[float, float, float]:
Represented as a tuple of R, G, B. Each value is in the range [0, 1].
- Example
- -------
+ Examples
+ --------
`(0.1, 0.2, 0.76)`
"""
r, g, b = self.rgb
@@ -206,8 +206,8 @@ def hex_code(self) -> str:
This is prepended with a `#` symbol, and will be in upper case.
- Example
- -------
+ Examples
+ --------
`#1A2B3C`
"""
return "#" + self.raw_hex_code
@@ -216,8 +216,8 @@ def hex_code(self) -> str:
def raw_hex_code(self) -> str:
"""Raw hex code.
- Example
- -------
+ Examples
+ --------
`1A2B3C`
"""
components = self.rgb
@@ -225,7 +225,7 @@ def raw_hex_code(self) -> str:
@property
def is_web_safe(self) -> bool:
- """`builtins.True` if the color is web safe, `builtins.False` otherwise."""
+ """Whether this color is web safe."""
return not (((self & 0xFF0000) % 0x110000) or ((self & 0xFF00) % 0x1100) or ((self & 0xFF) % 0x11))
@classmethod
@@ -236,11 +236,11 @@ def from_rgb(cls, red: int, green: int, blue: int, /) -> Color:
Parameters
----------
- red : builtins.int
+ red : int
Red channel.
- green : builtins.int
+ green : int
Green channel.
- blue : builtins.int
+ blue : int
Blue channel.
Returns
@@ -250,7 +250,7 @@ def from_rgb(cls, red: int, green: int, blue: int, /) -> Color:
Raises
------
- builtins.ValueError
+ ValueError
If red, green, or blue are outside the range [0x0, 0xFF].
"""
if not 0 <= red <= 0xFF:
@@ -270,11 +270,11 @@ def from_rgb_float(cls, red: float, green: float, blue: float, /) -> Color:
Parameters
----------
- red : builtins.float
+ red : float
Red channel.
- green : builtins.float
+ green : float
Green channel.
- blue : builtins.float
+ blue : float
Blue channel.
Returns
@@ -284,7 +284,7 @@ def from_rgb_float(cls, red: float, green: float, blue: float, /) -> Color:
Raises
------
- builtins.ValueError
+ ValueError
If red, green or blue are outside the range [0, 1].
"""
if not 0 <= red <= 1:
@@ -305,7 +305,7 @@ def from_hex_code(cls, hex_code: str, /) -> Color:
Parameters
----------
- hex_code : builtins.str
+ hex_code : str
A hexadecimal color code to parse. This may optionally start with
a case insensitive `0x` or `#`.
@@ -316,7 +316,7 @@ def from_hex_code(cls, hex_code: str, /) -> Color:
Raises
------
- builtins.ValueError
+ ValueError
If `hex_code` is not a hexadecimal or is a invalid length.
"""
if hex_code.startswith("#"):
@@ -369,31 +369,31 @@ def from_tuple_string(cls, tuple_str: str, /) -> Color:
Examples
--------
- ```py
- # Floats
- "1.0 1.0 1.0"
- "(1.0 1.0 1.0)"
- "[1.0 1.0 1.0]"
- "{1.0 1.0 1.0}"
- "1.0, 1.0, 1.0"
- "(1.0, 1.0, 1.0)"
- "[1.0, 1.0, 1.0]"
- "{1.0, 1.0, 1.0}"
-
- # Ints
- "252 252 252"
- "(252 252 252)"
- "[252 252 252]"
- "{252 252 252}"
- "252, 252, 252"
- "(252, 252, 252)"
- "[252, 252, 252]"
- "{252, 252, 252}"
- ```
+ .. code-block:: python
+
+ # Floats
+ "1.0 1.0 1.0"
+ "(1.0 1.0 1.0)"
+ "[1.0 1.0 1.0]"
+ "{1.0 1.0 1.0}"
+ "1.0, 1.0, 1.0"
+ "(1.0, 1.0, 1.0)"
+ "[1.0, 1.0, 1.0]"
+ "{1.0, 1.0, 1.0}"
+
+ # Ints
+ "252 252 252"
+ "(252 252 252)"
+ "[252 252 252]"
+ "{252 252 252}"
+ "252, 252, 252"
+ "(252, 252, 252)"
+ "[252, 252, 252]"
+ "{252, 252, 252}"
Parameters
----------
- tuple_str : builtins.str
+ tuple_str : str
The string to parse.
Returns
@@ -437,43 +437,43 @@ def of(cls, value: Colorish, /) -> Color:
Examples
--------
- ```py
- >>> Color.of(0xFF051A)
- Color(r=0xff, g=0x5, b=0x1a)
+ .. code-block:: python
- >>> Color.of(16712986)
- Color(r=0xff, g=0x5, b=0x1a)
+ >>> Color.of(0xFF051A)
+ Color(r=0xff, g=0x5, b=0x1a)
- >>> c = Color.of((255, 5, 26))
- Color(r=0xff, g=0x5, b=1xa)
+ >>> Color.of(16712986)
+ Color(r=0xff, g=0x5, b=0x1a)
- >>> c = Color.of([0xFF, 0x5, 0x1a])
- Color(r=0xff, g=0x5, b=1xa)
+ >>> c = Color.of((255, 5, 26))
+ Color(r=0xff, g=0x5, b=1xa)
- >>> c = Color.of("#1a2b3c")
- Color(r=0x1a, g=0x2b, b=0x3c)
+ >>> c = Color.of([0xFF, 0x5, 0x1a])
+ Color(r=0xff, g=0x5, b=1xa)
- >>> c = Color.of("#1AB")
- Color(r=0x11, g=0xaa, b=0xbb)
+ >>> c = Color.of("#1a2b3c")
+ Color(r=0x1a, g=0x2b, b=0x3c)
- >>> c = Color.of((1.0, 0.0196078431372549, 0.10196078431372549))
- Color(r=0xff, g=0x5, b=0x1a)
+ >>> c = Color.of("#1AB")
+ Color(r=0x11, g=0xaa, b=0xbb)
- >>> c = Color.of([1.0, 0.0196078431372549, 0.10196078431372549])
- Color(r=0xff, g=0x5, b=0x1a)
+ >>> c = Color.of((1.0, 0.0196078431372549, 0.10196078431372549))
+ Color(r=0xff, g=0x5, b=0x1a)
+
+ >>> c = Color.of([1.0, 0.0196078431372549, 0.10196078431372549])
+ Color(r=0xff, g=0x5, b=0x1a)
- # Commas and brackets are optional, whitespace is ignored, and these
- # are compatible with all-ints between 0-255 or all-floats between
- # 0.0 and 1.0 only.
- >>> c = Color.of("5, 22, 33")
- Color(r=0x5, g=0x16, b=0x21)
- >>> c = Color.of("(5, 22, 33)")
- Color(r=0x5, g=0x16, b=0x21)
- >>> c = Color.of("[5, 22, 33]")
- Color(r=0x5, g=0x16, b=0x21)
- >>> c = Color.of("{5, 22, 33}")
- Color(r=0x5, g=0x16, b=0x21)
- ```
+ # Commas and brackets are optional, whitespace is ignored, and these
+ # are compatible with all-ints between 0-255 or all-floats between
+ # 0.0 and 1.0 only.
+ >>> c = Color.of("5, 22, 33")
+ Color(r=0x5, g=0x16, b=0x21)
+ >>> c = Color.of("(5, 22, 33)")
+ Color(r=0x5, g=0x16, b=0x21)
+ >>> c = Color.of("[5, 22, 33]")
+ Color(r=0x5, g=0x16, b=0x21)
+ >>> c = Color.of("{5, 22, 33}")
+ Color(r=0x5, g=0x16, b=0x21)
Returns
-------
@@ -518,17 +518,17 @@ def to_bytes(
Parameters
----------
- length : builtins.int
+ length : int
The number of bytes to produce. Should be around `3`, but not less.
- byteorder : builtins.str
+ byteorder : str
The endianness of the value represented by the bytes.
Can be `"big"` endian or `"little"` endian.
- signed : builtins.bool
+ signed : bool
Whether the value is signed or unsigned.
Returns
-------
- builtins.bytes
+ bytes
The bytes representation of the Color.
"""
return int(self).to_bytes(length, byteorder, signed=signed)
@@ -549,12 +549,12 @@ def to_bytes(
1. `hikari.colors.Color`
2. `hikari.colours.Colour` (an alias for `hikari.colors.Color`).
-3. A value that can be cast to an `builtins.int` (RGB hex-code).
-4. a 3-`builtins.tuple` of `builtins.int` (RGB integers in range 0 through 255).
-5. a 3-`builtins.tuple` of `builtins.float` (RGB floats in range 0 through 1).
-6. a list of `builtins.int`.
-7. a list of `builtins.float`.
-8. a `builtins.str` hex colour code.
+3. A value that can be cast to an `int` (RGB hex-code).
+4. a 3-`tuple` of `int` (RGB integers in range 0 through 255).
+5. a 3-`tuple` of `float` (RGB floats in range 0 through 1).
+6. a list of `int`.
+7. a list of `float`.
+8. a `str` hex colour code.
A hex colour code is expected to be in one of the following formats. Each of the
following examples means the same thing semantically.
diff --git a/hikari/colours.py b/hikari/colours.py
index 012be20fa7..a456f99068 100644
--- a/hikari/colours.py
+++ b/hikari/colours.py
@@ -28,5 +28,10 @@
import typing
-from hikari.colors import Color as Colour
-from hikari.colors import Colorish as Colourish
+from hikari import colors
+
+Colour = colors.Color
+"""An alias for `hikari.colors.Color`."""
+
+Colourish = colors.Colorish
+"""An alias for `hikari.colors.Colorish`."""
diff --git a/hikari/commands.py b/hikari/commands.py
index 5b6abcef37..86ca8f790e 100644
--- a/hikari/commands.py
+++ b/hikari/commands.py
@@ -133,7 +133,7 @@ class CommandOption:
name: str = attr.field(repr=True)
r"""The command option's name.
- !!! note
+ .. note::
This will match the regex `^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$` in Unicode mode and will be
lowercase.
"""
@@ -141,7 +141,7 @@ class CommandOption:
description: str = attr.field(repr=False)
"""The command option's description.
- !!! note
+ .. note::
This will be inclusively between 1-100 characters in length.
"""
@@ -151,7 +151,7 @@ class CommandOption:
choices: typing.Optional[typing.Sequence[CommandChoice]] = attr.field(default=None, repr=False)
"""A sequence of up to (and including) 25 choices for this command.
- This will be `builtins.None` if the input values for this option aren't
+ This will be `None` if the input values for this option aren't
limited to specific values or if it's a subcommand or subcommand-group type
option.
"""
@@ -164,7 +164,7 @@ class CommandOption:
)
"""The channel types that this option will accept.
- If `builtins.None`, then all channel types will be accepted.
+ If `None`, then all channel types will be accepted.
"""
autocomplete: bool = attr.field(default=False, repr=False)
@@ -173,15 +173,15 @@ class CommandOption:
min_value: typing.Union[int, float, None] = attr.field(default=None, repr=False)
"""The minimum value permitted (inclusive).
- This will be `builtins.int` if the type of the option is `hikari.commands.OptionType.INTEGER`
- and `builtins.float` if the type is `hikari.commands.OptionType.FLOAT`.
+ This will be `int` if the type of the option is `hikari.commands.OptionType.INTEGER`
+ and `float` if the type is `hikari.commands.OptionType.FLOAT`.
"""
max_value: typing.Union[int, float, None] = attr.field(default=None, repr=False)
"""The maximum value permitted (inclusive).
- This will be `builtins.int` if the type of the option is `hikari.commands.OptionType.INTEGER`
- and `builtins.float` if the type is `hikari.commands.OptionType.FLOAT`.
+ This will be `int` if the type of the option is `hikari.commands.OptionType.INTEGER`
+ and `float` if the type is `hikari.commands.OptionType.FLOAT`.
"""
name_localizations: typing.Mapping[typing.Union[locales.Locale, str], str] = attr.field(factory=dict)
@@ -193,13 +193,13 @@ class CommandOption:
min_length: typing.Optional[int] = attr.field(default=None, repr=False)
"""The minimum length permitted (inclusive).
- This is only valid for `hikari.commands.OptionType.STRING`, otherwise it will be `builtins.None`.
+ This is only valid for `hikari.commands.OptionType.STRING`, otherwise it will be `None`.
"""
max_length: typing.Optional[int] = attr.field(default=None, repr=False)
"""The maximum length permitted (inclusive).
- This is only valid for `hikari.commands.OptionType.STRING`, otherwise it will be `builtins.None`.
+ This is only valid for `hikari.commands.OptionType.STRING`, otherwise it will be `None`.
"""
@@ -209,7 +209,7 @@ class PartialCommand(snowflakes.Unique):
"""Represents any application command on Discord."""
app: traits.RESTAware = attr.field(eq=False, hash=False, repr=False)
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
id: snowflakes.Snowflake = attr.field(hash=True, repr=True)
# <>.
@@ -223,7 +223,7 @@ class PartialCommand(snowflakes.Unique):
name: str = attr.field(eq=False, hash=False, repr=True)
r"""The command's name.
- !!! note
+ .. note::
This will match the regex `^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$` in Unicode mode and will be
lowercase.
"""
@@ -243,7 +243,7 @@ class PartialCommand(snowflakes.Unique):
guild_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=False)
"""ID of the guild this command is in.
- This will be `builtins.None` if this is a global command.
+ This will be `None` if this is a global command.
"""
version: snowflakes.Snowflake = attr.field(eq=False, hash=False, repr=True)
@@ -301,14 +301,10 @@ async def edit(
Other Parameters
----------------
- guild : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]]
- Object or ID of the guild to edit a command for if this is a guild
- specific command. Leave this as `hikari.undefined.UNDEFINED` to delete
- a global command.
- name : hikari.undefined.UndefinedOr[builtins.str]
+ name : hikari.undefined.UndefinedOr[str]
The name to set for the command. Leave as `hikari.undefined.UNDEFINED`
to not change.
- description : hikari.undefined.UndefinedOr[builtins.str]
+ description : hikari.undefined.UndefinedOr[str]
The description to set for the command. Leave as `hikari.undefined.UNDEFINED`
to not change.
options : hikari.undefined.UndefinedOr[typing.Sequence[CommandOption]]
@@ -429,7 +425,7 @@ async def set_guild_permissions(
) -> GuildCommandPermissions:
"""Set permissions for this command in a specific guild.
- !!! note
+ .. note::
This overwrites any previously set permissions.
Parameters
@@ -481,7 +477,7 @@ class SlashCommand(PartialCommand):
None if this command is not a slash command.
- !!! note
+ .. note::
This will be inclusively between 1-100 characters in length.
"""
diff --git a/hikari/components.py b/hikari/components.py
index d21af5f69d..0d08f45dec 100644
--- a/hikari/components.py
+++ b/hikari/components.py
@@ -57,18 +57,18 @@ class ComponentType(int, enums.Enum):
ACTION_ROW = 1
"""A non-interactive container component for other types of components.
- !!! note
+ .. note::
As this is a container component it can never be contained within another
component and therefore will always be top-level.
- !!! note
+ .. note::
As of writing this can only contain one component type.
"""
BUTTON = 2
"""A button component.
- !!! note
+ .. note::
This cannot be top-level and must be within a container component such
as `ComponentType.ACTION_ROW`.
"""
@@ -76,7 +76,7 @@ class ComponentType(int, enums.Enum):
SELECT_MENU = 3
"""A select menu component.
- !!! note
+ .. note::
This cannot be top-level and must be within a container component such
as `ComponentType.ACTION_ROW`.
"""
@@ -87,7 +87,7 @@ class ComponentType(int, enums.Enum):
!! note
This component may only be used inside a modal container.
- !!! note
+ .. note::
This cannot be top-level and must be within a container component such
as `ComponentType.ACTION_ROW`.
"""
@@ -116,7 +116,7 @@ class ButtonStyle(int, enums.Enum):
LINK = 5
"""A grey button which navigates to a URL.
- !!! warning
+ .. warning::
Unlike the other button styles, clicking this one will not trigger an
interaction and custom_id shouldn't be included for this style.
"""
@@ -187,7 +187,7 @@ class ButtonComponent(PartialComponent):
custom_id: typing.Optional[str] = attr.field(hash=True)
"""Developer defined identifier for this button (will be <= 100 characters).
- !!! note
+ .. note::
This is required for the following button styles:
* `ButtonStyle.PRIMARY`
diff --git a/hikari/embeds.py b/hikari/embeds.py
index 50ddc7f547..dbd08921ad 100644
--- a/hikari/embeds.py
+++ b/hikari/embeds.py
@@ -67,24 +67,12 @@ class EmbedResource(files.Resource[files.AsyncReader]):
@property
@typing.final
def url(self) -> str:
- """URL of this embed resource.
-
- Returns
- -------
- typing.Optional[builtins.str]
- The URL of this embed resource.
- """
+ """URL of this embed resource."""
return self.resource.url
@property
def filename(self) -> str:
- """File name of this embed resource.
-
- Returns
- -------
- typing.Optional[builtins.str]
- The file name of this embed resource.
- """
+ """File name of this embed resource."""
return self.resource.filename
def stream(
@@ -99,10 +87,10 @@ def stream(
----------
executor : typing.Optional[concurrent.futures.Executor]
The executor to run in for blocking operations.
- If `builtins.None`, then the default executor is used for the
+ If `None`, then the default executor is used for the
current event loop.
- head_only : builtins.bool
- Defaults to `builtins.False`. If `builtins.True`, then the
+ head_only : bool
+ Defaults to `False`. If `True`, then the
implementation may only retrieve HEAD information if supported.
This currently only has any effect for web requests.
"""
@@ -114,9 +102,9 @@ class EmbedResourceWithProxy(EmbedResource):
"""Resource with a corresponding proxied element."""
proxy_resource: typing.Optional[files.Resource[files.AsyncReader]] = attr.field(default=None, repr=False)
- """The proxied version of the resource, or `builtins.None` if not present.
+ """The proxied version of the resource, or `None` if not present.
- !!! note
+ .. note::
This field cannot be set by bots or webhooks while sending an embed
and will be ignored during serialization. Expect this to be
populated on any received embed attached to a message event.
@@ -125,27 +113,13 @@ class EmbedResourceWithProxy(EmbedResource):
@property
@typing.final
def proxy_url(self) -> typing.Optional[str]:
- """Proxied URL of this embed resource if applicable.
-
- Returns
- -------
- typing.Optional[builtins.str]
- The proxied URL of this embed resource if applicable, else
- `builtins.None`.
- """
+ """Proxied URL of this embed resource if applicable, else `None`."""
return self.proxy_resource.url if self.proxy_resource else None
@property
@typing.final
def proxy_filename(self) -> typing.Optional[str]:
- """File name of the proxied version of this embed resource if applicable.
-
- Returns
- -------
- typing.Optional[builtins.str]
- The file name of the proxied version of this embed resource if
- applicable, else `builtins.None`.
- """
+ """File name of the proxied version of this embed resource if applicable, else `None`."""
return self.proxy_resource.filename if self.proxy_resource else None
@@ -157,10 +131,10 @@ class EmbedFooter:
# Discord says this is never None. We know that is invalid because Discord.py
# sets it to None. Seems like undocumented behaviour again.
text: typing.Optional[str] = attr.field(default=None, repr=True)
- """The footer text, or `builtins.None` if not present."""
+ """The footer text, or `None` if not present."""
icon: typing.Optional[EmbedResourceWithProxy] = attr.field(default=None, repr=True)
- """The URL of the footer icon, or `builtins.None` if not present."""
+ """The URL of the footer icon, or `None` if not present."""
@attr.define(hash=False, kw_only=True, weakref_slot=False)
@@ -168,18 +142,18 @@ class EmbedImage(EmbedResourceWithProxy):
"""Represents an embed image."""
height: typing.Optional[int] = attr.field(default=None, repr=False)
- """The height of the image, if present and known, otherwise `builtins.None`.
+ """The height of the image, if present and known, otherwise `None`.
- !!! note
+ .. note::
This field cannot be set by bots or webhooks while sending an embed and
will be ignored during serialization. Expect this to be populated on
any received embed attached to a message event.
"""
width: typing.Optional[int] = attr.field(default=None, repr=False)
- """The width of the image, if present and known, otherwise `builtins.None`.
+ """The width of the image, if present and known, otherwise `None`.
- !!! note
+ .. note::
This field cannot be set by bots or webhooks while sending an embed and
will be ignored during serialization. Expect this to be populated on
any received embed attached to a message event.
@@ -190,7 +164,7 @@ class EmbedImage(EmbedResourceWithProxy):
class EmbedVideo(EmbedResourceWithProxy):
"""Represents an embed video.
- !!! note
+ .. note::
This object cannot be set by bots or webhooks while sending an embed and
will be ignored during serialization. Expect this to be populated on
any received embed attached to a message event with a video attached.
@@ -211,7 +185,7 @@ class yourself.**
class EmbedProvider:
"""Represents an embed provider.
- !!! note
+ .. note::
This object cannot be set by bots or webhooks while sending an embed and
will be ignored during serialization. Expect this to be populated on
any received embed attached to a message event provided by an external
@@ -234,16 +208,16 @@ class EmbedAuthor:
"""Represents an author of an embed."""
name: typing.Optional[str] = attr.field(default=None, repr=True)
- """The name of the author, or `builtins.None` if not specified."""
+ """The name of the author, or `None` if not specified."""
url: typing.Optional[str] = attr.field(default=None, repr=True)
"""The URL that the author's name should act as a hyperlink to.
- This may be `builtins.None` if no hyperlink on the author's name is specified.
+ This may be `None` if no hyperlink on the author's name is specified.
"""
icon: typing.Optional[EmbedResourceWithProxy] = attr.field(default=None, repr=False)
- """The author's icon, or `builtins.None` if not present."""
+ """The author's icon, or `None` if not present."""
@attr_extensions.with_copy
@@ -263,9 +237,9 @@ class EmbedField:
# in the constructor for `_inline`.
@property
def is_inline(self) -> bool:
- """Return `builtins.True` if the field should display inline.
+ """Return `True` if the field should display inline.
- Defaults to False.
+ Defaults to `False`.
"""
return self._inline
@@ -299,9 +273,6 @@ class Embed:
"_fields",
)
- # Don't document this.
- __pdoc__: typing.ClassVar[typing.Mapping[str, typing.Any]] = {"from_received_embed": False}
-
@classmethod
def from_received_embed(
cls,
@@ -321,7 +292,8 @@ def from_received_embed(
) -> Embed:
"""Generate an embed from the given attributes.
- You should never call this.
+ .. warning::
+ **This function is for internal use only!**
"""
# Create an empty instance without the overhead of invoking the regular
# constructor.
@@ -382,12 +354,7 @@ def __init__(
def title(self) -> typing.Optional[str]:
"""Return the title of the embed.
- This will be `builtins.None` if not set.
-
- Returns
- -------
- typing.Optional[builtins.str]
- The title of the embed.
+ This will be `None` if not set.
"""
return self._title
@@ -399,12 +366,7 @@ def title(self, value: typing.Any) -> None:
def description(self) -> typing.Optional[str]:
"""Return the description of the embed.
- This will be `builtins.None` if not set.
-
- Returns
- -------
- typing.Optional[builtins.str]
- The description of the embed.
+ This will be `None` if not set.
"""
return self._description
@@ -416,12 +378,7 @@ def description(self, value: typing.Any) -> None:
def url(self) -> typing.Optional[str]:
"""Return the URL of the embed title.
- This will be `builtins.None` if not set.
-
- Returns
- -------
- typing.Optional[builtins.str]
- The URL of the embed title
+ This will be `None` if not set.
"""
return self._url
@@ -433,12 +390,7 @@ def url(self, value: typing.Optional[str]) -> None:
def color(self) -> typing.Optional[colors.Color]:
"""Return the colour of the embed.
- This will be `builtins.None` if not set.
-
- Returns
- -------
- typing.Optional[hikari.colors.Color]
- The colour that is set.
+ This will be `None` if not set.
"""
return self._color
@@ -451,15 +403,7 @@ def color(self, value: typing.Optional[colors.Colorish]) -> None:
# Alias.
@property
def colour(self) -> typing.Optional[colors.Color]:
- """Return the colour of the embed. This is an alias of `Embed.color`.
-
- This will be `builtins.None` if not set.
-
- Returns
- -------
- typing.Optional[hikari.colors.Color]
- The colour that is set.
- """
+ """Alias of `color`."""
return self._color
# Alias.
@@ -473,14 +417,9 @@ def colour(self, value: typing.Optional[colors.Colorish]) -> None:
def timestamp(self) -> typing.Optional[datetime.datetime]:
"""Return the timestamp of the embed.
- This will be `builtins.None` if not set.
-
- Returns
- -------
- typing.Optional[datetime.datetime]
- The timestamp set on the embed.
+ This will be `None` if not set.
- !!! warning
+ .. warning::
Setting a non-timezone-aware datetime will result in a warning
being raised. This is done due to potential confusion caused by
Discord requiring a UTC timestamp for this field. Any non-timezone
@@ -593,10 +532,7 @@ def __warn_naive_datetime() -> None:
def footer(self) -> typing.Optional[EmbedFooter]:
"""Return the footer of the embed.
- Will be `builtins.None` if not set.
-
- typing.Optional[EmbedFooter]
- The footer of the embed.
+ Will be `None` if not set.
"""
return self._footer
@@ -604,12 +540,9 @@ def footer(self) -> typing.Optional[EmbedFooter]:
def image(self) -> typing.Optional[EmbedImage]:
"""Return the image set in the embed.
- Will be `builtins.None` if not set.
-
- typing.Optional[EmbedImage]
- The image of the embed.
+ Will be `None` if not set.
- !!! note
+ .. note::
Use `set_image` to update this value.
"""
return self._image
@@ -618,12 +551,9 @@ def image(self) -> typing.Optional[EmbedImage]:
def thumbnail(self) -> typing.Optional[EmbedImage]:
"""Return the thumbnail set in the embed.
- Will be `builtins.None` if not set.
-
- typing.Optional[EmbedImage]
- The thumbnail of the embed.
+ Will be `None` if not set.
- !!! note
+ .. note::
Use `set_thumbnail` to update this value.
"""
return self._thumbnail
@@ -632,14 +562,9 @@ def thumbnail(self) -> typing.Optional[EmbedImage]:
def video(self) -> typing.Optional[EmbedVideo]:
"""Return the video to show in the embed.
- Will be `builtins.None` if not set.
-
- Returns
- -------
- typing.Optional[EmbedVideo]
- The video of the embed.
+ Will be `None` if not set.
- !!! note
+ .. note::
This object cannot be set by bots or webhooks while sending an embed
and will be ignored during serialization. Expect this to be
populated on any received embed attached to a message event with a
@@ -651,14 +576,9 @@ def video(self) -> typing.Optional[EmbedVideo]:
def provider(self) -> typing.Optional[EmbedProvider]:
"""Return the provider to show in the embed.
- Will be `builtins.None` if not set.
+ Will be `None` if not set.
- Returns
- -------
- typing.Optional[EmbedProvider]
- The provider of the embed.
-
- !!! note
+ .. note::
This object cannot be set by bots or webhooks while sending an embed
and will be ignored during serialization. Expect this to be
populated on any received embed attached to a message event with a
@@ -670,14 +590,9 @@ def provider(self) -> typing.Optional[EmbedProvider]:
def author(self) -> typing.Optional[EmbedAuthor]:
"""Return the author to show in the embed.
- Will be `builtins.None` if not set.
-
- Returns
- -------
- typing.Optional[EmbedAuthor]
- The author of the embed.
+ Will be `None` if not set.
- !!! note
+ .. note::
Use `set_author` to update this value.
"""
return self._author
@@ -686,7 +601,7 @@ def author(self) -> typing.Optional[EmbedAuthor]:
def fields(self) -> typing.Sequence[EmbedField]:
"""Return the sequence of fields in the embed.
- !!! note
+ .. note::
Use `add_field` to add a new field, `edit_field` to edit an existing
field, or `remove_field` to remove a field.
"""
@@ -703,17 +618,17 @@ def set_author(
Parameters
----------
- name : typing.Optional[builtins.str]
+ name : typing.Optional[str]
The optional name of the author.
- url : typing.Optional[builtins.str]
+ url : typing.Optional[str]
The optional URL of the author.
icon : typing.Optional[hikari.files.Resourceish]
The optional image to show next to the embed author.
This can be many different things, to aid in convenience.
- - If `builtins.None`, nothing is set.
- - If a `pathlib.PurePath` or `builtins.str` to a valid URL, the URL
+ - If `None`, nothing is set.
+ - If a `pathlib.PurePath` or `str` to a valid URL, the URL
is linked to directly.
- Subclasses of `hikari.files.WebResource` such as
`hikari.files.URL`,
@@ -721,11 +636,11 @@ def set_author(
`hikari.emojis.Emoji`,
`EmbedResource`, etc will have their URL linked to directly.
this field.
- - If a `hikari.files.Bytes` is passed, or a `builtins.str`
+ - If a `hikari.files.Bytes` is passed, or a `str`
that contains a valid data URI is passed, then this is uploaded
as an attachment and linked into the embed.
- If a `hikari.files.File`, `pathlib.PurePath` or
- `builtins.str` that is an absolute or relative path to a file
+ `str` that is an absolute or relative path to a file
on your file system is passed, then this resource is uploaded
as an attachment using non-blocking code internally and linked
into the embed.
@@ -749,14 +664,14 @@ def set_footer(self, text: typing.Optional[str], *, icon: typing.Optional[files.
----------
text : typing.Optional[str]
The mandatory text string to set in the footer.
- If `builtins.None`, the footer is removed.
+ If `None`, the footer is removed.
icon : typing.Optional[hikari.files.Resourceish]
The optional image to show next to the embed footer.
This can be many different things, to aid in convenience.
- - If `builtins.None`, nothing is set.
- - If a `pathlib.PurePath` or `builtins.str` to a valid URL, the URL
+ - If `None`, nothing is set.
+ - If a `pathlib.PurePath` or `str` to a valid URL, the URL
is linked to directly.
- Subclasses of `hikari.files.WebResource` such as
`hikari.files.URL`,
@@ -764,11 +679,11 @@ def set_footer(self, text: typing.Optional[str], *, icon: typing.Optional[files.
`hikari.emojis.Emoji`,
`EmbedResource`, etc will have their URL linked to directly.
this field.
- - If a `hikari.files.Bytes` is passed, or a `builtins.str`
+ - If a `hikari.files.Bytes` is passed, or a `str`
that contains a valid data URI is passed, then this is uploaded
as an attachment and linked into the embed.
- If a `hikari.files.File`, `pathlib.PurePath` or
- `builtins.str` that is an absolute or relative path to a file
+ `str` that is an absolute or relative path to a file
on your file system is passed, then this resource is uploaded
as an attachment using non-blocking code internally and linked
into the embed.
@@ -801,8 +716,8 @@ def set_image(self, image: typing.Optional[files.Resourceish] = None, /) -> Embe
This can be many different things, to aid in convenience.
- - If `builtins.None`, nothing is set.
- - If a `pathlib.PurePath` or `builtins.str` to a valid URL, the URL
+ - If `None`, nothing is set.
+ - If a `pathlib.PurePath` or `str` to a valid URL, the URL
is linked to directly.
- Subclasses of `hikari.files.WebResource` such as
`hikari.files.URL`,
@@ -810,11 +725,11 @@ def set_image(self, image: typing.Optional[files.Resourceish] = None, /) -> Embe
`hikari.emojis.Emoji`,
`EmbedResource`, etc will have their URL linked to directly.
this field.
- - If a `hikari.files.Bytes` is passed, or a `builtins.str`
+ - If a `hikari.files.Bytes` is passed, or a `str`
that contains a valid data URI is passed, then this is uploaded
as an attachment and linked into the embed.
- If a `hikari.files.File`, `pathlib.PurePath` or
- `builtins.str` that is an absolute or relative path to a file
+ `str` that is an absolute or relative path to a file
on your file system is passed, then this resource is uploaded
as an attachment using non-blocking code internally and linked
into the embed.
@@ -841,19 +756,19 @@ def set_thumbnail(self, image: typing.Optional[files.Resourceish] = None, /) ->
This can be many different things, to aid in convenience.
- - If `builtins.None`, nothing is set.
- - If a `pathlib.PurePath` or `builtins.str` to a valid URL, the URL
+ - If `None`, nothing is set.
+ - If a `pathlib.PurePath` or `str` to a valid URL, the URL
is linked to directly.
- Subclasses of `hikari.files.WebResource` such as
`hikari.files.URL`,
`hikari.messages.Attachment`,
`hikari.emojis.Emoji`,
`EmbedResource`, etc will have their URL linked to directly.
- - If a `hikari.files.Bytes` is passed, or a `builtins.str`
+ - If a `hikari.files.Bytes` is passed, or a `str`
that contains a valid data URI is passed, then this is uploaded
as an attachment and linked into the embed.
- If a `hikari.files.File`, `pathlib.PurePath` or
- `builtins.str` that is an absolute or relative path to a file
+ `str` that is an absolute or relative path to a file
on your file system is passed, then this resource is uploaded
as an attachment using non-blocking code internally and linked
into the embed.
@@ -885,9 +800,9 @@ def add_field(self, name: str, value: str, *, inline: bool = False) -> Embed:
Other Parameters
----------------
inline : bool
- If `builtins.True`, the embed field may be shown "inline" on some
- Discord clients with other fields. If `builtins.False`, it is always placed
- on a separate line. This will default to `builtins.False`.
+ If `True`, the embed field may be shown "inline" on some
+ Discord clients with other fields. If `False`, it is always placed
+ on a separate line. This will default to `False`.
Returns
-------
@@ -923,8 +838,8 @@ def edit_field(
value : hikari.undefined.UndefinedOr[str]
The new field value to use. If left to the default (`undefined`),
then it will not be changed.
- inline : hikari.undefined.UndefinedOr[builtins.bool]
- `builtins.True` to inline the field, or `builtins.False` to force
+ inline : hikari.undefined.UndefinedOr[bool]
+ `True` to inline the field, or `False` to force
it to be on a separate line. If left to the default (`undefined`),
then it will not be changed.
@@ -935,7 +850,7 @@ def edit_field(
Raises
------
- builtins.IndexError
+ IndexError
Raised if the index is greater than `len(embed.fields) - 1` or
less than `-len(embed.fields)`
"""
@@ -966,7 +881,7 @@ def remove_field(self, index: int, /) -> Embed:
Raises
------
- builtins.IndexError
+ IndexError
Raised if the index is greater than `len(embed.fields) - 1` or
less than `-len(embed.fields)`
"""
@@ -993,7 +908,7 @@ def total_length(self) -> int:
Returns
-------
- builtins.int
+ int
The total character count of this embed, including title, description,
fields, footer, and author combined.
"""
diff --git a/hikari/emojis.py b/hikari/emojis.py
index 53f4ccb70f..becab9570e 100644
--- a/hikari/emojis.py
+++ b/hikari/emojis.py
@@ -86,7 +86,7 @@ def parse(cls, string: str, /) -> Emoji:
Parameters
----------
- string : builtins.str
+ string : str
The emoji object to parse.
Returns
@@ -97,7 +97,7 @@ def parse(cls, string: str, /) -> Emoji:
Raises
------
- builtins.ValueError
+ ValueError
If a mention is given that has an invalid format.
"""
if string.startswith("<") and string.endswith(">"):
@@ -108,7 +108,7 @@ def parse(cls, string: str, /) -> Emoji:
class UnicodeEmoji(str, Emoji):
"""Represents a unicode emoji.
- !!! warning
+ .. warning::
A word of warning if you try to upload this emoji as a file attachment.
While this emoji type can be used to upload the Twemoji representations
@@ -176,9 +176,13 @@ def url(self) -> str:
match what is on Discord if Discord have failed to keep their emoji
packs up-to-date with this repository.
- Example
- -------
- https://github.com/twitter/twemoji/raw/master/assets/72x72/1f004.png
+ Examples
+ --------
+ .. code-block:: python
+
+ >>> emoji = hikari.UnicodeEmoji("\N{OK HAND SIGN}")
+ >>> emoji.url
+ 'https://raw.githubusercontent.com/twitter/twemoji/master/assets/72x72/1f44c.png'
"""
return _TWEMOJI_PNG_BASE_URL + self.filename
@@ -217,7 +221,7 @@ def parse(cls, string: str, /) -> UnicodeEmoji:
Parameters
----------
- string : builtins.str
+ string : str
The emoji object to parse.
Returns
@@ -248,7 +252,7 @@ class CustomEmoji(snowflakes.Unique, Emoji):
>>> picks = random.choices(emojis, 5)
>>> await event.respond(files=picks)
- !!! warning
+ .. warning::
Discord will not provide information on whether these emojis are
animated or not when a reaction is removed and an event is fired. This
is problematic if you need to try and determine the emoji that was
@@ -256,7 +260,7 @@ class CustomEmoji(snowflakes.Unique, Emoji):
will not be correct.
This will not be changed as stated here:
- https://github.com/discord/discord-api-docs/issues/1614#issuecomment-628548913
+
"""
id: snowflakes.Snowflake = attr.field(hash=True, repr=True)
@@ -298,7 +302,7 @@ def parse(cls, string: str, /) -> CustomEmoji:
Parameters
----------
- string : builtins.str
+ string : str
The emoji mention to parse.
Returns
@@ -308,7 +312,7 @@ def parse(cls, string: str, /) -> CustomEmoji:
Raises
------
- builtins.ValueError
+ ValueError
If a mention is given that has an invalid format.
"""
if emoji_match := _CUSTOM_EMOJI_REGEX.match(string):
@@ -332,7 +336,7 @@ class KnownCustomEmoji(CustomEmoji):
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
guild_id: snowflakes.Snowflake = attr.field(eq=False, hash=False, repr=False)
"""The ID of the guild this emoji belongs to."""
@@ -346,8 +350,8 @@ class KnownCustomEmoji(CustomEmoji):
user: typing.Optional[users.User] = attr.field(eq=False, hash=False, repr=False)
"""The user that created the emoji.
- !!! note
- This will be `builtins.None` if you are missing the `MANAGE_EMOJIS_AND_STICKERS`
+ .. note::
+ This will be `None` if you are missing the `MANAGE_EMOJIS_AND_STICKERS`
permission in the server the emoji is from.
"""
@@ -360,5 +364,5 @@ class KnownCustomEmoji(CustomEmoji):
is_available: bool = attr.field(eq=False, hash=False, repr=False)
"""Whether this emoji can currently be used.
- May be `builtins.False` due to a loss of Sever Boosts on the emoji's guild.
+ May be `False` due to a loss of Sever Boosts on the emoji's guild.
"""
diff --git a/hikari/errors.py b/hikari/errors.py
index 545b2490c5..f70dfb909d 100644
--- a/hikari/errors.py
+++ b/hikari/errors.py
@@ -74,7 +74,7 @@ class HikariError(RuntimeError):
Any exceptions should derive from this.
- !!! note
+ .. note::
You should never initialize this exception directly.
"""
@@ -87,7 +87,7 @@ class HikariWarning(RuntimeWarning):
Any warnings should derive from this.
- !!! note
+ .. note::
You should never initialize this warning directly.
"""
@@ -169,7 +169,7 @@ class ShardCloseCode(int, enums.Enum):
@property
def is_standard(self) -> bool:
- """Return `builtins.True` if this is a standard code."""
+ """Return `True` if this is a standard code."""
return (self.value // 1000) == 1
@@ -186,30 +186,15 @@ class GatewayServerClosedConnectionError(GatewayError):
"""An exception raised when the server closes the connection."""
code: typing.Union[ShardCloseCode, int, None] = attr.field(default=None)
- """Return the close code that was received, if there is one.
-
- Returns
- -------
- typing.Union[ShardCloseCode, builtins.int, builtins.None]
- The shard close code if there was one. Will be a `ShardCloseCode`
- if the definition is known. Undocumented close codes may instead be
- an `builtins.int` instead.
-
- If no close code was received, this will be `builtins.None`.
- """
+ """Return the close code that was received, if there is one."""
can_reconnect: bool = attr.field(default=False)
- """Return `builtins.True` if we can recover from this closure.
+ """Return `True` if we can recover from this closure.
- If `builtins.True`, it will try to reconnect after this is raised rather
- than it being propagated to the caller. If `builtins.False`, this will
+ If `True`, it will try to reconnect after this is raised rather
+ than it being propagated to the caller. If `False`, this will
be raised, thus stopping the application unless handled explicitly by the
user.
-
- Returns
- -------
- builtins.bool
- Whether the closure can be recovered from via a reconnect.
"""
def __str__(self) -> str:
@@ -315,7 +300,7 @@ class BadRequestError(ClientHTTPResponseError):
"""Dict of top level field names to field specific error paths.
For more information, this error format is loosely defined at
- https://discord.com/developers/docs/reference#error-messages and is commonly
+ and is commonly
returned for 50035 errors.
"""
@@ -447,15 +432,10 @@ def _(self) -> str:
# only.
@property
def remaining(self) -> typing.Literal[0]:
- """The number of requests remaining in this window.
+ """Remaining requests in this window.
This will always be `0` symbolically.
-
- Returns
- -------
- builtins.int
- The number of requests remaining. Always `0`.
- """ # noqa: D401 - Imperative mood
+ """
return 0
def __str__(self) -> str:
@@ -495,13 +475,7 @@ class BulkDeleteError(HikariError):
@property
def percentage_completion(self) -> float:
- """Return the percentage completion of the bulk delete before it failed.
-
- Returns
- -------
- builtins.float
- A percentage completion between 0 and 100 inclusive.
- """
+ """Return the percentage completion of the bulk delete before it failed."""
deleted = len(self.messages_deleted)
total = deleted + len(self.messages_skipped)
return 100 * deleted / total
diff --git a/hikari/events/base_events.py b/hikari/events/base_events.py
index fd34e912eb..8d5dfe9761 100644
--- a/hikari/events/base_events.py
+++ b/hikari/events/base_events.py
@@ -86,13 +86,7 @@ def __init_subclass__(cls) -> None:
@property
@abc.abstractmethod
def app(self) -> traits.RESTAware:
- """App instance for this application.
-
- Returns
- -------
- hikari.traits.RESTAware
- The REST-aware app trait.
- """
+ """App instance for this application."""
@classmethod
def dispatches(cls) -> typing.Sequence[typing.Type[Event]]:
@@ -166,7 +160,7 @@ def decorator(cls: _T) -> _T:
doc = inspect.getdoc(cls) or ""
doc += (
"\n"
- "!!! warning\n"
+ ".. warning::\n"
" Any exceptions raised by handlers for this event will be dumped to the\n"
" application logger and silently discarded, preventing recursive loops\n"
" produced by faulty exception event handling. Thus, it is imperative\n"
@@ -196,8 +190,8 @@ def is_no_recursive_throw_event(obj: typing.Union[_T, typing.Type[_T]]) -> bool:
class ExceptionEvent(Event, typing.Generic[EventT]):
"""Event that is raised when another event handler raises an `Exception`.
- !!! note
- Only exceptions that derive from `builtins.Exception` will be caught.
+ .. note::
+ Only exceptions that derive from `Exception` will be caught.
Other exceptions outside this range will propagate past this callback.
This prevents event handlers interfering with critical exceptions
such as `KeyboardError` which would have potentially undesired
@@ -205,31 +199,13 @@ class ExceptionEvent(Event, typing.Generic[EventT]):
"""
exception: Exception = attr.field()
- """Exception that was raised.
-
- Returns
- -------
- builtins.Exception
- Exception that was raised in the event handler.
- """
+ """Exception that was raised."""
failed_event: EventT = attr.field()
- """Event instance that caused the exception.
-
- Returns
- -------
- hikari.events.base_events.Event
- Event that was being processed when the exception occurred.
- """
+ """Event instance that caused the exception."""
failed_callback: FailedCallbackT[EventT] = attr.field()
- """Event callback that threw an exception.
-
- Returns
- -------
- callback
- Event callback that failed execution.
- """
+ """Event callback that threw an exception."""
@property
def app(self) -> traits.RESTAware:
@@ -240,13 +216,8 @@ def app(self) -> traits.RESTAware:
def shard(self) -> typing.Optional[gateway_shard.GatewayShard]:
"""Shard that received the event, if there was one associated.
- Returns
- -------
- typing.Optional[hikari.api.shard.GatewayShard]
- Shard that raised this exception.
-
- This may be `builtins.None` if no specific shard was the cause of this
- exception (e.g. when starting up or shutting down).
+ This may be `None` if no specific shard was the cause of this
+ exception (e.g. when starting up or shutting down).
"""
shard = getattr(self.failed_event, "shard", None)
if isinstance(shard, gateway_shard.GatewayShard):
@@ -257,11 +228,8 @@ def shard(self) -> typing.Optional[gateway_shard.GatewayShard]:
def exc_info(self) -> typing.Tuple[typing.Type[Exception], Exception, typing.Optional[types.TracebackType]]:
"""Exception triplet that follows the same format as `sys.exc_info`.
- Returns
- -------
- builtins.tuple[typing.Type[Exception], Exception, typing.Optional[types.TracebackType]]
- The `sys.exc_info`-compatible tuple of the exception type, the
- exception instance, and the traceback of the exception.
+ The `sys.exc_info` tiplet consists of the exception type, the exception
+ instance, and the traceback of the exception.
"""
return type(self.exception), self.exception, self.exception.__traceback__
diff --git a/hikari/events/channel_events.py b/hikari/events/channel_events.py
index 8cce4b7528..a7c32e996b 100644
--- a/hikari/events/channel_events.py
+++ b/hikari/events/channel_events.py
@@ -83,19 +83,13 @@ class ChannelEvent(shard_events.ShardEvent, abc.ABC):
@property
@abc.abstractmethod
def channel_id(self) -> snowflakes.Snowflake:
- """ID of the channel the event relates to.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the channel this event relates to.
- """
+ """ID of the channel the event relates to."""
@abc.abstractmethod
async def fetch_channel(self) -> channels.PartialChannel:
"""Perform an API call to fetch the details about this channel.
- !!! note
+ .. note::
For `GuildChannelDeleteEvent` events, this will always raise
an exception, since the channel will have already been removed.
@@ -138,24 +132,18 @@ class GuildChannelEvent(ChannelEvent, abc.ABC):
@property
@abc.abstractmethod
def guild_id(self) -> snowflakes.Snowflake:
- """ID of the guild that this event relates to.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the guild that relates to this event.
- """
+ """ID of the guild that this event relates to."""
def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
"""Get the cached guild that this event relates to, if known.
- If not, return `builtins.None`.
+ If not, return `None`.
Returns
-------
typing.Optional[hikari.guilds.GatewayGuild]
The gateway guild this event relates to, if known. Otherwise
- this will return `builtins.None`.
+ this will return `None`.
"""
if not isinstance(self.app, traits.CacheAware):
return None
@@ -197,13 +185,13 @@ async def fetch_guild(self) -> guilds.RESTGuild:
def get_channel(self) -> typing.Optional[channels.PermissibleGuildChannel]:
"""Get the cached channel that this event relates to, if known.
- If not, return `builtins.None`.
+ If not, return `None`.
Returns
-------
typing.Optional[hikari.channels.GuildChannel]
The cached channel this event relates to. If not known, this
- will return `builtins.None` instead.
+ will return `None` instead.
"""
if not isinstance(self.app, traits.CacheAware):
return None
@@ -213,7 +201,7 @@ def get_channel(self) -> typing.Optional[channels.PermissibleGuildChannel]:
async def fetch_channel(self) -> channels.GuildChannel:
"""Perform an API call to fetch the details about this channel.
- !!! note
+ .. note::
For `GuildChannelDeleteEvent` events, this will always raise
an exception, since the channel will have already been removed.
@@ -259,7 +247,7 @@ class DMChannelEvent(ChannelEvent, abc.ABC):
async def fetch_channel(self) -> channels.PrivateChannel:
"""Perform an API call to fetch the details about this channel.
- !!! note
+ .. note::
For `GuildChannelDeleteEvent` events, this will always raise
an exception, since the channel will have already been removed.
@@ -307,13 +295,7 @@ class GuildChannelCreateEvent(GuildChannelEvent):
# <>.
channel: channels.PermissibleGuildChannel = attr.field(repr=True)
- """Guild channel that this event represents.
-
- Returns
- -------
- hikari.channels.GuildChannel
- The guild channel that was created.
- """
+ """Guild channel that this event represents."""
@property
def app(self) -> traits.RESTAware:
@@ -343,17 +325,11 @@ class GuildChannelUpdateEvent(GuildChannelEvent):
old_channel: typing.Optional[channels.PermissibleGuildChannel] = attr.field(repr=True)
"""The old guild channel object.
- This will be `builtins.None` if the channel missing from the cache.
+ This will be `None` if the channel missing from the cache.
"""
channel: channels.PermissibleGuildChannel = attr.field(repr=True)
- """Guild channel that this event represents.
-
- Returns
- -------
- hikari.channels.PermissibleGuildChannel
- The guild channel that was updated.
- """
+ """Guild channel that this event represents."""
@property
def app(self) -> traits.RESTAware:
@@ -381,13 +357,7 @@ class GuildChannelDeleteEvent(GuildChannelEvent):
# <>.
channel: channels.PermissibleGuildChannel = attr.field(repr=True)
- """Guild channel that this event represents.
-
- Returns
- -------
- hikari.channels.PermissibleGuildChannel
- The guild channel that was deleted.
- """
+ """Guild channel that this event represents."""
@property
def app(self) -> traits.RESTAware:
@@ -421,14 +391,8 @@ class PinsUpdateEvent(ChannelEvent, abc.ABC):
def last_pin_timestamp(self) -> typing.Optional[datetime.datetime]:
"""Datetime of when the most recent message was pinned in the channel.
- Will be `builtins.None` if nothing is pinned or the information is
+ Will be `None` if nothing is pinned or the information is
unavailable.
-
- Returns
- -------
- typing.Optional[datetime.datetime]
- The datetime of the most recent pinned message in the channel,
- or `builtins.None` if no pins are available.
"""
@abc.abstractmethod
@@ -478,13 +442,13 @@ class GuildPinsUpdateEvent(PinsUpdateEvent, GuildChannelEvent):
def get_channel(self) -> typing.Optional[channels.PermissibleGuildChannel]:
"""Get the cached channel that this event relates to, if known.
- If not, return `builtins.None`.
+ If not, return `None`.
Returns
-------
typing.Optional[hikari.channels.TextableGuildChannel]
The cached channel this event relates to. If not known, this
- will return `builtins.None` instead.
+ will return `None` instead.
"""
channel = super().get_channel()
assert channel is None or isinstance(channel, channels.PermissibleGuildChannel)
@@ -587,13 +551,7 @@ class InviteEvent(GuildChannelEvent, abc.ABC):
@property
@abc.abstractmethod
def code(self) -> str:
- """Code that is used in the URL for the invite.
-
- Returns
- -------
- builtins.str
- The invite code.
- """
+ """Code that is used in the URL for the invite."""
async def fetch_invite(self) -> invites.Invite:
"""Perform an API call to retrieve an up-to-date image of this invite.
@@ -636,13 +594,7 @@ class InviteCreateEvent(InviteEvent):
# <>.
invite: invites.InviteWithMetadata = attr.field()
- """Invite that was created.
-
- Returns
- -------
- hikari.invites.InviteWithMetadata
- The created invite object.
- """
+ """Invite that was created."""
@property
def app(self) -> traits.RESTAware:
@@ -691,7 +643,7 @@ class InviteDeleteEvent(InviteEvent):
old_invite: typing.Optional[invites.InviteWithMetadata] = attr.field()
"""Object of the old cached invite.
- This will be `builtins.None` if the invite is missing from the cache.
+ This will be `None` if the invite is missing from the cache.
"""
if typing.TYPE_CHECKING:
@@ -808,7 +760,7 @@ def thread_id(self) -> snowflakes.Snowflake:
async def fetch_channel(self) -> channels.GuildThreadChannel:
"""Perform an API call to fetch the details about this thread.
- !!! note
+ .. note::
For `GuildThreadDeleteEvent` events, this will always raise
an exception, since the channel will have already been removed.
@@ -980,7 +932,7 @@ class ThreadMembersUpdateEvent(GuildThreadEvent):
approximate_member_count: int = attr.field(eq=False, hash=False, repr=True)
"""Approximate count of members in the thread channel.
- !!! warning
+ .. warning::
This stops counting at 50 for threads created before 2022/06/01.
"""
@@ -1021,7 +973,7 @@ class ThreadListSyncEvent(shard_events.ShardEvent):
channel_ids: typing.Optional[typing.Sequence[snowflakes.Snowflake]] = attr.field()
"""IDs of the text channels threads are being synced for.
- If this is `builtins.None` then threads are being synced for all text
+ If this is `None` then threads are being synced for all text
channels in the guild.
This may contain channels that have no active threads as well to allow for
diff --git a/hikari/events/guild_events.py b/hikari/events/guild_events.py
index 65bb0b3a96..1e0448448e 100644
--- a/hikari/events/guild_events.py
+++ b/hikari/events/guild_events.py
@@ -78,13 +78,7 @@ class GuildEvent(shard_events.ShardEvent, abc.ABC):
@property
@abc.abstractmethod
def guild_id(self) -> snowflakes.Snowflake:
- """ID of the guild that this event relates to.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the guild that relates to this event.
- """
+ """ID of the guild that this event relates to."""
async def fetch_guild(self) -> guilds.RESTGuild:
"""Perform an API call to get the guild that this event relates to.
@@ -109,12 +103,12 @@ async def fetch_guild_preview(self) -> guilds.GuildPreview:
def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
"""Get the cached guild that this event relates to, if known.
- If not known, this will return `builtins.None` instead.
+ If not known, this will return `None` instead.
Returns
-------
typing.Optional[hikari.guilds.GatewayGuild]
- The guild this event relates to, or `builtins.None` if not known.
+ The guild this event relates to, or `None` if not known.
"""
if not isinstance(self.app, traits.CacheAware):
return None
@@ -143,7 +137,7 @@ class GuildAvailableEvent(GuildVisibilityEvent):
This will occur on startup or after outages.
- !!! note
+ .. note::
Some fields like `members` and `presences` are included here but not on
the other `GuildUpdateEvent` and `GuildUnavailableEvent` guild visibility
event models.
@@ -153,92 +147,39 @@ class GuildAvailableEvent(GuildVisibilityEvent):
# <>.
guild: guilds.GatewayGuild = attr.field()
- """Guild that just became available.
-
- Returns
- -------
- hikari.guilds.Guild
- The guild that relates to this event.
- """
+ """Guild that just became available."""
emojis: typing.Mapping[snowflakes.Snowflake, emojis_.KnownCustomEmoji] = attr.field(repr=False)
- """Mapping of emoji IDs to the emojis in the guild.
-
- Returns
- -------
- typing.Mapping[hikari.snowflakes.Snowflake, hikari.emojis.KnownCustomEmoji]
- The emojis in the guild.
- """
+ """Mapping of emoji IDs to the emojis in the guild."""
stickers: typing.Mapping[snowflakes.Snowflake, stickers_.GuildSticker] = attr.field(repr=False)
"""Mapping of sticker IDs to the stickers in the guild."""
roles: typing.Mapping[snowflakes.Snowflake, guilds.Role] = attr.field(repr=False)
- """Mapping of role IDs to the roles in the guild.
-
- Returns
- -------
- typing.Mapping[hikari.snowflakes.Snowflake, hikari.guilds.Role]
- The roles in the guild.
- """
+ """Mapping of role IDs to the roles in the guild."""
channels: typing.Mapping[snowflakes.Snowflake, channels_.PermissibleGuildChannel] = attr.field(repr=False)
- """Mapping of channel IDs to the channels in the guild.
-
- Returns
- -------
- typing.Mapping[hikari.snowflakes.Snowflake, hikari.channels.PermissibleGuildChannel]
- The channels in the guild.
- """
+ """Mapping of channel IDs to the channels in the guild."""
threads: typing.Mapping[snowflakes.Snowflake, channels_.GuildThreadChannel] = attr.field(repr=False)
- """Mapping of channel IDs to the threads in the guild.
-
- Returns
- -------
- typing.Mapping[hikari.snowflakes.Snowflake, hikari.channels.GuildThreadChannel]
- The threads in the guild.
- """
+ """Mapping of channel IDs to the threads in the guild."""
members: typing.Mapping[snowflakes.Snowflake, guilds.Member] = attr.field(repr=False)
- """Mapping of user IDs to the members in the guild.
-
- Returns
- -------
- typing.Mapping[hikari.snowflakes.Snowflake, hikari.guilds.Member]
- The members in the guild.
- """
+ """Mapping of user IDs to the members in the guild."""
presences: typing.Mapping[snowflakes.Snowflake, presences_.MemberPresence] = attr.field(repr=False)
- """Mapping of user IDs to the presences for the guild.
-
- Returns
- -------
- typing.Mapping[hikari.snowflakes.Snowflake, hikari.presences.MemberPresence]
- The member presences in the guild.
- """
+ """Mapping of user IDs to the presences for the guild."""
voice_states: typing.Mapping[snowflakes.Snowflake, voices.VoiceState] = attr.field(repr=False)
- """Mapping of user IDs to the voice states active in this guild.
-
- Returns
- -------
- typing.Mapping[hikari.snowflakes.Snowflake, hikari.voices.VoiceState]
- The voice states active in the guild.
- """
+ """Mapping of user IDs to the voice states active in this guild."""
chunk_nonce: typing.Optional[str] = attr.field(repr=False, default=None)
"""Nonce used to request the member chunks for this guild.
- This will be `builtins.None` if no chunks were requested.
+ This will be `None` if no chunks were requested.
- !!! note
+ .. note::
This is a synthetic field.
-
- Returns
- -------
- typing.Optional[builtins.str]
- The nonce used to request the member chunks.
"""
@property
@@ -258,7 +199,7 @@ def guild_id(self) -> snowflakes.Snowflake:
class GuildJoinEvent(GuildVisibilityEvent):
"""Event fired when the bot joins a new guild.
- !!! note
+ .. note::
Some fields like `members` and `presences` are included here but not on
the other `GuildUpdateEvent` and `GuildUnavailableEvent` guild visibility
event models.
@@ -297,9 +238,9 @@ class GuildJoinEvent(GuildVisibilityEvent):
chunk_nonce: typing.Optional[str] = attr.field(repr=False, default=None)
"""Nonce used to request the member chunks for this guild.
- This will be `builtins.None` if no chunks were requested.
+ This will be `None` if no chunks were requested.
- !!! note
+ .. note::
This is a synthetic field.
"""
@@ -335,7 +276,7 @@ class GuildLeaveEvent(GuildVisibilityEvent):
old_guild: typing.Optional[guilds.GatewayGuild] = attr.field()
"""The old guild object.
- This will be `builtins.None` if the guild missing from the cache.
+ This will be `None` if the guild missing from the cache.
"""
if typing.TYPE_CHECKING:
@@ -372,38 +313,20 @@ class GuildUpdateEvent(GuildEvent):
old_guild: typing.Optional[guilds.GatewayGuild] = attr.field()
"""The old guild object.
- This will be `builtins.None` if the guild missing from the cache.
+ This will be `None` if the guild missing from the cache.
"""
guild: guilds.GatewayGuild = attr.field()
- """Guild that was just updated.
-
- Returns
- -------
- hikari.guilds.Guild
- The guild that relates to this event.
- """
+ """Guild that was just updated."""
emojis: typing.Mapping[snowflakes.Snowflake, emojis_.KnownCustomEmoji] = attr.field(repr=False)
- """Mapping of emoji IDs to the emojis in the guild.
-
- Returns
- -------
- typing.Mapping[hikari.snowflakes.Snowflake, hikari.emojis.KnownCustomEmoji]
- The emojis in the guild.
- """
+ """Mapping of emoji IDs to the emojis in the guild."""
stickers: typing.Mapping[snowflakes.Snowflake, stickers_.GuildSticker] = attr.field(repr=False)
"""Mapping of sticker IDs to the stickers in the guild."""
roles: typing.Mapping[snowflakes.Snowflake, guilds.Role] = attr.field(repr=False)
- """Mapping of role IDs to the roles in the guild.
-
- Returns
- -------
- typing.Mapping[hikari.snowflakes.Snowflake, hikari.guilds.Role]
- The roles in the guild.
- """
+ """Mapping of role IDs to the roles in the guild."""
@property
def app(self) -> traits.RESTAware:
@@ -430,13 +353,12 @@ def app(self) -> traits.RESTAware:
@property
@abc.abstractmethod
def user(self) -> users.User:
- """User that this ban event affects.
+ """User that this ban event affects."""
- Returns
- -------
- hikari.users.User
- The user that this event concerns.
- """
+ @property
+ def user_id(self) -> snowflakes.Snowflake:
+ """User ID of the user that got banned."""
+ return self.user.id
async def fetch_user(self) -> users.User:
"""Perform an API call to fetch the user this ban event affects.
@@ -464,17 +386,6 @@ class BanCreateEvent(BanEvent):
user: users.User = attr.field()
# <>.
- @property
- def user_id(self) -> snowflakes.Snowflake:
- """User ID of the user that got banned.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- ID of the user the event concerns.
- """
- return self.user.id
-
async def fetch_ban(self) -> guilds.GuildBan:
"""Perform an API call to fetch the details about this ban.
@@ -523,24 +434,18 @@ class EmojisUpdateEvent(GuildEvent):
old_emojis: typing.Optional[typing.Sequence[emojis_.KnownCustomEmoji]] = attr.field()
"""Sequence of all old emojis in this guild.
- This will be `builtins.None` if it's missing from the cache.
+ This will be `None` if it's missing from the cache.
"""
emojis: typing.Sequence[emojis_.KnownCustomEmoji] = attr.field()
- """Sequence of all emojis in this guild.
-
- Returns
- -------
- typing.Sequence[emojis_.KnownCustomEmoji]
- All emojis in the guild.
- """
+ """Sequence of all emojis in this guild."""
async def fetch_emojis(self) -> typing.Sequence[emojis_.KnownCustomEmoji]:
"""Perform an API call to retrieve an up-to-date view of the emojis.
Returns
-------
- typing.Sequence[emojis_.KnownCustomEmoji]
+ typing.Sequence[hikari.emojis.KnownCustomEmoji]
All emojis in the guild.
"""
return await self.app.rest.fetch_guild_emojis(self.guild_id)
@@ -564,7 +469,7 @@ class StickersUpdateEvent(GuildEvent):
old_stickers: typing.Optional[typing.Sequence[stickers_.GuildSticker]] = attr.field()
"""Sequence of all old stickers in this guild.
- This will be `builtins.None` if it's missing from the cache.
+ This will be `None` if it's missing from the cache.
"""
stickers: typing.Sequence[stickers_.GuildSticker] = attr.field()
@@ -590,34 +495,22 @@ class IntegrationEvent(GuildEvent, abc.ABC):
@property
@abc.abstractmethod
def application_id(self) -> typing.Optional[snowflakes.Snowflake]:
- """ID of Discord bot application this integration is connected to.
-
- Returns
- -------
- typing.Optional[hikari.snowflakes.Snowflake]
- The ID of Discord bot application this integration is connected to.
- """
+ """ID of Discord bot application this integration is connected to."""
@property
@abc.abstractmethod
def id(self) -> snowflakes.Snowflake:
- """ID of the integration.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the integration.
- """
+ """ID of the integration."""
async def fetch_integrations(self) -> typing.Sequence[guilds.Integration]:
"""Perform an API call to fetch some number of guild integrations.
- !!! warning
+ .. warning::
The results of this are not clearly defined by Discord. The current
behaviour appears to be that only the first 50 integrations actually
get returned. Discord have made it clear that they are not willing
to fix this in
- https://github.com/discord/discord-api-docs/issues/1990.
+ .
Returns
-------
@@ -735,17 +628,11 @@ class PresenceUpdateEvent(shard_events.ShardEvent):
old_presence: typing.Optional[presences_.MemberPresence] = attr.field()
"""The old member presence object.
- This will be `builtins.None` if the member presence missing from the cache.
+ This will be `None` if the member presence missing from the cache.
"""
presence: presences_.MemberPresence = attr.field()
- """Member presence.
-
- Returns
- -------
- hikari.presences.MemberPresence
- Presence for the user in this guild.
- """
+ """Member presence."""
user: typing.Optional[users.PartialUser] = attr.field()
"""User that was updated.
@@ -753,14 +640,9 @@ class PresenceUpdateEvent(shard_events.ShardEvent):
This is a partial user object that only contains the fields that were
updated on the user profile.
- Will be `builtins.None` if the user itself did not change.
+ Will be `None` if the user itself did not change.
This is always the case if the user only updated their member
representation and did not change their user profile directly.
-
- Returns
- -------
- typing.Optional[hikari.users.PartialUser]
- The partial user containing the updated fields.
"""
@property
@@ -770,24 +652,12 @@ def app(self) -> traits.RESTAware:
@property
def user_id(self) -> snowflakes.Snowflake:
- """User ID of the user that updated their presence.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- ID of the user the event concerns.
- """
+ """User ID of the user that updated their presence."""
return self.presence.user_id
@property
def guild_id(self) -> snowflakes.Snowflake:
- """Guild ID that the presence was updated in.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- ID of the guild the event occurred in.
- """
+ """Guild ID that the presence was updated in."""
return self.presence.guild_id
def get_user(self) -> typing.Optional[users.User]:
@@ -796,7 +666,7 @@ def get_user(self) -> typing.Optional[users.User]:
Returns
-------
typing.Optional[hikari.users.User]
- The full cached user, or `builtins.None` if not cached.
+ The full cached user, or `None` if not cached.
"""
if not isinstance(self.app, traits.CacheAware):
return None
diff --git a/hikari/events/interaction_events.py b/hikari/events/interaction_events.py
index ae6786e4cc..750015b071 100644
--- a/hikari/events/interaction_events.py
+++ b/hikari/events/interaction_events.py
@@ -47,13 +47,7 @@ class InteractionCreateEvent(shard_events.ShardEvent):
"""Shard that received this event."""
interaction: base_interactions.PartialInteraction = attr.field(repr=True)
- """Interaction that this event is related to.
-
- Returns
- -------
- hikari.interactions.base_interactions.PartialInteraction
- Object of the interaction that this event is related to.
- """
+ """Interaction that this event is related to."""
@property
def app(self) -> traits.RESTAware:
diff --git a/hikari/events/lifetime_events.py b/hikari/events/lifetime_events.py
index 0f76a4be29..04ab7dcc4d 100644
--- a/hikari/events/lifetime_events.py
+++ b/hikari/events/lifetime_events.py
@@ -44,13 +44,13 @@
@attr_extensions.with_copy
@attr.define(kw_only=True, weakref_slot=False)
class StartingEvent(base_events.Event):
- """Event that is triggered before the application connects to discord.
+ """Event that is triggered before the application connects to Discord.
This will only fire once per `bot.run` / `bot.start`, so is suitable for
opening database connections and other resources that need to be
initialized within a coroutine function.
- !!! warning
+ .. warning::
The application will not proceed to connect to Discord until all event
handlers for this event have completed/terminated. This prevents the
risk of race conditions occurring (e.g. allowing message events
@@ -92,7 +92,7 @@ class StoppingEvent(base_events.Event):
closing database connections and other resources that need to be
closed within a coroutine function.
- !!! warning
+ .. warning::
The application will not proceed to disconnect from Discord until all
event handlers for this event have completed/terminated. This
prevents the risk of race conditions occurring from code that relies
@@ -115,14 +115,14 @@ class StoppedEvent(base_events.Event):
closing database connections and other resources that need to be
closed within a coroutine function.
- !!! warning
+ .. warning::
The application will not proceed to leave the `bot.run` call until all
event handlers for this event have completed/terminated. This
prevents the risk of race conditions occurring where a script may
terminate the process before a callback can occur.
If you want to do something when the application is preparing to shut down,
- but _before_ any connection to discord is closed, you should consider using
+ but _before_ any connection to Discord is closed, you should consider using
`StoppingEvent` instead.
"""
diff --git a/hikari/events/member_events.py b/hikari/events/member_events.py
index 8b91268ebe..e4b6ca75bb 100644
--- a/hikari/events/member_events.py
+++ b/hikari/events/member_events.py
@@ -57,46 +57,28 @@ def app(self) -> traits.RESTAware:
@property
@abc.abstractmethod
def guild_id(self) -> snowflakes.Snowflake:
- """ID of the guild that this event relates to.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the guild that relates to this event.
- """
+ """ID of the guild that this event relates to."""
@property
@abc.abstractmethod
def user(self) -> users.User:
- """User object for the member this event concerns.
-
- Returns
- -------
- hikari.users.User
- User object for the member this event concerns.
- """
+ """User object for the member this event concerns."""
@property
def user_id(self) -> snowflakes.Snowflake:
- """ID of the user that this event concerns.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the user that this event relates to.
- """
+ """ID of the user that this event concerns."""
return self.user.id
def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
"""Get the cached view of the guild this member event occurred in.
- If the guild itself is not cached, this will return `builtins.None`.
+ If the guild itself is not cached, this will return `None`.
Returns
-------
typing.Optional[hikari.guilds.GatewayGuild]
The guild that this event occurred in, if known, else
- `builtins.None`.
+ `None`.
"""
if not isinstance(self.app, traits.CacheAware):
return None
@@ -114,13 +96,7 @@ class MemberCreateEvent(MemberEvent):
# <>.
member: guilds.Member = attr.field()
- """Member object for the member that joined the guild.
-
- Returns
- -------
- hikari.guilds.Member
- The member object for the member who just joined.
- """
+ """Member object for the member that joined the guild."""
@property
def guild_id(self) -> snowflakes.Snowflake:
@@ -148,17 +124,11 @@ class MemberUpdateEvent(MemberEvent):
old_member: typing.Optional[guilds.Member] = attr.field()
"""The old member object.
- This will be `builtins.None` if the member missing from the cache.
+ This will be `None` if the member missing from the cache.
"""
member: guilds.Member = attr.field()
- """Member object for the member that was updated.
-
- Returns
- -------
- hikari.guilds.Member
- The member object for the member that was updated.
- """
+ """Member object for the member that was updated."""
@property
def guild_id(self) -> snowflakes.Snowflake:
@@ -189,5 +159,5 @@ class MemberDeleteEvent(MemberEvent):
old_member: typing.Optional[guilds.Member] = attr.field()
"""The old member object.
- This will be `builtins.None` if the member was missing from the cache.
+ This will be `None` if the member was missing from the cache.
"""
diff --git a/hikari/events/message_events.py b/hikari/events/message_events.py
index e108a82ed7..400fd0934d 100644
--- a/hikari/events/message_events.py
+++ b/hikari/events/message_events.py
@@ -69,24 +69,12 @@ class MessageEvent(shard_events.ShardEvent, abc.ABC):
@property
@abc.abstractmethod
def channel_id(self) -> snowflakes.Snowflake:
- """ID of the channel that this event concerns.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the channel that this event concerns.
- """
+ """ID of the channel that this event concerns."""
@property
@abc.abstractmethod
def message_id(self) -> snowflakes.Snowflake:
- """ID of the message that this event concerns.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the message that this event concerns.
- """
+ """ID of the message that this event concerns."""
@base_events.requires_intents(intents.Intents.DM_MESSAGES, intents.Intents.GUILD_MESSAGES)
@@ -102,24 +90,12 @@ def app(self) -> traits.RESTAware:
@property
def author(self) -> users.User:
- """User that sent the message.
-
- Returns
- -------
- hikari.users.User
- The user that sent the message.
- """
+ """User that sent the message."""
return self.message.author
@property
def author_id(self) -> snowflakes.Snowflake:
- """ID of the author of the message this event concerns.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the author.
- """
+ """ID of the author of the message this event concerns."""
return self.author.id
@property
@@ -131,81 +107,41 @@ def channel_id(self) -> snowflakes.Snowflake:
def content(self) -> typing.Optional[str]:
"""Content of the message.
- Returns
- -------
- typing.Optional[builtins.str]
- The content of the message, if present. This may be `builtins.None`
- or an empty string (or any falsy value) if no content is present
- (e.g. if only an embed was sent).
+ The content of the message, if present. This will be `None`
+ if no content is present (e.g. if only an embed was sent).
"""
return self.message.content
@property
def embeds(self) -> typing.Sequence[embeds_.Embed]:
- """Sequence of embeds in the message.
-
- Returns
- -------
- typing.Sequence[hikari.embeds.Embed]
- The embeds in the message.
- """
+ """Sequence of embeds in the message."""
return self.message.embeds
@property
def is_bot(self) -> bool:
- """Return `builtins.True` if the message is from a bot.
-
- Returns
- -------
- builtins.bool
- `builtins.True` if from a bot, or `builtins.False` otherwise.
- """
+ """Return `True` if the message is from a bot."""
return self.message.author.is_bot
@property
def is_human(self) -> bool:
- """Return `builtins.True` if the message was created by a human.
-
- Returns
- -------
- builtins.bool
- `builtins.True` if from a human user, or `builtins.False` otherwise.
- """
+ """Return `True` if the message was created by a human."""
# Not second-guessing some weird edge case will occur in the future with this,
# so I am being safe rather than sorry.
return not self.message.author.is_bot and self.message.webhook_id is None
@property
def is_webhook(self) -> bool:
- """Return `builtins.True` if the message was created by a webhook.
-
- Returns
- -------
- builtins.bool
- `builtins.True` if from a webhook, or `builtins.False` otherwise.
- """
+ """Return `True` if the message was created by a webhook."""
return self.message.webhook_id is not None
@property
@abc.abstractmethod
def message(self) -> messages.Message:
- """Message that was sent in the event.
-
- Returns
- -------
- hikari.messages.Message
- The message object that was sent with this event.
- """
+ """Message that was sent in the event."""
@property
def message_id(self) -> snowflakes.Snowflake:
- """ID of the message that this event concerns.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the message that this event concerns.
- """
+ """ID of the message that this event concerns."""
return self.message.id
@@ -226,36 +162,17 @@ class GuildMessageCreateEvent(MessageCreateEvent):
@property
def author(self) -> users.User:
- """User object of the user that sent the message.
-
- Returns
- -------
- hikari.users.User
- The user object of the user that sent the message.
- """
+ """User object of the user that sent the message."""
return self.message.author
@property
def member(self) -> typing.Optional[guilds.Member]:
- """Member object of the user that sent the message.
-
- Returns
- -------
- typing.Optional[hikari.guilds.Member]
- The member object of the user that sent the message or
- `builtins.None` if sent by a webhook.
- """
+ """Member object of the user that sent the message."""
return self.message.member
@property
def guild_id(self) -> snowflakes.Snowflake:
- """ID of the guild that this event occurred in.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the guild that this event occurred in.
- """
+ """ID of the guild that this event occurred in."""
guild_id = self.message.guild_id
# Always present on guild events
assert isinstance(guild_id, snowflakes.Snowflake), "no guild_id attribute set"
@@ -268,7 +185,7 @@ def get_channel(self) -> typing.Optional[channels.TextableGuildChannel]:
-------
typing.Optional[hikari.channels.TextableGuildChannel]
The channel that the message was sent in, if known and cached,
- otherwise, `builtins.None`.
+ otherwise, `None`.
"""
if not isinstance(self.app, traits.CacheAware):
return None
@@ -282,7 +199,7 @@ def get_channel(self) -> typing.Optional[channels.TextableGuildChannel]:
def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
"""Get the cached guild that this event occurred in, if known.
- !!! note
+ .. note::
This will require the `GUILDS` intent to be specified on start-up
in order to be known.
@@ -290,7 +207,7 @@ def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
-------
typing.Optional[hikari.guilds.GatewayGuild]
The guild that this event occurred in, if cached. Otherwise,
- `builtins.None` instead.
+ `None` instead.
"""
if not isinstance(self.app, traits.CacheAware):
return None
@@ -331,7 +248,7 @@ class DMMessageCreateEvent(MessageCreateEvent):
class MessageUpdateEvent(MessageEvent, abc.ABC):
"""Event that is fired when a message is updated.
- !!! note
+ .. note::
Less information will be available here than in the creation event
due to Discord limitations.
"""
@@ -371,13 +288,11 @@ def channel_id(self) -> snowflakes.Snowflake:
def content(self) -> undefined.UndefinedNoneOr[str]:
"""Content of the message.
- Returns
- -------
- hikari.undefined.UndefinedNoneOr[builtins.str]
- The content of the message, if present. This may be `builtins.None`
- or an empty string (or any falsy value) if no content is present
- (e.g. if only an embed was sent). If not part of the update, then
- this will be `hikari.undefined.UNDEFINED` instead.
+ The content of the message, if present. This may be `None`
+ if no content is present (e.g. if only an embed was sent).
+
+ If not part of the update, then this will be
+ `hikari.undefined.UNDEFINED` instead.
"""
return self.message.content
@@ -385,26 +300,18 @@ def content(self) -> undefined.UndefinedNoneOr[str]:
def embeds(self) -> undefined.UndefinedOr[typing.Sequence[embeds_.Embed]]:
"""Sequence of embeds in the message.
- Returns
- -------
- hikari.undefined.UndefinedOr[typing.Sequence[hikari.embeds.Embed]]
- The embeds in the message. If the embeds were not changed in this
- event, then this may instead be `hikari.undefined.UNDEFINED`.
+ If the embeds were not changed in this event, then this may instead be
+ `hikari.undefined.UNDEFINED`.
"""
return self.message.embeds
@property
def is_bot(self) -> undefined.UndefinedOr[bool]:
- """Return `builtins.True` if the message is from a bot.
+ """Whether the message is from a bot.
- Returns
- -------
- typing.Optional[builtins.bool]
- `builtins.True` if from a bot, or `builtins.False` otherwise.
-
- If the author is not known, due to the update event being caused
- by Discord adding an embed preview to accompany a URL, then this
- will return `hikari.undefined.UNDEFINED` instead.
+ If the author is not known, due to the update event being caused
+ by Discord adding an embed preview to accompany a URL, then this
+ will return `hikari.undefined.UNDEFINED` instead.
"""
if (author := self.message.author) is not undefined.UNDEFINED:
return author.is_bot
@@ -413,16 +320,11 @@ def is_bot(self) -> undefined.UndefinedOr[bool]:
@property
def is_human(self) -> undefined.UndefinedOr[bool]:
- """Return `builtins.True` if the message was created by a human.
-
- Returns
- -------
- typing.Optional[builtins.bool]
- `builtins.True` if from a human user, or `builtins.False` otherwise.
+ """Whether the message was created by a human.
- If the author is not known, due to the update event being caused
- by Discord adding an embed preview to accompany a URL, then this
- may return `hikari.undefined.UNDEFINED` instead.
+ If the author is not known, due to the update event being caused
+ by Discord adding an embed preview to accompany a URL, then this
+ may return `hikari.undefined.UNDEFINED` instead.
"""
# Not second-guessing some weird edge case will occur in the future with this,
# so I am being safe rather than sorry.
@@ -436,12 +338,11 @@ def is_human(self) -> undefined.UndefinedOr[bool]:
@property
def is_webhook(self) -> undefined.UndefinedOr[bool]:
- """Return `builtins.True` if the message was created by a webhook.
+ """Whether the message was created by a webhook.
- Returns
- -------
- builtins.bool
- `builtins.True` if from a webhook, or `builtins.False` otherwise.
+ If the author is not known, due to the update event being caused
+ by Discord adding an embed preview to accompany a URL, then this
+ may return `hikari.undefined.UNDEFINED` instead.
"""
if (webhook_id := self.message.webhook_id) is not undefined.UNDEFINED:
return webhook_id is not None
@@ -451,23 +352,11 @@ def is_webhook(self) -> undefined.UndefinedOr[bool]:
@property
@abc.abstractmethod
def message(self) -> messages.PartialMessage:
- """Partial message that was sent in the event.
-
- Returns
- -------
- hikari.messages.PartialMessage
- The partial message object that was sent with this event.
- """
+ """Partial message that was sent in the event."""
@property
def message_id(self) -> snowflakes.Snowflake:
- """ID of the message that this event concerns.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the message that this event concerns.
- """
+ """ID of the message that this event concerns."""
return self.message.id
@@ -477,7 +366,7 @@ def message_id(self) -> snowflakes.Snowflake:
class GuildMessageUpdateEvent(MessageUpdateEvent):
"""Event that is fired when a message is updated in a guild.
- !!! note
+ .. note::
Less information will be available here than in the creation event
due to Discord limitations.
"""
@@ -485,7 +374,7 @@ class GuildMessageUpdateEvent(MessageUpdateEvent):
old_message: typing.Optional[messages.PartialMessage] = attr.field()
"""The old message object.
- This will be `builtins.None` if the message missing from the cache.
+ This will be `None` if the message missing from the cache.
"""
message: messages.PartialMessage = attr.field()
@@ -498,7 +387,7 @@ class GuildMessageUpdateEvent(MessageUpdateEvent):
def member(self) -> undefined.UndefinedNoneOr[guilds.Member]:
"""Member that sent the message if provided by the event.
- If the message is not in a guild, this will be `builtins.None`.
+ If the message is not in a guild, this will be `None`.
This will also be `hikari.undefined.UNDEFINED` in some cases such as when Discord
updates a message with an embed URL preview.
@@ -520,13 +409,7 @@ def get_member(self) -> typing.Optional[guilds.Member]:
@property
def guild_id(self) -> snowflakes.Snowflake:
- """ID of the guild that this event occurred in.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the guild that this event occurred in.
- """
+ """ID of the guild that this event occurred in."""
guild_id = self.message.guild_id
# Always present on guild events
assert isinstance(guild_id, snowflakes.Snowflake), f"expected guild_id, got {guild_id}"
@@ -539,7 +422,7 @@ def get_channel(self) -> typing.Optional[channels.TextableGuildChannel]:
-------
typing.Optional[hikari.channels.TextableGuildChannel]
The channel that the message was sent in, if known and cached,
- otherwise, `builtins.None`.
+ otherwise, `None`.
"""
if not isinstance(self.app, traits.CacheAware):
return None
@@ -553,7 +436,7 @@ def get_channel(self) -> typing.Optional[channels.TextableGuildChannel]:
def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
"""Get the cached guild that this event occurred in, if known.
- !!! note
+ .. note::
This will require the `GUILDS` intent to be specified on start-up
in order to be known.
@@ -561,7 +444,7 @@ def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
-------
typing.Optional[hikari.guilds.GatewayGuild]
The guild that this event occurred in, if cached. Otherwise,
- `builtins.None` instead.
+ `None` instead.
"""
if not isinstance(self.app, traits.CacheAware):
return None
@@ -575,7 +458,7 @@ def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
class DMMessageUpdateEvent(MessageUpdateEvent):
"""Event that is fired when a message is updated in a DM.
- !!! note
+ .. note::
Less information will be available here than in the creation event
due to Discord limitations.
"""
@@ -583,7 +466,7 @@ class DMMessageUpdateEvent(MessageUpdateEvent):
old_message: typing.Optional[messages.PartialMessage] = attr.field()
"""The old message object.
- This will be `builtins.None` if the message missing from the cache.
+ This will be `None` if the message missing from the cache.
"""
message: messages.PartialMessage = attr.field()
@@ -597,7 +480,7 @@ class DMMessageUpdateEvent(MessageUpdateEvent):
class MessageDeleteEvent(MessageEvent, abc.ABC):
"""Special event that is triggered when a message gets deleted.
- !!! note
+ .. note::
Due to Discord limitations, most message information is unavailable
during deletion events.
"""
@@ -624,7 +507,7 @@ def old_message(self) -> typing.Optional[messages.Message]:
class GuildMessageDeleteEvent(MessageDeleteEvent):
"""Event that is triggered if a message is deleted in a guild.
- !!! note
+ .. note::
Due to Discord limitations, most message information is unavailable
during deletion events.
"""
@@ -653,7 +536,7 @@ def get_channel(self) -> typing.Optional[channels.TextableGuildChannel]:
Returns
-------
typing.Optional[hikari.channels.TextableGuildChannel]
- The channel the messages were sent in, or `builtins.None` if not
+ The channel the messages were sent in, or `None` if not
known/cached.
"""
if not isinstance(self.app, traits.CacheAware):
@@ -668,7 +551,7 @@ def get_channel(self) -> typing.Optional[channels.TextableGuildChannel]:
def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
"""Get the cached guild this event corresponds to, if known.
- !!! note
+ .. note::
You will need `hikari.intents.Intents.GUILDS` enabled to receive this
information.
@@ -690,7 +573,7 @@ def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
class DMMessageDeleteEvent(MessageDeleteEvent):
"""Event that is triggered if a message is deleted in a DM.
- !!! note
+ .. note::
Due to Discord limitations, most message information is unavailable
during deletion events.
"""
@@ -717,7 +600,7 @@ class DMMessageDeleteEvent(MessageDeleteEvent):
class GuildBulkMessageDeleteEvent(shard_events.ShardEvent):
"""Event that is triggered when a bulk deletion is triggered in a guild.
- !!! note
+ .. note::
Due to Discord limitations, most message information is unavailable
during deletion events.
"""
@@ -749,7 +632,7 @@ def get_channel(self) -> typing.Optional[channels.TextableGuildChannel]:
Returns
-------
typing.Optional[hikari.channels.TextableGuildChannel]
- The channel the messages were sent in, or `builtins.None` if not
+ The channel the messages were sent in, or `None` if not
known/cached.
"""
if not isinstance(self.app, traits.CacheAware):
@@ -764,7 +647,7 @@ def get_channel(self) -> typing.Optional[channels.TextableGuildChannel]:
def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
"""Get the cached guild this event corresponds to, if known.
- !!! note
+ .. note::
You will need `hikari.intents.Intents.GUILDS` enabled to receive this
information.
diff --git a/hikari/events/reaction_events.py b/hikari/events/reaction_events.py
index c9110c5cc3..a706e86e0b 100644
--- a/hikari/events/reaction_events.py
+++ b/hikari/events/reaction_events.py
@@ -69,24 +69,12 @@ class ReactionEvent(shard_events.ShardEvent, abc.ABC):
@property
@abc.abstractmethod
def channel_id(self) -> snowflakes.Snowflake:
- """ID of the channel that this event concerns.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the channel that this event concerns.
- """
+ """ID of the channel that this event concerns."""
@property
@abc.abstractmethod
def message_id(self) -> snowflakes.Snowflake:
- """ID of the message that this event concerns.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the message that this event concerns.
- """
+ """ID of the message that this event concerns."""
@base_events.requires_intents(intents.Intents.GUILD_MESSAGE_REACTIONS)
@@ -98,13 +86,7 @@ class GuildReactionEvent(ReactionEvent, abc.ABC):
@property
@abc.abstractmethod
def guild_id(self) -> snowflakes.Snowflake:
- """ID of the guild that this event concerns.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the guild that this event concerns.
- """
+ """ID of the guild that this event concerns."""
@base_events.requires_intents(intents.Intents.DM_MESSAGE_REACTIONS)
@@ -123,66 +105,42 @@ class ReactionAddEvent(ReactionEvent, abc.ABC):
@property
@abc.abstractmethod
def user_id(self) -> snowflakes.Snowflake:
- """ID of the user that added this reaction.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the user that added this reaction.
- """
+ """ID of the user that added this reaction."""
@property
@abc.abstractmethod
def emoji_name(self) -> typing.Union[emojis.UnicodeEmoji, str, None]:
"""Name of the emoji which was added if known.
- !!! note
- This will be `builtins.None` when the relevant custom emoji's data
- is not available (e.g. the emoji has been deleted).
-
- Returns
- -------
- typing.Union[hikari.emojis.UnicodeEmoji, builtins.str, builtins.None]
- Either the string name of the custom emoji which was added
- or the object of the `hikari.emojis.UnicodeEmoji` which was added.
+ This can either be the string name of the custom emoji which was added,
+ the object of the `hikari.emojis.UnicodeEmoji` which was added or
+ `None` when the relevant custom emoji's data is not available
+ (e.g. the emoji has been deleted).
"""
@property
@abc.abstractmethod
def emoji_id(self) -> typing.Optional[snowflakes.Snowflake]:
- """ID of the emoji which was added if it is custom.
-
- Returns
- -------
- typing.Optional[hikari.snowflakes.Snowflake]
- ID of the emoji which was added if it was a custom emoji or
- `builtins.None`.
- """
+ """ID of the emoji which was added if it is custom, else `None`."""
@property
@abc.abstractmethod
def is_animated(self) -> bool:
- """Whether the emoji which was added is animated.
-
- Returns
- -------
- builtins.bool
- Whether the emoji which was added is animated.
- """
+ """Whether the emoji which was added is animated."""
def is_for_emoji(self, emoji: typing.Union[emojis.Emoji, str], /) -> bool:
"""Get whether the reaction event is for a specific emoji.
Parameters
----------
- emoji : typing.Union[hikari.emojis.Emoji, builtins.str]
+ emoji : typing.Union[hikari.emojis.Emoji, str]
The emoji to check.
- Passing `builtins.str` here indicates a unicode emoji.
+ Passing `str` here indicates a unicode emoji.
Returns
-------
- builtins.bool
+ bool
Whether the emoji is the one which was added.
"""
return emoji.id == self.emoji_id if isinstance(emoji, emojis.CustomEmoji) else emoji == self.emoji_name
@@ -197,55 +155,37 @@ class ReactionDeleteEvent(ReactionEvent, abc.ABC):
@property
@abc.abstractmethod
def user_id(self) -> snowflakes.Snowflake:
- """User ID for the user that added this reaction initially.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the user that removed this reaction.
- """
+ """User ID for the user that added this reaction initially."""
@property
@abc.abstractmethod
def emoji_name(self) -> typing.Union[emojis.UnicodeEmoji, str, None]:
"""Name of the emoji which was removed.
- !!! note
- This will be `builtins.None` when the relevant custom emoji's data
- is not available (e.g. the emoji has been deleted).
-
- Returns
- -------
- typing.Union[hikari.emojis.UnicodeEmoji, builtins.str, builtins.None]
- Either the string name of the custom emoji which was removed
- or the object of the `hikari.emojis.UnicodeEmoji` which was removed.
+ Either the string name of the custom emoji which was removed, the object
+ of the `hikari.emojis.UnicodeEmoji` which was removed or `None`
+ when the relevant custom emoji's data is not available (e.g. the emoji
+ has been deleted).
"""
@property
@abc.abstractmethod
def emoji_id(self) -> typing.Optional[snowflakes.Snowflake]:
- """ID of the emoji which was removed if it was custom.
-
- Returns
- -------
- typing.Optional[hikari.snowflakes.Snowflake]
- ID of the emoji which was removed if it was a custom emoji or
- `builtins.None`.
- """
+ """ID of the emoji which was added if it is custom, else `None`."""
def is_for_emoji(self, emoji: typing.Union[emojis.Emoji, str], /) -> bool:
"""Get whether the reaction event is for a specific emoji.
Parameters
----------
- emoji : typing.Union[hikari.emojis.Emoji, builtins.str]
+ emoji : typing.Union[hikari.emojis.Emoji, str]
The emoji to check.
- Passing `builtins.str` here indicates a unicode emoji.
+ Passing `str` here indicates a unicode emoji.
Returns
-------
- builtins.bool
+ bool
Whether the emoji is the one which was removed.
"""
return emoji.id == self.emoji_id if isinstance(emoji, emojis.CustomEmoji) else emoji == self.emoji_name
@@ -267,44 +207,32 @@ class ReactionDeleteEmojiEvent(ReactionEvent, abc.ABC):
@property
@abc.abstractmethod
def emoji_name(self) -> typing.Union[emojis.UnicodeEmoji, str, None]:
- """Name of the emoji which was removed if known.
-
- !!! note
- This will be `builtins.None` when the relevant custom emoji's data
- is not available (e.g. the emoji has been deleted).
+ """Name of the emoji which was removed.
- Returns
- -------
- typing.Union[hikari.emojis.UnicodeEmoji, builtins.str, builtins.None]
- Either the string name of the custom emoji which was removed
- or the object of the `hikari.emojis.UnicodeEmoji` which was removed.
+ Either the string name of the custom emoji which was removed, the object
+ of the `hikari.emojis.UnicodeEmoji` which was removed or `None`
+ when the relevant custom emoji's data is not available (e.g. the emoji
+ has been deleted).
"""
@property
@abc.abstractmethod
def emoji_id(self) -> typing.Optional[snowflakes.Snowflake]:
- """ID of the emoji which was removed if it was custom.
-
- Returns
- -------
- typing.Optional[hikari.snowflakes.Snowflake]
- ID of the emoji which was removed if it was a custom emoji or
- `builtins.None`.
- """
+ """ID of the emoji which was added if it is custom, else `None`."""
def is_for_emoji(self, emoji: typing.Union[emojis.Emoji, str], /) -> bool:
"""Get whether the reaction event is for a specific emoji.
Parameters
----------
- emoji : typing.Union[hikari.emojis.Emoji, builtins.str]
+ emoji : typing.Union[hikari.emojis.Emoji, str]
The emoji to check.
- Passing `builtins.str` here indicates a unicode emoji.
+ Passing `str` here indicates a unicode emoji.
Returns
-------
- builtins.bool
+ bool
Whether the emoji is the one which was removed.
"""
return emoji.id == self.emoji_id if isinstance(emoji, emojis.CustomEmoji) else emoji == self.emoji_name
@@ -320,13 +248,7 @@ class GuildReactionAddEvent(GuildReactionEvent, ReactionAddEvent):
# <>.
member: guilds.Member = attr.field()
- """Member that added the reaction.
-
- Returns
- -------
- hikari.guilds.Member
- The member which added this reaction.
- """
+ """Member that added the reaction."""
channel_id: snowflakes.Snowflake = attr.field()
# <>.
diff --git a/hikari/events/role_events.py b/hikari/events/role_events.py
index e888f17a2b..0d0ceb4793 100644
--- a/hikari/events/role_events.py
+++ b/hikari/events/role_events.py
@@ -51,24 +51,12 @@ class RoleEvent(shard_events.ShardEvent, abc.ABC):
@property
@abc.abstractmethod
def guild_id(self) -> snowflakes.Snowflake:
- """ID of the guild that this event relates to.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the guild that relates to this event.
- """
+ """ID of the guild that this event relates to."""
@property
@abc.abstractmethod
def role_id(self) -> snowflakes.Snowflake:
- """ID of the role that this event relates to.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the role that relates to this event.
- """
+ """ID of the role that this event relates to."""
@attr_extensions.with_copy
@@ -81,13 +69,7 @@ class RoleCreateEvent(RoleEvent):
# <>.
role: guilds.Role = attr.field()
- """Role that was created.
-
- Returns
- -------
- hikari.guilds.Role
- The created role.
- """
+ """Role that was created."""
@property
def app(self) -> traits.RESTAware:
@@ -117,17 +99,11 @@ class RoleUpdateEvent(RoleEvent):
old_role: typing.Optional[guilds.Role] = attr.field()
"""The old role object.
- This will be `builtins.None` if the role missing from the cache.
+ This will be `None` if the role missing from the cache.
"""
role: guilds.Role = attr.field()
- """Role that was updated.
-
- Returns
- -------
- hikari.guilds.Role
- The created role.
- """
+ """Role that was updated."""
@property
def app(self) -> traits.RESTAware:
@@ -166,5 +142,5 @@ class RoleDeleteEvent(RoleEvent):
old_role: typing.Optional[guilds.Role] = attr.field()
"""The old role object.
- This will be `builtins.None` if the role was missing from the cache.
+ This will be `None` if the role was missing from the cache.
"""
diff --git a/hikari/events/shard_events.py b/hikari/events/shard_events.py
index 5b8e170635..379ff04c5e 100644
--- a/hikari/events/shard_events.py
+++ b/hikari/events/shard_events.py
@@ -62,13 +62,7 @@ class ShardEvent(base_events.Event, abc.ABC):
@property
@abc.abstractmethod
def shard(self) -> gateway_shard.GatewayShard:
- """Shard that received this event.
-
- Returns
- -------
- hikari.api.shard.GatewayShard
- The shard that triggered the event.
- """
+ """Shard that received this event."""
@attr_extensions.with_copy
@@ -76,7 +70,7 @@ def shard(self) -> gateway_shard.GatewayShard:
class ShardPayloadEvent(ShardEvent):
"""Event fired for most shard events with their raw payload.
- !!! note
+ .. note::
This will only be dispatched for real dispatch events received from
Discord and not artificial events like the `ShardStateEvent` events.
"""
@@ -136,64 +130,29 @@ class ShardReadyEvent(ShardStateEvent):
# <>.
actual_gateway_version: int = attr.field(repr=True)
- """Actual gateway version being used.
-
- Returns
- -------
- builtins.int
- The actual gateway version we are actively using for this protocol.
- """
+ """Actual gateway version being used."""
resume_gateway_url: str = attr.field(repr=False)
"""The URL to use to when reconnecting to the gateway."""
session_id: str = attr.field(repr=True)
- """ID for this session.
-
- Returns
- -------
- builtins.str
- The session ID for this gateway session.
- """
+ """ID for this session."""
my_user: users.OwnUser = attr.field(repr=True)
- """User for the current bot account this connection is authenticated with.
-
- Returns
- -------
- hikari.users.OwnUser
- This bot's user.
- """
+ """User for the current bot account this connection is authenticated with."""
unavailable_guilds: typing.Sequence[snowflakes.Snowflake] = attr.field(repr=False)
"""Sequence of the IDs for all guilds this bot is currently in.
All guilds will start off "unavailable" and should become available after
a few seconds of connecting one-by-one.
-
- Returns
- -------
- typing.Sequence[hikari.snowflakes.Snowflake]
- All guild IDs that the bot is in for this shard.
"""
application_id: snowflakes.Snowflake = attr.field(repr=True)
- """ID of the application this ready event is for.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The current application's ID.
- """
+ """ID of the application this ready event is for."""
application_flags: applications.ApplicationFlags = attr.field(repr=True)
- """Flags of the application this ready event is for.
-
- Returns
- -------
- hikari.applications.ApplicationFlags
- The current application's flags.
- """
+ """Flags of the application this ready event is for."""
@property
def app(self) -> traits.RESTAware:
@@ -228,65 +187,33 @@ class MemberChunkEvent(ShardEvent, typing.Sequence["guilds.Member"]):
# <>.
members: typing.Mapping[snowflakes.Snowflake, guilds.Member] = attr.field(repr=False)
- """Mapping of user IDs to the objects of the members in this chunk.
-
- Returns
- -------
- typing.Mapping[hikari.snowflakes.Snowflake, hikari.guilds.Member]
- Mapping of user IDs to corresponding member objects.
- """
+ """Mapping of user IDs to the objects of the members in this chunk."""
chunk_index: int = attr.field(repr=True)
- """Zero-indexed position of this within the queued up chunks for this request.
-
- Returns
- -------
- builtins.int
- The sequence index for this chunk.
- """
+ """Zero-indexed position of this within the queued up chunks for this request."""
chunk_count: int = attr.field(repr=True)
- """Total number of expected chunks for the request this is associated with.
-
- Returns
- -------
- builtins.int
- Total number of chunks to be expected.
- """
+ """Total number of expected chunks for the request this is associated with."""
not_found: typing.Sequence[snowflakes.Snowflake] = attr.field(repr=True)
"""Sequence of the snowflakes that were not found while making this request.
This is only applicable when user IDs are specified while making the
member request the chunk is associated with.
-
- Returns
- -------
- typing.Sequence[hikari.snowflakes.Snowflake]
- Sequence of user IDs that were not found.
"""
presences: typing.Mapping[snowflakes.Snowflake, presences_.MemberPresence] = attr.field(repr=False)
"""Mapping of user IDs to found member presence objects.
This will be empty if no presences are found or `include_presences` is not passed as
- `builtins.True` while requesting the member chunks.
-
- Returns
- -------
- typing.Mapping[hikari.snowflakes.Snowflake, hikari.presences.MemberPresence]
- Mapping of user IDs to corresponding presences.
+ `True` while requesting the member chunks.
"""
nonce: typing.Optional[str] = attr.field(repr=True)
"""String nonce used to identify the request member chunks are associated with.
- This is the nonce value passed while requesting member chunks.
-
- Returns
- -------
- typing.Optional[builtins.str]
- The request nonce if set, or `builtins.None` otherwise.
+ This is the nonce value passed while requesting member chunks or `None`
+ if there was no nonce passed.
"""
@typing.overload
diff --git a/hikari/events/typing_events.py b/hikari/events/typing_events.py
index 6d02278c2e..7ffbf69881 100644
--- a/hikari/events/typing_events.py
+++ b/hikari/events/typing_events.py
@@ -56,35 +56,17 @@ class TypingEvent(shard_events.ShardEvent, abc.ABC):
@property
@abc.abstractmethod
def channel_id(self) -> snowflakes.Snowflake:
- """ID of the channel that this event concerns.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the channel that this event concerns.
- """
+ """ID of the channel that this event concerns."""
@property
@abc.abstractmethod
def user_id(self) -> snowflakes.Snowflake:
- """ID of the user who triggered this typing event.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- ID of the user who is typing.
- """
+ """ID of the user who triggered this typing event."""
@property
@abc.abstractmethod
def timestamp(self) -> datetime.datetime:
- """Timestamp of when this typing event started.
-
- Returns
- -------
- datetime.datetime
- UTC timestamp of when the user started typing.
- """
+ """Timestamp of when this typing event started."""
async def fetch_channel(self) -> channels.TextableChannel:
"""Perform an API call to fetch an up-to-date image of this channel.
@@ -169,22 +151,10 @@ class GuildTypingEvent(TypingEvent):
# <>.
guild_id: snowflakes.Snowflake = attr.field()
- """ID of the guild that this event relates to.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID of the guild that relates to this event.
- """
+ """ID of the guild that this event relates to."""
member: guilds.Member = attr.field(repr=False)
- """Object of the member who triggered this typing event.
-
- Returns
- -------
- hikari.guilds.Member
- Object of the member who triggered this typing event.
- """
+ """Object of the member who triggered this typing event."""
@property
def app(self) -> traits.RESTAware:
@@ -260,12 +230,12 @@ def get_channel(self) -> typing.Optional[channels.TextableGuildChannel]:
def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
"""Get the cached object of the guild this typing event occurred in.
- If the guild is not found then this will return `builtins.None`.
+ If the guild is not found then this will return `None`.
Returns
-------
typing.Optional[hikari.guilds.GatewayGuild]
- The object of the gateway guild if found else `builtins.None`.
+ The object of the gateway guild if found else `None`.
"""
if not isinstance(self.app, traits.CacheAware):
return None
diff --git a/hikari/events/user_events.py b/hikari/events/user_events.py
index f332b0b4fa..65679c7dc9 100644
--- a/hikari/events/user_events.py
+++ b/hikari/events/user_events.py
@@ -49,17 +49,11 @@ class OwnUserUpdateEvent(shard_events.ShardEvent):
old_user: typing.Optional[users.OwnUser] = attr.field()
"""The old application user.
- This will be `builtins.None` if the user missing from the cache.
+ This will be `None` if the user missing from the cache.
"""
user: users.OwnUser = attr.field()
- """This application user.
-
- Returns
- -------
- hikari.users.OwnUser
- This application user.
- """
+ """This application user."""
@property
def app(self) -> traits.RESTAware:
diff --git a/hikari/events/voice_events.py b/hikari/events/voice_events.py
index 23c7bec440..95f972bcab 100644
--- a/hikari/events/voice_events.py
+++ b/hikari/events/voice_events.py
@@ -51,13 +51,7 @@ class VoiceEvent(shard_events.ShardEvent, abc.ABC):
@property
@abc.abstractmethod
def guild_id(self) -> snowflakes.Snowflake:
- """ID of the guild this event is for.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The guild ID of the guild this event relates to.
- """
+ """ID of the guild this event is for."""
@base_events.requires_intents(intents.Intents.GUILD_VOICE_STATES)
@@ -78,17 +72,11 @@ class VoiceStateUpdateEvent(VoiceEvent):
old_state: typing.Optional[voices.VoiceState] = attr.field(repr=True)
"""The old voice state.
- This will be `builtins.None` if the voice state missing from the cache.
+ This will be `None` if the voice state missing from the cache.
"""
state: voices.VoiceState = attr.field(repr=True)
- """Voice state that this update contained.
-
- Returns
- -------
- hikari.voices.VoiceState
- The voice state that was updated.
- """
+ """Voice state that this update contained."""
@property
def app(self) -> traits.RESTAware:
@@ -120,44 +108,27 @@ class VoiceServerUpdateEvent(VoiceEvent):
# <>
token: str = attr.field(repr=False)
- """Token that should be used to authenticate with the voice gateway.
-
- Returns
- -------
- builtins.str
- The token to use to authenticate with the voice gateway.
- """
+ """Token that should be used to authenticate with the voice gateway."""
raw_endpoint: typing.Optional[str] = attr.field(repr=True)
"""Raw endpoint URI that Discord sent.
- If this is `builtins.None`, it means that the server has been deallocated
+ If this is `None`, it means that the server has been deallocated
and you have to disconnect. You will later receive a new event specifying
what endpoint to connect to.
- !!! warning
+ .. warning::
This will not contain the scheme to use. Use the `endpoint` property
to get a representation that has this prepended.
-
- Returns
- -------
- builtins.str
- A scheme-less endpoint URI for the endpoint to use for a new voice
- websocket.
"""
@property
def endpoint(self) -> typing.Optional[str]:
"""URI for this voice server host, with the correct scheme prepended.
- If this is `builtins.None`, it means that the server has been deallocated
+ If this is `None`, it means that the server has been deallocated
and you have to disconnect. You will later receive a new event specifying
what endpoint to connect to.
-
- Returns
- -------
- typing.Optional[builtins.str]
- If not `builtins.None`, the URI to use to connect to the voice gateway.
"""
if self.raw_endpoint is None:
return None
diff --git a/hikari/files.py b/hikari/files.py
index b852ee271e..3ef996a5f0 100644
--- a/hikari/files.py
+++ b/hikari/files.py
@@ -77,7 +77,7 @@
This may be one of:
-- `builtins.str` path.
+- `str` path.
- `os.PathLike` derivative, such as `pathlib.PurePath` and `pathlib.Path`.
"""
@@ -133,7 +133,7 @@
This may be one of:
- `Resource` or a derivative.
-- `builtins.str` path.
+- `str` path.
- `os.PathLike` derivative, such as `pathlib.PurePath` and `pathlib.Path`.
- `bytes`
- `bytearray`
@@ -168,7 +168,7 @@ def ensure_resource(url_or_resource: Resourceish, /) -> Resource[AsyncReader]:
Parameters
----------
url_or_resource : Resourceish
- The item to convert. Ff a `Resource` is passed, it is
+ The item to convert. If a `Resource` is passed, it is
simply returned again. Anything else is converted to a `Resource` first.
Returns
@@ -204,13 +204,13 @@ def guess_mimetype_from_filename(name: str, /) -> typing.Optional[str]:
Parameters
----------
- name : builtins.bytes
+ name : bytes
The filename to inspect.
Returns
-------
- typing.Optional[builtins.str]
- The closest guess to the given filename. May be `builtins.None` if
+ typing.Optional[str]
+ The closest guess to the given filename. May be `None` if
no match was found.
"""
guess, _ = mimetypes.guess_type(name)
@@ -220,20 +220,20 @@ def guess_mimetype_from_filename(name: str, /) -> typing.Optional[str]:
def guess_mimetype_from_data(data: bytes, /) -> typing.Optional[str]:
"""Guess the mimetype of some data from the header.
- !!! warning
+ .. warning::
This function only detects valid image headers that Discord allows
the use of. Anything else will go undetected.
Parameters
----------
- data : builtins.bytes
+ data : bytes
The byte content to inspect.
Returns
-------
- typing.Optional[builtins.str]
+ typing.Optional[str]
The mimetype, if it was found. If the header is unrecognised, then
- `builtins.None` is returned.
+ `None` is returned.
"""
if data.startswith(b"\211PNG\r\n\032\n"):
return "image/png"
@@ -251,21 +251,21 @@ def guess_file_extension(mimetype: str) -> typing.Optional[str]:
Parameters
----------
- mimetype : builtins.str
+ mimetype : str
The mimetype to guess the extension for.
- Example
- -------
- ```py
- >>> guess_file_extension("image/png")
- ".png"
- ```
+ Examples
+ --------
+ .. code-block:: python
+
+ >>> guess_file_extension("image/png")
+ ".png"
Returns
-------
- typing.Optional[builtins.str]
+ typing.Optional[str]
The file extension, prepended with a `.`. If no match was found,
- return `builtins.None`.
+ return `None`.
"""
return mimetypes.guess_extension(mimetype)
@@ -280,16 +280,16 @@ def generate_filename_from_details(
Parameters
----------
- mimetype : typing.Optional[builtins.str]
- The mimetype of the content, or `builtins.None` if not known.
- extension : typing.Optional[builtins.str]
- The file extension to use, or `builtins.None` if not known.
- data : typing.Optional[builtins.bytes]
- The data to inspect, or `builtins.None` if not known.
+ mimetype : typing.Optional[str]
+ The mimetype of the content, or `None` if not known.
+ extension : typing.Optional[str]
+ The file extension to use, or `None` if not known.
+ data : typing.Optional[bytes]
+ The data to inspect, or `None` if not known.
Returns
-------
- builtins.str
+ str
A generated quasi-unique filename.
"""
if data is not None and mimetype is None:
@@ -312,14 +312,14 @@ def to_data_uri(data: bytes, mimetype: typing.Optional[str]) -> str:
Parameters
----------
- data : builtins.bytes
+ data : bytes
The data to encode as base64.
- mimetype : typing.Optional[builtins.str]
- The mimetype, or `builtins.None` if we should attempt to guess it.
+ mimetype : typing.Optional[str]
+ The mimetype, or `None` if we should attempt to guess it.
Returns
-------
- builtins.str
+ str
A data URI string.
"""
if mimetype is None:
@@ -344,7 +344,7 @@ class AsyncReader(typing.AsyncIterable[bytes], abc.ABC):
"""The filename of the resource."""
mimetype: typing.Optional[str] = attr.field(repr=True)
- """The mimetype of the resource. May be `builtins.None` if not known."""
+ """The mimetype of the resource. May be `None` if not known."""
async def data_uri(self) -> str:
"""Fetch the data URI.
@@ -354,7 +354,7 @@ async def data_uri(self) -> str:
return to_data_uri(await self.read(), self.mimetype)
async def read(self) -> bytes:
- """Read the rest of the resource and return it in a `builtins.bytes` object."""
+ """Read the rest of the resource and return it in a `bytes` object."""
buff = bytearray()
async for chunk in self:
buff.extend(chunk)
@@ -441,14 +441,14 @@ async def read(
) -> bytes:
"""Read the entire resource at once into memory.
- ```py
- data = await resource.read(...)
- # ^-- This is a shortcut for the following --v
- async with resource.stream(...) as reader:
- data = await reader.read()
- ```
+ .. code-block:: python
- !!! warning
+ data = await resource.read(...)
+ # ^-- This is a shortcut for the following --v
+ async with resource.stream(...) as reader:
+ data = await reader.read()
+
+ .. warning::
If you simply wish to re-upload this resource to Discord via
any endpoint in Hikari, you should opt to just pass this
resource object directly. This way, Hikari can perform byte
@@ -459,12 +459,12 @@ async def read(
----------
executor : typing.Optional[concurrent.futures.Executor]
The executor to run in for blocking operations.
- If `builtins.None`, then the default executor is used for the
+ If `None`, then the default executor is used for the
current event loop.
Returns
-------
- builtins.bytes
+ bytes
The entire resource.
"""
async with self.stream(executor=executor) as reader:
@@ -483,10 +483,10 @@ def stream(
----------
executor : typing.Optional[concurrent.futures.Executor]
The executor to run in for blocking operations.
- If `builtins.None`, then the default executor is used for the
+ If `None`, then the default executor is used for the
current event loop.
- head_only : builtins.bool
- Defaults to `builtins.False`. If `builtins.True`, then the
+ head_only : bool
+ Defaults to `False`. If `True`, then the
implementation may only retrieve HEAD information if supported.
This currently only has any effect for web requests. This will
fetch the headers for the HTTP resource this object points to
@@ -544,7 +544,7 @@ class WebReader(AsyncReader):
"""The size of the resource, if known."""
head_only: bool = attr.field()
- """If `builtins.True`, then only the HEAD was requested.
+ """If `True`, then only the HEAD was requested.
In this case, neither `__aiter__` nor `read` would return anything other
than an empty byte string.
@@ -630,16 +630,12 @@ class WebResource(Resource[WebReader], abc.ABC):
The logic for identifying this resource is left to each implementation
to define.
- !!! info
- For a usable concrete implementation, use `URL` instead.
+ For a usable concrete implementation, use `URL` instead.
- !!! note
Some components may choose to not upload this resource directly and
instead simply refer to the URL as needed. The main place this will
- occur is within embeds.
-
- If you need to re-upload the resource, you should download it into
- a `builtins.bytes` and pass that instead in these cases.
+ occur is within embeds. If you need to re-upload the resource, you
+ should download it into a `bytes` and pass that instead in these cases.
"""
__slots__: typing.Sequence[str] = ()
@@ -659,35 +655,40 @@ def stream(
----------
executor : typing.Optional[concurrent.futures.Executor]
Not used. Provided only to match the underlying interface.
- head_only : builtins.bool
- Defaults to `builtins.False`. If `builtins.True`, then the
+ head_only : bool
+ Defaults to `False`. If `True`, then the
implementation may only retrieve HEAD information if supported.
This currently only has any effect for web requests.
Examples
--------
Downloading an entire resource at once into memory:
- ```py
- async with obj.stream() as stream:
- data = await stream.read()
- ```
+
+ .. code-block:: python
+
+ async with obj.stream() as stream:
+ data = await stream.read()
+
Checking the metadata:
- ```py
- async with obj.stream() as stream:
- mimetype = stream.mimetype
- if mimetype is None:
- ...
- elif mimetype not in whitelisted_mimetypes:
- ...
- else:
- ...
- ```
+ .. code-block:: python
+
+ async with obj.stream() as stream:
+ mimetype = stream.mimetype
+
+ if mimetype is None:
+ ...
+ elif mimetype not in whitelisted_mimetypes:
+ ...
+ else:
+ ...
+
Fetching the data-uri of a resource:
- ```py
- async with obj.stream() as stream:
- data_uri = await stream.data_uri()
- ```
+
+ .. code-block:: python
+
+ async with obj.stream() as stream:
+ data_uri = await stream.data_uri()
Returns
-------
@@ -719,6 +720,14 @@ def stream(
class URL(WebResource):
"""A URL that represents a web resource.
+ .. note::
+ Some components may choose to not upload this resource directly and
+ instead simply refer to the URL as needed. The main place this will
+ occur is within embeds.
+
+ If you need to re-upload the resource, you should download it into
+ a `bytes` and pass that instead in these cases.
+
Parameters
----------
url : builtins.str
@@ -726,15 +735,7 @@ class URL(WebResource):
filename : typing.Optional[builtins.str]
The filename for the resource.
- If not specified, it will be gotten from the url.
-
- !!! note
- Some components may choose to not upload this resource directly and
- instead simply refer to the URL as needed. The main place this will
- occur is within embeds.
-
- If you need to re-upload the resource, you should download it into
- a `builtins.bytes` and pass that instead in these cases.
+ If not specified, it will be obtained from the url.
"""
__slots__: typing.Sequence[str] = ("_url", "_filename")
@@ -823,21 +824,20 @@ class File(Resource[ThreadedFileReader]):
Parameters
----------
- path : typing.Union[builtins.str, os.PathLike, pathlib.Path]
+ path : typing.Union[str, os.PathLike, pathlib.Path]
The path to use.
- !!! note
- If passing a `pathlib.Path`, this must not be a `pathlib.PurePath`
- directly, as it will be used to expand tokens such as `~` that
- denote the home directory, and `..` for relative paths.
+ If passing a `pathlib.Path`, this must not be a `pathlib.PurePath`
+ directly, as it will be used to expand tokens such as `~` that
+ denote the home directory, and `..` for relative paths.
- This will all be performed as required in an executor to prevent
- blocking the event loop.
- filename : typing.Optional[builtins.str]
- The filename to use. If this is `builtins.None`, the name of the file is taken
+ This will all be performed as required in an executor to prevent
+ blocking the event loop.
+ filename : typing.Optional[str]
+ The filename to use. If this is `None`, the name of the file is taken
from the path instead.
spoiler : bool
- Whether to mark the file as a spoiler in Discord. Defaults to `builtins.False`.
+ Whether to mark the file as a spoiler in Discord. Defaults to `False`.
"""
__slots__: typing.Sequence[str] = ("path", "_filename", "is_spoiler")
@@ -881,11 +881,11 @@ def stream(
----------
executor : typing.Optional[concurrent.futures.Executor]
The thread executor to run the blocking read operations in. If
- `builtins.None`, the default executor for the running event loop
+ `None`, the default executor for the running event loop
will be used instead.
Only `concurrent.futures.TheadPoolExecutor` is supported.
- head_only : builtins.bool
+ head_only : bool
Not used. Provided only to match the underlying interface.
Returns
@@ -993,14 +993,14 @@ class Bytes(Resource[IteratorReader]):
----------
data : typing.Union[Rawish, LazyByteIteratorish]
The raw data.
- filename : builtins.str
+ filename : str
The filename to use.
- mimetype : typing.Optional[builtins.str]
- The mimetype, or `builtins.None` if you do not wish to specify this.
+ mimetype : typing.Optional[str]
+ The mimetype, or `None` if you do not wish to specify this.
If not provided, then this will be generated from the file extension
of the filename instead.
spoiler : bool
- Whether to mark the file as a spoiler in Discord. Defaults to `builtins.False`.
+ Whether to mark the file as a spoiler in Discord. Defaults to `False`.
"""
__slots__: typing.Sequence[str] = ("data", "_filename", "mimetype", "is_spoiler")
@@ -1009,7 +1009,7 @@ class Bytes(Resource[IteratorReader]):
"""The raw data/provider of raw data to upload."""
mimetype: typing.Optional[str]
- """The provided mimetype, if provided. Otherwise `builtins.None`."""
+ """The provided mimetype, if provided. Otherwise `None`."""
is_spoiler: bool
"""Whether the file will be marked as a spoiler."""
@@ -1061,7 +1061,7 @@ def stream(
----------
executor : typing.Optional[concurrent.futures.Executor]
Not used. Provided only to match the underlying interface.
- head_only : builtins.bool
+ head_only : bool
Not used. Provided only to match the underlying interface.
Returns
@@ -1078,9 +1078,9 @@ def from_data_uri(data_uri: str, filename: typing.Optional[str] = None) -> Bytes
Parameters
----------
- data_uri : builtins.str
+ data_uri : str
The data URI to parse.
- filename : typing.Optional[builtins.str]
+ filename : typing.Optional[str]
Filename to use. If this is not provided, then this is generated
instead.
@@ -1091,7 +1091,7 @@ def from_data_uri(data_uri: str, filename: typing.Optional[str] = None) -> Bytes
Raises
------
- builtins.ValueError
+ ValueError
If the parsed argument is not a data URI.
"""
if not data_uri.startswith("data:"):
diff --git a/hikari/guilds.py b/hikari/guilds.py
index 332cef372f..d8648bef57 100644
--- a/hikari/guilds.py
+++ b/hikari/guilds.py
@@ -276,7 +276,7 @@ class GuildWidget:
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
channel_id: typing.Optional[snowflakes.Snowflake] = attr.field(repr=True)
"""The ID of the channel the invite for this embed targets, if enabled."""
@@ -287,7 +287,7 @@ class GuildWidget:
async def fetch_channel(self) -> typing.Optional[channels_.GuildChannel]:
"""Fetch the widget channel.
- This will be `builtins.None` if not set.
+ This will be `None` if not set.
Returns
-------
@@ -295,7 +295,7 @@ async def fetch_channel(self) -> typing.Optional[channels_.GuildChannel]:
The requested channel.
You can check the type of the channel by
- using `builtins.isinstance`.
+ using `isinstance`.
Raises
------
@@ -337,14 +337,14 @@ class Member(users.User):
"""The ID of the guild this member belongs to."""
is_deaf: undefined.UndefinedOr[bool] = attr.field(repr=False)
- """`builtins.True` if this member is deafened in the current voice channel.
+ """`True` if this member is deafened in the current voice channel.
This will be `hikari.undefined.UNDEFINED` if it's state is
unknown.
"""
is_mute: undefined.UndefinedOr[bool] = attr.field(repr=False)
- """`builtins.True` if this member is muted in the current voice channel.
+ """`True` if this member is muted in the current voice channel.
This will be `hikari.undefined.UNDEFINED` if it's state is unknown.
"""
@@ -361,21 +361,21 @@ class Member(users.User):
nickname: typing.Optional[str] = attr.field(repr=True)
"""This member's nickname.
- This will be `builtins.None` if not set.
+ This will be `None` if not set.
"""
premium_since: typing.Optional[datetime.datetime] = attr.field(repr=False)
"""The datetime of when this member started "boosting" this guild.
- Will be `builtins.None` if the member is not a premium user.
+ Will be `None` if the member is not a premium user.
"""
raw_communication_disabled_until: typing.Optional[datetime.datetime] = attr.field(repr=False)
"""The datetime when this member's timeout will expire.
- Will be `builtins.None` if the member is not timed out.
+ Will be `None` if the member is not timed out.
- !!! note
+ .. note::
The datetime might be in the past, so it is recommended to use
`communication_disabled_until` method to check if the member is timed
out at the time of the call.
@@ -394,9 +394,9 @@ class Member(users.User):
"""This member's corresponding user object."""
guild_avatar_hash: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
- """Hash of the member's guild avatar guild if set, else `builtins.None`.
+ """Hash of the member's guild avatar guild if set, else `None`.
- !!! note
+ .. note::
This takes precedence over `Member.avatar_hash`.
"""
@@ -417,7 +417,7 @@ def avatar_url(self) -> typing.Optional[files.URL]:
def guild_avatar_url(self) -> typing.Optional[files.URL]:
"""Guild Avatar URL for the user, if they have one set.
- May be `builtins.None` if no guild avatar is set. In this case, you
+ May be `None` if no guild avatar is set. In this case, you
should use `avatar_hash` or `default_avatar_url` instead.
"""
return self.make_guild_avatar_url()
@@ -453,15 +453,10 @@ def display_name(self) -> str:
If the member has a nickname, this will return that nickname.
Otherwise, it will return the username instead.
- Returns
- -------
- builtins.str
- The member display name.
-
See Also
--------
- Nickname: `Member.nickname`
- Username: `Member.username`
+ Nickname: `Member.nickname`.
+ Username: `Member.username`.
"""
return self.nickname if isinstance(self.nickname, str) else self.username
@@ -489,9 +484,9 @@ def communication_disabled_until(self) -> typing.Optional[datetime.datetime]:
"""Return when the timeout for this member ends.
Unlike `raw_communication_disabled_until`, this will always be
- `builtins.None` if the member is not currently timed out.
+ `None` if the member is not currently timed out.
- !!! note
+ .. note::
The output of this function can depend based on when
the function is called.
"""
@@ -508,7 +503,7 @@ def get_guild(self) -> typing.Optional[Guild]:
Returns
-------
typing.Optional[hikari.guilds.Guild]
- The linked guild object or `builtins.None` if it's not cached.
+ The linked guild object or `None` if it's not cached.
"""
if not isinstance(self.user.app, traits.CacheAware):
return None
@@ -525,7 +520,7 @@ def get_presence(self) -> typing.Optional[presences_.MemberPresence]:
Returns
-------
typing.Optional[hikari.presences.MemberPresence]
- The member presence, or `builtins.None` if not known.
+ The member presence, or `None` if not known.
"""
if not isinstance(self.user.app, traits.CacheAware):
return None
@@ -559,7 +554,7 @@ def get_top_role(self) -> typing.Optional[Role]:
Returns
-------
typing.Optional[hikari.guilds.Role]
- `builtins.None` if the cache is missing the roles information or
+ `None` if the cache is missing the roles information or
the highest role the user has.
"""
roles = sorted(self.get_roles(), key=lambda r: r.position, reverse=True)
@@ -581,21 +576,21 @@ def make_guild_avatar_url(
) -> typing.Optional[files.URL]:
"""Generate the guild specific avatar url for this member, if set.
- If no guild avatar is set, this returns `builtins.None`. You can then
+ If no guild avatar is set, this returns `None`. You can then
use the `make_avatar_url` to get their global custom avatar or
`default_avatar_url` if they have no custom avatar set.
Parameters
----------
- ext : typing.Optional[builtins.str]
+ ext : typing.Optional[str]
The ext to use for this URL, defaults to `png` or `gif`.
Supports `png`, `jpeg`, `jpg`, `webp` and `gif` (when
animated). Will be ignored for default avatars which can only be
`png`.
- If `builtins.None`, then the correct default extension is
+ If `None`, then the correct default extension is
determined based on whether the icon is animated or not.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Will be ignored for default avatars.
@@ -603,11 +598,11 @@ def make_guild_avatar_url(
Returns
-------
typing.Optional[hikari.files.URL]
- The URL to the avatar, or `builtins.None` if not present.
+ The URL to the avatar, or `None` if not present.
Raises
------
- builtins.ValueError
+ ValueError
If `size` is not a power of two or not between 16 and 4096.
"""
if self.guild_avatar_hash is None:
@@ -702,10 +697,10 @@ async def ban(
Other Parameters
----------------
- delete_message_days : hikari.undefined.UndefinedNoneOr[builtins.int]
+ delete_message_days : hikari.undefined.UndefinedOr[int]
If provided, the number of days to delete messages for.
This must be between 0 and 7.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -746,7 +741,7 @@ async def unban(
Other Parameters
----------------
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -785,7 +780,7 @@ async def kick(
Other Parameters
----------------
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -828,7 +823,7 @@ async def add_role(
Other Parameters
----------------
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -869,7 +864,7 @@ async def remove_role(
Other Parameters
----------------
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -914,8 +909,8 @@ async def edit(
Other Parameters
----------------
- nickname : hikari.undefined.UndefinedNoneOr[builtins.str]
- If provided, the new nick for the member. If `builtins.None`,
+ nickname : hikari.undefined.UndefinedNoneOr[str]
+ If provided, the new nick for the member. If `None`,
will remove the members nick.
Requires the `MANAGE_NICKNAMES` permission.
@@ -923,33 +918,33 @@ async def edit(
If provided, the new roles for the member.
Requires the `MANAGE_ROLES` permission.
- mute : hikari.undefined.UndefinedOr[builtins.bool]
+ mute : hikari.undefined.UndefinedOr[bool]
If provided, the new server mute state for the member.
Requires the `MUTE_MEMBERS` permission.
- deaf : hikari.undefined.UndefinedOr[builtins.bool]
+ deaf : hikari.undefined.UndefinedOr[bool]
If provided, the new server deaf state for the member.
Requires the `DEAFEN_MEMBERS` permission.
voice_channel : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildVoiceChannel]]]
- If provided, `builtins.None` or the object or the ID of
+ If provided, `None` or the object or the ID of
an existing voice channel to move the member to.
- If `builtins.None`, will disconnect the member from voice.
+ If `None`, will disconnect the member from voice.
Requires the `MOVE_MEMBERS` permission and the `CONNECT`
permission in the original voice channel and the target
voice channel.
- !!! note
+ .. note::
If the member is not in a voice channel, this will
take no effect.
communication_disabled_until : hikari.undefined.UndefinedNoneOr[datetime.datetime]
If provided, the datetime when the timeout (disable communication)
- of the member expires, up to 28 days in the future, or `builtins.None`
+ of the member expires, up to 28 days in the future, or `None`
to remove the timeout from the member.
Requires the `MODERATE_MEMBERS` permission.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -1007,12 +1002,12 @@ def __eq__(self, other: object) -> bool:
@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class PartialRole(snowflakes.Unique):
- """Represents a partial guild bound Role object."""
+ """Represents a partial guild bound role object."""
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
id: snowflakes.Snowflake = attr.field(hash=True, repr=True)
"""The ID of this entity."""
@@ -1022,13 +1017,7 @@ class PartialRole(snowflakes.Unique):
@property
def mention(self) -> str:
- """Return a raw mention string for the role.
-
- Returns
- -------
- builtins.str
- The mention string to use.
- """
+ """Return a raw mention string for the role."""
return f"<@&{self.id}>"
def __str__(self) -> str:
@@ -1046,19 +1035,19 @@ class Role(PartialRole):
"""
guild_id: snowflakes.Snowflake = attr.field(eq=False, hash=False, repr=True)
- """The ID of the guild this role belongs to"""
+ """The ID of the guild this role belongs to."""
is_hoisted: bool = attr.field(eq=False, hash=False, repr=True)
"""Whether this role is hoisting the members it's attached to in the member list.
- members will be hoisted under their highest role where this is set to `builtins.True`.
+ Members will be hoisted under their highest role where this is set to `True`.
"""
icon_hash: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
- """Hash of the role's icon if set, else `builtins.None`."""
+ """Hash of the role's icon if set, else `None`."""
unicode_emoji: typing.Optional[emojis_.UnicodeEmoji] = attr.field(eq=False, hash=False, repr=False)
- """Role's icon as an unicode emoji if set, else `builtins.None`."""
+ """Role's icon as an unicode emoji if set, else `None`."""
is_managed: bool = attr.field(eq=False, hash=False, repr=False)
"""Whether this role is managed by an integration."""
@@ -1067,7 +1056,7 @@ class Role(PartialRole):
"""Whether this role can be mentioned by all regardless of permissions."""
permissions: permissions_.Permissions = attr.field(eq=False, hash=False, repr=False)
- """The guild wide permissions this role gives to the members it's attached to,
+ """The guild wide permissions this role gives to the members it's attached to.
This may be overridden by channel overwrites.
"""
@@ -1082,13 +1071,13 @@ class Role(PartialRole):
bot_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=True)
"""The ID of the bot this role belongs to.
- If `builtins.None`, this is not a bot role.
+ If `None`, this is not a bot role.
"""
integration_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=True)
"""The ID of the integration this role belongs to.
- If `builtins.None`, this is not a integration role.
+ If `None`, this is not a integration role.
"""
is_premium_subscriber_role: bool = attr.field(eq=False, hash=False, repr=True)
@@ -1101,37 +1090,31 @@ def colour(self) -> colours.Colour:
@property
def icon_url(self) -> typing.Optional[files.URL]:
- """Role icon URL, if there is one.
-
- Returns
- -------
- typing.Optional[hikari.files.URL]
- The URL, or `builtins.None` if no icon exists.
- """
+ """Role icon URL, if there is one."""
return self.make_icon_url()
def make_icon_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
"""Generate the icon URL for this role, if set.
- If no role icon is set, this returns `builtins.None`.
+ If no role icon is set, this returns `None`.
Parameters
----------
- ext : builtins.str
+ ext : str
The extension to use for this URL, defaults to `png`.
Supports `png`, `jpeg`, `jpg` and `webp`.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Returns
-------
typing.Optional[hikari.files.URL]
- The URL to the icon, or `builtins.None` if not present.
+ The URL to the icon, or `None` if not present.
Raises
------
- builtins.ValueError
+ ValueError
If `size` is not a power of two or not between 16 and 4096.
"""
if self.icon_hash is None:
@@ -1206,13 +1189,7 @@ def __str__(self) -> str:
@property
def icon_url(self) -> typing.Optional[files.URL]:
- """Team icon URL, if there is one.
-
- Returns
- -------
- typing.Optional[hikari.files.URL]
- The URL, or `builtins.None` if no icon exists.
- """
+ """Team icon URL, if there is one."""
return self.make_icon_url()
def make_icon_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
@@ -1220,21 +1197,21 @@ def make_icon_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optiona
Parameters
----------
- ext : builtins.str
+ ext : str
The extension to use for this URL, defaults to `png`.
Supports `png`, `jpeg`, `jpg` and `webp`.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Returns
-------
typing.Optional[hikari.files.URL]
- The URL, or `builtins.None` if no icon exists.
+ The URL, or `None` if no icon exists.
Raises
------
- builtins.ValueError
+ ValueError
If the size is not an integer power of 2 between 16 and 4096
(inclusive).
"""
@@ -1293,16 +1270,15 @@ class Integration(PartialIntegration):
This will not be enacted until after `GuildIntegration.expire_grace_period`
passes.
- !!! note
- This will always be `builtins.None` for Discord integrations.
+ .. note::
+ This will always be `None` for Discord integrations.
"""
expire_grace_period: typing.Optional[datetime.timedelta] = attr.field(eq=False, hash=False, repr=False)
- """How many days users with expired subscriptions are given until
- `GuildIntegration.expire_behavior` is enacted out on them.
+ """How many days users with expired subscriptions are given until the expire behavior is enacted out on them.
- !!! note
- This will always be `builtins.None` for Discord integrations.
+ .. note::
+ This will always be `None` for Discord integrations.
"""
is_enabled: bool = attr.field(eq=False, hash=False, repr=True)
@@ -1332,7 +1308,7 @@ class Integration(PartialIntegration):
application: typing.Optional[IntegrationApplication] = attr.field(eq=False, hash=False, repr=False)
"""The bot/OAuth2 application associated with this integration.
- !!! note
+ .. note::
This is only available for Discord integrations.
"""
@@ -1353,7 +1329,7 @@ class WelcomeChannel:
)
"""The emoji shown in the welcome screen channel if set to a unicode emoji.
- !!! warning
+ .. warning::
While it may also be present for custom emojis, this is neither guaranteed
to be provided nor accurate.
"""
@@ -1380,7 +1356,7 @@ class GuildBan:
"""Used to represent guild bans."""
reason: typing.Optional[str] = attr.field(repr=True)
- """The reason for this ban, will be `builtins.None` if no reason was given."""
+ """The reason for this ban, will be `None` if no reason was given."""
user: users.User = attr.field(repr=True)
"""The object of the user this ban targets."""
@@ -1394,7 +1370,7 @@ class PartialGuild(snowflakes.Unique):
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
id: snowflakes.Snowflake = attr.field(hash=True, repr=True)
"""The ID of this entity."""
@@ -1410,7 +1386,7 @@ def __str__(self) -> str:
@property
def icon_url(self) -> typing.Optional[files.URL]:
- """Icon URL for the guild, if set; otherwise `builtins.None`."""
+ """Icon URL for the guild, if set; otherwise `None`."""
return self.make_icon_url()
@property
@@ -1432,25 +1408,25 @@ def make_icon_url(self, *, ext: typing.Optional[str] = None, size: int = 4096) -
Parameters
----------
- ext : typing.Optional[builtins.str]
+ ext : typing.Optional[str]
The extension to use for this URL, defaults to `png` or `gif`.
Supports `png`, `jpeg`, `jpg`, `webp` and `gif` (when
animated).
- If `builtins.None`, then the correct default extension is
+ If `None`, then the correct default extension is
determined based on whether the icon is animated or not.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Returns
-------
typing.Optional[hikari.files.URL]
- The URL to the resource, or `builtins.None` if no icon is set.
+ The URL to the resource, or `None` if no icon is set.
Raises
------
- builtins.ValueError
+ ValueError
If `size` is not a power of two or not between 16 and 4096.
"""
if self.icon_hash is None:
@@ -1481,15 +1457,15 @@ async def ban(
Parameters
----------
- user: hikari.snowflakes.Snowflakeish[hikari.users.PartialUser]
- The user to ban from the guild
+ user : hikari.snowflakes.Snowflakeish[hikari.users.PartialUser]
+ The user to ban from the guild.
Other Parameters
----------------
- delete_message_days : hikari.undefined.UndefinedNoneOr[builtins.int]
+ delete_message_days : hikari.undefined.UndefinedOr[int]
If provided, the number of days to delete messages for.
This must be between 0 and 7.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -1529,12 +1505,12 @@ async def unban(
Parameters
----------
- user: hikari.snowflakes.Snowflakeish[hikari.users.PartialUser]
- The user to unban from the guild
+ user : hikari.snowflakes.Snowflakeish[hikari.users.PartialUser]
+ The user to unban from the guild.
Other Parameters
----------------
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -1570,16 +1546,16 @@ async def kick(
*,
reason: undefined.UndefinedOr[str] = undefined.UNDEFINED,
) -> None:
- """Kicks the given user from this guild.
+ """Kick the given user from this guild.
Parameters
----------
- user: hikari.snowflakes.Snowflakeish[hikari.users.PartialUser]
- The user to kick from the guild
+ user : hikari.snowflakes.Snowflakeish[hikari.users.PartialUser]
+ The user to kick from the guild.
Other Parameters
----------------
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -1636,11 +1612,11 @@ async def edit(
preferred_locale: undefined.UndefinedOr[typing.Union[str, locales.Locale]] = undefined.UNDEFINED,
reason: undefined.UndefinedOr[str] = undefined.UNDEFINED,
) -> RESTGuild:
- """Edits the guild.
+ """Edit the guild.
Parameters
----------
- name : hikari.undefined.UndefinedOr[builtins.str]
+ name : hikari.undefined.UndefinedOr[str]
If provided, the new name for the guild.
verification_level : hikari.undefined.UndefinedOr[hikari.guilds.GuildVerificationLevel]
If provided, the new verification level.
@@ -1659,7 +1635,7 @@ async def edit(
owner : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.users.PartialUser]]]
If provided, the new guild owner.
- !!! warning
+ .. warning::
You need to be the owner of the server to use this.
splash : hikari.undefined.UndefinedNoneOr[hikari.files.Resourceish]
If provided, the new guild splash. Must be a 16:9 image and the
@@ -1673,9 +1649,9 @@ async def edit(
If provided, the new rules channel.
public_updates_channel : hikari.undefined.UndefinedNoneOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildTextChannel]]
If provided, the new public updates channel.
- preferred_locale : hikari.undefined.UndefinedNoneOr[builtins.str]
+ preferred_locale : hikari.undefined.UndefinedNoneOr[str]
If provided, the new preferred locale.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -1876,25 +1852,25 @@ async def create_sticker(
) -> stickers.GuildSticker:
"""Create a sticker in a guild.
+ .. note::
+ Lottie support is only available for verified and partnered
+ servers.
+
Parameters
----------
- name : builtins.str
+ name : str
The name for the sticker.
- tag : builtins.str
+ tag : str
The tag for the sticker.
image : hikari.files.Resourceish
The 320x320 image for the sticker. Maximum upload size is 500kb.
This can be a still or an animated PNG or a Lottie.
- !!! note
- Lottie support is only available for verified and partnered
- servers.
-
Other Parameters
----------------
- description: hikari.undefined.UndefinedOr[builtins.str]
+ description : hikari.undefined.UndefinedOr[str]
If provided, the description of the sticker.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -1949,13 +1925,13 @@ async def edit_sticker(
Other Parameters
----------------
- name : hikari.undefined.UndefinedOr[builtins.str]
+ name : hikari.undefined.UndefinedOr[str]
If provided, the new name for the sticker.
- description : hikari.undefined.UndefinedOr[builtins.str]
+ description : hikari.undefined.UndefinedOr[str]
If provided, the new description for the sticker.
- tag : hikari.undefined.UndefinedOr[builtins.str]
+ tag : hikari.undefined.UndefinedOr[str]
If provided, the new sticker tag.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -2008,7 +1984,7 @@ async def delete_sticker(
Other Parameters
----------------
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -2050,16 +2026,16 @@ async def create_category(
Parameters
----------
- name : builtins.str
+ name : str
The channels name. Must be between 2 and 1000 characters.
Other Parameters
----------------
- position : hikari.undefined.UndefinedOr[builtins.int]
+ position : hikari.undefined.UndefinedOr[int]
If provided, the position of the category.
permission_overwrites : hikari.undefined.UndefinedOr[typing.Sequence[hikari.channels.PermissionOverwrite]]
If provided, the permission overwrites for the category.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -2114,17 +2090,17 @@ async def create_text_channel(
Parameters
----------
- name : builtins.str
+ name : str
The channels name. Must be between 2 and 1000 characters.
Other Parameters
----------------
- position : hikari.undefined.UndefinedOr[builtins.int]
+ position : hikari.undefined.UndefinedOr[int]
If provided, the position of the channel (relative to the
category, if any).
- topic : hikari.undefined.UndefinedOr[builtins.str]
+ topic : hikari.undefined.UndefinedOr[str]
If provided, the channels topic. Maximum 1024 characters.
- nsfw : hikari.undefined.UndefinedOr[builtins.bool]
+ nsfw : hikari.undefined.UndefinedOr[bool]
If provided, whether to mark the channel as NSFW.
rate_limit_per_user : hikari.undefined.UndefinedOr[hikari.internal.time.Intervalish]
If provided, the amount of seconds a user has to wait
@@ -2135,7 +2111,7 @@ async def create_text_channel(
category : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildCategory]]
The category to create the channel under. This may be the
object or the ID of an existing category.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -2198,17 +2174,17 @@ async def create_news_channel(
Parameters
----------
- name : builtins.str
+ name : str
The channels name. Must be between 2 and 1000 characters.
Other Parameters
----------------
- position : hikari.undefined.UndefinedOr[builtins.int]
+ position : hikari.undefined.UndefinedOr[int]
If provided, the position of the channel (relative to the
category, if any).
- topic : hikari.undefined.UndefinedOr[builtins.str]
+ topic : hikari.undefined.UndefinedOr[str]
If provided, the channels topic. Maximum 1024 characters.
- nsfw : hikari.undefined.UndefinedOr[builtins.bool]
+ nsfw : hikari.undefined.UndefinedOr[bool]
If provided, whether to mark the channel as NSFW.
rate_limit_per_user : hikari.undefined.UndefinedOr[hikari.internal.time.Intervalish]
If provided, the amount of seconds a user has to wait
@@ -2219,7 +2195,7 @@ async def create_news_channel(
category : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildCategory]]
The category to create the channel under. This may be the
object or the ID of an existing category.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -2283,37 +2259,34 @@ async def create_voice_channel(
Parameters
----------
- guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
- The guild to create the channel in. This may be the
- object or the ID of an existing guild.
- name : builtins.str
+ name : str
The channels name. Must be between 2 and 1000 characters.
Other Parameters
----------------
- position : hikari.undefined.UndefinedOr[builtins.int]
+ position : hikari.undefined.UndefinedOr[int]
If provided, the position of the channel (relative to the
category, if any).
- user_limit : hikari.undefined.UndefinedOr[builtins.int]
+ user_limit : hikari.undefined.UndefinedOr[int]
If provided, the maximum users in the channel at once.
Must be between 0 and 99 with 0 meaning no limit.
- bitrate : hikari.undefined.UndefinedOr[builtins.int]
+ bitrate : hikari.undefined.UndefinedOr[int]
If provided, the bitrate for the channel. Must be
between 8000 and 96000 or 8000 and 128000 for VIP
servers.
- video_quality_mode: hikari.undefined.UndefinedOr[typing.Union[hikari.channels.VideoQualityMode, builtins.int]]
+ video_quality_mode : hikari.undefined.UndefinedOr[typing.Union[hikari.channels.VideoQualityMode, int]]
If provided, the new video quality mode for the channel.
permission_overwrites : hikari.undefined.UndefinedOr[typing.Sequence[hikari.channels.PermissionOverwrite]]
If provided, the permission overwrites for the channel.
- region : hikari.undefined.UndefinedOr[typing.Union[hikari.voices.VoiceRegion, builtins.str]]
+ region : hikari.undefined.UndefinedOr[typing.Union[hikari.voices.VoiceRegion, str]]
If provided, the voice region to for this channel. Passing
- `builtins.None` here will set it to "auto" mode where the used
+ `None` here will set it to "auto" mode where the used
region will be decided based on the first person who connects to it
when it's empty.
category : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildCategory]]
The category to create the channel under. This may be the
object or the ID of an existing category.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -2377,32 +2350,32 @@ async def create_stage_channel(
Parameters
----------
- name : builtins.str
+ name : str
The channel's name. Must be between 2 and 1000 characters.
Other Parameters
----------------
- position : hikari.undefined.UndefinedOr[builtins.int]
+ position : hikari.undefined.UndefinedOr[int]
If provided, the position of the channel (relative to the
category, if any).
- user_limit : hikari.undefined.UndefinedOr[builtins.int]
+ user_limit : hikari.undefined.UndefinedOr[int]
If provided, the maximum users in the channel at once.
Must be between 0 and 99 with 0 meaning no limit.
- bitrate : hikari.undefined.UndefinedOr[builtins.int]
+ bitrate : hikari.undefined.UndefinedOr[int]
If provided, the bitrate for the channel. Must be
between 8000 and 96000 or 8000 and 128000 for VIP
servers.
permission_overwrites : hikari.undefined.UndefinedOr[typing.Sequence[hikari.channels.PermissionOverwrite]]
If provided, the permission overwrites for the channel.
- region : hikari.undefined.UndefinedOr[typing.Union[hikari.voices.VoiceRegion, builtins.str]]
+ region : hikari.undefined.UndefinedOr[typing.Union[hikari.voices.VoiceRegion, str]]
If provided, the voice region to for this channel. Passing
- `builtins.None` here will set it to "auto" mode where the used
+ `None` here will set it to "auto" mode where the used
region will be decided based on the first person who connects to it
when it's empty.
category : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildCategory]]
The category to create the channel under. This may be the
object or the ID of an existing category.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs.
Maximum of 512 characters.
@@ -2452,9 +2425,13 @@ async def delete_channel(
) -> channels_.GuildChannel:
"""Delete a channel in the guild.
- !!! note
+ .. note::
This method can also be used for deleting guild categories as well.
+ .. note::
+ For Public servers, the set 'Rules' or 'Guidelines' channels and the
+ 'Public Server Updates' channel cannot be deleted.
+
Parameters
----------
channel : hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildChannel]
@@ -2487,10 +2464,6 @@ async def delete_channel(
nature, and will trigger this exception if they occur.
hikari.errors.InternalServerError
If an internal error occurs on Discord while handling the request.
-
- !!! note
- For Public servers, the set 'Rules' or 'Guidelines' channels and the
- 'Public Server Updates' channel cannot be deleted.
"""
deleted_channel = await self.app.rest.delete_channel(channel)
assert isinstance(deleted_channel, channels_.GuildChannel)
@@ -2541,8 +2514,8 @@ async def fetch_roles(self) -> typing.Sequence[Role]:
------
hikari.errors.UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
- hikari.errors.NotFoundError
- If the guild is not found.
+ hikari.errors.NotFoundError
+ If the guild is not found.
hikari.errors.RateLimitTooLongError
Raised in the event that a rate limit occurs that is
longer than `max_rate_limit` when making a request.
@@ -2602,10 +2575,10 @@ def make_discovery_splash_url(self, *, ext: str = "png", size: int = 4096) -> ty
Parameters
----------
- ext : builtins.str
+ ext : str
The extension to use for this URL, defaults to `png`.
Supports `png`, `jpeg`, `jpg` and `webp`.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
@@ -2616,7 +2589,7 @@ def make_discovery_splash_url(self, *, ext: str = "png", size: int = 4096) -> ty
Raises
------
- builtins.ValueError
+ ValueError
If `size` is not a power of two or not between 16 and 4096.
"""
if self.discovery_splash_hash is None:
@@ -2635,21 +2608,21 @@ def make_splash_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optio
Parameters
----------
- ext : builtins.str
+ ext : str
The extension to use for this URL, defaults to `png`.
Supports `png`, `jpeg`, `jpg` and `webp`.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Returns
-------
typing.Optional[hikari.files.URL]
- The URL to the splash, or `builtins.None` if not set.
+ The URL to the splash, or `None` if not set.
Raises
------
- builtins.ValueError
+ ValueError
If `size` is not a power of two or not between 16 and 4096.
"""
if self.splash_hash is None:
@@ -2674,13 +2647,13 @@ class Guild(PartialGuild):
application_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=False)
"""The ID of the application that created this guild.
- This will always be `builtins.None` for guilds that weren't created by a bot.
+ This will always be `None` for guilds that weren't created by a bot.
"""
afk_channel_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=False)
"""The ID for the channel that AFK voice users get sent to.
- If `builtins.None`, then no AFK channel is set up for this guild.
+ If `None`, then no AFK channel is set up for this guild.
"""
afk_timeout: datetime.timedelta = attr.field(eq=False, hash=False, repr=False)
@@ -2694,7 +2667,7 @@ class Guild(PartialGuild):
"""The hash for the guild's banner.
This is only present if the guild has `GuildFeature.BANNER` in
- `Guild.features` for this guild. For all other purposes, it is `builtins.None`.
+ `Guild.features` for this guild. For all other purposes, it is `None`.
"""
default_message_notifications: typing.Union[GuildMessageNotificationsLevel, int] = attr.field(
@@ -2706,7 +2679,7 @@ class Guild(PartialGuild):
"""The guild's description.
This is only present if certain `GuildFeature`'s are set in
- `Guild.features` for this guild. Otherwise, this will always be `builtins.None`.
+ `Guild.features` for this guild. Otherwise, this will always be `None`.
"""
discovery_splash_hash: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
@@ -2720,13 +2693,13 @@ class Guild(PartialGuild):
is_widget_enabled: typing.Optional[bool] = attr.field(eq=False, hash=False, repr=False)
"""Describes whether the guild widget is enabled or not.
- If this information is not present, this will be `builtins.None`.
+ If this information is not present, this will be `None`.
"""
max_video_channel_users: typing.Optional[int] = attr.field(eq=False, hash=False, repr=False)
"""The maximum number of users allowed in a video channel together.
- This information may not be present, in which case, it will be `builtins.None`.
+ This information may not be present, in which case, it will be `None`.
"""
mfa_level: typing.Union[GuildMFALevel, int] = attr.field(eq=False, hash=False, repr=False)
@@ -2745,25 +2718,23 @@ class Guild(PartialGuild):
premium_subscription_count: typing.Optional[int] = attr.field(eq=False, hash=False, repr=False)
"""The number of nitro boosts that the server currently has.
- This information may not be present, in which case, it will be `builtins.None`.
+ This information may not be present, in which case, it will be `None`.
"""
premium_tier: typing.Union[GuildPremiumTier, int] = attr.field(eq=False, hash=False, repr=False)
"""The premium tier for this guild."""
public_updates_channel_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=False)
- """The channel ID of the channel where admins and moderators receive notices
- from Discord.
+ """The channel ID of the channel where admins and moderators receive notices from Discord.
This is only present if `GuildFeature.COMMUNITY` is in `Guild.features` for
- this guild. For all other purposes, it should be considered to be `builtins.None`.
+ this guild. For all other purposes, it should be considered to be `None`.
"""
rules_channel_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=False)
- """The ID of the channel where guilds with the `GuildFeature.COMMUNITY`
- `features` display rules and guidelines.
+ """The ID of the channel where rules and guidelines will be displayed.
- If the `GuildFeature.COMMUNITY` feature is not defined, then this is `builtins.None`.
+ If the `GuildFeature.COMMUNITY` feature is not defined, then this is `None`.
"""
splash_hash: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
@@ -2773,15 +2744,10 @@ class Guild(PartialGuild):
"""Return flags for the guild system channel.
These are used to describe which notifications are suppressed.
-
- Returns
- -------
- GuildSystemChannelFlag
- The system channel flags for this channel.
"""
system_channel_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=False)
- """The ID of the system channel or `builtins.None` if it is not enabled.
+ """The ID of the system channel or `None` if it is not enabled.
Welcome messages and Nitro boost messages may be sent to this channel.
"""
@@ -2790,7 +2756,7 @@ class Guild(PartialGuild):
"""The vanity URL code for the guild's vanity URL.
This is only present if `GuildFeature.VANITY_URL` is in `Guild.features` for
- this guild. If not, this will always be `builtins.None`.
+ this guild. If not, this will always be `None`.
"""
verification_level: typing.Union[GuildVerificationLevel, int] = attr.field(eq=False, hash=False, repr=False)
@@ -2800,7 +2766,7 @@ class Guild(PartialGuild):
"""The channel ID that the widget's generated invite will send the user to.
If this information is unavailable or this is not enabled for the guild then
- this will be `builtins.None`.
+ this will be `None`.
"""
nsfw_level: GuildNSFWLevel = attr.field(eq=False, hash=False, repr=False)
@@ -2916,25 +2882,25 @@ def make_banner_url(self, *, ext: typing.Optional[str] = None, size: int = 4096)
Parameters
----------
- ext : typing.Optional[builtins.str]
+ ext : typing.Optional[str]
The ext to use for this URL, defaults to `png` or `gif`.
Supports `png`, `jpeg`, `jpg`, `webp` and `gif` (when
animated).
- If `builtins.None`, then the correct default extension is
+ If `None`, then the correct default extension is
determined based on whether the banner is animated or not.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Returns
-------
typing.Optional[hikari.files.URL]
- The URL of the banner, or `builtins.None` if no banner is set.
+ The URL of the banner, or `None` if no banner is set.
Raises
------
- builtins.ValueError
+ ValueError
If `size` is not a power of two or not between 16 and 4096.
"""
if self.banner_hash is None:
@@ -2960,10 +2926,10 @@ def make_discovery_splash_url(self, *, ext: str = "png", size: int = 4096) -> ty
Parameters
----------
- ext : builtins.str
+ ext : str
The extension to use for this URL, defaults to `png`.
Supports `png`, `jpeg`, `jpg` and `webp`.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
@@ -2974,7 +2940,7 @@ def make_discovery_splash_url(self, *, ext: str = "png", size: int = 4096) -> ty
Raises
------
- builtins.ValueError
+ ValueError
If `size` is not a power of two or not between 16 and 4096.
"""
if self.discovery_splash_hash is None:
@@ -2993,21 +2959,21 @@ def make_splash_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optio
Parameters
----------
- ext : builtins.str
+ ext : str
The extension to use for this URL, defaults to `png`.
Supports `png`, `jpeg`, `jpg` and `webp`.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Returns
-------
typing.Optional[hikari.files.URL]
- The URL to the splash, or `builtins.None` if not set.
+ The URL to the splash, or `None` if not set.
Raises
------
- builtins.ValueError
+ ValueError
If `size` is not a power of two or not between 16 and 4096.
"""
if self.splash_hash is None:
@@ -3035,7 +3001,7 @@ def get_channel(
Returns
-------
typing.Optional[hikari.channels.GuildChannel]
- The object of the guild channel found in cache or `builtins.None.
+ The object of the guild channel found in cache or `None`.
"""
if not isinstance(self.app, traits.CacheAware):
return None
@@ -3053,7 +3019,7 @@ def get_member(self, user: snowflakes.SnowflakeishOr[users.PartialUser]) -> typi
Returns
-------
typing.Optional[Member]
- The cached member object if found, else `builtins.None`.
+ The cached member object if found, else `None`.
"""
if not isinstance(self.app, traits.CacheAware):
return None
@@ -3066,7 +3032,7 @@ def get_my_member(self) -> typing.Optional[Member]:
Returns
-------
typing.Optional[Member]
- The cached member for this guild, or `builtins.None` if not known.
+ The cached member for this guild, or `None` if not known.
"""
if not isinstance(self.app, traits.ShardAware):
return None
@@ -3090,7 +3056,7 @@ def get_presence(
Returns
-------
typing.Optional[hikari.presences.MemberPresence]
- The cached presence object if found, else `builtins.None`.
+ The cached presence object if found, else `None`.
"""
if not isinstance(self.app, traits.CacheAware):
return None
@@ -3110,7 +3076,7 @@ def get_voice_state(
Returns
-------
typing.Optional[hikari.voices.VoiceState]
- The cached voice state object if found, else `builtins.None`.
+ The cached voice state object if found, else `None`.
"""
if not isinstance(self.app, traits.CacheAware):
return None
@@ -3131,7 +3097,7 @@ def get_emoji(
-------
typing.Optional[hikari.emojis.KnownCustomEmoji]
The object of the custom emoji if found in cache, else
- `builtins.None`.
+ `None`.
"""
if not isinstance(self.app, traits.CacheAware):
return None
@@ -3152,7 +3118,7 @@ def get_sticker(
-------
typing.Optional[hikari.stickers.GuildSticker]
The object of the sticker if found in cache, else
- `builtins.None`.
+ `None`.
"""
if not isinstance(self.app, traits.CacheAware):
return None
@@ -3170,7 +3136,7 @@ def get_role(self, role: snowflakes.SnowflakeishOr[PartialRole]) -> typing.Optio
Returns
-------
typing.Optional[Role]
- The object of the role found in cache, else `builtins.None`.
+ The object of the role found in cache, else `None`.
"""
if not isinstance(self.app, traits.CacheAware):
return None
@@ -3210,12 +3176,12 @@ async def fetch_owner(self) -> Member:
async def fetch_widget_channel(self) -> typing.Optional[channels_.GuildChannel]:
"""Fetch the widget channel.
- This will be `builtins.None` if not set.
+ This will be `None` if not set.
Returns
-------
typing.Optional[hikari.channels.GuildChannel]
- The channel the widget is linked to or else `builtins.None`.
+ The channel the widget is linked to or else `None`.
Raises
------
@@ -3252,7 +3218,7 @@ async def fetch_afk_channel(self) -> typing.Optional[channels_.GuildVoiceChannel
Returns
-------
typing.Optional[hikari.channels.GuildVoiceChannel]
- The AFK channel or `builtins.None` if not enabled.
+ The AFK channel or `None` if not enabled.
Raises
------
@@ -3289,7 +3255,7 @@ async def fetch_system_channel(self) -> typing.Optional[channels_.GuildTextChann
Returns
-------
typing.Optional[hikari.channels.GuildTextChannel]
- The system channel for this guild or `builtins.None` if not
+ The system channel for this guild or `None` if not
enabled.
Raises
@@ -3324,12 +3290,12 @@ async def fetch_system_channel(self) -> typing.Optional[channels_.GuildTextChann
async def fetch_rules_channel(self) -> typing.Optional[channels_.GuildTextChannel]:
"""Fetch the channel where guilds display rules and guidelines.
- If the `GuildFeature.COMMUNITY` feature is not defined, then this is `builtins.None`.
+ If the `GuildFeature.COMMUNITY` feature is not defined, then this is `None`.
Returns
-------
typing.Optional[hikari.channels.GuildTextChannel]
- The channel where the rules of the guild are specified or else `builtins.None`.
+ The channel where the rules of the guild are specified or else `None`.
Raises
------
@@ -3364,7 +3330,7 @@ async def fetch_public_updates_channel(self) -> typing.Optional[channels_.GuildT
"""Fetch channel ID of the channel where admins and moderators receive notices from Discord.
This is only present if `GuildFeature.COMMUNITY` is in `Guild.features` for
- this guild. For all other purposes, it should be considered to be `builtins.None`.
+ this guild. For all other purposes, it should be considered to be `None`.
Returns
-------
@@ -3419,19 +3385,19 @@ class RESTGuild(Guild):
approximate_active_member_count: typing.Optional[int] = attr.field(eq=False, hash=False, repr=False)
"""The approximate number of members in the guild that are not offline.
- This will be `builtins.None` when creating a guild.
+ This will be `None` when creating a guild.
"""
approximate_member_count: typing.Optional[int] = attr.field(eq=False, hash=False, repr=False)
"""The approximate number of members in the guild.
- This will be `builtins.None` when creating a guild.
+ This will be `None` when creating a guild.
"""
max_presences: typing.Optional[int] = attr.field(eq=False, hash=False, repr=False)
"""The maximum number of presences for the guild.
- If `builtins.None`, then there is no limit.
+ If `None`, then there is no limit.
"""
max_members: int = attr.field(eq=False, hash=False, repr=False)
@@ -3447,7 +3413,7 @@ class GatewayGuild(Guild):
This information is only available if the guild was sent via a `GUILD_CREATE`
event. If the guild is received from any other place, this will always be
- `builtins.None`.
+ `None`.
The implications of a large guild are that presence information will not be
sent about members who are offline or invisible.
@@ -3458,7 +3424,7 @@ class GatewayGuild(Guild):
This information is only available if the guild was sent via a `GUILD_CREATE`
event. If the guild is received from any other place, this will always be
- `builtins.None`.
+ `None`.
"""
member_count: typing.Optional[int] = attr.field(eq=False, hash=False, repr=False)
@@ -3466,5 +3432,5 @@ class GatewayGuild(Guild):
This information is only available if the guild was sent via a `GUILD_CREATE`
event. If the guild is received from any other place, this will always be
- `builtins.None`.
+ `None`.
"""
diff --git a/hikari/impl/bot.py b/hikari/impl/bot.py
index 0aae257bee..01e948c14c 100644
--- a/hikari/impl/bot.py
+++ b/hikari/impl/bot.py
@@ -103,15 +103,22 @@ class GatewayBot(traits.GatewayBotAware):
This is the class you will want to use to start, control, and build a bot
with.
+ .. note::
+ Settings that control the gateway session are provided to the
+ `GatewayBot.run` and `GatewayBot.start` functions in this class. This is done
+ to allow you to contextually customise details such as sharding
+ configuration without having to re-initialize the entire application
+ each time.
+
Parameters
----------
- token : builtins.str
+ token : str
The bot token to sign in with.
Other Parameters
----------------
- allow_color : builtins.bool
- Defaulting to `builtins.True`, this will enable coloured console logs
+ allow_color : bool
+ Defaulting to `True`, this will enable coloured console logs
on any platform that is a TTY.
Setting a `"CLICOLOR"` environment variable to any **non `0`** value
will override this setting.
@@ -121,12 +128,12 @@ class GatewayBot(traits.GatewayBotAware):
awkward or not support features in a standard way, the option to
explicitly disable this is provided. See `force_color` for an
alternative.
- banner : typing.Optional[builtins.str]
+ banner : typing.Optional[str]
The package to search for a `banner.txt` in. Defaults to `"hikari"` for
the `"hikari/banner.txt"` banner.
- Setting this to `builtins.None` will disable the banner being shown.
+ Setting this to `None` will disable the banner being shown.
executor : typing.Optional[concurrent.futures.Executor]
- Defaults to `builtins.None`. If non-`builtins.None`, then this executor
+ Defaults to `None`. If non-`None`, then this executor
is used instead of the `concurrent.futures.ThreadPoolExecutor` attached
to the `asyncio.AbstractEventLoop` that the bot will run on. This
executor is used primarily for file-IO.
@@ -134,14 +141,16 @@ class GatewayBot(traits.GatewayBotAware):
While mainly supporting the `concurrent.futures.ThreadPoolExecutor`
implementation in the standard lib, Hikari's file handling systems
should also work with `concurrent.futures.ProcessPoolExecutor`, which
- relies on all objects used in IPC to be `pickle`able. Many third-party
+ relies on all objects used in IPC to be pickleable. Many third-party
libraries will not support this fully though, so your mileage may vary
on using ProcessPoolExecutor implementations with this parameter.
- force_color : builtins.bool
- Defaults to `builtins.False`. If `builtins.True`, then this application
+ force_color : bool
+ Defaults to `False`. If `True`, then this application
will __force__ colour to be used in console-based output. Specifying a
`"CLICOLOR_FORCE"` environment variable with a non-`"0"` value will
override this setting.
+
+ This will take precedence over `allow_color` if both are specified.
cache_settings : typing.Optional[hikari.impl.config.CacheSettings]
Optional cache settings. If unspecified, will use the defaults.
http_settings : typing.Optional[hikari.impl.config.HTTPSettings]
@@ -153,23 +162,23 @@ class GatewayBot(traits.GatewayBotAware):
Defaults to `hikari.intents.Intents.ALL_UNPRIVILEGED`. This allows you
to change which intents your application will use on the gateway. This
can be used to control and change the types of events you will receive.
- auto_chunk_members : builtins.bool
- Defaults to `builtins.True`. If `builtins.False`, then no member chunks
+ auto_chunk_members : bool
+ Defaults to `True`. If `False`, then no member chunks
will be requested automatically, even if there are reasons to do so.
All following statements must be true to automatically request chunks:
- 1. `auto_chunk_members` is `builtins.True`.
+ 1. `auto_chunk_members` is `True`.
2. The members intent is enabled.
3. The server is marked as "large" or the presences intent is not enabled
- (since Discord only sends other members when presences are declared,
- we should also chunk small guilds if the presences are not declared).
+ (since Discord only sends other members when presences are declared,
+ we should also chunk small guilds if the presences are not declared).
4. The members cache is enabled or there are listeners for the
- `MemberChunkEvent`.
- logs : typing.Union[builtins.None, LoggerLevel, typing.Dict[str, typing.Any]]
+ `MemberChunkEvent`.
+ logs : typing.Union[None, LoggerLevel, typing.Dict[str, typing.Any]]
Defaults to `"INFO"`.
- If `builtins.None`, then the Python logging system is left uninitialized
+ If `None`, then the Python logging system is left uninitialized
on startup, and you will need to configure it manually to view most
logs that are output by components of this library.
@@ -190,7 +199,7 @@ class GatewayBot(traits.GatewayBotAware):
Note that `"TRACE_HIKARI"` is a library-specific logging level
which is expected to be more verbose than `"DEBUG"`.
- max_rate_limit : builtins.float
+ max_rate_limit : float
The max number of seconds to backoff for when rate limited. Anything
greater than this will instead raise an error.
@@ -203,50 +212,49 @@ class GatewayBot(traits.GatewayBotAware):
Note that this only applies to the REST API component that communicates
with Discord, and will not affect sharding or third party HTTP endpoints
that may be in use.
- max_retries : typing.Optional[builtins.int]
+ max_retries : typing.Optional[int]
Maximum number of times a request will be retried if
- it fails with a `5xx` status. Defaults to 3 if set to `builtins.None`.
+ it fails with a `5xx` status. Defaults to 3 if set to `None`.
proxy_settings : typing.Optional[hikari.impl.config.ProxySettings]
Custom proxy settings to use with network-layer logic
in your application to get through an HTTP-proxy.
- rest_url : typing.Optional[builtins.str]
- Defaults to the Discord REST API URL if `builtins.None`. Can be
+ rest_url : typing.Optional[str]
+ Defaults to the Discord REST API URL if `None`. Can be
overridden if you are attempting to point to an unofficial endpoint, or
if you are attempting to mock/stub the Discord API for any reason.
Generally you do not want to change this.
- !!! note
- `force_color` will always take precedence over `allow_color`.
-
- !!! note
- Settings that control the gateway session are provided to the
- `GatewayBot.run` and `GatewayBot.start` functions in this class. This is done
- to allow you to contextually customise details such as sharding
- configuration without having to re-initialize the entire application
- each time.
-
- Example
- -------
+ Examples
+ --------
Setting up logging using a dictionary configuration:
- ```py
- import os
+ .. code-block:: python
+
+ import os
- import hikari
+ import hikari
- # We want to make gateway logs output as DEBUG, and TRACE for all ratelimit content.
- bot = hikari.GatewayBot(
- token=os.environ["BOT_TOKEN"],
- logs={
- "version": 1,
- "incremental": True,
- "loggers": {
- "hikari.gateway": {"level": "DEBUG"},
- "hikari.ratelimits": {"level": "TRACE_HIKARI"},
+ # We want to make gateway logs output as DEBUG, and TRACE for all ratelimit content.
+ bot = hikari.GatewayBot(
+ token=os.environ["BOT_TOKEN"],
+ logs={
+ "version": 1,
+ "incremental": True,
+ "loggers": {
+ "hikari.gateway": {"level": "DEBUG"},
+ "hikari.ratelimits": {"level": "TRACE_HIKARI"},
+ },
},
- },
- )
- ```
+ )
+ """
+
+ shards: typing.Mapping[int, gateway_shard.GatewayShard]
+ """Mapping of shards in this application instance.
+
+ Each shard ID is mapped to the corresponding shard instance.
+
+ If the application has not started, it is acceptable to assume the
+ result of this call will be an empty mapping.
"""
__slots__: typing.Sequence[str] = (
@@ -337,7 +345,7 @@ def __init__(
# We populate these on startup instead, as we need to possibly make some
# HTTP requests to determine what to put in this mapping.
self._shards: typing.Dict[int, gateway_shard.GatewayShard] = {}
- self.shards: typing.Mapping[int, gateway_shard.GatewayShard] = types.MappingProxyType(self._shards)
+ self.shards = types.MappingProxyType(self._shards)
@property
def cache(self) -> cache_.Cache:
@@ -462,62 +470,62 @@ def dispatch(self, event: base_events.Event) -> asyncio.Future[typing.Any]:
event : hikari.events.base_events.Event
The event to dispatch.
- Example
- -------
+ Examples
+ --------
We can dispatch custom events by first defining a class that
derives from `hikari.events.base_events.Event`.
- ```py
- import attr
+ .. code-block:: python
- from hikari.traits import RESTAware
- from hikari.events.base_events import Event
- from hikari.users import User
- from hikari.snowflakes import Snowflake
+ import attr
- @attr.define()
- class EveryoneMentionedEvent(Event):
- app: RESTAware = attr.field()
+ from hikari.traits import RESTAware
+ from hikari.events.base_events import Event
+ from hikari.users import User
+ from hikari.snowflakes import Snowflake
- author: User = attr.field()
- '''The user who mentioned everyone.'''
+ @attr.define()
+ class EveryoneMentionedEvent(Event):
+ app: RESTAware = attr.field()
- content: str = attr.field()
- '''The message that was sent.'''
+ author: User = attr.field()
+ '''The user who mentioned everyone.'''
- message_id: Snowflake = attr.field()
- '''The message ID.'''
+ content: str = attr.field()
+ '''The message that was sent.'''
- channel_id: Snowflake = attr.field()
- '''The channel ID.'''
- ```
+ message_id: Snowflake = attr.field()
+ '''The message ID.'''
+
+ channel_id: Snowflake = attr.field()
+ '''The channel ID.'''
We can then dispatch our event as we see fit.
- ```py
- from hikari.events.messages import MessageCreateEvent
-
- @bot.listen(MessageCreateEvent)
- async def on_message(event):
- if "@everyone" in event.content or "@here" in event.content:
- event = EveryoneMentionedEvent(
- author=event.author,
- content=event.content,
- message_id=event.id,
- channel_id=event.channel_id,
- )
+ .. code-block:: python
+
+ from hikari.events.messages import MessageCreateEvent
+
+ @bot.listen(MessageCreateEvent)
+ async def on_message(event):
+ if "@everyone" in event.content or "@here" in event.content:
+ event = EveryoneMentionedEvent(
+ author=event.author,
+ content=event.content,
+ message_id=event.id,
+ channel_id=event.channel_id,
+ )
- bot.dispatch(event)
- ```
+ bot.dispatch(event)
This event can be listened to elsewhere by subscribing to it with
- `EventManager.subscribe`.
+ `hikari.impl.event_manager_base.EventManager.subscribe`.
- ```py
- @bot.listen(EveryoneMentionedEvent)
- async def on_everyone_mentioned(event):
- print(event.user, "just pinged everyone in", event.channel_id)
- ```
+ .. code-block:: python
+
+ @bot.listen(EveryoneMentionedEvent)
+ async def on_everyone_mentioned(event):
+ print(event.user, "just pinged everyone in", event.channel_id)
Returns
-------
@@ -529,11 +537,11 @@ async def on_everyone_mentioned(event):
See Also
--------
- Listen: `hikari.impl.bot.GatewayBot.listen`
- Stream: `hikari.impl.bot.GatewayBot.stream`
- Subscribe: `hikari.impl.bot.GatewayBot.subscribe`
- Unsubscribe: `hikari.impl.bot.GatewayBot.unsubscribe`
- Wait_for: `hikari.impl.bot.GatewayBot.wait_for`
+ Listen : `hikari.impl.bot.GatewayBot.listen`.
+ Stream : `hikari.impl.bot.GatewayBot.stream`.
+ Subscribe : `hikari.impl.bot.GatewayBot.subscribe`.
+ Unsubscribe : `hikari.impl.bot.GatewayBot.unsubscribe`.
+ Wait_for : `hikari.impl.bot.GatewayBot.wait_for`.
"""
return self._event_manager.dispatch(event)
@@ -547,19 +555,17 @@ def get_listeners(
event_type : typing.Type[EventT]
The event type to look for.
`EventT` must be a subclass of `hikari.events.base_events.Event`.
- polymorphic : builtins.bool
- If `builtins.True`, this will also return the listeners of the
- subclasses of the given event type. If `builtins.False`, then
+ polymorphic : bool
+ If `True`, this will also return the listeners of the
+ subclasses of the given event type. If `False`, then
only listeners for this class specifically are returned. The
- default is `builtins.True`.
+ default is `True`.
Returns
-------
- typing.Collection[typing.Callable[[EventT], typing.Coroutine[typing.Any, typing.Any, builtins.None]]]
+ typing.Collection[typing.Callable[[EventT], typing.Coroutine[typing.Any, typing.Any, None]]]
A copy of the collection of listeners for the event. Will return
an empty collection if nothing is registered.
-
- `EventT` must be a subclass of `hikari.events.base_events.Event`.
"""
return self._event_manager.get_listeners(event_type, polymorphic=polymorphic)
@@ -595,11 +601,11 @@ def listen(
See Also
--------
- Dispatch: `hikari.impl.bot.GatewayBot.dispatch`
- Stream: `hikari.impl.bot.GatewayBot.stream`
- Subscribe: `hikari.impl.bot.GatewayBot.subscribe`
- Unsubscribe: `hikari.impl.bot.GatewayBot.unsubscribe`
- Wait_for: `hikari.impl.bot.GatewayBot.wait_for`
+ Dispatch : `hikari.impl.bot.GatewayBot.dispatch`.
+ Stream : `hikari.impl.bot.GatewayBot.stream`.
+ Subscribe : `hikari.impl.bot.GatewayBot.subscribe`.
+ Unsubscribe : `hikari.impl.bot.GatewayBot.unsubscribe`.
+ Wait_for : `hikari.impl.bot.GatewayBot.wait_for`.
"""
return self._event_manager.listen(*event_types)
@@ -621,26 +627,25 @@ def print_banner(
Parameters
----------
- banner : typing.Optional[builtins.str]
+ banner : typing.Optional[str]
The package to find a `banner.txt` in.
- allow_color : builtins.bool
+ allow_color : bool
A flag that allows advising whether to allow color if supported or
not. Can be overridden by setting a `"CLICOLOR"` environment
variable to a non-`"0"` string.
- force_color : builtins.bool
+ force_color : bool
A flag that allows forcing color to always be output, even if the
terminal device may not support it. Setting the `"CLICOLOR_FORCE"`
environment variable to a non-`"0"` string will override this.
- !!! note
- `force_color` will always take precedence over `allow_color`.
- extra_args : typing.Optional[typing.Dict[builtins.str, builtins.str]]
+ This will take precedence over `allow_color` if both are specified.
+ extra_args : typing.Optional[typing.Dict[str, str]]
If provided, extra $-substitutions to use when printing the banner.
Default substitutions can not be overwritten.
Raises
------
- builtins.ValueError
+ ValueError
If `extra_args` contains a default $-substitution.
"""
ux.print_banner(banner, allow_color, force_color, extra_args=extra_args)
@@ -670,25 +675,25 @@ def run(
----------------
activity : typing.Optional[hikari.presences.Activity]
The initial activity to display in the bot user presence, or
- `builtins.None` (default) to not show any.
- afk : builtins.bool
+ `None` (default) to not show any.
+ afk : bool
The initial AFK state to display in the bot user presence, or
- `builtins.False` (default) to not show any.
- asyncio_debug : builtins.bool
- Defaults to `builtins.False`. If `builtins.True`, then debugging is
+ `False` (default) to not show any.
+ asyncio_debug : bool
+ Defaults to `False`. If `True`, then debugging is
enabled for the asyncio event loop in use.
- check_for_updates : builtins.bool
- Defaults to `builtins.True`. If `builtins.True`, will check for
+ check_for_updates : bool
+ Defaults to `True`. If `True`, will check for
newer versions of `hikari` on PyPI and notify if available.
- close_passed_executor : builtins.bool
- Defaults to `builtins.False`. If `builtins.True`, any custom
+ close_passed_executor : bool
+ Defaults to `False`. If `True`, any custom
`concurrent.futures.Executor` passed to the constructor will be
shut down when the application terminates. This does not affect the
default executor associated with the event loop, and will not
do anything if you do not provide a custom executor to the
constructor.
- close_loop : builtins.bool
- Defaults to `builtins.True`. If `builtins.True`, then once the bot
+ close_loop : bool
+ Defaults to `True`. If `True`, then once the bot
enters a state where all components have shut down permanently
during application shut down, then all asyncgens and background tasks
will be destroyed, and the event loop will be shut down.
@@ -697,17 +702,17 @@ def run(
had time to attempt to shut down correctly (around 250ms), and on
Python 3.9 and newer, will also shut down the default event loop
executor too.
- coroutine_tracking_depth : typing.Optional[builtins.int]
- Defaults to `builtins.None`. If an integer value and supported by
+ coroutine_tracking_depth : typing.Optional[int]
+ Defaults to `None`. If an integer value and supported by
the interpreter, then this many nested coroutine calls will be
tracked with their call origin state. This allows you to determine
where non-awaited coroutines may originate from, but generally you
do not want to leave this enabled for performance reasons.
- enable_signal_handlers : typing.Optional[builtins.bool]
- Defaults to `builtins.True` if this is started in the main thread.
+ enable_signal_handlers : typing.Optional[bool]
+ Defaults to `True` if this is started in the main thread.
- If on a __non-Windows__ OS with builtin support for kernel-level
- POSIX signals, then setting this to `builtins.True` will allow
+ If on a non-Windows OS with builtin support for kernel-level
+ POSIX signals, then setting this to `True` will allow
treating keyboard interrupts and other OS signals to safely shut
down the application as calls to shut down the application properly
rather than just killing the process in a dirty state immediately.
@@ -715,36 +720,36 @@ def run(
signal handling yourself.
idle_since : typing.Optional[datetime.datetime]
The `datetime.datetime` the user should be marked as being idle
- since, or `builtins.None` (default) to not show this.
- ignore_session_start_limit : builtins.bool
- Defaults to `builtins.False`. If `builtins.False`, then attempting
+ since, or `None` (default) to not show this.
+ ignore_session_start_limit : bool
+ Defaults to `False`. If `False`, then attempting
to start more sessions than you are allowed in a 24 hour window
will throw a `RuntimeError` rather than going ahead
and hitting the IDENTIFY limit, which may result in your token
- being reset. Setting to `builtins.True` disables this behavior.
- large_threshold : builtins.int
+ being reset. Setting to `True` disables this behavior.
+ large_threshold : int
Threshold for members in a guild before it is treated as being
"large" and no longer sending member details in the `GUILD CREATE`
event. Defaults to `250`.
- propagate_interrupts : builtins.bool
- Defaults to `builtins.False`. If set to `builtins.True`, then any
+ propagate_interrupts : bool
+ Defaults to `False`. If set to `True`, then any
internal `hikari.errors.HikariInterrupt` that is raises as a
result of catching an OS level signal will result in the
exception being rethrown once the application has closed. This can
allow you to use hikari signal handlers and still be able to
determine what kind of interrupt the application received after
- it closes. When `builtins.False`, nothing is raised and the call
+ it closes. When `False`, nothing is raised and the call
will terminate cleanly and silently where possible instead.
- shard_ids : typing.Optional[typing.Sequence[builtins.int]]
- The shard IDs to create shards for. If not `builtins.None`, then
+ shard_ids : typing.Optional[typing.Sequence[int]]
+ The shard IDs to create shards for. If not `None`, then
a non-`None` `shard_count` must ALSO be provided. Defaults to
- `builtins.None`, which means the Discord-recommended count is used
+ `None`, which means the Discord-recommended count is used
for your application instead.
Note that the sequence will be de-duplicated.
- shard_count : typing.Optional[builtins.int]
+ shard_count : typing.Optional[int]
The number of shards to use in the entire distributed application.
- Defaults to `builtins.None` which results in the count being
+ Defaults to `None` which results in the count being
determined dynamically on startup.
status : hikari.presences.Status
The initial status to show for the user presence on startup.
@@ -754,7 +759,7 @@ def run(
------
hikari.errors.ComponentStateConflictError
If bot is already running.
- builtins.TypeError
+ TypeError
If `shard_ids` is passed without `shard_count`.
"""
if self._closed_event:
@@ -833,36 +838,36 @@ async def start(
----------------
activity : typing.Optional[hikari.presences.Activity]
The initial activity to display in the bot user presence, or
- `builtins.None` (default) to not show any.
- afk : builtins.bool
+ `None` (default) to not show any.
+ afk : bool
The initial AFK state to display in the bot user presence, or
- `builtins.False` (default) to not show any.
- check_for_updates : builtins.bool
- Defaults to `builtins.True`. If `builtins.True`, will check for
+ `False` (default) to not show any.
+ check_for_updates : bool
+ Defaults to `True`. If `True`, will check for
newer versions of `hikari` on PyPI and notify if available.
idle_since : typing.Optional[datetime.datetime]
The `datetime.datetime` the user should be marked as being idle
- since, or `builtins.None` (default) to not show this.
- ignore_session_start_limit : builtins.bool
- Defaults to `builtins.False`. If `builtins.False`, then attempting
+ since, or `None` (default) to not show this.
+ ignore_session_start_limit : bool
+ Defaults to `False`. If `False`, then attempting
to start more sessions than you are allowed in a 24 hour window
will throw a `RuntimeError` rather than going ahead
and hitting the IDENTIFY limit, which may result in your token
- being reset. Setting to `builtins.True` disables this behavior.
- large_threshold : builtins.int
+ being reset. Setting to `True` disables this behavior.
+ large_threshold : int
Threshold for members in a guild before it is treated as being
"large" and no longer sending member details in the `GUILD CREATE`
event. Defaults to `250`.
- shard_ids : typing.Optional[typing.Sequence[builtins.int]]
- The shard IDs to create shards for. If not `builtins.None`, then
+ shard_ids : typing.Optional[typing.Sequence[int]]
+ The shard IDs to create shards for. If not `None`, then
a non-`None` `shard_count` must ALSO be provided. Defaults to
- `builtins.None`, which means the Discord-recommended count is used
+ `None`, which means the Discord-recommended count is used
for your application instead.
Note that the sequence will be de-duplicated.
- shard_count : typing.Optional[builtins.int]
+ shard_count : typing.Optional[int]
The number of shards to use in the entire distributed application.
- Defaults to `builtins.None` which results in the count being
+ Defaults to `None` which results in the count being
determined dynamically on startup.
status : hikari.presences.Status
The initial status to show for the user presence on startup.
@@ -870,10 +875,10 @@ async def start(
Raises
------
+ TypeError
+ If `shard_ids` is passed without `shard_count`.
hikari.errors.ComponentStateConflictError
If bot is already running.
- builtins.TypeError
- If `shard_ids` is passed without `shard_count`.
"""
if self._closed_event:
raise errors.ComponentStateConflictError("bot is already running")
@@ -981,18 +986,23 @@ def stream(
) -> event_manager_.EventStream[base_events.EventT]:
"""Return a stream iterator for the given event and sub-events.
+ .. warning::
+ If you use `stream.open()` to start the stream then you must
+ also close it with `stream.close()` otherwise it may queue
+ events in memory indefinitely.
+
Parameters
----------
event_type : typing.Type[hikari.events.base_events.Event]
The event type to listen for. This will listen for subclasses of
this type additionally.
- timeout : typing.Optional[builtins.int, builtins.float]
+ timeout : typing.Optional[int, float]
How long this streamer should wait for the next event before
- ending the iteration. If `builtins.None` then this will continue
+ ending the iteration. If `None` then this will continue
until explicitly broken from.
- limit : typing.Optional[builtins.int]
+ limit : typing.Optional[int]
The limit for how many events this should queue at one time before
- dropping extra incoming events, leave this as `builtins.None` for
+ dropping extra incoming events, leave this as `None` for
the cache size to be unlimited.
Returns
@@ -1002,39 +1012,33 @@ def stream(
with `with stream:` or `stream.open()` before
asynchronously iterating over it.
- !!! warning
- If you use `stream.open()` to start the stream then you must
- also close it with `stream.close()` otherwise it may queue
- events in memory indefinitely.
-
Examples
--------
+ .. code-block:: python
- ```py
- with bot.stream(events.ReactionAddEvent, timeout=30).filter(("message_id", message.id)) as stream:
- async for user_id in stream.map("user_id").limit(50):
- ...
- ```
+ with bot.stream(events.ReactionAddEvent, timeout=30).filter(("message_id", message.id)) as stream:
+ async for user_id in stream.map("user_id").limit(50):
+ ...
or using `open()` and `close()`
- ```py
- stream = bot.stream(events.ReactionAddEvent, timeout=30).filter(("message_id", message.id))
- stream.open()
+ .. code-block:: python
- async for user_id in stream.map("user_id").limit(50)
- ...
+ stream = bot.stream(events.ReactionAddEvent, timeout=30).filter(("message_id", message.id))
+ stream.open()
- stream.close()
- ```
+ async for user_id in stream.map("user_id").limit(50)
+ ...
+
+ stream.close()
See Also
--------
- Dispatch: `hikari.impl.bot.GatewayBot.dispatch`
- Listen: `hikari.impl.bot.GatewayBot.listen`
- Subscribe: `hikari.impl.bot.GatewayBot.subscribe`
- Unsubscribe: `hikari.impl.bot.GatewayBot.unsubscribe`
- Wait_for: `hikari.impl.bot.GatewayBot.wait_for`
+ Dispatch : `hikari.impl.bot.GatewayBot.dispatch`.
+ Listen : `hikari.impl.bot.GatewayBot.listen`.
+ Subscribe : `hikari.impl.bot.GatewayBot.subscribe`.
+ Unsubscribe : `hikari.impl.bot.GatewayBot.unsubscribe`.
+ Wait_for : `hikari.impl.bot.GatewayBot.wait_for`.
"""
self._check_if_alive()
return self._event_manager.stream(event_type, timeout=timeout, limit=limit)
@@ -1057,27 +1061,27 @@ def subscribe(self, event_type: typing.Type[typing.Any], callback: event_manager
consume an instance of the given event, or an instance of a valid
subclass if one exists. Any result is discarded.
- Example
- -------
+ Examples
+ --------
The following demonstrates subscribing a callback to message creation
events.
- ```py
- from hikari.events.messages import MessageCreateEvent
+ .. code-block:: python
+
+ from hikari.events.messages import MessageCreateEvent
- async def on_message(event):
- ...
+ async def on_message(event):
+ ...
- bot.subscribe(MessageCreateEvent, on_message)
- ```
+ bot.subscribe(MessageCreateEvent, on_message)
See Also
--------
- Dispatch: `hikari.impl.bot.GatewayBot.dispatch`
- Listen: `hikari.impl.bot.GatewayBot.listen`
- Stream: `hikari.impl.bot.GatewayBot.stream`
- Unsubscribe: `hikari.impl.bot.GatewayBot.unsubscribe`
- Wait_for: `hikari.impl.bot.GatewayBot.wait_for`
+ Dispatch : `hikari.impl.bot.GatewayBot.dispatch`.
+ Listen : `hikari.impl.bot.GatewayBot.listen`.
+ Stream : `hikari.impl.bot.GatewayBot.stream`.
+ Unsubscribe : `hikari.impl.bot.GatewayBot.unsubscribe`.
+ Wait_for : `hikari.impl.bot.GatewayBot.wait_for`.
"""
self._event_manager.subscribe(event_type, callback)
@@ -1097,27 +1101,27 @@ def unsubscribe(self, event_type: typing.Type[typing.Any], callback: event_manag
callback
The callback to unsubscribe.
- Example
- -------
+ Examples
+ --------
The following demonstrates unsubscribing a callback from a message
creation event.
- ```py
- from hikari.events.messages import MessageCreateEvent
+ .. code-block:: python
- async def on_message(event):
- ...
+ from hikari.events.messages import MessageCreateEvent
- bot.unsubscribe(MessageCreateEvent, on_message)
- ```
+ async def on_message(event):
+ ...
+
+ bot.unsubscribe(MessageCreateEvent, on_message)
See Also
--------
- Dispatch: `hikari.impl.bot.GatewayBot.dispatch`
- Listen: `hikari.impl.bot.GatewayBot.listen`
- Stream: `hikari.impl.bot.GatewayBot.stream`
- Subscribe: `hikari.impl.bot.GatewayBot.subscribe`
- Wait_for: `hikari.impl.bot.GatewayBot.wait_for`
+ Dispatch : `hikari.impl.bot.GatewayBot.dispatch`.
+ Listen : `hikari.impl.bot.GatewayBot.listen`.
+ Stream : `hikari.impl.bot.GatewayBot.stream`.
+ Subscribe : `hikari.impl.bot.GatewayBot.subscribe`.
+ Wait_for : `hikari.impl.bot.GatewayBot.wait_for`.
"""
self._event_manager.unsubscribe(event_type, callback)
@@ -1130,6 +1134,9 @@ async def wait_for(
) -> base_events.EventT:
"""Wait for a given event to occur once, then return the event.
+ .. warning::
+ Async predicates are not supported.
+
Parameters
----------
event_type : typing.Type[hikari.events.base_events.Event]
@@ -1137,17 +1144,14 @@ async def wait_for(
this type additionally.
predicate
A function taking the event as the single parameter.
- This should return `builtins.True` if the event is one you want to
- return, or `builtins.False` if the event should not be returned.
+ This should return `True` if the event is one you want to
+ return, or `False` if the event should not be returned.
If left as `None` (the default), then the first matching event type
that the bot receives (or any subtype) will be the one returned.
-
- !!! warning
- Async predicates are not supported.
- timeout : typing.Union[builtins.float, builtins.int, builtins.None]
+ timeout : typing.Union[float, int, None]
The amount of time to wait before raising an `asyncio.TimeoutError`
and giving up instead. This is measured in seconds. If
- `builtins.None`, then no timeout will be waited for (no timeout can
+ `None`, then no timeout will be waited for (no timeout can
result in "leaking" of coroutines that never complete if called in
an uncontrolled way, so is not recommended).
@@ -1159,16 +1163,16 @@ async def wait_for(
Raises
------
asyncio.TimeoutError
- If the timeout is not `builtins.None` and is reached before an
- event is received that the predicate returns `builtins.True` for.
+ If the timeout is not `None` and is reached before an
+ event is received that the predicate returns `True` for.
See Also
--------
- Dispatch: `hikari.impl.bot.GatewayBot.dispatch`
- Listen: `hikari.impl.bot.GatewayBot.listen`
- Stream: `hikari.impl.bot.GatewayBot.stream`
- Subscribe: `hikari.impl.bot.GatewayBot.subscribe`
- Unsubscribe: `hikari.impl.bot.GatewayBot.unsubscribe`
+ Dispatch : `hikari.impl.bot.GatewayBot.dispatch`.
+ Listen : `hikari.impl.bot.GatewayBot.listen`.
+ Stream : `hikari.impl.bot.GatewayBot.stream`.
+ Subscribe : `hikari.impl.bot.GatewayBot.subscribe`.
+ Unsubscribe : `hikari.impl.bot.GatewayBot.unsubscribe`.
"""
self._check_if_alive()
return await self._event_manager.wait_for(event_type, timeout=timeout, predicate=predicate)
diff --git a/hikari/impl/buckets.py b/hikari/impl/buckets.py
index 806020e632..e68cbdd002 100644
--- a/hikari/impl/buckets.py
+++ b/hikari/impl/buckets.py
@@ -63,7 +63,7 @@
Rate limits, on the other hand, apply to a bucket and are specific to the major
parameters of the compiled route. This means that `POST /channels/123/messages`
and `POST /channels/456/messages` do not share the same real bucket, despite
-Discord providing the same bucket hash. A real bucket hash is the `builtins.str` hash of
+Discord providing the same bucket hash. A real bucket hash is the `str` hash of
the bucket that Discord sends us in a response concatenated to the corresponding
major parameters. This is used for quick bucket indexing internally in this
module.
@@ -121,15 +121,15 @@
These headers are:
* `X-RateLimit-Limit`:
- an `builtins.int` describing the max requests in the bucket from empty to
+ an `int` describing the max requests in the bucket from empty to
being rate limited.
* `X-RateLimit-Remaining`:
- an `builtins.int` describing the remaining number of requests before rate
+ an `int` describing the remaining number of requests before rate
limiting occurs in the current window.
* `X-RateLimit-Bucket`:
- a `builtins.str` containing the initial bucket hash.
+ a `str` containing the initial bucket hash.
* `X-RateLimit-Reset-After`:
- a `builtins.float` containing the number of seconds when the current rate
+ a `float` containing the number of seconds when the current rate
limit bucket will reset with decimal millisecond precision.
Each of the above values should be passed to the `update_rate_limits` method to
@@ -165,7 +165,7 @@
No information is sent in headers about these specific limits. You will only
be made aware that they exist once you get ratelimited. In the 429 ratelimited
-response, you will have the `"global"` attribute set to `builtins.False`, and a
+response, you will have the `"global"` attribute set to `False`, and a
`"reset_after"` attribute that differs entirely to the `X-RateLimit-Reset-After`
header. Thus, it is important to not assume the value in the 429 response
for the reset time is the same as the one in the bucket headers. Hikari's
@@ -248,7 +248,7 @@ async def __aexit__(
@property
def is_unknown(self) -> bool:
- """Return `builtins.True` if the bucket represents an `UNKNOWN` bucket."""
+ """Return `True` if the bucket represents an `UNKNOWN` bucket."""
return self.name.startswith(UNKNOWN_HASH)
def release(self) -> None:
@@ -258,7 +258,7 @@ def release(self) -> None:
async def acquire(self) -> None:
"""Acquire time and the lock on this bucket.
- !!! note
+ .. note::
You should afterwards invoke `RESTBucket.update_rate_limit` to
update any rate limit information you are made aware of and
`RESTBucket.release` to release the lock.
@@ -293,18 +293,18 @@ async def acquire(self) -> None:
def update_rate_limit(self, remaining: int, limit: int, reset_at: float) -> None:
"""Update the rate limit information.
+ .. note::
+ The `reset_at` epoch is expected to be a `time.monotonic_timestamp`
+ monotonic epoch, rather than a `time.time` date-based epoch.
+
Parameters
----------
- remaining : builtins.int
+ remaining : int
The calls remaining in this time window.
- limit : builtins.int
+ limit : int
The total calls allowed in this time window.
- reset_at : builtins.float
+ reset_at : float
The epoch at which to reset the limit.
-
- !!! note
- The `reset_at` epoch is expected to be a `time.monotonic_timestamp`
- monotonic epoch, rather than a `time.time` date-based epoch.
"""
self.remaining: int = remaining
self.limit: int = limit
@@ -316,12 +316,12 @@ def resolve(self, real_bucket_hash: str) -> None:
Parameters
----------
- real_bucket_hash: builtins.str
+ real_bucket_hash : str
The real bucket hash for this bucket.
Raises
------
- builtins.RuntimeError
+ RuntimeError
If the hash of the bucket is already known.
"""
if not self.is_unknown:
@@ -343,7 +343,7 @@ class RESTBucketManager:
Parameters
----------
- max_rate_limit : builtins.float
+ max_rate_limit : float
The max number of seconds to backoff for when rate limited. Anything
greater than this will instead raise an error.
"""
@@ -360,9 +360,10 @@ class RESTBucketManager:
"""Maps routes to their `X-RateLimit-Bucket` header being used."""
real_hashes_to_buckets: typing.Final[typing.MutableMapping[str, RESTBucket]]
- """Maps full bucket hashes (`X-RateLimit-Bucket` appended with a hash of
- major parameters used in that compiled route) to their corresponding rate
- limiters.
+ """Maps full bucket hashes to their corresponding rate limiters.
+
+ The full bucket hash consists of `X-RateLimit-Bucket` appended with a hash of
+ major parameters used in that compiled route.
"""
closed_event: typing.Final[asyncio.Event]
@@ -404,10 +405,10 @@ def start(self, poll_period: float = 20.0, expire_after: float = 10.0) -> None:
Parameters
----------
- poll_period : builtins.float
+ poll_period : float
Period to poll the garbage collector at in seconds. Defaults
to `20` seconds.
- expire_after : builtins.float
+ expire_after : float
Time after which the last `reset_at` was hit for a bucket to
remove it. Higher values will retain unneeded ratelimit info for
longer, but may produce more effective rate-limiting logic as a
@@ -435,7 +436,7 @@ def close(self) -> None:
# Ignore docstring not starting in an imperative mood
async def gc(self, poll_period: float, expire_after: float) -> None:
- """The garbage collector loop.
+ """Run the garbage collector loop.
This is designed to run in the background and manage removing unused
route references from the rate-limiter collection to save memory.
@@ -443,22 +444,22 @@ async def gc(self, poll_period: float, expire_after: float) -> None:
This will run forever until `RESTBucketManager.closed_event` is set.
This will invoke `RESTBucketManager.do_gc_pass` periodically.
+ .. warning::
+ You generally have no need to invoke this directly. Use
+ `RESTBucketManager.start` and `RESTBucketManager.close` to control
+ this instead.
+
Parameters
----------
- poll_period : builtins.float
+ poll_period : float
The period to poll at.
- expire_after : builtins.float
+ expire_after : float
Time after which the last `reset_at` was hit for a bucket to
remove it. Higher values will retain unneeded ratelimit info for
longer, but may produce more effective ratelimiting logic as a
result. Using `0` will make the bucket get garbage collected as soon
as the rate limit has reset.
-
- !!! warning
- You generally have no need to invoke this directly. Use
- `RESTBucketManager.start` and `RESTBucketManager.close` to control
- this instead.
- """ # noqa: D401 - Imperative mood
+ """
# Prevent filling memory increasingly until we run out by removing dead buckets every 20s
# Allocations are somewhat cheap if we only do them every so-many seconds, after all.
_LOGGER.log(ux.TRACE, "rate limit garbage collector started")
@@ -480,18 +481,18 @@ def do_gc_pass(self, expire_after: float) -> None:
If the removed routes are used again in the future, they will be
re-cached automatically.
+ .. warning::
+ You generally have no need to invoke this directly. Use
+ `RESTBucketManager.start` and `RESTBucketManager.close` to control
+ this instead.
+
Parameters
----------
- expire_after : builtins.float
+ expire_after : float
Time after which the last `reset_at` was hit for a bucket to\
remove it. Defaults to `reset_at` + 20 seconds. Higher values will
retain unneeded ratelimit info for longer, but may produce more
effective ratelimiting logic as a result.
-
- !!! warning
- You generally have no need to invoke this directly. Use
- `RESTBucketManager.start` and `RESTBucketManager.close` to control
- this instead.
"""
buckets_to_purge: typing.List[str] = []
@@ -528,6 +529,11 @@ def do_gc_pass(self, expire_after: float) -> None:
def acquire(self, compiled_route: routes.CompiledRoute) -> RESTBucket:
"""Acquire a bucket for the given route.
+ .. note::
+ You MUST keep the context manager of the bucket acquired during the
+ full duration of the request. From making the request until calling
+ `update_rate_limits`.
+
Parameters
----------
compiled_route : hikari.internal.routes.CompiledRoute
@@ -537,11 +543,6 @@ def acquire(self, compiled_route: routes.CompiledRoute) -> RESTBucket:
-------
hikari.impl.RESTBucket
The bucket for this route.
-
- !!! note
- You MUST keep the context manager of the bucket acquired during the
- full duration of the request. From making the request until calling
- `update_rate_limits`.
"""
try:
bucket_hash = self.routes_to_hashes[compiled_route.route]
@@ -573,14 +574,14 @@ def update_rate_limits(
----------
compiled_route : hikari.internal.routes.CompiledRoute
The compiled route to get the bucket for.
- bucket_header : typing.Optional[builtins.str]
+ bucket_header : typing.Optional[str]
The `X-RateLimit-Bucket` header that was provided in the response.
- remaining_header : builtins.int
- The `X-RateLimit-Remaining` header cast to an `builtins.int`.
- limit_header : builtins.int
- The `X-RateLimit-Limit` header cast to an `builtins.int`.
- reset_after : builtins.float
- The `X-RateLimit-Reset-After` header cast to a `builtins.float`.
+ remaining_header : int
+ The `X-RateLimit-Remaining` header cast to an `int`.
+ limit_header : int
+ The `X-RateLimit-Limit` header cast to an `int`.
+ reset_after : float
+ The `X-RateLimit-Reset-After` header cast to a `float`.
"""
self.routes_to_hashes[compiled_route.route] = bucket_header
real_bucket_hash = compiled_route.create_real_bucket_hash(bucket_header)
@@ -625,5 +626,5 @@ def update_rate_limits(
@property
def is_started(self) -> bool:
- """Return `builtins.True` if the rate limiter GC task is started."""
+ """Return `True` if the rate limiter GC task is started."""
return self.gc_task is not None
diff --git a/hikari/impl/config.py b/hikari/impl/config.py
index bafd48581e..0981cbe95d 100644
--- a/hikari/impl/config.py
+++ b/hikari/impl/config.py
@@ -66,43 +66,23 @@ class BasicAuthHeader:
username: str = attr.field(validator=attr.validators.instance_of(str))
"""Username for the header.
- Returns
- -------
- builtins.str
- The username to use. This must not contain `":"`.
+ .. warning::
+ This must not contain `":"`.
"""
password: str = attr.field(repr=False, validator=attr.validators.instance_of(str))
- """Password to use.
-
- Returns
- -------
- builtins.str
- The password to use.
- """
+ """Password to use."""
charset: str = attr.field(default="utf-8", validator=attr.validators.instance_of(str))
"""Encoding to use for the username and password.
Default is `"utf-8"`, but you may choose to use something else,
including third-party encodings (e.g. IBM's EBCDIC codepages).
-
- Returns
- -------
- builtins.str
- The encoding to use.
"""
@property
def header(self) -> str:
- """Create the full `Authentication` header value.
-
- Returns
- -------
- builtins.str
- A base64-encoded string containing
- `"{username}:{password}"`.
- """
+ """Create the full `Authentication` header value."""
raw_token = f"{self.username}:{self.password}".encode(self.charset)
token_part = base64.b64encode(raw_token).decode(self.charset)
return f"{_BASICAUTH_TOKEN_PREFIX} {token_part}"
@@ -119,21 +99,15 @@ class ProxySettings(config.ProxySettings):
auth: typing.Any = attr.field(default=None)
"""Authentication header value to use.
- When cast to a `builtins.str`, this should provide the full value
+ When cast to a `str`, this should provide the full value
for the authentication header.
If you are using basic auth, you should consider using the
`BasicAuthHeader` helper object here, as this will provide any
transformations you may require into a base64 string.
- The default is to have this set to `builtins.None`, which will
+ The default is to have this set to `None`, which will
result in no authentication being provided.
-
- Returns
- -------
- typing.Any
- The value for the `Authentication` header, or `builtins.None`
- to disable.
"""
headers: typing.Optional[data_binding.Headers] = attr.field(default=None)
@@ -142,46 +116,30 @@ class ProxySettings(config.ProxySettings):
url: typing.Union[None, str] = attr.field(default=None)
"""Proxy URL to use.
- Defaults to `builtins.None` which disables the use of an explicit proxy.
-
- Returns
- -------
- typing.Union[builtins.None, builtins.str]
- The proxy URL to use, or `builtins.None` to disable it.
+ Defaults to `None` which disables the use of an explicit proxy.
"""
trust_env: bool = attr.field(default=False, validator=attr.validators.instance_of(bool))
"""Toggle whether to look for a `netrc` file or environment variables.
- If `builtins.True`, and no `url` is given on this object, then
+ If `True`, and no `url` is given on this object, then
`HTTP_PROXY` and `HTTPS_PROXY` will be used from the environment
variables, or a `netrc` file may be read to determine credentials.
- If `builtins.False`, then this information is instead ignored.
+ If `False`, then this information is instead ignored.
- Defaults to `builtins.False` to prevent potentially unwanted behavior.
+ Defaults to `False` to prevent potentially unwanted behavior.
- !!! note
+ .. note::
For more details of using `netrc`, visit:
- https://www.gnu.org/software/inetutils/manual/html_node/The-_002enetrc-file.html
-
- Returns
- -------
- builtins.bool
- `builtins.True` if allowing the use of environment variables
- and/or `netrc` to determine proxy settings; `builtins.False`
- if this should be disabled explicitly.
+
"""
@property
def all_headers(self) -> typing.Optional[data_binding.Headers]:
"""Return all proxy headers.
- Returns
- -------
- typing.Optional[hikari.internal.data_binding.Headers]
- Any headers that are set, or `builtins.None` if no headers are to
- be sent with any request.
+ Will be `None` if no headers are to be send with any request.
"""
if self.headers is None:
if self.auth is None:
@@ -201,45 +159,29 @@ class HTTPTimeoutSettings:
acquire_and_connect: typing.Optional[float] = attr.field(default=None)
"""Timeout for `request_socket_connect` PLUS connection acquisition.
- By default, this has no timeout allocated.
-
- Returns
- -------
- typing.Optional[builtins.float]
- The timeout, or `builtins.None` to disable it.
+ By default, this has no timeout allocated. Setting it to `None`
+ will disable it.
"""
request_socket_connect: typing.Optional[float] = attr.field(default=None)
"""Timeout for connecting a socket.
- By default, this has no timeout allocated.
-
- Returns
- -------
- typing.Optional[builtins.float]
- The timeout, or `builtins.None` to disable it.
+ By default, this has no timeout allocated. Setting it to `None`
+ will disable it.
"""
request_socket_read: typing.Optional[float] = attr.field(default=None)
"""Timeout for reading a socket.
- By default, this has no timeout allocated.
-
- Returns
- -------
- typing.Optional[builtins.float]
- The timeout, or `builtins.None` to disable it.
+ By default, this has no timeout allocated. Setting it to `None`
+ will disable it.
"""
total: typing.Optional[float] = attr.field(default=30.0)
"""Total timeout for entire request.
- By default, this has a 30 second timeout allocated.
-
- Returns
- -------
- typing.Optional[builtins.float]
- The timeout, or `builtins.None` to disable it.
+ By default, this has a 30 second timeout allocated. Setting it to `None`
+ will disable it.
"""
@acquire_and_connect.validator
@@ -261,41 +203,29 @@ class HTTPSettings(config.HTTPSettings):
enable_cleanup_closed: bool = attr.field(default=True, validator=attr.validators.instance_of(bool))
"""Toggle whether to clean up closed transports.
- This defaults to `builtins.True` to combat various protocol and asyncio
+ This defaults to `True` to combat various protocol and asyncio
issues present when using Microsoft Windows. If you are sure you know
what you are doing, you may instead set this to `False` to disable this
behavior internally.
-
- Returns
- -------
- builtins.bool
- `builtins.True` to enable this behavior, `builtins.False` to disable
- it.
"""
force_close_transports: bool = attr.field(default=True, validator=attr.validators.instance_of(bool))
"""Toggle whether to force close transports on shut down.
- This defaults to `builtins.True` to combat various protocol and asyncio
+ This defaults to `True` to combat various protocol and asyncio
issues present when using Microsoft Windows. If you are sure you know
what you are doing, you may instead set this to `False` to disable this
behavior internally.
-
- Returns
- -------
- builtins.bool
- `builtins.True` to enable this behavior, `builtins.False` to disable
- it.
"""
max_redirects: typing.Optional[int] = attr.field(default=10)
"""Behavior for handling redirect HTTP responses.
- If a `builtins.int`, allow following redirects from `3xx` HTTP responses
+ If a `int`, allow following redirects from `3xx` HTTP responses
for up to this many redirects. Exceeding this value will raise an
exception.
- If `builtins.None`, then disallow any redirects.
+ If `None`, then disallow any redirects.
The default is to disallow this behavior for security reasons.
@@ -303,17 +233,9 @@ class HTTPSettings(config.HTTPSettings):
future where you need to enable this if Discord change their URL without
warning.
- !!! note
+ .. note::
This will only apply to the REST API. WebSockets remain unaffected
by any value set here.
-
- Returns
- -------
- typing.Optional[builtins.int]
- The number of redirects to allow at a maximum per request.
- `builtins.None` disables the handling
- of redirects and will result in exceptions being raised instead
- should one occur.
"""
@max_redirects.validator
@@ -330,24 +252,24 @@ def _(self, _: attr.Attribute[typing.Optional[int]], value: typing.Any) -> None:
)
"""SSL context to use.
- This may be __assigned__ a `builtins.bool` or an `ssl.SSLContext` object.
+ This may be assigned a `bool` or an `ssl.SSLContext` object.
- If assigned to `builtins.True`, a default SSL context is generated by
+ If assigned to `True`, a default SSL context is generated by
this class that will enforce SSL verification. This is then stored in
this field.
- If `builtins.False`, then a default SSL context is generated by this
+ If `False`, then a default SSL context is generated by this
class that will **NOT** enforce SSL verification. This is then stored
in this field.
If an instance of `ssl.SSLContext`, then this context will be used.
- !!! warning
+ .. warning::
Setting a custom value here may have security implications, or
may result in the application being unable to connect to Discord
at all.
- !!! warning
+ .. warning::
Disabling SSL verification is almost always unadvised. This
is because your application will no longer check whether you are
connecting to Discord, or to some third party spoof designed
@@ -358,11 +280,6 @@ class that will **NOT** enforce SSL verification. This is then stored
allows you to work around any issues that are occurring, but
you should immediately seek a better solution where possible
if any form of personal security is in your interest.
-
- Returns
- -------
- ssl.SSLContext
- The SSL context to use for this application.
"""
timeouts: HTTPTimeoutSettings = attr.field(
@@ -372,11 +289,6 @@ class that will **NOT** enforce SSL verification. This is then stored
The behaviour if this is not explicitly defined is to use sane
defaults that are most efficient for optimal use of this library.
-
- Returns
- -------
- HTTPTimeoutSettings
- The HTTP timeout settings to use for connection timeouts.
"""
diff --git a/hikari/impl/event_manager.py b/hikari/impl/event_manager.py
index d09ed59962..e683e742a3 100644
--- a/hikari/impl/event_manager.py
+++ b/hikari/impl/event_manager.py
@@ -745,6 +745,7 @@ async def on_message_reaction_remove_emoji(
async def on_presence_update(self, shard: gateway_shard.GatewayShard, payload: data_binding.JSONObject) -> None:
"""See https://discord.com/developers/docs/topics/gateway-events#presence-update for more info."""
old: typing.Optional[presences_.MemberPresence] = None
+
if self._cache:
old = self._cache.get_presence(
snowflakes.Snowflake(payload["guild_id"]), snowflakes.Snowflake(payload["user"]["id"])
diff --git a/hikari/impl/event_manager_base.py b/hikari/impl/event_manager_base.py
index 08e2824de0..a420959ab9 100644
--- a/hikari/impl/event_manager_base.py
+++ b/hikari/impl/event_manager_base.py
@@ -119,7 +119,7 @@ async def call_weak_method(event: base_events.Event) -> None:
class EventStream(event_manager_.EventStream[base_events.EventT]):
"""An implementation of an event `EventStream` class.
- !!! note
+ .. note::
While calling `EventStream.filter` on an active "opened" event stream
will return a wrapping lazy iterator, calling it on an inactive "closed"
event stream will return the event stream and add the given predicates
diff --git a/hikari/impl/interaction_server.py b/hikari/impl/interaction_server.py
index f0e4708c98..439a876294 100644
--- a/hikari/impl/interaction_server.py
+++ b/hikari/impl/interaction_server.py
@@ -180,9 +180,9 @@ class InteractionServer(interaction_server.InteractionServer):
The JSON encoder this server should use. Defaults to `json.dumps`.
loads : aiohttp.typedefs.JSONDecoder
The JSON decoder this server should use. Defaults to `json.loads`.
- public_key : builtins.bytes
+ public_key : bytes
The public key this server should use for verifying request payloads from
- Discord. If left as `builtins.None` then the client will try to work this
+ Discord. If left as `None` then the client will try to work this
out using `rest_client`.
rest_client : hikari.api.rest.RESTClient
The client this should use for making REST requests.
@@ -240,13 +240,7 @@ def __init__(
@property
def is_alive(self) -> bool:
- """Whether this interaction server is active.
-
- Returns
- -------
- builtins.bool
- Whether this interaction server is active
- """
+ """Whether this interaction server is active."""
return self._server is not None
async def _fetch_public_key(self) -> signing.VerifyKey:
@@ -385,18 +379,18 @@ async def join(self) -> None:
async def on_interaction(self, body: bytes, signature: bytes, timestamp: bytes) -> interaction_server.Response:
"""Handle an interaction received from Discord as a REST server.
- !!! note
+ .. note::
If this server instance is alive then this will be called internally
by the server but if the instance isn't alive then this may still be
called externally to trigger interaction dispatch.
Parameters
----------
- body : builtins.bytes
+ body : bytes
The interaction payload.
- signature : builtins.bytes
+ signature : bytes
Value of the `"X-Signature-Ed25519"` header used to verify the body.
- timestamp : builtins.bytes
+ timestamp : bytes
Value of the `"X-Signature-Timestamp"` header used to verify the body.
Returns
@@ -477,34 +471,34 @@ async def start(
) -> None:
"""Start the bot and wait for the internal server to startup then return.
+ .. note::
+ For more information on the other parameters such as defaults see
+ AIOHTTP's documentation.
+
Other Parameters
----------------
- backlog : builtins.int
+ backlog : int
The number of unaccepted connections that the system will allow before
refusing new connections.
- host : typing.Optional[typing.Union[builtins.str, aiohttp.web.HostSequence]]
+ host : typing.Optional[typing.Union[str, aiohttp.web.HostSequence]]
TCP/IP host or a sequence of hosts for the HTTP server.
- port : typing.Optional[builtins.int]
+ port : typing.Optional[int]
TCP/IP port for the HTTP server.
- path : typing.Optional[builtins.str]
+ path : typing.Optional[str]
File system path for HTTP server unix domain socket.
- reuse_address : typing.Optional[builtins.bool]
+ reuse_address : typing.Optional[bool]
Tells the kernel to reuse a local socket in TIME_WAIT state, without
waiting for its natural timeout to expire.
- reuse_port : typing.Optional[builtins.bool]
+ reuse_port : typing.Optional[bool]
Tells the kernel to allow this endpoint to be bound to the same port
as other existing endpoints are also bound to.
socket : typing.Optional[socket.socket]
A pre-existing socket object to accept connections on.
- shutdown_timeout : builtins.float
- A delay to wait for graceful server shut down before forcefully
+ shutdown_timeout : float
+ A delay to wait for graceful server shutdown before forcefully
disconnecting all open client sockets. This defaults to 60 seconds.
ssl_context : typing.Optional[ssl.SSLContext]
SSL context for HTTPS servers.
-
- !!! note
- For more information on the other parameters such as defaults see
- AIOHTTP's documentation.
"""
if self._server:
raise errors.ComponentStateConflictError("Cannot start an already active interaction server")
diff --git a/hikari/impl/rate_limits.py b/hikari/impl/rate_limits.py
index 449a179dc7..d2dd254e08 100644
--- a/hikari/impl/rate_limits.py
+++ b/hikari/impl/rate_limits.py
@@ -92,7 +92,7 @@ class BurstRateLimiter(BaseRateLimiter, abc.ABC):
"""The name of the rate limiter."""
throttle_task: typing.Optional[asyncio.Task[typing.Any]]
- """The throttling task, or `builtins.None` if it is not running."""
+ """The throttling task, or `None` if it is not running."""
queue: typing.List[asyncio.Future[typing.Any]]
"""The queue of any futures under a rate limit."""
@@ -138,7 +138,7 @@ def close(self) -> None:
@property
def is_empty(self) -> bool:
- """Return `builtins.True` if no futures are on the queue being rate limited."""
+ """Return `True` if no futures are on the queue being rate limited."""
return len(self.queue) == 0
@@ -193,24 +193,24 @@ def throttle(self, retry_after: float) -> None:
Iterates repeatedly while the queue is not empty, adhering to any
rate limits that occur in the mean time.
- Parameters
- ----------
- retry_after : builtins.float
- How long to sleep for before unlocking and releasing any futures
- in the queue.
-
- !!! note
+ .. note::
This will invoke `ManualRateLimiter.unlock_later` as a scheduled
task in the future (it will not await it to finish).
When the `ManualRateLimiter.unlock_later` coroutine function
completes, it should be expected to set the `throttle_task` to
- `builtins.None`. This means you can check if throttling is occurring
- by checking if `throttle_task` is not `builtins.None`.
+ `None`. This means you can check if throttling is occurring
+ by checking if `throttle_task` is not `None`.
If this is invoked while another throttle is in progress, that one
is cancelled and a new one is started. This enables new rate limits
to override existing ones.
+
+ Parameters
+ ----------
+ retry_after : float
+ How long to sleep for before unlocking and releasing any futures
+ in the queue.
"""
if self.throttle_task is not None:
self.throttle_task.cancel()
@@ -219,22 +219,22 @@ def throttle(self, retry_after: float) -> None:
self.throttle_task = loop.create_task(self.unlock_later(retry_after))
async def unlock_later(self, retry_after: float) -> None:
- """Sleeps for a while, then removes the lock.
+ """Sleep for a while, then remove the lock.
- Parameters
- ----------
- retry_after : builtins.float
- How long to sleep for before unlocking and releasing any futures
- in the queue.
-
- !!! note
+ .. warning::
You should not need to invoke this directly. Call
`ManualRateLimiter.throttle` instead.
When the `ManualRateLimiter.unlock_later` coroutine function
completes, it should be expected to set the `throttle_task` to
- `builtins.None`. This means you can check if throttling is occurring
- by checking if `throttle_task` is not `builtins.None`.
+ `None`. This means you can check if throttling is occurring
+ by checking if `throttle_task` is not `None`.
+
+ Parameters
+ ----------
+ retry_after : float
+ How long to sleep for before unlocking and releasing any futures
+ in the queue.
"""
_LOGGER.warning("you are being globally rate limited for %ss", retry_after)
await asyncio.sleep(retry_after)
@@ -250,7 +250,7 @@ class WindowedBurstRateLimiter(BurstRateLimiter):
Rate limiter for rate limits that last fixed periods of time with a
fixed number of times it can be used in that time frame.
- To use this, you should call WindowedBurstRateLimiter.acquire` and await the
+ To use this, you should call `WindowedBurstRateLimiter.acquire` and await the
result immediately before performing your rate-limited task.
If the rate limit has been hit, acquiring time will return an incomplete
@@ -282,17 +282,13 @@ class WindowedBurstRateLimiter(BurstRateLimiter):
"""The `time.monotonic_timestamp` that the limit window ends at."""
remaining: int
- """The number of `WindowedBurstRateLimiter.acquire`'s left in this window
- before you will get rate limited.
- """
+ """The number of `WindowedBurstRateLimiter.acquire`'s left in this window before you will get rate limited."""
period: float
"""How long the window lasts for from the start in seconds."""
limit: int
- """The maximum number of `WindowedBurstRateLimiter.acquire`'s allowed in
- this time window.
- """
+ """The maximum number of `WindowedBurstRateLimiter.acquire`'s allowed in this time window."""
def __init__(self, name: str, period: float, limit: int) -> None:
super().__init__(name)
@@ -326,21 +322,21 @@ async def acquire(self) -> None:
def get_time_until_reset(self, now: float) -> float:
"""Determine how long until the current rate limit is reset.
- Parameters
- ----------
- now : builtins.float
- The monotonic `time.monotonic_timestamp` timestamp.
-
- !!! warning
+ .. warning::
Invoking this method will update the internal state if we were
previously rate limited, but at the given time are no longer under
that limit. This makes it imperative that you only pass the current
timestamp to this function, and not past or future timestamps. The
effects of doing the latter are undefined behaviour.
+ Parameters
+ ----------
+ now : float
+ The monotonic `time.monotonic_timestamp` timestamp.
+
Returns
-------
- builtins.float
+ float
The time left to sleep before the rate limit is reset. If no rate limit
is in effect, then this will return `0.0` instead.
"""
@@ -351,23 +347,23 @@ def get_time_until_reset(self, now: float) -> float:
def is_rate_limited(self, now: float) -> bool:
"""Determine if we are under a rate limit at the given time.
+ .. warning::
+ Invoking this method will update the internal state if we were
+ previously rate limited, but at the given time are no longer under
+ that limit. This makes it imperative that you only pass the current
+ timestamp to this function, and not past or future timestamps. The
+ effects of doing the latter are undefined behaviour.
+
Parameters
----------
- now : builtins.float
+ now : float
The monotonic `time.monotonic_timestamp` timestamp.
Returns
-------
- builtins.bool
- `builtins.True` if we are being rate limited, or `builtins.False` if
+ bool
+ `True` if we are being rate limited, or `False` if
we are not.
-
- !!! warning
- Invoking this method will update the internal state if we were
- previously rate limited, but at the given time are no longer under
- that limit. This makes it imperative that you only pass the current
- timestamp to this function, and not past or future timestamps. The
- effects of doing the latter are undefined behaviour.
"""
if self.reset_at <= now:
self.remaining = self.limit
@@ -377,7 +373,7 @@ def is_rate_limited(self, now: float) -> bool:
return self.remaining <= 0
def drip(self) -> None:
- """Decrements the remaining counter."""
+ """Decrement the remaining counter."""
self.remaining -= 1
async def throttle(self) -> None:
@@ -386,14 +382,14 @@ async def throttle(self) -> None:
Iterates repeatedly while the queue is not empty, adhering to any
rate limits that occur in the mean time.
- !!! note
+ .. note::
You should usually not need to invoke this directly, but if you do,
ensure to call it using `asyncio.create_task`, and store the
task immediately in `throttle_task`.
When this coroutine function completes, it will set the
- `throttle_task` to `builtins.None`. This means you can check if throttling
- is occurring by checking if `throttle_task` is not `builtins.None`.
+ `throttle_task` to `None`. This means you can check if throttling
+ is occurring by checking if `throttle_task` is not `None`.
"""
_LOGGER.debug(
"you are being rate limited on bucket %s, backing off for %ss",
@@ -416,34 +412,33 @@ async def throttle(self) -> None:
class ExponentialBackOff:
r"""Implementation of an asyncio-compatible exponential back-off algorithm with random jitter.
- .. math::
-
- t_{backoff} = b^{i} + m \cdot \mathrm{rand}()
+ $t_{backoff} = b^{i} + m \cdot \mathrm{rand}()$
- Such that \(t_{backoff}\) is the backoff time, \(b\) is the base,
- \(i\) is the increment that increases by 1 for each invocation, and
- \(m\) is the jitter multiplier. \(\mathrm{rand}()\) returns a value in
- the range \([0,1]\).
+ Such that $\(t_{backoff}\)$ is the backoff time, $\(b\)$ is the base,
+ $\(i\)$ is the increment that increases by 1 for each invocation, and
+ $\(m\)$ is the jitter multiplier. $\(\mathrm{rand}()\)$ returns a value in
+ the range $\([0,1]\)$.
Parameters
----------
- base : builtins.float
+ base : float
The base to use. Defaults to `2.0`.
- maximum : builtins.float
- The max value the backoff can be in a single iteration. Anything above
- this will be capped to this base value plus random jitter.
- jitter_multiplier : builtins.float
+ maximum : float
+ The max value the backoff can be in a single iteration.
+
+ All values will be capped to this base value plus some random jitter.
+ jitter_multiplier : float
The multiplier for the random jitter. Defaults to `1.0`.
Set to `0` to disable jitter.
- initial_increment : builtins.int
+ initial_increment : int
The initial increment to start at. Defaults to `0`.
Raises
------
ValueError
- If an `builtins.int` that's too big to be represented as a
- `builtins.float` or a non-finite value is passed in place of a field
- that's annotated as `builtins.float`.
+ If an `int` that's too big to be represented as a
+ `float` or a non-finite value is passed in place of a field
+ that's annotated as `float`.
"""
__slots__: typing.Sequence[str] = ("base", "increment", "maximum", "jitter_multiplier")
@@ -455,9 +450,7 @@ class ExponentialBackOff:
"""The current increment."""
maximum: float
- """This is the max value the backoff can be in a single iteration before an
- `asyncio.TimeoutError` is raised.
- """
+ """This is the max value the backoff can be in a single iteration before an `asyncio.TimeoutError` is raised."""
jitter_multiplier: typing.Final[float]
"""The multiplier for the random jitter.
diff --git a/hikari/impl/rest.py b/hikari/impl/rest.py
index 074b5c8233..d296e8924b 100644
--- a/hikari/impl/rest.py
+++ b/hikari/impl/rest.py
@@ -121,10 +121,10 @@ class ClientCredentialsStrategy(rest_api.TokenStrategy):
Parameters
----------
- client: typing.Optional[snowflakes.SnowflakeishOr[guilds.PartialApplication]]
+ client : typing.Optional[hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialApplication]]
Object or ID of the application this client credentials strategy should
authorize as.
- client_secret : typing.Optional[builtins.str]
+ client_secret : typing.Optional[str]
Client secret to use when authorizing.
Other Parameters
@@ -163,13 +163,7 @@ def __init__(
@property
def client_id(self) -> snowflakes.Snowflake:
- """ID of the application this token strategy authenticates with.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- ID of the application this token strategy authenticates with.
- """
+ """ID of the application this token strategy authenticates with."""
return self._client_id
@property
@@ -178,13 +172,7 @@ def _is_expired(self) -> bool:
@property
def scopes(self) -> typing.Sequence[typing.Union[applications.OAuth2Scope, str]]:
- """Scopes this token strategy authenticates for.
-
- Returns
- -------
- typing.Sequence[typing.Union[hikari.applications.OAuth2Scope, builtins.str]]
- The scopes this token strategy authenticates for.
- """
+ """Sequence of scopes this token strategy authenticates for."""
return self._scopes
@property
@@ -270,13 +258,13 @@ class RESTApp(traits.ExecutorAware):
Parameters
----------
executor : typing.Optional[concurrent.futures.Executor]
- The executor to use for blocking file IO operations. If `builtins.None`
+ The executor to use for blocking file IO operations. If `None`
is passed, then the default `concurrent.futures.ThreadPoolExecutor` for
the `asyncio.AbstractEventLoop` will be used instead.
http_settings : typing.Optional[hikari.impl.config.HTTPSettings]
HTTP settings to use. Sane defaults are used if this is
- `builtins.None`.
- max_rate_limit : builtins.float
+ `None`.
+ max_rate_limit : float
Maximum number of seconds to sleep for when rate limited. If a rate
limit occurs that is longer than this value, then a
`hikari.errors.RateLimitedError` will be raised instead of waiting.
@@ -285,19 +273,15 @@ class RESTApp(traits.ExecutorAware):
rate limits.
Defaults to five minutes if unspecified.
- max_retries : typing.Optional[builtins.int]
+ max_retries : typing.Optional[int]
Maximum number of times a request will be retried if
- it fails with a `5xx` status. Defaults to 3 if set to `builtins.None`.
+ it fails with a `5xx` status. Defaults to 3 if set to `None`.
proxy_settings : typing.Optional[hikari.impl.config.ProxySettings]
- Proxy settings to use. If `builtins.None` then no proxy configuration
+ Proxy settings to use. If `None` then no proxy configuration
will be used.
- url : typing.Optional[builtins.str]
+ url : typing.Optional[str]
The base URL for the API. You can generally leave this as being
- `builtins.None` and the correct default API base URL will be generated.
-
- !!! note
- This event loop will be bound to a connector when the first call
- to `acquire` is made.
+ `None` and the correct default API base URL will be generated.
"""
__slots__: typing.Sequence[str] = (
@@ -357,34 +341,34 @@ def acquire(
) -> RESTClientImpl:
"""Acquire an instance of this REST client.
- !!! note
+ .. note::
The returned REST client should be started before it can be used,
either by calling `RESTClientImpl.start` or by using it as an
asynchronous context manager.
Examples
--------
- ```py
- rest_app = RESTApp()
+ .. code-block:: python
+
+ rest_app = RESTApp()
- # Using the returned client as a context manager to implicitly start
- # and stop it.
- async with rest_app.acquire("A token", "Bot") as client:
- user = await client.fetch_my_user()
- ```
+ # Using the returned client as a context manager to implicitly start
+ # and stop it.
+ async with rest_app.acquire("A token", "Bot") as client:
+ user = await client.fetch_my_user()
Parameters
----------
- token : typing.Union[builtins.str, builtins.None, hikari.api.rest.TokenStrategy]
+ token : typing.Union[str, None, hikari.api.rest.TokenStrategy]
The bot or bearer token. If no token is to be used,
this can be undefined.
- token_type : typing.Union[builtins.str, hikari.applications.TokenType, builtins.None]
- The type of token in use. This should only be passed when `builtins.str`
+ token_type : typing.Union[str, hikari.applications.TokenType, None]
+ The type of token in use. This should only be passed when `str`
is passed for `token`, can be `"Bot"` or `"Bearer"` and will be
defaulted to `"Bearer"` in this situation.
- This should be left as `builtins.None` when either
- `hikari.api.rest.TokenStrategy` or `builtins.None` is passed for
+ This should be left as `None` when either
+ `hikari.api.rest.TokenStrategy` or `None` is passed for
`token`.
Returns
@@ -394,7 +378,7 @@ def acquire(
Raises
------
- builtins.ValueError
+ ValueError
If `token_type` is provided when a token strategy is passed for `token`.
"""
# Since we essentially mimic a fake App instance, we need to make a circular provider.
@@ -429,7 +413,7 @@ def acquire(
class _LiveAttributes:
"""Fields which are only present within `RESTClientImpl` while it's "alive".
- !!! note
+ .. note::
This must be started within an active asyncio event loop.
"""
@@ -447,7 +431,7 @@ def build(
) -> _LiveAttributes:
"""Build a live attributes object.
- !!! warning
+ .. warning::
This can only be called when the current thread has an active
asyncio loop.
"""
@@ -508,37 +492,37 @@ class RESTClientImpl(rest_api.RESTClient):
The entity factory to use.
executor : typing.Optional[concurrent.futures.Executor]
The executor to use for blocking IO. Defaults to the `asyncio` thread
- pool if set to `builtins.None`.
- max_rate_limit : builtins.float
+ pool if set to `None`.
+ max_rate_limit : float
Maximum number of seconds to sleep for when rate limited. If a rate
limit occurs that is longer than this value, then a
`hikari.errors.RateLimitedError` will be raised instead of waiting.
This is provided since some endpoints may respond with non-sensible
rate limits.
- max_retries : typing.Optional[builtins.int]
+ max_retries : typing.Optional[int]
Maximum number of times a request will be retried if
- it fails with a `5xx` status. Defaults to 3 if set to `builtins.None`.
- token : typing.Union[builtins.str, builtins.None, hikari.api.rest.TokenStrategy]
+ it fails with a `5xx` status. Defaults to 3 if set to `None`.
+ token : typing.Union[str, None, hikari.api.rest.TokenStrategy]
The bot or bearer token. If no token is to be used,
this can be undefined.
- token_type : typing.Union[builtins.str, hikari.applications.TokenType, builtins.None]
- The type of token in use. This must be passed when a `builtins.str` is
+ token_type : typing.Union[str, hikari.applications.TokenType, None]
+ The type of token in use. This must be passed when a `str` is
passed for `token` but and can be `"Bot"` or `"Bearer"`.
- This should be left as `builtins.None` when either
- `hikari.api.rest.TokenStrategy` or `builtins.None` is passed for
+ This should be left as `None` when either
+ `hikari.api.rest.TokenStrategy` or `None` is passed for
`token`.
- rest_url : builtins.str
+ rest_url : str
The HTTP API base URL. This can contain format-string specifiers to
interpolate information such as API version in use.
Raises
------
- builtins.ValueError
- * If `token_type` is provided when a token strategy is passed for `token`.
- * if `token_type` is left as `builtins.None` when a string is passed for `token`.
- * If the a value more than 5 is provided for `max_retries`
+ ValueError
+ If `token_type` is provided when a token strategy is passed for `token`, if
+ `token_type` is left as `None` when a string is passed for `token` or if a
+ value greater than 5 is provided for `max_retries`.
"""
__slots__: typing.Sequence[str] = (
@@ -632,7 +616,7 @@ async def close(self) -> None:
def start(self) -> None:
"""Start the HTTP client.
- !!! note
+ .. note::
This must be called within an active event loop.
Raises
diff --git a/hikari/impl/rest_bot.py b/hikari/impl/rest_bot.py
index 79c8e6566e..fe817463ab 100644
--- a/hikari/impl/rest_bot.py
+++ b/hikari/impl/rest_bot.py
@@ -73,19 +73,19 @@ class RESTBot(traits.RESTBotAware, interaction_server_.InteractionServer):
Parameters
----------
- token : typing.Union[builtins.str, hikari.api.rest.TokenStrategy]
+ token : typing.Union[str, hikari.api.rest.TokenStrategy]
The bot or bearer token.
- token_type : typing.Union[builtins.str, hikari.applications.TokenType]
- The type of token in use. This should only be passed when `builtins.str`
+ token_type : typing.Union[str, hikari.applications.TokenType, None]
+ The type of token in use. This should only be passed when `str`
is passed for `token`, can be `"Bot"` or `"Bearer"`.
- This should be left as `builtins.None` when `hikari.api.rest.TokenStrategy`
+ This should be left as `None` when `hikari.api.rest.TokenStrategy`
is passed for `token`.
Other Parameters
----------------
- allow_color : builtins.bool
- Defaulting to `builtins.True`, this will enable coloured console logs
+ allow_color : bool
+ Defaulting to `True`, this will enable coloured console logs
on any platform that is a TTY.
Setting a `"CLICOLOR"` environment variable to any **non `0`** value
will override this setting.
@@ -95,12 +95,12 @@ class RESTBot(traits.RESTBotAware, interaction_server_.InteractionServer):
awkward or not support features in a standard way, the option to
explicitly disable this is provided. See `force_color` for an
alternative.
- banner : typing.Optional[builtins.str]
+ banner : typing.Optional[str]
The package to search for a `banner.txt` in. Defaults to `"hikari"` for
the `"hikari/banner.txt"` banner.
- Setting this to `builtins.None` will disable the banner being shown.
+ Setting this to `None` will disable the banner being shown.
executor : typing.Optional[concurrent.futures.Executor]
- Defaults to `builtins.None`. If non-`builtins.None`, then this executor
+ Defaults to `None`. If non-`None`, then this executor
is used instead of the `concurrent.futures.ThreadPoolExecutor` attached
to the `asyncio.AbstractEventLoop` that the bot will run on. This
executor is used primarily for file-IO.
@@ -108,23 +108,25 @@ class RESTBot(traits.RESTBotAware, interaction_server_.InteractionServer):
While mainly supporting the `concurrent.futures.ThreadPoolExecutor`
implementation in the standard lib, Hikari's file handling systems
should also work with `concurrent.futures.ProcessPoolExecutor`, which
- relies on all objects used in IPC to be `pickle`able. Many third-party
+ relies on all objects used in IPC to be pickleable. Many third-party
libraries will not support this fully though, so your mileage may vary
on using ProcessPoolExecutor implementations with this parameter.
- force_color : builtins.bool
- Defaults to `builtins.False`. If `builtins.True`, then this application
+ force_color : bool
+ Defaults to `False`. If `True`, then this application
will __force__ colour to be used in console-based output. Specifying a
`"CLICOLOR_FORCE"` environment variable with a non-`"0"` value will
override this setting.
+
+ This will take precedence over `allow_color` if both are specified.
http_settings : typing.Optional[hikari.config.HTTPSettings]
Optional custom HTTP configuration settings to use. Allows you to
customise functionality such as whether SSL-verification is enabled,
what timeouts `aiohttp` should expect to use for requests, and behavior
regarding HTTP-redirects.
- logs : typing.Union[builtins.None, LoggerLevel, typing.Dict[str, typing.Any]]
+ logs : typing.Union[None, LoggerLevel, typing.Dict[str, typing.Any]]
Defaults to `"INFO"`.
- If `builtins.None`, then the Python logging system is left uninitialized
+ If `None`, then the Python logging system is left uninitialized
on startup, and you will need to configure it manually to view most
logs that are output by components of this library.
@@ -145,7 +147,7 @@ class RESTBot(traits.RESTBotAware, interaction_server_.InteractionServer):
Note that `"TRACE_HIKARI"` is a library-specific logging level
which is expected to be more verbose than `"DEBUG"`.
- max_rate_limit : builtins.float
+ max_rate_limit : float
The max number of seconds to backoff for when rate limited. Anything
greater than this will instead raise an error.
@@ -158,31 +160,28 @@ class RESTBot(traits.RESTBotAware, interaction_server_.InteractionServer):
Note that this only applies to the REST API component that communicates
with Discord, and will not affect sharding or third party HTTP endpoints
that may be in use.
- max_retries : typing.Optional[builtins.int]
+ max_retries : typing.Optional[int]
Maximum number of times a request will be retried if
- it fails with a `5xx` status. Defaults to 3 if set to `builtins.None`.
- proxy_settings : typing.Optional[config.ProxySettings]
+ it fails with a `5xx` status. Defaults to 3 if set to `None`.
+ proxy_settings : typing.Optional[hikari.impl.config.ProxySettings]
Custom proxy settings to use with network-layer logic
in your application to get through an HTTP-proxy.
- public_key : typing.Union[builtins.str, builtins.bytes, builtins.None]
+ public_key : typing.Union[str, bytes, None]
The public key to use to verify received interaction requests.
- This may be a hex encoded `builtins.str` or the raw `builtins.bytes`.
- If left as `builtins.None` then the client will try to work this value
+ This may be a hex encoded `str` or the raw `bytes`.
+ If left as `None` then the client will try to work this value
out based on `token`.
- rest_url : typing.Optional[builtins.str]
- Defaults to the Discord REST API URL if `builtins.None`. Can be
+ rest_url : typing.Optional[str]
+ Defaults to the Discord REST API URL if `None`. Can be
overridden if you are attempting to point to an unofficial endpoint, or
if you are attempting to mock/stub the Discord API for any reason.
Generally you do not want to change this.
- !!! note
- `force_color` will always take precedence over `allow_color`.
-
Raises
------
- builtins.ValueError
+ ValueError
* If `token_type` is provided when a token strategy is passed for `token`.
- * if `token_type` is left as `builtins.None` when a string is passed for `token`.
+ * if `token_type` is left as `None` when a string is passed for `token`.
"""
__slots__: typing.Sequence[str] = (
@@ -353,26 +352,25 @@ def print_banner(
Parameters
----------
- banner : typing.Optional[builtins.str]
+ banner : typing.Optional[str]
The package to find a `banner.txt` in.
- allow_color : builtins.bool
+ allow_color : bool
A flag that allows advising whether to allow color if supported or
not. Can be overridden by setting a `"CLICOLOR"` environment
variable to a non-`"0"` string.
- force_color : builtins.bool
+ force_color : bool
A flag that allows forcing color to always be output, even if the
terminal device may not support it. Setting the `"CLICOLOR_FORCE"`
environment variable to a non-`"0"` string will override this.
- !!! note
- `force_color` will always take precedence over `allow_color`.
- extra_args : typing.Optional[typing.Dict[builtins.str, builtins.str]]
+ This will take precedence over `allow_color` if both are specified.
+ extra_args : typing.Optional[typing.Dict[str, str]]
If provided, extra $-substitutions to use when printing the banner.
Default substitutions can not be overwritten.
Raises
------
- builtins.ValueError
+ ValueError
If `extra_args` contains a default $-substitution.
"""
ux.print_banner(banner, allow_color, force_color, extra_args=extra_args)
@@ -454,17 +452,17 @@ def run(
Other Parameters
----------------
- asyncio_debug : builtins.bool
- Defaults to `builtins.False`. If `builtins.True`, then debugging is
+ asyncio_debug : bool
+ Defaults to `False`. If `True`, then debugging is
enabled for the asyncio event loop in use.
- backlog : builtins.int
+ backlog : int
The number of unaccepted connections that the system will allow before
refusing new connections.
- check_for_updates : builtins.bool
- Defaults to `builtins.True`. If `builtins.True`, will check for
+ check_for_updates : bool
+ Defaults to `True`. If `True`, will check for
newer versions of `hikari` on PyPI and notify if available.
- close_loop : builtins.bool
- Defaults to `builtins.True`. If `builtins.True`, then once the bot
+ close_loop : bool
+ Defaults to `True`. If `True`, then once the bot
enters a state where all components have shut down permanently
during application shut down, then all asyncgens and background tasks
will be destroyed, and the event loop will be shut down.
@@ -473,44 +471,44 @@ def run(
had time to attempt to shut down correctly (around 250ms), and on
Python 3.9 and newer, will also shut down the default event loop
executor too.
- close_passed_executor : builtins.bool
- Defaults to `builtins.False`. If `builtins.True`, any custom
+ close_passed_executor : bool
+ Defaults to `False`. If `True`, any custom
`concurrent.futures.Executor` passed to the constructor will be
shut down when the application terminates. This does not affect the
default executor associated with the event loop, and will not
do anything if you do not provide a custom executor to the
constructor.
- coroutine_tracking_depth : typing.Optional[builtins.int]
- Defaults to `builtins.None`. If an integer value and supported by
+ coroutine_tracking_depth : typing.Optional[int]
+ Defaults to `None`. If an integer value and supported by
the interpreter, then this many nested coroutine calls will be
tracked with their call origin state. This allows you to determine
where non-awaited coroutines may originate from, but generally you
do not want to leave this enabled for performance reasons.
- enable_signal_handlers : typing.Optional[builtins.bool]
- Defaults to `builtins.True` if this is started in the main thread.
+ enable_signal_handlers : typing.Optional[bool]
+ Defaults to `True` if this is started in the main thread.
- If on a __non-Windows__ OS with builtin support for kernel-level
- POSIX signals, then setting this to `builtins.True` will allow
+ If on a non-Windows OS with builtin support for kernel-level
+ POSIX signals, then setting this to `True` will allow
treating keyboard interrupts and other OS signals to safely shut
down the application as calls to shut down the application properly
rather than just killing the process in a dirty state immediately.
You should leave this enabled unless you plan to implement your own
signal handling yourself.
- host : typing.Optional[typing.Union[builtins.str, aiohttp.web.HostSequence]]
+ host : typing.Optional[typing.Union[str, aiohttp.web.HostSequence]]
TCP/IP host or a sequence of hosts for the HTTP server.
- port : typing.Optional[builtins.int]
+ port : typing.Optional[int]
TCP/IP port for the HTTP server.
- path : typing.Optional[builtins.str]
+ path : typing.Optional[str]
File system path for HTTP server unix domain socket.
- reuse_address : typing.Optional[builtins.bool]
+ reuse_address : typing.Optional[bool]
Tells the kernel to reuse a local socket in TIME_WAIT state, without
waiting for its natural timeout to expire.
- reuse_port : typing.Optional[builtins.bool]
+ reuse_port : typing.Optional[bool]
Tells the kernel to allow this endpoint to be bound to the same port
as other existing endpoints are also bound to.
socket : typing.Optional[socket.socket]
A pre-existing socket object to accept connections on.
- shutdown_timeout : builtins.float
+ shutdown_timeout : float
A delay to wait for graceful server shut down before forcefully
disconnecting all open client sockets. This defaults to 60 seconds.
ssl_context : typing.Optional[ssl.SSLContext]
@@ -584,37 +582,37 @@ async def start(
) -> None:
"""Start the bot and wait for the internal server to startup then return.
+ .. note::
+ For more information on the other parameters such as defaults see
+ AIOHTTP's documentation.
+
Other Parameters
----------------
- backlog : builtins.int
+ backlog : int
The number of unaccepted connections that the system will allow before
refusing new connections.
- check_for_updates : builtins.bool
- Defaults to `builtins.True`. If `builtins.True`, will check for
+ check_for_updates : bool
+ Defaults to `True`. If `True`, will check for
newer versions of `hikari` on PyPI and notify if available.
- host : typing.Optional[typing.Union[builtins.str, aiohttp.web.HostSequence]]
+ host : typing.Optional[typing.Union[str, aiohttp.web.HostSequence]]
TCP/IP host or a sequence of hosts for the HTTP server.
- port : typing.Optional[builtins.int]
+ port : typing.Optional[int]
TCP/IP port for the HTTP server.
- path : typing.Optional[builtins.str]
+ path : typing.Optional[str]
File system path for HTTP server unix domain socket.
- reuse_address : typing.Optional[builtins.bool]
+ reuse_address : typing.Optional[bool]
Tells the kernel to reuse a local socket in TIME_WAIT state, without
waiting for its natural timeout to expire.
- reuse_port : typing.Optional[builtins.bool]
+ reuse_port : typing.Optional[bool]
Tells the kernel to allow this endpoint to be bound to the same port
as other existing endpoints are also bound to.
socket : typing.Optional[socket.socket]
A pre-existing socket object to accept connections on.
- shutdown_timeout : builtins.float
+ shutdown_timeout : float
A delay to wait for graceful server shut down before forcefully
disconnecting all open client sockets. This defaults to 60 seconds.
ssl_context : typing.Optional[ssl.SSLContext]
SSL context for HTTPS servers.
-
- !!! note
- For more information on the other parameters such as defaults see
- AIOHTTP's documentation.
"""
if self.is_alive:
raise errors.ComponentStateConflictError("Cannot start an already active interaction server")
diff --git a/hikari/impl/shard.py b/hikari/impl/shard.py
index 9ace9dada3..5311cbf565 100644
--- a/hikari/impl/shard.py
+++ b/hikari/impl/shard.py
@@ -348,11 +348,22 @@ def _serialize_activity(activity: typing.Optional[presences.Activity]) -> data_b
class GatewayShardImpl(shard.GatewayShard):
"""Implementation of a V10 compatible gateway.
+ .. note::
+ If all four of `initial_activity`, `initial_idle_since`,
+ `initial_is_afk`, and `initial_status` are not defined and left to their
+ default values, then the presence will not be _updated_ on startup
+ at all.
+ If any of these _are_ specified, then any that are not specified will
+ be set to sane defaults, which may change the previous status. This will
+ only occur during startup, and is an artifact of how Discord manages
+ these updates internally. All other calls to update the status of
+ the shard will support partial updates.
+
Parameters
----------
- token : builtins.str
+ token : str
The bot token to use.
- url : builtins.str
+ url : str
The gateway URL to use. This should not contain a query-string or
fragments.
event_manager : hikari.api.event_manager.EventManager
@@ -362,48 +373,37 @@ class GatewayShardImpl(shard.GatewayShard):
Other Parameters
----------------
- compression : typing.Optional[builtins.str]
+ compression : typing.Optional[str]
Compression format to use for the shard. Only supported values are
- `"transport_zlib_stream"` or `builtins.None` to disable it.
+ `"transport_zlib_stream"` or `None` to disable it.
initial_activity : typing.Optional[hikari.presences.Activity]
The initial activity to appear to have for this shard, or
- `builtins.None` if no activity should be set initially. This is the
+ `None` if no activity should be set initially. This is the
default.
initial_idle_since : typing.Optional[datetime.datetime]
- The datetime to appear to be idle since, or `builtins.None` if the
- shard should not provide this. The default is `builtins.None`.
+ The datetime to appear to be idle since, or `None` if the
+ shard should not provide this. The default is `None`.
initial_is_afk : bool
Whether to appear to be AFK or not on login. Defaults to
- `builtins.False`.
+ `False`.
initial_status : hikari.presences.Status
The initial status to set on login for the shard. Defaults to
`hikari.presences.Status.ONLINE`.
intents : hikari.intents.Intents
Collection of intents to use.
- large_threshold : builtins.int
+ large_threshold : int
The number of members to have in a guild for it to be considered large.
- shard_id : builtins.int
+ shard_id : int
The shard ID.
- shard_count : builtins.int
+ shard_count : int
The shard count.
http_settings : hikari.impl.config.HTTPSettings
The HTTP-related settings to use while negotiating a websocket.
proxy_settings : hikari.impl.config.ProxySettings
The proxy settings to use while negotiating a websocket.
- data_format : builtins.str
+ data_format : str
Data format to use for inbound data. Only supported format is
`"json"`.
-
- !!! note
- If all four of `initial_activity`, `initial_idle_since`,
- `initial_is_afk`, and `initial_status` are not defined and left to their
- default values, then the presence will not be _updated_ on startup
- at all.
- If any of these _are_ specified, then any that are not specified will
- be set to sane defaults, which may change the previous status. This will
- only occur during startup, and is an artifact of how Discord manages
- these updates internally. All other calls to update the status of
- the shard will support partial updates.
"""
__slots__: typing.Sequence[str] = (
diff --git a/hikari/impl/special_endpoints.py b/hikari/impl/special_endpoints.py
index f499021f5c..c87742caa3 100644
--- a/hikari/impl/special_endpoints.py
+++ b/hikari/impl/special_endpoints.py
@@ -144,7 +144,7 @@ class TypingIndicator(special_endpoints.TypingIndicator):
the typing indicator once, or an async context manager to keep triggering
the typing indicator repeatedly until the context finishes.
- !!! note
+ .. note::
This is a helper class that is used by `hikari.api.rest.RESTClient`.
You should only ever need to use instances of this class that are
produced by that API.
@@ -226,70 +226,63 @@ class GuildBuilder(special_endpoints.GuildBuilder):
the logic behind creating a guild on an API level is somewhat confusing
and detailed.
- !!! note
- This is a helper class that is used by `hikari.api.rest.RESTClient`.
- You should only ever need to use instances of this class that are
- produced by that API, thus, any details about the constructor are
- omitted from the following examples for brevity.
+ .. note::
+ If you call `add_role`, the default roles provided by Discord will
+ be created. This also applies to the `add_` functions for
+ text channels/voice channels/categories.
+
+ .. note::
+ Functions that return a `hikari.snowflakes.Snowflake` do
+ **not** provide the final ID that the object will have once the
+ API call is made. The returned IDs are only able to be used to
+ re-reference particular objects while building the guild format
+ to allow for the creation of channels within categories,
+ and to provide permission overwrites.
Examples
--------
- Creating an empty guild.
+ Creating an empty guild:
- ```py
- guild = await rest.guild_builder("My Server!").create()
- ```
+ .. code-block:: python
- Creating a guild with an icon
+ guild = await rest.guild_builder("My Server!").create()
- ```py
- from hikari.files import WebResourceStream
+ Creating a guild with an icon:
- guild_builder = rest.guild_builder("My Server!")
- guild_builder.icon = WebResourceStream("cat.png", "http://...")
- guild = await guild_builder.create()
- ```
+ .. code-block:: python
- Adding roles to your guild.
+ from hikari.files import WebResourceStream
- ```py
- from hikari.permissions import Permissions
+ guild_builder = rest.guild_builder("My Server!")
+ guild_builder.icon = WebResourceStream("cat.png", "http://...")
+ guild = await guild_builder.create()
- guild_builder = rest.guild_builder("My Server!")
+ Adding roles to your guild:
- everyone_role_id = guild_builder.add_role("@everyone")
- admin_role_id = guild_builder.add_role("Admins", permissions=Permissions.ADMINISTRATOR)
+ .. code-block:: python
- await guild_builder.create()
- ```
+ from hikari.permissions import Permissions
- !!! warning
- The first role must always be the `@everyone` role.
+ guild_builder = rest.guild_builder("My Server!")
- !!! note
- If you call `add_role`, the default roles provided by discord will
- be created. This also applies to the `add_` functions for
- text channels/voice channels/categories.
+ everyone_role_id = guild_builder.add_role("@everyone")
+ admin_role_id = guild_builder.add_role("Admins", permissions=Permissions.ADMINISTRATOR)
- !!! note
- Functions that return a `hikari.snowflakes.Snowflake` do
- **not** provide the final ID that the object will have once the
- API call is made. The returned IDs are only able to be used to
- re-reference particular objects while building the guild format.
+ await guild_builder.create()
- This is provided to allow creation of channels within categories,
- and to provide permission overwrites.
+ .. warning::
+ The first role must always be the `@everyone` role.
- Adding a text channel to your guild.
+ Adding a text channel to your guild:
- ```py
- guild_builder = rest.guild_builder("My Server!")
+ .. code-block:: python
- category_id = guild_builder.add_category("My safe place")
- channel_id = guild_builder.add_text_channel("general", parent_id=category_id)
+ guild_builder = rest.guild_builder("My Server!")
- await guild_builder.create()
- ```
+ category_id = guild_builder.add_category("My safe place")
+ channel_id = guild_builder.add_text_channel("general", parent_id=category_id)
+
+ await guild_builder.create()
"""
# Required arguments.
@@ -703,8 +696,8 @@ def __init__(
self._route = routes.GET_GUILD_MEMBERS.compile(guild=guild)
self._request_call = request_call
self._entity_factory = entity_factory
- # This starts at the default provided by discord instead of the max snowflake
- # because that caused discord to take about 2 seconds more to return the first response.
+ # This starts at the default provided by Discord instead of the max snowflake
+ # because that caused Discord to take about 2 seconds more to return the first response.
self._first_id = undefined.UNDEFINED
async def _next_chunk(self) -> typing.Optional[typing.Generator[guilds.Member, typing.Any, None]]:
@@ -997,7 +990,7 @@ class InteractionMessageBuilder(special_endpoints.InteractionMessageBuilder):
Other Parameters
----------------
- content : hikari.undefined.UndefinedOr[builtins.str]
+ content : hikari.undefined.UndefinedOr[str]
The content of this response, if supplied. This follows the same rules
as "content" on create message.
"""
@@ -1439,12 +1432,12 @@ def _build_emoji(
Parameters
----------
- emoji : typing.Union[hikari.snowflakes.Snowflakeish, hikari.emojis.Emoji, builtins.str, hikari.undefined.UndefinedType]
+ emoji : typing.Union[hikari.snowflakes.Snowflakeish, hikari.emojis.Emoji, str, hikari.undefined.UndefinedType]
The ID, object or raw string of an emoji to set on a component.
Returns
-------
- typing.Tuple[hikari.undefined.UndefinedOr[builtins.str], hikari.undefined.UndefinedOr[builtins.str]]
+ typing.Tuple[hikari.undefined.UndefinedOr[str], hikari.undefined.UndefinedOr[str]]
A union of the custom emoji's id if defined (index 0) or the unicode
emoji's string representation (index 1).
"""
@@ -1819,7 +1812,7 @@ class MessageActionRowBuilder(special_endpoints.MessageActionRowBuilder):
"""Standard implementation of `hikari.api.special_endpoints.ActionRowBuilder`."""
_components: typing.List[special_endpoints.ComponentBuilder] = attr.field(factory=list)
- _stored_type: typing.Optional[component_models.ComponentType] = attr.field(default=None)
+ _stored_type: typing.Optional[component_models.ComponentType] = attr.field(default=None, init=False)
@property
def components(self) -> typing.Sequence[special_endpoints.ComponentBuilder]:
diff --git a/hikari/intents.py b/hikari/intents.py
index 6b00e1cf98..aaad9d7114 100644
--- a/hikari/intents.py
+++ b/hikari/intents.py
@@ -41,7 +41,7 @@ class Intents(enums.Flag):
Any events not in an intent category will be fired regardless of what
intents you provide.
- !!! info
+ .. note::
Discord now places limits on certain events you can receive without
whitelisting your bot first. On the `Bot` tab in the developer's portal
for your bot, you should now have the option to enable functionality
@@ -51,7 +51,7 @@ class Intents(enums.Flag):
your bot for, you will be disconnected on startup with a `4014` closure
code.
- !!! warning
+ .. warning::
If you are using the V7 Gateway, you will be REQUIRED to provide some
form of intent value when you connect. Failure to do so may result in
immediate termination of the session server-side.
@@ -62,29 +62,29 @@ class Intents(enums.Flag):
For example, if we wish to only refer to the `GUILDS` intent, then it is
simply a case of accessing it normally.
- ```py
- my_intents = Intents.GUILDS
- ```
+ .. code-block:: python
+
+ my_intents = Intents.GUILDS
If we wanted to have several intents grouped together, we would use the
bitwise-or operator to combine them (`|`). This can be done in-place
with the `|=` operator if needed.
- ```py
- # One or two values that fit on one line.
- my_intents = Intents.GUILD_MESSAGES | Intents.PRIVATE_MESSAGES
-
- # Several intents together. You may find it useful to format these like
- # so to keep your code readable.
- my_intents = (
- Intents.GUILDS |
- Intents.GUILD_BANS |
- Intents.GUILD_EMOJIS |
- Intents.GUILD_INTEGRATIONS |
- Intents.GUILD_MESSAGES |
- Intents.PRIVATE_MESSAGES
- )
- ```
+ .. code-block:: python
+
+ # One or two values that fit on one line.
+ my_intents = Intents.GUILD_MESSAGES | Intents.PRIVATE_MESSAGES
+
+ # Several intents together. You may find it useful to format these like
+ # so to keep your code readable.
+ my_intents = (
+ Intents.GUILDS |
+ Intents.GUILD_BANS |
+ Intents.GUILD_EMOJIS |
+ Intents.GUILD_INTEGRATIONS |
+ Intents.GUILD_MESSAGES |
+ Intents.PRIVATE_MESSAGES
+ )
To check if an intent **is present** in a given intents bitfield, you can
use the bitwise-and operator (`&`) to check. This returns the "intersection"
@@ -92,36 +92,36 @@ class Intents(enums.Flag):
use the `==` operator to check that specific values are present. You can
check in-place with the `&=` operator if needed.
- ```py
- # Check if an intent is set:
- if (my_intents & Intents.GUILD_MESSAGES) == Intents.GUILD_MESSAGES:
- print("Guild messages are enabled")
+ .. code-block:: python
+
+ # Check if an intent is set:
+ if (my_intents & Intents.GUILD_MESSAGES) == Intents.GUILD_MESSAGES:
+ print("Guild messages are enabled")
- # Checking if ALL in a combination are set:
- expected_intents = (Intents.GUILD_MESSAGES | Intents.PRIVATE_MESSAGES)
- if (my_intents & expected_intents) == expected_intents:
- print("Messages are enabled in guilds and private messages.")
+ # Checking if ALL in a combination are set:
+ expected_intents = (Intents.GUILD_MESSAGES | Intents.PRIVATE_MESSAGES)
+ if (my_intents & expected_intents) == expected_intents:
+ print("Messages are enabled in guilds and private messages.")
- # Checking if AT LEAST ONE in a combination is set:
- expected_intents = (Intents.GUILD_MESSAGES | Intents.PRIVATE_MESSAGES)
- if my_intents & expected_intents:
- print("Messages are enabled in guilds or private messages.")
- ```
+ # Checking if AT LEAST ONE in a combination is set:
+ expected_intents = (Intents.GUILD_MESSAGES | Intents.PRIVATE_MESSAGES)
+ if my_intents & expected_intents:
+ print("Messages are enabled in guilds or private messages.")
Removing one or more intents from a combination can be done with the
bitwise-xor (`^`) operator. The `^=` operator can do this in-place.
- ```py
- # Remove GUILD_MESSAGES
- my_intents = my_intents ^ Intents.GUILD_MESSAGES
- # or, simplifying:
- my_intents ^= Intents.GUILD_MESSAGES
+ .. code-block:: python
+
+ # Remove GUILD_MESSAGES
+ my_intents = my_intents ^ Intents.GUILD_MESSAGES
+ # or, simplifying:
+ my_intents ^= Intents.GUILD_MESSAGES
- # Remove all messages events.
- my_intents = my_intents ^ (Intents.GUILD_MESSAGES | Intents.PRIVATE_MESSAGES)
- # or, simplifying
- my_intents ^= (Intents.GUILD_MESSAGES | Intents.PRIVATE_MESSAGES)
- ```
+ # Remove all messages events.
+ my_intents = my_intents ^ (Intents.GUILD_MESSAGES | Intents.PRIVATE_MESSAGES)
+ # or, simplifying
+ my_intents ^= (Intents.GUILD_MESSAGES | Intents.PRIVATE_MESSAGES)
What is and is not covered by intents?
--------------------------------------
@@ -179,7 +179,7 @@ class Intents(enums.Flag):
"""Represents no intents."""
GUILDS = 1 << 0
- """Subscribes to the following events:
+ """Subscribes to the events listed below.
* `GUILD_CREATE`
* `GUILD_UPDATE`
@@ -198,42 +198,42 @@ class Intents(enums.Flag):
* `THREAD_MEMBER_UPDATE`
* `THREAD_MEMBERS_UPDATE`
- !!! note
+ .. note::
Both `GUILDS` and `GUILD_MEMBERS` are required to receive
`THREAD_MEMBERS_UPDATE`.
"""
GUILD_MEMBERS = 1 << 1
- """Subscribes to the following events:
+ """Subscribes to the events listed below.
* `GUILD_MEMBER_ADD`
* `GUILD_MEMBER_UPDATE`
* `GUILD_MEMBER_REMOVE`
* `THREAD_MEMBERS_UPDATE`
- !!! note
+ .. note::
Both `GUILDS` and `GUILD_MEMBERS` are required to receive
`THREAD_MEMBERS_UPDATE`.
- !!! warning
+ .. warning::
This intent is privileged, and requires enabling/whitelisting to use.
"""
GUILD_BANS = 1 << 2
- """Subscribes to the following events:
+ """Subscribes to the events listed below.
* `GUILD_BAN_ADD`
* `GUILD_BAN_REMOVE`
"""
GUILD_EMOJIS = 1 << 3
- """Subscribes to the following events:
+ """Subscribes to the events listed below.
* `GUILD_EMOJIS_UPDATE`
"""
GUILD_INTEGRATIONS = 1 << 4
- """Subscribes to the following events:
+ """Subscribes to the events listed below.
* `INTEGRATION_CREATE`
* `INTEGRATION_DELETE`
@@ -241,35 +241,35 @@ class Intents(enums.Flag):
"""
GUILD_WEBHOOKS = 1 << 5
- """Subscribes to the following events:
+ """Subscribes to the events listed below.
* `WEBHOOKS_UPDATE`
"""
GUILD_INVITES = 1 << 6
- """Subscribes to the following events:
+ """Subscribes to the events listed below.
* `INVITE_CREATE`
* `INVITE_DELETE`
"""
GUILD_VOICE_STATES = 1 << 7
- """Subscribes to the following events:
+ """Subscribes to the events listed below.
* `VOICE_STATE_UPDATE`
"""
GUILD_PRESENCES = 1 << 8
- """Subscribes to the following events:
+ """Subscribes to the events listed below.
* `PRESENCE_UPDATE`
- !!! warning
+ .. warning::
This intent is privileged, and requires enabling/whitelisting to use.
"""
GUILD_MESSAGES = 1 << 9
- """Subscribes to the following events:
+ """Subscribes to the events listed below.
* `MESSAGE_CREATE` (in guilds only)
* `MESSAGE_UPDATE` (in guilds only)
@@ -278,7 +278,7 @@ class Intents(enums.Flag):
"""
GUILD_MESSAGE_REACTIONS = 1 << 10
- """Subscribes to the following events:
+ """Subscribes to the events listed below.
* `MESSAGE_REACTION_ADD` (in guilds only)
* `MESSAGE_REACTION_REMOVE` (in guilds only)
@@ -287,13 +287,13 @@ class Intents(enums.Flag):
"""
GUILD_MESSAGE_TYPING = 1 << 11
- """Subscribes to the following events:
+ """Subscribes to the events listed below.
* `TYPING_START` (in guilds only)
"""
DM_MESSAGES = 1 << 12
- """Subscribes to the following events:
+ """Subscribes to the events listed below.
* `MESSAGE_CREATE` (in private message channels (non-guild bound) only)
* `MESSAGE_UPDATE` (in private message channels (non-guild bound) only)
@@ -301,7 +301,7 @@ class Intents(enums.Flag):
"""
DM_MESSAGE_REACTIONS = 1 << 13
- """Subscribes to the following events:
+ """Subscribes to the events listed below.
* `MESSAGE_REACTION_ADD` (in private message channels (non-guild bound) only)
* `MESSAGE_REACTION_REMOVE` (in private message channels (non-guild bound) only)
@@ -310,7 +310,7 @@ class Intents(enums.Flag):
"""
DM_MESSAGE_TYPING = 1 << 14
- """Subscribes to the following events:
+ """Subscribes to the events listed below.
* `TYPING_START` (in private message channels (non-guild bound) only)
"""
@@ -320,12 +320,12 @@ class Intents(enums.Flag):
DM's to the bot and messages that mention it are exempt from this.
- !!! warning
+ .. warning::
This intent is privileged, and requires enabling/whitelisting to use.
"""
GUILD_SCHEDULED_EVENTS = 1 << 16
- """Subscribes to the following events:
+ """Subscribes to the events listed below.
* `GUILD_SCHEDULED_EVENT_CREATE`
* `GUILD_SCHEDULED_EVENT_UPDATE`
@@ -357,7 +357,7 @@ class Intents(enums.Flag):
ALL_GUILDS_PRIVILEGED = GUILD_MEMBERS | GUILD_PRESENCES
"""All privileged guild intents.
- !!! warning
+ .. warning::
This set of intent is privileged, and requires enabling/whitelisting to
use.
"""
@@ -368,7 +368,7 @@ class Intents(enums.Flag):
This combines `Intents.ALL_GUILDS_UNPRIVILEGED` and
`Intents.ALL_GUILDS_PRIVILEGED`.
- !!! warning
+ .. warning::
This set of intent is privileged, and requires enabling/whitelisting to
use.
"""
@@ -391,7 +391,7 @@ class Intents(enums.Flag):
ALL_PRIVILEGED = ALL_GUILDS_PRIVILEGED | MESSAGE_CONTENT
"""All privileged intents.
- !!! warning
+ .. warning::
This set of intent is privileged, and requires enabling/whitelisting to
use.
"""
@@ -399,7 +399,7 @@ class Intents(enums.Flag):
ALL = ALL_UNPRIVILEGED | ALL_PRIVILEGED
"""All unprivileged and privileged intents.
- !!! warning
+ .. warning::
This set of intent is privileged, and requires enabling/whitelisting to
use.
"""
@@ -408,7 +408,7 @@ class Intents(enums.Flag):
def is_privileged(self) -> bool:
"""Determine whether the intent requires elevated privileges.
- If this is `builtins.True`, you will be required to opt-in to using
+ If this is `True`, you will be required to opt-in to using
this intent on the Discord Developer Portal before you can utilise it
in your application.
"""
diff --git a/hikari/interactions/base_interactions.py b/hikari/interactions/base_interactions.py
index 5fa2c37e6e..9e8686cbd4 100644
--- a/hikari/interactions/base_interactions.py
+++ b/hikari/interactions/base_interactions.py
@@ -188,7 +188,7 @@ class PartialInteraction(snowflakes.Unique, webhooks.ExecutableWebhook):
"""The base model for all interaction models."""
app: traits.RESTAware = attr.field(repr=False, eq=False, metadata={attr_extensions.SKIP_DEEP_COPY: True})
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
id: snowflakes.Snowflake = attr.field(hash=True, repr=True)
# <>.
@@ -273,7 +273,7 @@ async def create_initial_response(
) -> None:
"""Create the initial response for this interaction.
- !!! warning
+ .. warning::
Calling this on an interaction which already has an initial
response will result in this raising a `hikari.errors.NotFoundError`.
This includes if the REST interaction server has already responded
@@ -281,7 +281,7 @@ async def create_initial_response(
Parameters
----------
- response_type : typing.Union[builtins.int, CommandResponseTypesT]
+ response_type : typing.Union[int, CommandResponseTypesT]
The type of interaction response this is.
Other Parameters
@@ -290,7 +290,7 @@ async def create_initial_response(
If provided, the message contents. If
`hikari.undefined.UNDEFINED`, then nothing will be sent
in the content. Any other value here will be cast to a
- `builtins.str`.
+ `str`.
If this is a `hikari.embeds.Embed` and no `embed` nor `embeds` kwarg
is provided, then this will instead update the embed. This allows
@@ -310,28 +310,28 @@ async def create_initial_response(
If provided, the message embed.
embeds : hikari.undefined.UndefinedNoneOr[typing.Sequence[hikari.embeds.Embed]]
If provided, the message embeds.
- flags : typing.Union[builtins.int, hikari.messages.MessageFlag, hikari.undefined.UndefinedType]
+ flags : typing.Union[int, hikari.messages.MessageFlag, hikari.undefined.UndefinedType]
If provided, the message flags this response should have.
As of writing the only message flag which can be set here is
`hikari.messages.MessageFlag.EPHEMERAL`.
- tts : hikari.undefined.UndefinedOr[builtins.bool]
+ tts : hikari.undefined.UndefinedOr[bool]
If provided, whether the message will be read out by a screen
reader using Discord's TTS (text-to-speech) system.
- mentions_everyone : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_everyone : hikari.undefined.UndefinedOr[bool]
If provided, whether the message should parse @everyone/@here
mentions.
- user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
- If provided, and `builtins.True`, all user mentions will be detected.
- If provided, and `builtins.False`, all user mentions will be ignored
+ user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], bool]]
+ If provided, and `True`, all user mentions will be detected.
+ If provided, and `False`, all user mentions will be ignored
if appearing in the message body.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.users.PartialUser` derivatives to enforce mentioning
specific users.
- role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], builtins.bool]]
- If provided, and `builtins.True`, all role mentions will be detected.
- If provided, and `builtins.False`, all role mentions will be ignored
+ role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], bool]]
+ If provided, and `True`, all role mentions will be detected.
+ If provided, and `False`, all role mentions will be ignored
if appearing in the message body.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
@@ -340,10 +340,10 @@ async def create_initial_response(
Raises
------
- builtins.ValueError
+ ValueError
If more than 100 unique objects/entities are passed for
`role_mentions` or `user_mentions`.
- builtins.TypeError
+ TypeError
If both `embed` and `embeds` are specified.
hikari.errors.BadRequestError
This may be raised in several discrete situations, such as messages
@@ -413,13 +413,28 @@ async def edit_initial_response(
) -> messages.Message:
"""Edit the initial response of this command interaction.
+ .. note::
+ Mentioning everyone, roles, or users in message edits currently
+ will not send a push notification showing a new mention to people
+ on Discord. It will still highlight in their chat as if they
+ were mentioned, however.
+
+ .. warning::
+ If you specify a text `content`, `mentions_everyone`,
+ `mentions_reply`, `user_mentions`, and `role_mentions` will default
+ to `False` as the message will be re-parsed for mentions. This will
+ also occur if only one of the four are specified
+
+ This is a limitation of Discord's design. If in doubt, specify all
+ four of them each time.
+
Other Parameters
----------------
content : hikari.undefined.UndefinedNoneOr[typing.Any]
If provided, the message contents. If
`hikari.undefined.UNDEFINED`, then nothing will be sent
in the content. Any other value here will be cast to a
- `builtins.str`.
+ `str`.
If this is a `hikari.embeds.Embed` and neither the
`embed` or `embeds` kwargs are provided or if this is a
@@ -434,70 +449,56 @@ async def edit_initial_response(
attachment : hikari.undefined.UndefinedNoneOr[typing.Union[hikari.files.Resourceish, hikari.messages.Attachment]]
If provided, the attachment to set on the message. If
`hikari.undefined.UNDEFINED`, the previous attachment, if
- present, is not changed. If this is `builtins.None`, then the
+ present, is not changed. If this is `None`, then the
attachment is removed, if present. Otherwise, the new attachment
that was provided will be attached.
attachments : hikari.undefined.UndefinedNoneOr[typing.Sequence[typing.Union[hikari.files.Resourceish, hikari.messages.Attachment]]]
If provided, the attachments to set on the message. If
`hikari.undefined.UNDEFINED`, the previous attachments, if
- present, are not changed. If this is `builtins.None`, then the
+ present, are not changed. If this is `None`, then the
attachments is removed, if present. Otherwise, the new attachments
that were provided will be attached.
component : hikari.undefined.UndefinedNoneOr[hikari.api.special_endpoints.ComponentBuilder]
If provided, builder object of the component to set for this message.
This component will replace any previously set components and passing
- `builtins.None` will remove all components.
+ `None` will remove all components.
components : hikari.undefined.UndefinedNoneOr[typing.Sequence[hikari.api.special_endpoints.ComponentBuilder]]
If provided, a sequence of the component builder objects set for
this message. These components will replace any previously set
- components and passing `builtins.None` or an empty sequence will
+ components and passing `None` or an empty sequence will
remove all components.
embed : hikari.undefined.UndefinedNoneOr[hikari.embeds.Embed]
If provided, the embed to set on the message. If
`hikari.undefined.UNDEFINED`, the previous embed(s) are not changed.
- If this is `builtins.None` then any present embeds are removed.
+ If this is `None` then any present embeds are removed.
Otherwise, the new embed that was provided will be used as the
replacement.
embeds : hikari.undefined.UndefinedNoneOr[typing.Sequence[hikari.embeds.Embed]]
If provided, the embeds to set on the message. If
`hikari.undefined.UNDEFINED`, the previous embed(s) are not changed.
- If this is `builtins.None` then any present embeds are removed.
+ If this is `None` then any present embeds are removed.
Otherwise, the new embeds that were provided will be used as the
replacement.
- mentions_everyone : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_everyone : hikari.undefined.UndefinedOr[bool]
If provided, whether the message should parse @everyone/@here
mentions.
- user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
- If provided, and `builtins.True`, all user mentions will be detected.
- If provided, and `builtins.False`, all user mentions will be ignored
+ user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], bool]]
+ If provided, and `True`, all user mentions will be detected.
+ If provided, and `False`, all user mentions will be ignored
if appearing in the message body.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.users.PartialUser` derivatives to enforce mentioning
specific users.
- role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], builtins.bool]]
- If provided, and `builtins.True`, all role mentions will be detected.
- If provided, and `builtins.False`, all role mentions will be ignored
+ role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], bool]]
+ If provided, and `True`, all role mentions will be detected.
+ If provided, and `False`, all role mentions will be ignored
if appearing in the message body.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.guilds.PartialRole` derivatives to enforce mentioning
specific roles.
- !!! note
- Mentioning everyone, roles, or users in message edits currently
- will not send a push notification showing a new mention to people
- on Discord. It will still highlight in their chat as if they
- were mentioned, however.
-
- !!! warning
- If you specify one of `mentions_everyone`, `user_mentions`, or
- `role_mentions`, then all others will default to `builtins.False`,
- even if they were enabled previously.
-
- This is a limitation of Discord's design. If in doubt, specify all three of
- them each time.
-
Returns
-------
hikari.messages.Message
@@ -505,10 +506,10 @@ async def edit_initial_response(
Raises
------
- builtins.ValueError
+ ValueError
If more than 100 unique objects/entities are passed for
`role_mentions` or `user_mentions`.
- builtins.TypeError
+ TypeError
If both `embed` and `embeds` are specified.
hikari.errors.BadRequestError
This may be raised in several discrete situations, such as messages
diff --git a/hikari/interactions/command_interactions.py b/hikari/interactions/command_interactions.py
index dd713e6785..a75d3613b5 100644
--- a/hikari/interactions/command_interactions.py
+++ b/hikari/interactions/command_interactions.py
@@ -49,7 +49,6 @@
if typing.TYPE_CHECKING:
from hikari import guilds
- from hikari import locales
from hikari import messages as messages_
from hikari import permissions as permissions_
from hikari import users as users_
@@ -171,7 +170,10 @@ class AutocompleteInteractionOption(CommandInteractionOption):
@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class BaseCommandInteraction(base_interactions.PartialInteraction):
- """Represents a base command interaction on Discord."""
+ """Represents a base command interaction on Discord.
+
+ May be a command interaction or an autocomplete interaction.
+ """
channel_id: snowflakes.Snowflake = attr.field(eq=False, hash=False, repr=True)
"""ID of the channel this command interaction event was triggered in."""
@@ -179,15 +181,15 @@ class BaseCommandInteraction(base_interactions.PartialInteraction):
guild_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=True)
"""ID of the guild this command interaction event was triggered in.
- This will be `builtins.None` for command interactions triggered in DMs.
+ This will be `None` for command interactions triggered in DMs.
"""
- guild_locale: typing.Optional[typing.Union[str, locales.Locale]] = attr.field(eq=False, hash=False, repr=True)
+ guild_locale: typing.Optional[str] = attr.field(eq=False, hash=False, repr=True)
"""The preferred language of the guild this command interaction was triggered in.
- This will be `builtins.None` for command interactions triggered in DMs.
+ This will be `None` for command interactions triggered in DMs.
- !!! note
+ .. note::
This value can usually only be changed if `COMMUNITY` is in `hikari.guilds.Guild.features`
for the guild and will otherwise default to `en-US`.
"""
@@ -195,9 +197,9 @@ class BaseCommandInteraction(base_interactions.PartialInteraction):
member: typing.Optional[base_interactions.InteractionMember] = attr.field(eq=False, hash=False, repr=True)
"""The member who triggered this command interaction.
- This will be `builtins.None` for command interactions triggered in DMs.
+ This will be `None` for command interactions triggered in DMs.
- !!! note
+ .. note::
This member object comes with the extra field `permissions` which
contains the member's permissions in the current channel.
"""
@@ -205,7 +207,7 @@ class BaseCommandInteraction(base_interactions.PartialInteraction):
user: users_.User = attr.field(eq=False, hash=False, repr=True)
"""The user who triggered this command interaction."""
- locale: typing.Union[str, locales.Locale] = attr.field(eq=False, hash=False, repr=True)
+ locale: str = attr.field(eq=False, hash=False, repr=True)
"""The selected language of the user who triggered this command interaction."""
command_id: snowflakes.Snowflake = attr.field(eq=False, hash=False, repr=True)
@@ -258,15 +260,15 @@ async def fetch_channel(self) -> channels.TextableChannel:
def get_channel(self) -> typing.Optional[channels.TextableGuildChannel]:
"""Get the guild channel this was triggered in from the cache.
- !!! note
- This will always return `builtins.None` for interactions triggered
+ .. note::
+ This will always return `None` for interactions triggered
in a DM channel.
Returns
-------
typing.Optional[hikari.channels.TextableGuildChannel]
The object of the guild channel that was found in the cache or
- `builtins.None`.
+ `None`.
"""
if isinstance(self.app, traits.CacheAware):
channel = self.app.cache.get_guild_channel(self.channel_id)
@@ -315,7 +317,7 @@ async def fetch_guild(self) -> typing.Optional[guilds.RESTGuild]:
Returns
-------
typing.Optional[hikari.guilds.RESTGuild]
- Object of the guild this interaction happened in or `builtins.None`
+ Object of the guild this interaction happened in or `None`
if this occurred within a DM channel.
Raises
@@ -351,7 +353,7 @@ def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
Returns
-------
typing.Optional[hikari.guilds.GatewayGuild]
- The object of the guild if found, else `builtins.None`.
+ The object of the guild if found, else `None`.
"""
if self.guild_id and isinstance(self.app, traits.CacheAware):
return self.app.cache.get_guild(self.guild_id)
@@ -383,22 +385,22 @@ class CommandInteraction(
def build_response(self) -> special_endpoints.InteractionMessageBuilder:
"""Get a message response builder for use in the REST server flow.
- !!! note
+ .. note::
For interactions received over the gateway
`CommandInteraction.create_initial_response` should be used to set
the interaction response message.
Examples
--------
- ```py
- async def handle_command_interaction(interaction: CommandInteraction) -> InteractionMessageBuilder:
- return (
- interaction
- .build_response()
- .add_embed(Embed(description="Hi there"))
- .set_content("Konnichiwa")
- )
- ```
+ .. code-block:: python
+
+ async def handle_command_interaction(interaction: CommandInteraction) -> InteractionMessageBuilder:
+ return (
+ interaction
+ .build_response()
+ .add_embed(Embed(description="Hi there"))
+ .set_content("Konnichiwa")
+ )
Returns
-------
@@ -410,12 +412,12 @@ async def handle_command_interaction(interaction: CommandInteraction) -> Interac
def build_deferred_response(self) -> special_endpoints.InteractionDeferredBuilder:
"""Get a deferred message response builder for use in the REST server flow.
- !!! note
+ .. note::
For interactions received over the gateway
`CommandInteraction.create_initial_response` should be used to set
the interaction response message.
- !!! note
+ .. note::
Unlike `hikari.api.special_endpoints.InteractionMessageBuilder`,
the result of this call can be returned as is without any modifications
being made to it.
@@ -441,26 +443,26 @@ def build_response(
) -> special_endpoints.InteractionAutocompleteBuilder:
"""Get a message response builder for use in the REST server flow.
- !!! note
+ .. note::
For interactions received over the gateway
`AutocompleteInteraction.create_response` should be used to set
the interaction response.
Examples
--------
- ```py
- async def handle_autocomplete_interaction(interaction: AutocompleteInteraction) -> InteractionAutocompleteBuilder:
- return (
- interaction
- .build_response(
- [
- CommandChoice(name="foo", value="a"),
- CommandChoice(name="bar", value="b"),
- CommandChoice(name="baz", value="c"),
- ]
+ .. code-block:: python
+
+ async def handle_autocomplete_interaction(interaction: AutocompleteInteraction) -> InteractionAutocompleteBuilder:
+ return (
+ interaction
+ .build_response(
+ [
+ CommandChoice(name="foo", value="a"),
+ CommandChoice(name="bar", value="b"),
+ CommandChoice(name="baz", value="c"),
+ ]
+ )
)
- )
- ```
Returns
-------
diff --git a/hikari/interactions/component_interactions.py b/hikari/interactions/component_interactions.py
index d85d18fd14..04ab8c2770 100644
--- a/hikari/interactions/component_interactions.py
+++ b/hikari/interactions/component_interactions.py
@@ -96,7 +96,7 @@ class ComponentInteraction(
component_type: typing.Union[components_.ComponentType, int] = attr.field(eq=False)
"""The type of component which triggers this interaction.
- !!! note
+ .. note::
This will never be `ButtonStyle.LINK` as link buttons don't trigger
interactions.
"""
@@ -110,15 +110,15 @@ class ComponentInteraction(
guild_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False)
"""ID of the guild this interaction was triggered in.
- This will be `builtins.None` for component interactions triggered in DMs.
+ This will be `None` for component interactions triggered in DMs.
"""
guild_locale: typing.Optional[typing.Union[str, locales.Locale]] = attr.field(eq=False, hash=False, repr=True)
"""The preferred language of the guild this component interaction was triggered in.
- This will be `builtins.None` for component interactions triggered in DMs.
+ This will be `None` for component interactions triggered in DMs.
- !!! note
+ .. note::
This value can usually only be changed if `COMMUNITY` is in `hikari.guilds.Guild.features`
for the guild and will otherwise default to `en-US`.
"""
@@ -129,9 +129,9 @@ class ComponentInteraction(
member: typing.Optional[base_interactions.InteractionMember] = attr.field(eq=False, hash=False, repr=True)
"""The member who triggered this interaction.
- This will be `builtins.None` for interactions triggered in DMs.
+ This will be `None` for interactions triggered in DMs.
- !!! note
+ .. note::
This member object comes with the extra field `permissions` which
contains the member's permissions in the current channel.
"""
@@ -148,14 +148,14 @@ class ComponentInteraction(
def build_response(self, type_: _ImmediateTypesT, /) -> special_endpoints.InteractionMessageBuilder:
"""Get a message response builder for use in the REST server flow.
- !!! note
+ .. note::
For interactions received over the gateway
`ComponentInteraction.create_initial_response` should be used to set
the interaction response message.
Parameters
----------
- type_ : typing.Union[builtins.int, hikari.interactions.base_interactions.ResponseType]
+ type_ : typing.Union[int, hikari.interactions.base_interactions.ResponseType]
The type of immediate response this should be.
This may be one of the following:
@@ -165,15 +165,15 @@ def build_response(self, type_: _ImmediateTypesT, /) -> special_endpoints.Intera
Examples
--------
- ```py
- async def handle_component_interaction(interaction: ComponentInteraction) -> InteractionMessageBuilder:
- return (
- interaction
- .build_response(ResponseType.MESSAGE_UPDATE)
- .add_embed(Embed(description="Hi there"))
- .set_content("Konnichiwa")
- )
- ```
+ .. code-block:: python
+
+ async def handle_component_interaction(interaction: ComponentInteraction) -> InteractionMessageBuilder:
+ return (
+ interaction
+ .build_response(ResponseType.MESSAGE_UPDATE)
+ .add_embed(Embed(description="Hi there"))
+ .set_content("Konnichiwa")
+ )
Returns
-------
@@ -188,19 +188,19 @@ async def handle_component_interaction(interaction: ComponentInteraction) -> Int
def build_deferred_response(self, type_: _DeferredTypesT, /) -> special_endpoints.InteractionDeferredBuilder:
"""Get a deferred message response builder for use in the REST server flow.
- !!! note
+ .. note::
For interactions received over the gateway
`ComponentInteraction.create_initial_response` should be used to set
the interaction response message.
- !!! note
+ .. note::
Unlike `hikari.api.special_endpoints.InteractionMessageBuilder`,
the result of this call can be returned as is without any modifications
being made to it.
Parameters
----------
- type_ : typing.Union[builtins.int, hikari.interactions.base_interactions.ResponseType]
+ type_ : typing.Union[int, hikari.interactions.base_interactions.ResponseType]
The type of deferred response this should be.
This may be one of the following:
@@ -258,15 +258,15 @@ async def fetch_channel(self) -> channels.TextableChannel:
def get_channel(self) -> typing.Union[channels.GuildTextChannel, channels.GuildNewsChannel, None]:
"""Get the guild channel this interaction occurred in.
- !!! note
- This will always return `builtins.None` for interactions triggered
+ .. note::
+ This will always return `None` for interactions triggered
in a DM channel.
Returns
-------
- typing.Union[hikari.channels.GuildTextChannel, hikari.channels.GuildNewsChannel, builtins.None]
+ typing.Union[hikari.channels.GuildTextChannel, hikari.channels.GuildNewsChannel, None]
The object of the guild channel that was found in the cache or
- `builtins.None`.
+ `None`.
"""
if isinstance(self.app, traits.CacheAware):
channel = self.app.cache.get_guild_channel(self.channel_id)
@@ -281,7 +281,7 @@ async def fetch_guild(self) -> typing.Optional[guilds.RESTGuild]:
Returns
-------
typing.Optional[hikari.guilds.RESTGuild]
- Object of the guild this interaction happened in or `builtins.None`
+ Object of the guild this interaction happened in or `None`
if this occurred within a DM channel.
Raises
@@ -312,12 +312,12 @@ async def fetch_guild(self) -> typing.Optional[guilds.RESTGuild]:
return await self.app.rest.fetch_guild(self.guild_id)
def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
- """Get the object of this interaction's guild guild from the cache.
+ """Get the object of this interaction's guild from the cache.
Returns
-------
typing.Optional[hikari.guilds.GatewayGuild]
- The object of the guild if found, else `builtins.None`.
+ The object of the guild if found, else `None`.
"""
if self.guild_id and isinstance(self.app, traits.CacheAware):
return self.app.cache.get_guild(self.guild_id)
diff --git a/hikari/interactions/modal_interactions.py b/hikari/interactions/modal_interactions.py
index 54735b31de..a62ba2e4fb 100644
--- a/hikari/interactions/modal_interactions.py
+++ b/hikari/interactions/modal_interactions.py
@@ -91,7 +91,7 @@ class ModalInteraction(base_interactions.MessageResponseMixin[ModalResponseTypes
This will be `builtins.None` for modal interactions triggered in DMs.
- !!! note
+ .. note::
This value can usually only be changed if `COMMUNITY` is in `hikari.guilds.Guild.features`
for the guild and will otherwise default to `en-US`.
"""
@@ -107,7 +107,7 @@ class ModalInteraction(base_interactions.MessageResponseMixin[ModalResponseTypes
This will be `builtins.None` for modal interactions triggered in DMs.
- !!! note
+ .. note::
This member object comes with the extra field `permissions` which
contains the member's permissions in the current channel.
"""
@@ -165,7 +165,7 @@ async def fetch_channel(self) -> channels.TextableChannel:
def get_channel(self) -> typing.Optional[channels.TextableGuildChannel]:
"""Get the guild channel this interaction was triggered in from the cache.
- !!! note
+ .. note::
This will always return `builtins.None` for interactions triggered
in a DM channel.
@@ -234,7 +234,7 @@ def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
def build_response(self) -> special_endpoints.InteractionMessageBuilder:
"""Get a message response builder for use in the REST server flow.
- !!! note
+ .. note::
For interactions received over the gateway
`ModalInteraction.create_initial_response` should be used to set
the interaction response message.
@@ -261,12 +261,12 @@ async def handle_modal_interaction(interaction: ModalInteraction) -> Interaction
def build_deferred_response(self) -> special_endpoints.InteractionDeferredBuilder:
"""Get a deferred message response builder for use in the REST server flow.
- !!! note
+ .. note::
For interactions received over the gateway
`ModalInteraction.create_initial_response` should be used to set
the interaction response message.
- !!! note
+ .. note::
Unlike `hikari.api.special_endpoints.InteractionMessageBuilder`,
the result of this call can be returned as is without any modifications
being made to it.
diff --git a/hikari/internal/aio.py b/hikari/internal/aio.py
index 08f0285c73..37d34843f7 100644
--- a/hikari/internal/aio.py
+++ b/hikari/internal/aio.py
@@ -57,8 +57,8 @@ def completed_future(result: typing.Optional[T_inv] = None, /) -> asyncio.Future
result : T
The value to set for the result of the future.
`T` is a generic type placeholder for the type that
- the future will have set as the result. `T` may be `builtins.None`, in
- which case, this will return `asyncio.Future[builtins.None]`.
+ the future will have set as the result. `T` may be `None`, in
+ which case, this will return `asyncio.Future[None]`.
Returns
-------
@@ -118,17 +118,17 @@ async def first_completed(
If the first awaitable raises an exception, then that exception will be
propagated.
+ .. note::
+ If more than one awaitable is completed before entering this call, then
+ the first future is always returned.
+
Parameters
----------
*aws : typing.Awaitable[typing.Any]
Awaitables to wait for.
timeout : typing.Optional[float]
- Optional timeout to wait for, or `builtins.None` to not use one.
+ Optional timeout to wait for, or `None` to not use one.
If the timeout is reached, all awaitables are cancelled immediately.
-
- !!! note
- If more than one awaitable is completed before entering this call, then
- the first future is always returned.
"""
fs = tuple(map(asyncio.ensure_future, aws))
iterator = asyncio.as_completed(fs, timeout=timeout)
@@ -163,7 +163,7 @@ async def all_of(
*aws : typing.Awaitable[T_co]
Awaitables to wait for.
timeout : typing.Optional[float]
- Optional timeout to wait for, or `builtins.None` to not use one.
+ Optional timeout to wait for, or `None` to not use one.
If the timeout is reached, all awaitables are cancelled immediately.
Returns
@@ -203,6 +203,7 @@ def get_or_make_loop() -> asyncio.AbstractEventLoop:
Returns
-------
asyncio.AbstractEventLoop
+ The requested loop.
"""
# get_event_loop will error under oddly specific cases such as if set_event_loop has been called before even
# if it was just called with None or if it's called on a thread which isn't the main Thread.
diff --git a/hikari/internal/attr_extensions.py b/hikari/internal/attr_extensions.py
index faf114d62b..0fc15a3c18 100644
--- a/hikari/internal/attr_extensions.py
+++ b/hikari/internal/attr_extensions.py
@@ -73,7 +73,7 @@ def get_fields_definition(
Returns
-------
- typing.Sequence[typing.Tuple[builtins.str, builtins.str]]
+ typing.Sequence[typing.Tuple[str, str]]
A sequence of tuples of string attribute names to string key-word names.
"""
init_results: typing.List[typing.Tuple[attr.Attribute[typing.Any], str]] = []
@@ -223,17 +223,17 @@ def get_or_generate_deep_copier(
def deep_copy_attrs(model: ModelT, memo: typing.Optional[typing.MutableMapping[int, typing.Any]] = None) -> ModelT:
"""Deep copy an attrs model with `init` enabled.
+ .. note::
+ This won't deep copy attributes where "skip_deep_copy" is set to
+ `True` in their metadata.
+
Parameters
----------
model : ModelT
The attrs model to deep copy.
- memo : typing.Optional[typing.MutableMapping[builtins.int, typing.Any]]
+ memo : typing.Optional[typing.MutableMapping[int, typing.Any]]
A memo dictionary of objects already copied during the current copying
- pass, see https://docs.python.org/3/library/copy.html for more details.
-
- !!! note
- This won't deep copy attributes where "skip_deep_copy" is set to
- `builtins.True` in their metadata.
+ pass, see for more details.
Returns
-------
@@ -252,7 +252,7 @@ def deep_copy_attrs(model: ModelT, memo: typing.Optional[typing.MutableMapping[i
def with_copy(cls: typing.Type[ModelT]) -> typing.Type[ModelT]:
"""Add a custom implementation for copying attrs models to a class.
- !!! note
+ .. note::
This will only work if the class has an attrs generated init.
"""
cls.__copy__ = copy_attrs # type: ignore[attr-defined]
diff --git a/hikari/internal/cache.py b/hikari/internal/cache.py
index 37fde96025..368f59f74e 100644
--- a/hikari/internal/cache.py
+++ b/hikari/internal/cache.py
@@ -190,20 +190,20 @@ class GuildRecord:
is_available: typing.Optional[bool] = attr.field(default=None)
"""Whether the cached guild is available or not.
- This will be `builtins.None` when no `GuildRecord.guild` is also
- `builtins.None` else `builtins.bool`.
+ This will be `None` when no `GuildRecord.guild` is also
+ `None` else `bool`.
"""
guild: typing.Optional[guilds.GatewayGuild] = attr.field(default=None)
"""A cached guild object.
- This will be `hikari.guilds.GatewayGuild` or `builtins.None` if not cached.
+ This will be `hikari.guilds.GatewayGuild` or `None` if not cached.
"""
channels: typing.Optional[typing.MutableSet[snowflakes.Snowflake]] = attr.field(default=None)
"""A set of the IDs of the guild channels cached for this guild.
- This will be `builtins.None` if no channels are cached for this guild else
+ This will be `None` if no channels are cached for this guild else
`typing.MutableSet[hikari.snowflakes.Snowflake]` of channel IDs.
"""
@@ -217,21 +217,21 @@ class GuildRecord:
emojis: typing.Optional[typing.MutableSet[snowflakes.Snowflake]] = attr.field(default=None)
"""A set of the IDs of the emojis cached for this guild.
- This will be `builtins.None` if no emojis are cached for this guild else
+ This will be `None` if no emojis are cached for this guild else
`typing.MutableSet[hikari.snowflakes.Snowflake]` of emoji IDs.
"""
stickers: typing.Optional[typing.MutableSet[snowflakes.Snowflake]] = attr.field(default=None)
"""A sequence of sticker IDs cached for this guild.
- This will be `builtins.None` if no stickers are cached for this guild else
+ This will be `None` if no stickers are cached for this guild else
`typing.Sequence[hikari.snowflakes.Snowflake]` of emoji IDs.
"""
invites: typing.Optional[typing.MutableSequence[str]] = attr.field(default=None)
- """A set of the `builtins.str` codes of the invites cached for this guild.
+ """A set of the `str` codes of the invites cached for this guild.
- This will be `builtins.None` if no invites are cached for this guild else
+ This will be `None` if no invites are cached for this guild else
`typing.MutableSequence[str]` of invite codes.
"""
@@ -240,7 +240,7 @@ class GuildRecord:
] = attr.field(default=None)
"""A mapping of user IDs to the objects of members cached for this guild.
- This will be `builtins.None` if no members are cached for this guild else
+ This will be `None` if no members are cached for this guild else
`hikari.internal.collections.ExtendedMutableMapping[hikari.snowflakes.Snowflake, MemberData]`.
"""
@@ -249,14 +249,14 @@ class GuildRecord:
] = attr.field(default=None)
"""A mapping of user IDs to objects of the presences cached for this guild.
- This will be `builtins.None` if no presences are cached for this guild else
+ This will be `None` if no presences are cached for this guild else
`hikari.internal.collections.ExtendedMutableMapping[hikari.snowflakes.Snowflake, MemberPresenceData]`.
"""
roles: typing.Optional[typing.MutableSet[snowflakes.Snowflake]] = attr.field(default=None)
"""A set of the IDs of the roles cached for this guild.
- This will be `builtins.None` if no roles are cached for this guild else
+ This will be `None` if no roles are cached for this guild else
`typing.MutableSet[hikari.snowflakes.Snowflake]` of role IDs.
"""
@@ -265,7 +265,7 @@ class GuildRecord:
] = attr.field(default=None)
"""A mapping of user IDs to objects of the voice states cached for this guild.
- This will be `builtins.None` if no voice states are cached for this guild else
+ This will be `None` if no voice states are cached for this guild else
`hikari.internal.collections.ExtendedMutableMapping[hikari.snowflakes.Snowflake, VoiceStateData]`.
"""
@@ -274,7 +274,7 @@ def empty(self) -> bool:
Returns
-------
- builtins.bool
+ bool
Whether this guild record has any resources attached to it.
"""
# As `.is_available` should be paired with `.guild`, we don't need to check both.
@@ -295,7 +295,7 @@ def empty(self) -> bool:
class BaseData(abc.ABC, typing.Generic[ValueT]):
"""A data class used for in-memory storage of entities in a more primitive form.
- !!! note
+ .. note::
This base implementation assumes that all the fields it'll handle will
be immutable and to handle mutable fields you'll have to override
build_entity and build_from_entity to explicitly copy them.
@@ -314,7 +314,8 @@ def build_entity(self, app: traits.RESTAware, /) -> ValueT:
Returns
-------
- The initialised entity object.
+ ValueT
+ The initialised entity object.
"""
@classmethod
@@ -329,7 +330,8 @@ def build_from_entity(cls: typing.Type[DataT], entity: ValueT, /) -> DataT:
Returns
-------
- The built data class.
+ DataT
+ The built data class.
"""
@@ -421,7 +423,7 @@ class MemberData(BaseData[guilds.Member]):
is_pending: undefined.UndefinedOr[bool] = attr.field()
raw_communication_disabled_until: typing.Optional[datetime.datetime] = attr.field()
# meta-attribute
- has_been_deleted: bool = attr.field(default=False)
+ has_been_deleted: bool = attr.field(default=False, init=False)
@classmethod
def build_from_entity(
@@ -1031,7 +1033,7 @@ def unwrap_ref_cell(cell: RefCell[ValueT]) -> ValueT:
Parameters
----------
cell : RefCell[ValueT]
- The reference cell instance to unwrap
+ The reference cell instance to unwrap.
Returns
-------
diff --git a/hikari/internal/collections.py b/hikari/internal/collections.py
index 3c5509e083..0245af8164 100644
--- a/hikari/internal/collections.py
+++ b/hikari/internal/collections.py
@@ -72,7 +72,7 @@ def copy(self: ExtendedMapT) -> ExtendedMapT:
This may look like calling `dict.copy` and wrapping the result in a
mapped collection.
- !!! note
+ .. note::
Any removal policy on this mapped collection will be copied over.
Returns
@@ -89,7 +89,7 @@ def freeze(self) -> typing.MutableMapping[KeyT, ValueT]:
around how the data is being stored to allow for a more efficient copy.
This may look like calling `dict.copy`.
- !!! note
+ .. note::
Unlike `ExtendedMutableMapping.copy`, this should return a pure
mapping with no removal policy at all.
@@ -142,18 +142,15 @@ class LimitedCapacityCacheMap(ExtendedMutableMapping[KeyT, ValueT]):
Parameters
----------
+ source : typing.Optional[typing.Dict[KeyT, ValueT]]
+ A source dictionary of keys to values to create this from.
limit : int
The limit for how many objects should be stored by this mapping before
it starts removing the oldest entries.
-
- Other Parameters
- ----------------
- source : typing.Optional[typing.Dict[KeyT, ValueT]]
- A source dictionary of keys to values to create this from.
on_expire : typing.Optional[typing.Callable[[ValueT], None]]
A function to call each time an item is garbage collected from this
map. This should take one positional argument of the same type stored
- in this mapping as the value and should return `builtins.None.
+ in this mapping as the value and should return `None`.
This will always be called after the entry has been removed.
"""
@@ -231,20 +228,20 @@ class SnowflakeSet(typing.MutableSet[snowflakes.Snowflake]):
$$ \mathcal{O} \left( \log n \right) $$ and best case will be
$$ \Omega \left\( k \right) $$
- !!! warning
+ .. warning::
This is not thread-safe and must not be iterated across whilst being
concurrently modified.
Other Parameters
----------------
- *ids : builtins.int
+ *ids : int
The IDs to fill this table with.
"""
__slots__: typing.Sequence[str] = ("_ids",)
def __init__(self, *ids: int) -> None:
- self._ids: array.array[int] = array.array(_LONG_LONG_UNSIGNED)
+ self._ids: typing.MutableSequence[int] = array.array(_LONG_LONG_UNSIGNED)
if ids:
self.add_all(ids)
diff --git a/hikari/internal/data_binding.py b/hikari/internal/data_binding.py
index 8d54bbe4b0..e048ea97ab 100644
--- a/hikari/internal/data_binding.py
+++ b/hikari/internal/data_binding.py
@@ -33,6 +33,7 @@
"load_json",
"JSONDecodeError",
"JSONObjectBuilder",
+ "StringMapBuilder",
"URLEncodedFormBuilder",
)
@@ -82,7 +83,7 @@
if typing.TYPE_CHECKING:
JSONDecodeError: typing.Type[Exception] = Exception
- """Exception raised when loading an invalid JSON string"""
+ """Exception raised when loading an invalid JSON string."""
def dump_json(_: typing.Union[JSONArray, JSONObject], /, *, indent: int = ...) -> str:
"""Convert a Python type to a JSON string."""
@@ -102,7 +103,7 @@ def load_json(_: typing.AnyStr, /) -> typing.Union[JSONArray, JSONObject]:
"""Convert a JSON string to a Python type."""
JSONDecodeError = json.JSONDecodeError
- """Exception raised when loading an invalid JSON string"""
+ """Exception raised when loading an invalid JSON string."""
@typing.final
@@ -141,12 +142,12 @@ class StringMapBuilder(multidict.MultiDict[str]):
"""Helper class used to quickly build query strings or header maps.
This will consume any items that are not `hikari.undefined.UNDEFINED`.
- If a value _is_ unspecified, it will be ignored when inserting it. This reduces
+ If a value is unspecified, it will be ignored when inserting it. This reduces
the amount of boilerplate needed for generating the headers and query strings for
low-level HTTP API interaction, amongst other things.
- !!! warning
- Because this subclasses `builtins.dict`, you should not use the
+ .. warning::
+ Because this subclasses `dict`, you should not use the
index operator to set items on this object. Doing so will skip any
form of validation on the type. Use the `put*` methods instead.
"""
@@ -188,9 +189,15 @@ def put(
) -> None:
"""Add a key and value to the string map.
+ .. note::
+ The value will always be cast to a `str` before inserting it.
+ `True` will be translated to `"true"`, `False` will be
+ translated to `"false"`, and `None` will be translated to
+ `"null"`.
+
Parameters
----------
- key : builtins.str
+ key : str
The string key.
value : hikari.undefined.UndefinedOr[typing.Any]
The value to set.
@@ -199,13 +206,6 @@ def put(
----------------
conversion : typing.Optional[typing.Callable[[typing.Any], typing.Any]]
An optional conversion to perform.
-
- !!! note
- The value will always be cast to a `builtins.str` before inserting it.
-
- `builtins.True` will be translated to `"true"`, `builtins.False`
- ill be translated to `"false"`, and `builtins.None` will be
- translated to `"null"`.
"""
if value is not undefined.UNDEFINED:
if conversion is not None:
@@ -236,8 +236,8 @@ class JSONObjectBuilder(typing.Dict[str, JSONish]):
This speeds up generation of JSON payloads for low level HTTP and websocket
API interaction.
- !!! warning
- Because this subclasses `builtins.dict`, you should not use the
+ .. warning::
+ Because this subclasses `dict`, you should not use the
index operator to set items on this object. Doing so will skip any
form of validation on the type. Use the `put*` methods instead.
"""
@@ -277,7 +277,7 @@ def put(
Parameters
----------
- key : builtins.str
+ key : str
The key to give the element.
value : hikari.undefined.UndefinedOr[typing.Any]
The JSON type to put. This may be a non-JSON type if a conversion
@@ -333,7 +333,7 @@ def put_array(
Parameters
----------
- key : builtins.str
+ key : str
The key to give the element.
values : hikari.undefined.UndefinedOr[typing.Iterable[T_co]]
The JSON types to put. This may be an iterable of non-JSON types if
@@ -360,11 +360,11 @@ def put_snowflake(
Parameters
----------
- key : builtins.str
+ key : str
The key to give the element.
value : hikari.undefined.UndefinedNoneOr[hikari.snowflakes.SnowflakeishOr[hikari.snowflakes.Unique]]
The JSON type to put. This may alternatively be undefined, in this
- case, nothing is performed. This may also be `builtins.None`, in this
+ case, nothing is performed. This may also be `None`, in this
case the value isn't cast.
"""
if value is not undefined.UNDEFINED and value is not None:
@@ -382,11 +382,11 @@ def put_snowflake_array(
If the value is `hikari.undefined.UNDEFINED` it will not be stored.
- Each snowflake should be castable to an `builtins.int`.
+ Each snowflake should be castable to an `int`.
Parameters
----------
- key : builtins.str
+ key : str
The key to give the element.
values : hikari.undefined.UndefinedOr[typing.Iterable[hikari.snowflakes.SnowflakeishOr[hikari.snowflakes.Unique]]]
The JSON snowflakes to put. This may alternatively be undefined.
diff --git a/hikari/internal/deprecation.py b/hikari/internal/deprecation.py
index 271665270a..29be981994 100644
--- a/hikari/internal/deprecation.py
+++ b/hikari/internal/deprecation.py
@@ -40,6 +40,9 @@ def warn_deprecated(name: str, /, *, removal_version: str, additional_info: str,
----------
name : str
What is being deprecated.
+
+ Other Parameters
+ ----------------
removal_version : str
The version it will be removed in.
additional_info : str
diff --git a/hikari/internal/enums.py b/hikari/internal/enums.py
index 1742951299..4af0454a67 100644
--- a/hikari/internal/enums.py
+++ b/hikari/internal/enums.py
@@ -101,6 +101,7 @@ def __setitem__(self, name: str, value: typing.Any) -> None:
class _EnumMeta(type):
def __call__(cls, value: typing.Any) -> typing.Any:
+ """Cast a value to the enum, returning the raw value that was passed if value not found."""
try:
return cls._value_to_member_map_[value]
except KeyError:
@@ -147,7 +148,7 @@ def __new__(
},
}
- # We don't want to override the __str__ behaviour inherited from builtins.str for string based enums.
+ # We don't want to override the __str__ behaviour inherited from str for string based enums.
if issubclass(base, str):
new_namespace.pop("__str__", None)
@@ -209,7 +210,7 @@ class Enum(metaclass=_EnumMeta):
that can be used in place of this type. This acts as a type-safe way
of representing a set number of "things".
- !!! warning
+ .. warning::
Some semantics such as subtype checking and instance checking may
differ. It is recommended to compare these values using the
`==` operator rather than the `is` operator for safety reasons.
@@ -224,49 +225,49 @@ class Enum(metaclass=_EnumMeta):
* ` __objtype__` :
Always the first type that the enum is derived from. For example:
- ```py
- >>> class UserType(str, Enum):
- ... USER = "user"
- ... PARTIAL = "partial"
- ... MEMBER = "member"
- >>> print(UserType.__objtype__)
-
- ```
+ .. code-block:: python
+
+ >>> class UserType(str, Enum):
+ ... USER = "user"
+ ... PARTIAL = "partial"
+ ... MEMBER = "member"
+ >>> print(UserType.__objtype__)
+
Operators on the class
----------------------
* `EnumType["FOO"]` :
- Return the member that has the name `FOO`, raising a `builtins.KeyError`
+ Return the member that has the name `FOO`, raising a `KeyError`
if it is not present.
* `EnumType.FOO` :
Return the member that has the name `FOO`, raising a
- `builtins.AttributeError` if it is not present.
+ `AttributeError` if it is not present.
* `EnumType(x)` :
Attempt to cast `x` to the enum type by finding an existing member that
has the same __value__. If this fails, you should expect a
- `builtins.ValueError` to be raised.
+ `ValueError` to be raised.
Operators on each enum member
-----------------------------
- * `e1 == e2` : `builtins.bool`
+ * `e1 == e2` : `bool`
Compare equality.
- * `e1 != e2` : `builtins.bool`
+ * `e1 != e2` : `bool`
Compare inequality.
- * `builtins.repr(e)` : `builtins.str`
+ * `repr(e)` : `str`
Get the machine readable representation of the enum member `e`.
- * `builtins.str(e)` : `builtins.str`
- Get the `builtins.str` name of the enum member `e`.
+ * `str(e)` : `str`
+ Get the `str` name of the enum member `e`.
Special properties on each enum member
--------------------------------------
- * `name` : `builtins.str`
+ * `name` : `str`
The name of the member.
* `value` :
The value of the member. The type depends on the implementation type
of the enum you are using.
All other methods and operators on enum members are inherited from the
- member's __value__. For example, an enum extending `builtins.int` would
+ member's __value__. For example, an enum extending `int` would
be able to be used as an `int` type outside these overridden definitions.
"""
@@ -281,7 +282,7 @@ class Enum(metaclass=_EnumMeta):
@property
def name(self) -> str:
- """Return the name of the enum member as a `builtins.str`."""
+ """Return the name of the enum member as a `str`."""
return self._name_
@property
@@ -322,6 +323,7 @@ def _name_resolver(members: typing.Dict[int, _Flag], value: int) -> typing.Gener
class _FlagMeta(type):
def __call__(cls, value: int = 0) -> typing.Any:
+ """Cast a value to the flag enum, returning the raw value that was passed if values not found."""
# We want to handle value invariantly to avoid issues brought in by different behaviours from sub-classed ints
# and floats. This also ensures that .__int__ only returns an invariant int.
value = int(value)
@@ -455,23 +457,20 @@ class Flag(metaclass=_FlagMeta):
implementation, while retaining the majority of the external interface
that Python's `enum.Flag` provides.
- In simple terms, an `Flag` is a set of wrapped constant `builtins.int`
+ In simple terms, an `Flag` is a set of wrapped constant `int`
values that can be combined in any combination to make a special value.
This is a more efficient way of combining things like permissions together
- into a single integral value, and works by setting individual `1`s and `0`s
+ into a single integral value, and works by setting the individual `1` and `0`
on the binary representation of the integer.
This implementation has extra features, in that it will actively behave
- like a `builtins.set` as well.
-
- !!! warning
- Despite wrapping `builtins.int` values, conceptually this does not
- behave as if it were a subclass of `int`.
+ like a `set` as well.
- !!! danger
- Some semantics such as subtype checking and instance checking may
- differ. It is recommended to compare these values using the
- `==` operator rather than the `is` operator for safety reasons.
+ .. warning::
+ It is important to keep in mind that some semantics such as subtype
+ checking and instance checking may differ. It is recommended to compare
+ these values using the `==` operator rather than the `is` operator for
+ safety reasons.
Especially where pseudo-members created from combinations are cached,
results of using of `is` may not be deterministic. This is a side
@@ -480,6 +479,9 @@ class Flag(metaclass=_FlagMeta):
Failing to observe this __will__ result in unexpected behaviour
occurring in your application!
+ Also important to note is that despite wrapping `int` values,
+ conceptually this does not behave as if it were a subclass of `int`.
+
Special Members on the class
----------------------------
* `__enumtype__` :
@@ -490,16 +492,16 @@ class Flag(metaclass=_FlagMeta):
An immutable `typing.Mapping` that maps each member name to the member
value.
* ` __objtype__` :
- Always `builtins.int`.
+ Always `int`.
Operators on the class
----------------------
* `FlagType["FOO"]` :
- Return the member that has the name `FOO`, raising a `builtins.KeyError`
+ Return the member that has the name `FOO`, raising a `KeyError`
if it is not present.
* `FlagType.FOO` :
Return the member that has the name `FOO`, raising a
- `builtins.AttributeError` if it is not present.
+ `AttributeError` if it is not present.
* `FlagType(x)` :
Attempt to cast `x` to the enum type by finding an existing member that
has the same __value__. If this fails, then a special __composite__
@@ -511,17 +513,17 @@ class Flag(metaclass=_FlagMeta):
* `e1 & e2` :
Bitwise `AND` operation. Will return a member that contains all flags
that are common between both oprands on the values. This also works with
- one of the oprands being an `builtins.int`eger. You may instead use
+ one of the oprands being an `int`eger. You may instead use
the `intersection` method.
* `e1 | e2` :
Bitwise `OR` operation. Will return a member that contains all flags
that appear on at least one of the oprands. This also works with
- one of the oprands being an `builtins.int`eger. You may instead use
+ one of the oprands being an `int`eger. You may instead use
the `union` method.
* `e1 ^ e2` :
Bitwise `XOR` operation. Will return a member that contains all flags
that only appear on at least one and at most one of the oprands.
- This also works with one of the oprands being an `builtins.int`eger.
+ This also works with one of the oprands being an `int`eger.
You may instead use the `symmetric_difference` method.
* `~e` :
Return the inverse of this value. This is equivalent to disabling all
@@ -532,11 +534,11 @@ class Flag(metaclass=_FlagMeta):
Bitwise set difference operation. Returns all flags set on `e1` that are
not set on `e2` as well. You may instead use the `difference`
method.
- * `bool(e)` : `builtins.bool`
- Return `builtins.True` if `e` has a non-zero value, otherwise
- `builtins.False`.
- * `E.A in e`: `builtins.bool`
- `builtins.True` if `E.A` is in `e`. This is functionally equivalent
+ * `bool(e)` : `bool`
+ Return `True` if `e` has a non-zero value, otherwise
+ `False`.
+ * `E.A in e`: `bool`
+ `True` if `E.A` is in `e`. This is functionally equivalent
to `E.A & e == E.A`.
* `iter(e)` :
Explode the value into a iterator of each __documented__ flag that can
@@ -546,36 +548,36 @@ class Flag(metaclass=_FlagMeta):
powers of two (this means if converted to twos-compliment binary,
exactly one bit must be a `1`). In simple terms, this means that you
should not expect combination flags to be returned.
- * `e1 == e2` : `builtins.bool`
+ * `e1 == e2` : `bool`
Compare equality.
- * `e1 != e2` : `builtins.bool`
+ * `e1 != e2` : `bool`
Compare inequality.
- * `e1 < e2` : `builtins.bool`
+ * `e1 < e2` : `bool`
Compare by ordering.
- * `builtins.int(e)` : `builtins.int`
+ * `int(e)` : `int`
Get the integer value of this flag
- * `builtins.repr(e)` : `builtins.str`
+ * `repr(e)` : `str`
Get the machine readable representation of the flag member `e`.
- * `builtins.str(e)` : `builtins.str`
- Get the `builtins.str` name of the flag member `e`.
+ * `str(e)` : `str`
+ Get the `str` name of the flag member `e`.
Special properties on each flag member
--------------------------------------
- * `e.name` : `builtins.str`
+ * `e.name` : `str`
The name of the member. For composite members, this will be generated.
- * `e.value` : `builtins.int`
+ * `e.value` : `int`
The value of the member.
Special members on each flag member
-----------------------------------
- * `e.all(E.A, E.B, E.C, ...)` : `builtins.bool`
- Returns `builtins.True` if __all__ of `E.A`, `E.B`, `E.C`, et cetera
+ * `e.all(E.A, E.B, E.C, ...)` : `bool`
+ Returns `True` if __all__ of `E.A`, `E.B`, `E.C`, et cetera
make up the value of `e`.
- * `e.any(E.A, E.B, E.C, ...)` : `builtins.bool`
- Returns `builtins.True` if __any__ of `E.A`, `E.B`, `E.C`, et cetera
+ * `e.any(E.A, E.B, E.C, ...)` : `bool`
+ Returns `True` if __any__ of `E.A`, `E.B`, `E.C`, et cetera
make up the value of `e`.
- * `e.none(E.A, E.B, E.C, ...)` : `builtins.bool`
- Returns `builtins.True` if __none__ of `E.A`, `E.B`, `E.C`, et cetera
+ * `e.none(E.A, E.B, E.C, ...)` : `bool`
+ Returns `True` if __none__ of `E.A`, `E.B`, `E.C`, et cetera
make up the value of `e`.
* `e.split()` : `typing.Sequence`
Explode the value into a sequence of each __documented__ flag that can
@@ -586,7 +588,7 @@ class Flag(metaclass=_FlagMeta):
All other methods and operators on `Flag` members are inherited from the
member's __value__.
- !!! note
+ .. note::
Due to limitations around how this is re-implemented, this class is not
considered a subclass of `Enum` at runtime, even if MyPy believes this
is possible
@@ -605,14 +607,14 @@ class Flag(metaclass=_FlagMeta):
@property
def name(self) -> str:
- """Return the name of the flag combination as a `builtins.str`."""
+ """Return the name of the flag combination as a `str`."""
if self._name_ is None:
self._name_ = "|".join(_name_resolver(self._value_to_member_map_, self._value_))
return self._name_
@property
def value(self) -> int:
- """Return the `builtins.int` value of the flag."""
+ """Return the `int` value of the flag."""
return self._value_
def all(self: _T, *flags: _T) -> bool:
@@ -620,9 +622,9 @@ def all(self: _T, *flags: _T) -> bool:
Returns
-------
- builtins.bool
- `builtins.True` if any of the given flags are part of this value.
- Otherwise, return `builtins.False`.
+ bool
+ `True` if any of the given flags are part of this value.
+ Otherwise, return `False`.
"""
return all((flag & self) == flag for flag in flags)
@@ -631,9 +633,9 @@ def any(self: _T, *flags: _T) -> bool:
Returns
-------
- builtins.bool
- `builtins.True` if any of the given flags are part of this value.
- Otherwise, return `builtins.False`.
+ bool
+ `True` if any of the given flags are part of this value.
+ Otherwise, return `False`.
"""
return any((flag & self) == flag for flag in flags)
@@ -661,8 +663,8 @@ def is_disjoint(self: _T, other: typing.Union[_T, int]) -> bool:
"""Return whether two sets have a intersection or not.
If the two sets have an intersection, then this returns
- `builtins.False`. If no common flag values exist between them, then
- this returns `builtins.True`.
+ `False`. If no common flag values exist between them, then
+ this returns `True`.
"""
return not (self & other)
@@ -680,14 +682,14 @@ def is_superset(self: _T, other: typing.Union[_T, int]) -> bool:
def none(self: _T, *flags: _T) -> bool:
"""Check if none of the given flags are part of this value.
- !!! note
+ .. note::
This is essentially the opposite of `Flag.any`.
Returns
-------
- builtins.bool
- `builtins.True` if none of the given flags are part of this value.
- Otherwise, return `builtins.False`.
+ bool
+ `True` if none of the given flags are part of this value.
+ Otherwise, return `False`.
"""
return not self.any(*flags)
diff --git a/hikari/internal/fast_protocol.py b/hikari/internal/fast_protocol.py
index 5cc27a5cb4..289267ee77 100644
--- a/hikari/internal/fast_protocol.py
+++ b/hikari/internal/fast_protocol.py
@@ -105,7 +105,7 @@ def __instancecheck__(self: _T, other: typing.Any) -> bool:
class FastProtocolChecking(typing.Protocol, metaclass=_FastProtocolChecking):
"""An extension to make protocols with faster instance checks.
- !!! note
+ .. note::
All protocols that subclass this class must be decorated with
`@typing.runtime_checkable` to keep mypy happy.
"""
diff --git a/hikari/internal/mentions.py b/hikari/internal/mentions.py
index 964579cd2c..6494e9203f 100644
--- a/hikari/internal/mentions.py
+++ b/hikari/internal/mentions.py
@@ -46,19 +46,19 @@ def generate_allowed_mentions(
Parameters
----------
- mentions_everyone : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_everyone : hikari.undefined.UndefinedOr[bool]
Whether @everyone and @here mentions are enabled. If
- `hikari.undefined.UNDEFINED` or `builtins.False` then this will be disabled.
- mentions_reply : hikari.undefined.UndefinedOr[builtins.bool]
+ `hikari.undefined.UNDEFINED` or `False` then this will be disabled.
+ mentions_reply : hikari.undefined.UndefinedOr[bool]
Whether the reply mention should be enabled. If `hikari.undefined.UNDEFINED`
- or `builtins.False` then this will be disabled.
- user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
+ or `False` then this will be disabled.
+ user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], bool]]
Either a sequence of objects/IDs of the users to enabled mentions for,
- `True` to allow all mentions or `builtins.False`/`hikari.undefined.UNDEFINED`
+ `True` to allow all mentions or `False`/`hikari.undefined.UNDEFINED`
to disable all user mentions.
- role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], builtins.bool]]
+ role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], bool]]
Either a sequence of objects/IDs of the roles to enabled mentions for,
- `True` to allow all mentions or `builtins.False`/`hikari.undefined.UNDEFINED`
+ `True` to allow all mentions or `False`/`hikari.undefined.UNDEFINED`
to disable all user mentions.
Returns
@@ -78,14 +78,14 @@ def generate_allowed_mentions(
if user_mentions is True:
parsed_mentions.append("users")
elif isinstance(user_mentions, typing.Collection):
- # Duplicates will cause discord to error.
+ # Duplicates will cause Discord to error.
ids = {str(int(u)) for u in user_mentions}
allowed_mentions["users"] = list(ids)
if role_mentions is True:
parsed_mentions.append("roles")
elif isinstance(role_mentions, typing.Collection):
- # Duplicates will cause discord to error.
+ # Duplicates will cause Discord to error.
ids = {str(int(r)) for r in role_mentions}
allowed_mentions["roles"] = list(ids)
diff --git a/hikari/internal/net.py b/hikari/internal/net.py
index 3aa1ffc89a..59243fd36c 100644
--- a/hikari/internal/net.py
+++ b/hikari/internal/net.py
@@ -90,12 +90,12 @@ def create_tcp_connector(
Optional Parameters
-------------------
- dns_cache: typing.Union[builtins.None, builtins.bool, int]
- If `builtins.True`, DNS caching is used with a default TTL of 10 seconds.
- If `builtins.False`, DNS caching is disabled. If an `builtins.int` is
+ dns_cache: typing.Union[None, bool, int]
+ If `True`, DNS caching is used with a default TTL of 10 seconds.
+ If `False`, DNS caching is disabled. If an `int` is
given, then DNS caching is enabled with an explicit TTL set. If
- `builtins.None`, the cache will be enabled and never invalidate.
- limit : builtins.int
+ `None`, the cache will be enabled and never invalidate.
+ limit : int
Number of connections to allow in the pool at a maximum.
Returns
@@ -122,10 +122,10 @@ def create_client_session(
) -> aiohttp.ClientSession:
"""Generate a client session using the given settings.
- !!! warning
+ .. warning::
You must invoke this from within a running event loop.
- !!! note
+ .. note::
If you pass an explicit connector, then the connection
that is created will not own the connector. You will be
expected to manually close it __after__ the returned
@@ -135,17 +135,17 @@ def create_client_session(
----------
connector : aiohttp.BaseConnector
The connector to use.
- connector_owner : builtins.bool
- If `builtins.True`, then the client session will close the
- connector on shut down. Otherwise, you must do it manually.
- http_settings : hikari.config.HTTPSettings
+ connector_owner : bool
+ If `True`, then the client session will close the
+ connector on shutdown. Otherwise, you must do it manually.
+ http_settings : hikari.impl.config.HTTPSettings
HTTP settings to use.
- raise_for_status : builtins.bool
- `builtins.True` to default to throwing exceptions if a request
- fails, or `builtins.False` to default to not.
- trust_env : builtins.bool
- `builtins.True` to trust anything in environment variables
- and the `netrc` file, `builtins.False` to ignore it.
+ raise_for_status : bool
+ `True` to default to throwing exceptions if a request
+ fails, or `False` to default to not.
+ trust_env : bool
+ `True` to trust anything in environment variables
+ and the `netrc` file, `False` to ignore it.
Returns
-------
diff --git a/hikari/internal/reflect.py b/hikari/internal/reflect.py
index 627cfa4f42..f2c5b7b152 100644
--- a/hikari/internal/reflect.py
+++ b/hikari/internal/reflect.py
@@ -41,16 +41,16 @@
def resolve_signature(func: typing.Callable[..., typing.Any]) -> inspect.Signature:
"""Get the `inspect.Signature` of `func` with resolved forward annotations.
+ .. warning::
+ This will use `eval` to resolve string type-hints and forward
+ references. This has a slight performance overhead, so attempt to cache
+ this info as much as possible.
+
Parameters
----------
func : typing.Callable[..., typing.Any]
The function to get the resolved annotations from.
- !!! warning
- This will use `builtins.eval` to resolve string type-hints and forward
- references. This has a slight performance overhead, so attempt to cache
- this info as much as possible.
-
Returns
-------
inspect.Signature
@@ -84,7 +84,7 @@ def profiled(call: typing.Callable[..., _T]) -> typing.Callable[..., _T]: # pra
Profile results are dumped to stdout.
- !!! warning
+ .. warning::
This is NOT part of the public API. It should be considered to be
internal detail and will likely be removed without prior warning in
the future. You have been warned!
diff --git a/hikari/internal/routes.py b/hikari/internal/routes.py
index 561a8d5089..210cd9899e 100644
--- a/hikari/internal/routes.py
+++ b/hikari/internal/routes.py
@@ -78,12 +78,12 @@ def create_url(self, base_url: str) -> str:
Parameters
----------
- base_url : builtins.str
+ base_url : str
The base of the URL to prepend to the compiled path.
Returns
-------
- builtins.str
+ str
The full URL for the route.
"""
return base_url + self.compiled_path
@@ -96,13 +96,13 @@ def create_real_bucket_hash(self, initial_bucket_hash: str) -> str:
Parameters
----------
- initial_bucket_hash : builtins.str
+ initial_bucket_hash : str
The initial bucket hash provided by Discord in the HTTP headers
for a given response.
Returns
-------
- builtins.str
+ str
The input hash amalgamated with a hash code produced by the
major parameters in this compiled route instance.
"""
@@ -123,9 +123,9 @@ class Route:
Parameters
----------
- method : builtins.str
- The HTTP method
- path_template : builtins.str
+ method : str
+ The HTTP method.
+ path_template : str
The template string for the path to use.
"""
@@ -192,10 +192,7 @@ class CDNRoute:
"""Template string for this endpoint."""
valid_formats: typing.AbstractSet[str] = attr.field(
- converter=_cdn_valid_formats_converter,
- eq=False,
- hash=False,
- repr=False,
+ converter=_cdn_valid_formats_converter, eq=False, hash=False, repr=False
)
"""Valid file formats for this endpoint."""
@@ -204,8 +201,8 @@ def _(self, _: attr.Attribute[typing.AbstractSet[str]], values: typing.AbstractS
if not values:
raise ValueError(f"{self.path_template} must have at least one valid format set")
- sizable: bool = attr.field(default=True, kw_only=True, repr=False, hash=False, eq=False)
- """`builtins.True` if a `size` param can be specified, or `builtins.False` otherwise."""
+ is_sizable: bool = attr.field(default=True, kw_only=True, repr=False, hash=False, eq=False)
+ """Whether a `size` param can be specified."""
def compile(
self,
@@ -219,30 +216,29 @@ def compile(
Parameters
----------
- base_url : builtins.str
+ base_url : str
The base URL for the CDN. The generated route is concatenated onto
this.
- file_format : builtins.str
+ file_format : str
The file format to use for the asset.
- size : typing.Optional[builtins.int]
- The custom size query parameter to set. If `builtins.None`,
+ size : typing.Optional[int]
+ The custom size query parameter to set. If `None`,
it is not passed.
**kwargs : typing.Any
Parameters to interpolate into the path template.
Returns
-------
- builtins.str
+ str
The full asset URL.
Raises
------
- builtins.TypeError
+ TypeError
If a GIF is requested, but the asset is not animated;
if an invalid file format for the endpoint is passed; or if a `size`
- is passed but the route is not `sizable`.
-
- builtins.ValueError
+ is passed but the route is not sizable.
+ ValueError
If `size` is specified, but is not an integer power of `2` between
`16` and `4096` inclusive or is negative.
"""
@@ -262,7 +258,7 @@ def compile(
url = base_url + self.path_template.format(**kwargs) + f".{file_format}"
if size is not None:
- if not self.sizable:
+ if not self.is_sizable:
raise TypeError("This asset cannot be resized.")
if size < 0:
@@ -563,7 +559,7 @@ def compile_to_file(
)
CDN_GUILD_BANNER: typing.Final[CDNRoute] = CDNRoute("/banners/{guild_id}/{hash}", {PNG, *JPEG_JPG, WEBP, GIF})
-CDN_DEFAULT_USER_AVATAR: typing.Final[CDNRoute] = CDNRoute("/embed/avatars/{discriminator}", {PNG}, sizable=False)
+CDN_DEFAULT_USER_AVATAR: typing.Final[CDNRoute] = CDNRoute("/embed/avatars/{discriminator}", {PNG}, is_sizable=False)
CDN_USER_AVATAR: typing.Final[CDNRoute] = CDNRoute("/avatars/{user_id}/{hash}", {PNG, *JPEG_JPG, WEBP, GIF})
CDN_USER_BANNER: typing.Final[CDNRoute] = CDNRoute("/banners/{user_id}/{hash}", {PNG, *JPEG_JPG, WEBP, GIF})
CDN_MEMBER_AVATAR: typing.Final[CDNRoute] = CDNRoute(
@@ -583,7 +579,7 @@ def compile_to_file(
# undocumented on the Discord docs.
CDN_CHANNEL_ICON: typing.Final[CDNRoute] = CDNRoute("/channel-icons/{channel_id}/{hash}", {PNG, *JPEG_JPG, WEBP})
-CDN_STICKER: typing.Final[CDNRoute] = CDNRoute("/stickers/{sticker_id}", {PNG, LOTTIE}, sizable=False)
+CDN_STICKER: typing.Final[CDNRoute] = CDNRoute("/stickers/{sticker_id}", {PNG, LOTTIE}, is_sizable=False)
CDN_STICKER_PACK_BANNER: typing.Final[CDNRoute] = CDNRoute(
"/app-assets/710982414301790216/store/{hash}", {PNG, *JPEG_JPG, WEBP}
)
diff --git a/hikari/internal/time.py b/hikari/internal/time.py
index 72f59b4b8c..17c1df0a69 100644
--- a/hikari/internal/time.py
+++ b/hikari/internal/time.py
@@ -49,7 +49,7 @@
This is a type that is like an interval of some sort.
This is an alias for `typing.Union[int, float, datetime.datetime]`,
-where `builtins.int` and `builtins.float` types are interpreted as a number of seconds.
+where `int` and `float` types are interpreted as a number of seconds.
"""
DISCORD_EPOCH: typing.Final[datetime.timedelta] = datetime.timedelta(seconds=1_420_070_400)
@@ -71,7 +71,7 @@ def slow_iso8601_datetime_string_to_datetime(datetime_str: str) -> datetime.date
Parameters
----------
- datetime_str : builtins.str
+ datetime_str : str
The date string to parse.
Returns
@@ -110,7 +110,7 @@ def discord_epoch_to_datetime(epoch: int, /) -> datetime.datetime:
Parameters
----------
- epoch : builtins.int
+ epoch : int
Number of milliseconds since `1/1/2015 00:00:00 UTC`.
Returns
@@ -122,7 +122,7 @@ def discord_epoch_to_datetime(epoch: int, /) -> datetime.datetime:
def datetime_to_discord_epoch(timestamp: datetime.datetime) -> int:
- """Parse a `datetime.datetime` object into an `builtins.int` `DISCORD_EPOCH` offset.
+ """Parse a `datetime.datetime` object into an `int` `DISCORD_EPOCH` offset.
Parameters
----------
@@ -131,7 +131,7 @@ def datetime_to_discord_epoch(timestamp: datetime.datetime) -> int:
Returns
-------
- builtins.int
+ int
Number of milliseconds since `1/1/2015 00:00:00 UTC`.
"""
return int((timestamp - DISCORD_EPOCH).timestamp() * 1_000)
@@ -140,18 +140,18 @@ def datetime_to_discord_epoch(timestamp: datetime.datetime) -> int:
def unix_epoch_to_datetime(epoch: typing.Union[int, float], /, *, is_millis: bool = True) -> datetime.datetime:
"""Parse a UNIX epoch to a `datetime.datetime` object.
- !!! note
+ .. note::
If an epoch that's outside the range of what this system can handle,
this will return `datetime.datetime.max` if the timestamp is positive,
or `datetime.datetime.min` otherwise.
Parameters
----------
- epoch : typing.Union[builtins.int, builtins.float]
+ epoch : typing.Union[int, float]
Number of seconds/milliseconds since `1/1/1970 00:00:00 UTC`.
- is_millis : builtins.bool
- `builtins.True` by default, indicates the input timestamp is measured in
- milliseconds rather than seconds
+ is_millis : bool
+ `True` by default, indicates the input timestamp is measured in
+ milliseconds rather than seconds.
Returns
-------
@@ -180,7 +180,7 @@ def timespan_to_int(value: Intervalish, /) -> int:
Returns
-------
- builtins.int
+ int
The integer number of seconds. Fractions are discarded. Negative values
are removed.
"""
diff --git a/hikari/internal/ux.py b/hikari/internal/ux.py
index b3be760daa..9252b81421 100644
--- a/hikari/internal/ux.py
+++ b/hikari/internal/ux.py
@@ -72,28 +72,28 @@ def init_logging(
Parameters
----------
- flavor : typing.Optional[builtins.None, builtins.str, typing.Dict[builtins.str, typing.Any]]
+ flavor : typing.Optional[None, str, typing.Dict[str, typing.Any]]
The hint for configuring logging.
- This can be `builtins.None` to not enable logging automatically.
+ This can be `None` to not enable logging automatically.
- If you pass a `builtins.str` or a `builtins.int`, it is interpreted as
+ If you pass a `str` or a `int`, it is interpreted as
the global logging level to use, and should match one of `"DEBUG"`,
- `"INFO"`, `"WARNING"`, `"ERROR"` or `"CRITICAL"`, if `builtins.str`.
+ `"INFO"`, `"WARNING"`, `"ERROR"` or `"CRITICAL"`, if `str`.
The configuration will be set up to use a `colorlog` coloured logger,
and to use a sane logging format strategy. The output will be written
to `sys.stderr` using this configuration.
- If you pass a `builtins.dict`, it is treated as the mapping to pass to
+ If you pass a `dict`, it is treated as the mapping to pass to
`logging.config.dictConfig`. If the dict defines any handlers, default
handlers will not be setup.
- allow_color : builtins.bool
- If `builtins.False`, no colour is allowed. If `builtins.True`, the
- output device must be supported for this to return `builtins.True`.
- force_color : builtins.bool
- If `builtins.True`, return `builtins.True` always, otherwise only
- return `builtins.True` if the device supports colour output and the
- `allow_color` flag is not `builtins.False`.
+ allow_color : bool
+ If `False`, no colour is allowed. If `True`, the
+ output device must be supported for this to return `True`.
+ force_color : bool
+ If `True`, return `True` always, otherwise only
+ return `True` if the device supports colour output and the
+ `allow_color` flag is not `False`.
"""
# One observation that has been repeatedly made from seeing beginners writing
# bots in Python is that most people seem to have no idea what logging is or
@@ -165,31 +165,31 @@ def print_banner(
Inspired by Spring Boot, we display an ASCII logo on startup. This is styled
to grab the user's attention, and contains info such as the library version,
the Python interpreter, the OS, and links to our Discord server and
- documentation. Users can override this by placing a `banner.txt' in some
+ documentation. Users can override this by placing a `banner.txt` in some
package and referencing it in this call.
+ .. note::
+ The `banner.txt` must be in the root folder of the package.
+
Parameters
----------
- package : typing.Optional[builtins.str]
- The package to find the `banner.txt` in, or `builtins.None` if no
+ package : typing.Optional[str]
+ The package to find the `banner.txt` in, or `None` if no
banner should be shown.
-
- !!! note
- The `banner.txt` must be in the root folder of the package.
- allow_color : builtins.bool
- If `builtins.False`, no colour is allowed. If `builtins.True`, the
- output device must be supported for this to return `builtins.True`.
- force_color : builtins.bool
- If `builtins.True`, return `builtins.True` always, otherwise only
- return `builtins.True` if the device supports colour output and the
- `allow_color` flag is not `builtins.False`.
- extra_args : typing.Optional[typing.Dict[builtins.str, builtins.str]]
+ allow_color : bool
+ If `False`, no colour is allowed. If `True`, the
+ output device must be supported for this to return `True`.
+ force_color : bool
+ If `True`, return `True` always, otherwise only
+ return `True` if the device supports colour output and the
+ `allow_color` flag is not `False`.
+ extra_args : typing.Optional[typing.Dict[str, str]]
If provided, extra $-substitutions to use when printing the banner.
Default substitutions can not be overwritten.
Raises
------
- builtins.ValueError
+ ValueError
If `extra_args` contains a default $-substitution.
"""
if package is None:
@@ -234,23 +234,23 @@ def print_banner(
def supports_color(allow_color: bool, force_color: bool) -> bool:
- """Return `builtins.True` if the terminal device supports color output.
+ """Return `True` if the terminal device supports color output.
Parameters
----------
- allow_color : builtins.bool
- If `builtins.False`, no color is allowed. If `builtins.True`, the
- output device must be supported for this to return `builtins.True`.
- force_color : builtins.bool
- If `builtins.True`, return `builtins.True` always, otherwise only
- return `builtins.True` if the device supports color output and the
- `allow_color` flag is not `builtins.False`.
+ allow_color : bool
+ If `False`, no color is allowed. If `True`, the
+ output device must be supported for this to return `True`.
+ force_color : bool
+ If `True`, return `True` always, otherwise only
+ return `True` if the device supports color output and the
+ `allow_color` flag is not `False`.
Returns
-------
- builtins.bool
- `builtins.True` if color is allowed on the output terminal, or
- `builtins.False` otherwise.
+ bool
+ `True` if color is allowed on the output terminal, or
+ `False` otherwise.
"""
if not allow_color:
return False
@@ -374,22 +374,21 @@ async def check_for_updates(http_settings: config.HTTPSettings, proxy_settings:
this_version = HikariVersion(about.__version__)
is_dev = this_version.prerelease is not None
- newer_releases: typing.List[HikariVersion] = []
+ newest_version: typing.Optional[HikariVersion] = None
for release_string, artifacts in data["releases"].items():
if not all(artifact["yanked"] for artifact in artifacts):
v = HikariVersion(release_string)
- if v.prerelease is not None and not is_dev:
- # Don't encourage the user to upgrade from a stable to a dev release...
+ if (v.prerelease is not None and not is_dev) or v <= this_version:
+ # Don't encourage the user to upgrade from a stable to a dev release, nor a lower version...
continue
- if v == this_version:
+ if newest_version is not None and newest_version > v:
continue
- if v > this_version:
- newer_releases.append(v)
- if newer_releases:
- newest = max(newer_releases)
- _LOGGER.info("A newer version of hikari is available, consider upgrading to %s", newest)
+ newest_version = v
+
+ if newest_version:
+ _LOGGER.info("A newer version of hikari is available, consider upgrading to %s", newest_version)
except Exception as ex:
_LOGGER.debug("Failed to fetch hikari version details", exc_info=ex)
diff --git a/hikari/invites.py b/hikari/invites.py
index 79b424be03..4423d060c7 100644
--- a/hikari/invites.py
+++ b/hikari/invites.py
@@ -74,13 +74,7 @@ class InviteCode(abc.ABC):
@property
@abc.abstractmethod
def code(self) -> str:
- """Return the code for this invite.
-
- Returns
- -------
- builtins.str
- The invite code that can be appended to a URL.
- """
+ """Code for this invite."""
def __str__(self) -> str:
return f"https://discord.gg/{self.code}"
@@ -94,7 +88,7 @@ class VanityURL(InviteCode):
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
code: str = attr.field(hash=True, repr=True)
"""The code for this invite."""
@@ -117,14 +111,14 @@ class InviteGuild(guilds.PartialGuild):
"""The hash for the guild's banner.
This is only present if `hikari.guilds.GuildFeature.BANNER` is in the
- `features` for this guild. For all other purposes, it is `builtins.None`.
+ `features` for this guild. For all other purposes, it is `None`.
"""
description: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
"""The guild's description.
This is only present if certain `features` are set in this guild.
- Otherwise, this will always be `builtins.None`. For all other purposes, it is `builtins.None`.
+ Otherwise, this will always be `None`. For all other purposes, it is `None`.
"""
verification_level: typing.Union[guilds.GuildVerificationLevel, int] = attr.field(eq=False, hash=False, repr=False)
@@ -134,7 +128,7 @@ class InviteGuild(guilds.PartialGuild):
"""The vanity URL code for the guild's vanity URL.
This is only present if `hikari.guilds.GuildFeature.VANITY_URL` is in the
- `features` for this guild. If not, this will always be `builtins.None`.
+ `features` for this guild. If not, this will always be `None`.
"""
welcome_screen: typing.Optional[guilds.WelcomeScreen] = attr.field(eq=False, hash=False, repr=False)
@@ -153,21 +147,21 @@ def make_splash_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optio
Parameters
----------
- ext : builtins.str
+ ext : str
The extension to use for this URL, defaults to `png`.
Supports `png`, `jpeg`, `jpg` and `webp`.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Returns
-------
typing.Optional[hikari.files.URL]
- The URL to the splash, or `builtins.None` if not set.
+ The URL to the splash, or `None` if not set.
Raises
------
- builtins.ValueError
+ ValueError
If `size` is not a power of two or not between 16 and 4096.
"""
if self.splash_hash is None:
@@ -191,25 +185,25 @@ def make_banner_url(self, *, ext: typing.Optional[str] = None, size: int = 4096)
Parameters
----------
- ext : typing.Optional[builtins.str]
+ ext : typing.Optional[str]
The ext to use for this URL, defaults to `png` or `gif`.
Supports `png`, `jpeg`, `jpg`, `webp` and `gif` (when
animated).
- If `builtins.None`, then the correct default extension is
+ If `None`, then the correct default extension is
determined based on whether the banner is animated or not.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Returns
-------
typing.Optional[hikari.files.URL]
- The URL of the banner, or `builtins.None` if no banner is set.
+ The URL of the banner, or `None` if no banner is set.
Raises
------
- builtins.ValueError
+ ValueError
If `size` is not a power of two or not between 16 and 4096.
"""
if self.banner_hash is None:
@@ -239,7 +233,7 @@ class Invite(InviteCode):
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
code: str = attr.field(hash=True, repr=True)
"""The code for this invite."""
@@ -247,20 +241,20 @@ class Invite(InviteCode):
guild: typing.Optional[InviteGuild] = attr.field(eq=False, hash=False, repr=False)
"""The partial object of the guild this invite belongs to.
- Will be `builtins.None` for group DM invites and when attached to a gateway event;
+ Will be `None` for group DM invites and when attached to a gateway event;
for invites received over the gateway you should refer to `Invite.guild_id`.
"""
guild_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=True)
"""The ID of the guild this invite belongs to.
- Will be `builtins.None` for group DM invites.
+ Will be `None` for group DM invites.
"""
channel: typing.Optional[channels.PartialChannel] = attr.field(eq=False, hash=False, repr=False)
"""The partial object of the channel this invite targets.
- Will be `builtins.None` for invite objects that are attached to gateway events,
+ Will be `None` for invite objects that are attached to gateway events,
in which case you should refer to `Invite.channel_id`.
"""
@@ -295,8 +289,8 @@ class Invite(InviteCode):
"""When this invite will expire.
This field is only returned by the GET Invite REST endpoint and will be
- returned as `builtins.None` by said endpoint if the invite doesn't have a set
- expiry date. Other places will always return this as `builtins.None`.
+ returned as `None` by said endpoint if the invite doesn't have a set
+ expiry date. Other places will always return this as `None`.
"""
@@ -314,7 +308,7 @@ class InviteWithMetadata(Invite):
max_uses: typing.Optional[int] = attr.field(eq=False, hash=False, repr=True)
"""The limit for how many times this invite can be used before it expires.
- If set to `builtins.None` then this is unlimited.
+ If set to `None` then this is unlimited.
"""
# TODO: can we use a non-None value to represent infinity here somehow, or
@@ -322,7 +316,7 @@ class InviteWithMetadata(Invite):
max_age: typing.Optional[datetime.timedelta] = attr.field(eq=False, hash=False, repr=False)
"""The timedelta of how long this invite will be valid for.
- If set to `builtins.None` then this is unlimited.
+ If set to `None` then this is unlimited.
"""
is_temporary: bool = attr.field(eq=False, hash=False, repr=True)
@@ -334,18 +328,14 @@ class InviteWithMetadata(Invite):
expires_at: typing.Optional[datetime.datetime]
"""When this invite will expire.
- If this invite doesn't have a set expiry then this will be `builtins.None`.
+ If this invite doesn't have a set expiry then this will be `None`.
"""
@property
def uses_left(self) -> typing.Optional[int]:
"""Return the number of uses left for this invite.
- Returns
- -------
- typing.Optional[builtins.int]
- The number of uses left for this invite. This will be `builtins.None`
- if the invite has unlimited uses.
+ This will be `None` if the invite has unlimited uses.
"""
if self.max_uses:
return self.max_uses - self.uses
diff --git a/hikari/iterators.py b/hikari/iterators.py
index 8b83de560a..2137c19b79 100644
--- a/hikari/iterators.py
+++ b/hikari/iterators.py
@@ -54,47 +54,49 @@ class All(typing.Generic[ValueT]):
"""Helper that wraps predicates and invokes them together.
Calling this object will pass the input item to each item, returning
- `builtins.True` only when all wrapped predicates return True when called
+ `True` only when all wrapped predicates return True when called
with the given item.
For example...
- ```py
- if w(foo) and x(foo) andy(foo) and z(foo):
- ...
- ```
+ .. code-block:: python
+
+ if w(foo) and x(foo) and y(foo) and z(foo):
+ ...
+
is equivalent to
- ```py
- condition = All([w, x, y, z])
- if condition(foo):
- ...
- ```
+ .. code-block:: python
- This behaves like a lazy wrapper implementation of the `builtins.all` builtin.
+ condition = All([w, x, y, z])
- !!! note
+ if condition(foo):
+ ...
+
+ This behaves like a lazy wrapper implementation of the `all` builtin.
+
+ .. note::
Like the rest of the standard library, this is a short-circuiting
- operation. This means that if a predicate returns `builtins.False`, no
+ operation. This means that if a predicate returns `False`, no
predicates after this are invoked, as the result is already known. In
this sense, they are invoked in-order.
- !!! warning
+ .. warning::
You should not generally need to use this outside of extending the
iterators API in this library!
Operators
---------
* `this(value : ValueT) -> bool`:
- Return `builtins.True` if all conditions return `builtins.True` when
+ Return `True` if all conditions return `True` when
invoked with the given value.
* `~this`:
Return a condition that, when invoked with the value, returns
- `builtins.False` if all conditions were `builtins.True` in this object.
+ `False` if all conditions were `True` in this object.
Parameters
----------
- *conditions : typing.Callable[[ValueT], builtins.bool]
+ conditions : typing.Callable[[ValueT], bool]
The predicates to wrap.
"""
@@ -129,7 +131,7 @@ class AttrComparator(typing.Generic[ValueT]):
Parameters
----------
- attr_name : builtins.str
+ attr_name : str
The attribute name. Can be prepended with a `.` optionally.
If the attribute name ends with a `()`, then the call is invoked
rather than treated as a property (useful for methods like
@@ -170,50 +172,50 @@ class LazyIterator(typing.Generic[ValueT], abc.ABC):
As an async iterable:
- ```py
- >>> async for item in paginated_results:
- ... process(item)
- ```
+ .. code-block:: python
+
+ >>> async for item in paginated_results:
+ ... process(item)
As an eagerly retrieved set of results (performs all API calls at once,
which may be slow for large sets of data):
- ```py
- >>> results = await paginated_results
- >>> # ... which is equivalent to this...
- >>> results = [item async for item in paginated_results]
- ```
+ .. code-block:: python
+
+ >>> results = await paginated_results
+ >>> # ... which is equivalent to this...
+ >>> results = [item async for item in paginated_results]
As an async iterator (not recommended):
- ```py
- >>> try:
- ... while True:
- ... process(await paginated_results.__anext__())
- ... except StopAsyncIteration:
- ... pass
- ```
+ .. code-block:: python
+
+ >>> try:
+ ... while True:
+ ... process(await paginated_results.__anext__())
+ ... except StopAsyncIteration:
+ ... pass
Additionally, you can make use of some of the provided helper methods
on this class to perform basic operations easily.
- Iterating across the items with indexes (like `builtins.enumerate` for normal
+ Iterating across the items with indexes (like `enumerate` for normal
iterables):
- ```py
- >>> async for i, item in paginated_results.enumerate():
- ... print(i, item)
- (0, foo)
- (1, bar)
- (2, baz)
- ```
+ .. code-block:: python
+
+ >>> async for i, item in paginated_results.enumerate():
+ ... print(i, item)
+ (0, foo)
+ (1, bar)
+ (2, baz)
Limiting the number of results you iterate across:
- ```py
- >>> async for item in paginated_results.limit(3):
- ... process(item)
- ```
+ .. code-block:: python
+
+ >>> async for item in paginated_results.limit(3):
+ ... process(item)
"""
__slots__: typing.Sequence[str] = ()
@@ -241,7 +243,7 @@ def map(
Parameters
----------
- transformation : typing.Union[typing.Callable[[ValueT], builtins.bool], builtins.str]
+ transformation : typing.Union[typing.Callable[[ValueT], bool], str]
The function to use to map the attribute. This may alternatively
be a string attribute name to replace the input value with. You
can provide nested attributes using the `.` operator.
@@ -257,7 +259,7 @@ def map(
return _MappingLazyIterator(self, transformation)
async def for_each(self, consumer: typing.Callable[[ValueT], typing.Any]) -> None:
- """Pass each value to a given consumer immediately."""
+ """Forward each value to a given consumer immediately."""
if asyncio.iscoroutinefunction(consumer):
async for item in self:
await consumer(item)
@@ -275,17 +277,17 @@ def filter(
Each condition is treated as a predicate, being called with each item
that this iterator would return when it is requested.
- All conditions must evaluate to `builtins.True` for the item to be
+ All conditions must evaluate to `True` for the item to be
returned. If this is not met, then the item is discarded and ignored,
the next matching item will be returned instead, if there is one.
Parameters
----------
- *predicates : typing.Union[typing.Callable[[ValueT], builtins.bool], typing.Tuple[builtins.str, typing.Any]]
+ *predicates : typing.Union[typing.Callable[[ValueT], bool], typing.Tuple[str, typing.Any]]
Predicates to invoke. These are functions that take a value and
- return `builtins.True` if it is of interest, or `builtins.False`
- otherwise. These may instead include 2-`builtins.tuple` objects
- consisting of a `builtins.str` attribute name (nested attributes
+ return `True` if it is of interest, or `False`
+ otherwise. These may instead include 2-`tuple` objects
+ consisting of a `str` attribute name (nested attributes
are referred to using the `.` operator), and values to compare for
equality. This allows you to specify conditions such as
`members.filter(("user.bot", True))`.
@@ -311,11 +313,11 @@ def take_while(
Parameters
----------
- *predicates : typing.Union[typing.Callable[[ValueT], builtins.bool], typing.Tuple[builtins.str, typing.Any]]
+ *predicates : typing.Union[typing.Callable[[ValueT], bool], typing.Tuple[str, typing.Any]]
Predicates to invoke. These are functions that take a value and
- return `builtins.True` if it is of interest, or `builtins.False`
- otherwise. These may instead include 2-`builtins.tuple` objects
- consisting of a `builtins.str` attribute name (nested attributes
+ return `True` if it is of interest, or `False`
+ otherwise. These may instead include 2-`tuple` objects
+ consisting of a `str` attribute name (nested attributes
are referred to using the `.` operator), and values to compare for
equality. This allows you to specify conditions such as
`members.take_while(("user.bot", True))`.
@@ -341,11 +343,11 @@ def take_until(
Parameters
----------
- *predicates : typing.Union[typing.Callable[[ValueT], builtins.bool], typing.Tuple[builtins.str, typing.Any]]
+ *predicates : typing.Union[typing.Callable[[ValueT], bool], typing.Tuple[str, typing.Any]]
Predicates to invoke. These are functions that take a value and
- return `builtins.True` if it is of interest, or `builtins.False`
- otherwise. These may instead include 2-`builtins.tuple` objects
- consisting of a `builtins.str` attribute name (nested attributes are
+ return `True` if it is of interest, or `False`
+ otherwise. These may instead include 2-`tuple` objects
+ consisting of a `str` attribute name (nested attributes are
referred to using the `.` operator), and values to compare for
equality. This allows you to specify conditions such as
`members.take_until(("user.bot", True))`.
@@ -373,11 +375,11 @@ def skip_while(
Parameters
----------
- *predicates : typing.Union[typing.Callable[[ValueT], builtins.bool], typing.Tuple[builtins.str, typing.Any]]
+ *predicates : typing.Union[typing.Callable[[ValueT], bool], typing.Tuple[str, typing.Any]]
Predicates to invoke. These are functions that take a value and
- return `builtins.True` if it is of interest, or `builtins.False`
- otherwise. These may instead include 2-`builtins.tuple` objects
- consisting of a `builtins.str` attribute name (nested attributes
+ return `True` if it is of interest, or `False`
+ otherwise. These may instead include 2-`tuple` objects
+ consisting of a `str` attribute name (nested attributes
are referred to using the `.` operator), and values to compare for
equality. This allows you to specify conditions such as
`members.skip_while(("user.bot", True))`.
@@ -405,11 +407,11 @@ def skip_until(
Parameters
----------
- *predicates : typing.Union[typing.Callable[[ValueT], builtins.bool], typing.Tuple[builtins.str, typing.Any]]
+ *predicates : typing.Union[typing.Callable[[ValueT], bool], typing.Tuple[str, typing.Any]]
Predicates to invoke. These are functions that take a value and
- return `builtins.True` if it is of interest, or `builtins.False`
- otherwise. These may instead include 2-`builtins.tuple` objects
- consisting of a `builtins.str` attribute name (nested attributes are
+ return `True` if it is of interest, or `False`
+ otherwise. These may instead include 2-`tuple` objects
+ consisting of a `str` attribute name (nested attributes are
referred to using the `.` operator), and values to compare for
equality. This allows you to specify conditions such as
`members.skip_until(("user.bot", True))`.
@@ -429,17 +431,19 @@ def skip_until(
def enumerate(self, *, start: int = 0) -> LazyIterator[typing.Tuple[int, ValueT]]:
"""Enumerate the paginated results lazily.
- This behaves as an asyncio-friendly version of `builtins.enumerate`
+ This behaves as an asyncio-friendly version of `enumerate`
which uses much less memory than collecting all the results first and
- calling `builtins.enumerate` across them.
+ calling `enumerate` across them.
Parameters
----------
- start : builtins.int
+ start : int
Optional int to start at. If omitted, this is `0`.
Examples
--------
+ .. code-block:: python
+
>>> async for i, item in paginated_results.enumerate():
... print(i, item)
(0, foo)
@@ -464,7 +468,7 @@ def enumerate(self, *, start: int = 0) -> LazyIterator[typing.Tuple[int, ValueT]
Returns
-------
- LazyIterator[typing.Tuple[builtins.int, T]]
+ LazyIterator[typing.Tuple[int, T]]
A paginated results view that asynchronously yields an increasing
counter in a tuple with each result, lazily.
"""
@@ -475,11 +479,13 @@ def limit(self, limit: int) -> LazyIterator[ValueT]:
Parameters
----------
- limit : builtins.int
+ limit : int
The number of items to get. This must be greater than zero.
Examples
--------
+ .. code-block:: python
+
>>> async for item in paginated_results.limit(3):
... print(item)
@@ -496,7 +502,7 @@ def skip(self, number: int) -> LazyIterator[ValueT]:
Parameters
----------
- number : builtins.int
+ number : int
The max number of items to drop before any items are yielded.
Returns
@@ -517,7 +523,7 @@ async def next(self) -> ValueT:
Raises
------
- builtins.LookupError
+ LookupError
If no more results exist.
"""
try:
@@ -528,17 +534,17 @@ async def next(self) -> ValueT:
async def last(self) -> ValueT:
"""Return the last element of this iterator only.
+ .. note::
+ This method will consume the whole iterator if run.
+
Returns
-------
ValueT
The last result.
- !!! note
- This method will consume the whole iterator if run.
-
Raises
------
- builtins.LookupError
+ LookupError
If no result exists.
"""
return await self.reversed().next()
@@ -575,7 +581,7 @@ async def count(self) -> int:
Returns
-------
- builtins.int
+ int
Number of results found.
"""
count = 0
@@ -608,26 +614,25 @@ def flat_map(self, flattener: _FlattenerT[ValueT, AnotherValueT]) -> LazyIterato
A function that returns either an async iterator or iterator of
new values. Could be an attribute name instead.
- Example
- -------
-
+ Examples
+ --------
The following example generates a distinct collection of all mentioned
users in the given channel from the past 500 messages.
- ```py
- def iter_mentioned_users(message: hikari.Message) -> typing.Iterable[Snowflake]:
- for match in re.findall(r"<@!?(\d+)>", message.content):
- yield Snowflake(match)
-
- mentioned_users = await (
- channel
- .history()
- .limit(500)
- .map(".content")
- .flat_map(iter_mentioned_users)
- .distinct()
- )
- ```
+ .. code-block:: python
+
+ def iter_mentioned_users(message: hikari.Message) -> typing.Iterable[Snowflake]:
+ for match in re.findall(r"<@!?(\d+)>", message.content):
+ yield Snowflake(match)
+
+ mentioned_users = await (
+ channel
+ .history()
+ .limit(500)
+ .map(".content")
+ .flat_map(iter_mentioned_users)
+ .distinct()
+ )
Returns
-------
@@ -639,34 +644,32 @@ def iter_mentioned_users(message: hikari.Message) -> typing.Iterable[Snowflake]:
def awaiting(self, window_size: int = 10) -> LazyIterator[ValueT]:
"""Await each item concurrently in a fixed size window.
- Parameters
- ----------
- window_size : int
- The window size of how many tasks to await at once. You can set this
- to `0` to await everything at once, but see the below warning.
-
- Returns
- -------
- LazyIterator[ValueT]
- The new lazy iterator to return.
-
- !!! warning
+ .. warning::
Setting a large window size, or setting it to 0 to await everything
is a dangerous thing to do if you are making API calls. Some
endpoints will get ratelimited and cause a backup of waiting
tasks, others may begin to spam global rate limits instead
(the `fetch_user` endpoint seems to be notorious for doing this).
- !!! note
+ .. note::
This call assumes that the iterator contains awaitable values as
input. MyPy cannot detect this nicely, so any cast is forced
internally.
-
If the item is not awaitable, you will receive a
- `builtins.TypeError` instead.
-
+ `TypeError` instead.
You have been warned. You cannot escape the ways of the duck type
young grasshopper.
+
+ Parameters
+ ----------
+ window_size : int
+ The window size of how many tasks to await at once. You can set this
+ to `0` to await everything at once, but see the below warning.
+
+ Returns
+ -------
+ LazyIterator[ValueT]
+ The new lazy iterator to return.
"""
# Not type safe. Can I make this type safe?
return _AwaitingLazyIterator(typing.cast("LazyIterator[typing.Awaitable[ValueT]]", self), window_size)
@@ -738,32 +741,32 @@ class BufferedLazyIterator(typing.Generic[ValueT], LazyIterator[ValueT], abc.ABC
thus reducing the amount of work needed if only a few objects out of, say,
100, need to be deserialized.
- This `_next_chunk` should return `builtins.None` once the end of all items
+ This `_next_chunk` should return `None` once the end of all items
has been reached.
An example would look like the following:
- ```py
- async def some_http_call(i):
- ...
+ .. code-block:: python
+
+ async def some_http_call(i):
+ ...
- class SomeEndpointLazyIterator(BufferedLazyIterator[SomeObject]):
- def __init__(self):
- super().__init__()
- self._i = 0
+ class SomeEndpointLazyIterator(BufferedLazyIterator[SomeObject]):
+ def __init__(self):
+ super().__init__()
+ self._i = 0
- def _next_chunk(self) -> typing.Optional[typing.Generator[ValueT, None, None]]:
- raw_items = await some_http_call(self._i)
- self._i += 1
+ def _next_chunk(self) -> typing.Optional[typing.Generator[ValueT, None, None]]:
+ raw_items = await some_http_call(self._i)
+ self._i += 1
- if not raw_items:
- return None
+ if not raw_items:
+ return None
- generator = (SomeObject(raw_item) for raw_item in raw_items)
- return generator
- ```
+ generator = (SomeObject(raw_item) for raw_item in raw_items)
+ return generator
"""
__slots__: typing.Sequence[str] = ("_buffer",)
diff --git a/hikari/locales.py b/hikari/locales.py
index a02a5b10e1..512a388ff6 100644
--- a/hikari/locales.py
+++ b/hikari/locales.py
@@ -35,91 +35,91 @@ class Locale(str, enums.Enum):
"""Possible user/guild locales."""
DA = "da"
- """Danish"""
+ """Danish."""
DE = "de"
- """German"""
+ """German."""
EN_GB = "en-GB"
- """English, UK"""
+ """English, UK."""
EN_US = "en-US"
- """English, US"""
+ """English, US."""
ES_ES = "es-ES"
- """Spanish"""
+ """Spanish."""
FR = "fr"
- """French"""
+ """French."""
HR = "hr"
- """Croatian"""
+ """Croatian."""
IT = "it"
- """Italian"""
+ """Italian."""
LT = "lt"
- """Lithuanian"""
+ """Lithuanian."""
HU = "hu"
- """Hungarian"""
+ """Hungarian."""
NL = "nl"
- """Dutch"""
+ """Dutch."""
NO = "no"
- """Norwegian"""
+ """Norwegian."""
PL = "pl"
- """Polish"""
+ """Polish."""
PT_BR = "pt-BR"
- """Portuguese, Bralizian"""
+ """Portuguese, Bralizian."""
RO = "ro"
- """Romian"""
+ """Romian."""
FI = "fi"
- """Finnish"""
+ """Finnish."""
SV_SE = "sv-SE"
- """Swedish"""
+ """Swedish."""
VI = "vi"
- """Vietnamese"""
+ """Vietnamese."""
TR = "tr"
- """Turkish"""
+ """Turkish."""
CS = "cs"
- """Czech"""
+ """Czech."""
EL = "el"
- """Greek"""
+ """Greek."""
BG = "bg"
- """Bulgarian"""
+ """Bulgarian."""
RU = "ru"
- """Russian"""
+ """Russian."""
UK = "uk"
- """Ukrainian"""
+ """Ukrainian."""
HI = "hi"
- """Hindi"""
+ """Hindi."""
TH = "th"
- """Thai"""
+ """Thai."""
ZH_CN = "zh-CN"
- """Chinese, China"""
+ """Chinese, China."""
JA = "ja"
- """Japanese"""
+ """Japanese."""
ZH_TW = "zh-TW"
- """Chinese, Taiwan"""
+ """Chinese, Taiwan."""
KO = "ko"
- """Korean"""
+ """Korean."""
diff --git a/hikari/messages.py b/hikari/messages.py
index 09bc534f3d..b1fc1b09a5 100644
--- a/hikari/messages.py
+++ b/hikari/messages.py
@@ -139,7 +139,7 @@ class MessageFlag(enums.Flag):
"""Additional flags for message options."""
NONE = 0
- """None"""
+ """None."""
CROSSPOSTED = 1 << 0
"""This message has been published to subscribed channels via channel following."""
@@ -275,12 +275,12 @@ class MessageReference:
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
id: typing.Optional[snowflakes.Snowflake] = attr.field(repr=True)
"""The ID of the original message.
- This will be `builtins.None` for channel follow add messages. This may
+ This will be `None` for channel follow add messages. This may
point to a deleted message.
"""
@@ -290,7 +290,7 @@ class MessageReference:
guild_id: typing.Optional[snowflakes.Snowflake] = attr.field(repr=True)
"""The ID of the guild that the message originated from.
- This will be `builtins.None` when the original message is not from
+ This will be `None` when the original message is not from
a guild.
"""
@@ -305,13 +305,7 @@ class MessageApplication(guilds.PartialApplication):
@property
def cover_image_url(self) -> typing.Optional[files.URL]:
- """Rich presence cover image URL for this application, if set.
-
- Returns
- -------
- typing.Optional[hikari.files.URL]
- The URL, or `builtins.None` if no cover image exists.
- """
+ """Rich presence cover image URL for this application, if set."""
return self.make_cover_image_url()
def make_cover_image_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
@@ -319,21 +313,21 @@ def make_cover_image_url(self, *, ext: str = "png", size: int = 4096) -> typing.
Parameters
----------
- ext : builtins.str
+ ext : str
The extension to use for this URL, defaults to `png`.
Supports `png`, `jpeg`, `jpg` and `webp`.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Returns
-------
typing.Optional[hikari.files.URL]
- The URL, or `builtins.None` if no cover image exists.
+ The URL, or `None` if no cover image exists.
Raises
------
- builtins.ValueError
+ ValueError
If the size is not an integer power of 2 between 16 and 4096
(inclusive).
"""
@@ -388,7 +382,7 @@ class PartialMessage(snowflakes.Unique):
`MessageUpdateEvent`, but for all other purposes should be treated as
being optionally specified.
- !!! warning
+ .. warning::
All fields on this model except `channel` and `id` may be set to
`hikari.undefined.UNDEFINED` (a singleton) if we have not
received information about their state from Discord alongside field
@@ -398,7 +392,7 @@ class PartialMessage(snowflakes.Unique):
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
id: snowflakes.Snowflake = attr.field(hash=True, repr=True)
"""The ID of this entity."""
@@ -407,11 +401,11 @@ class PartialMessage(snowflakes.Unique):
"""The ID of the channel that the message was sent in."""
guild_id: typing.Optional[snowflakes.Snowflake] = attr.field(hash=False, eq=False, repr=True)
- """The ID of the guild that the message was sent in or `builtins.None` for messages out of guilds.
+ """The ID of the guild that the message was sent in or `None` for messages out of guilds.
- !!! warning
- This will also be `builtins.None` for messages received from the REST API.
- This is a Discord limitation as stated here https://github.com/discord/discord-api-docs/issues/912
+ .. warning::
+ This will also be `None` for messages received from the REST API.
+ This is a Discord limitation as stated here
"""
author: undefined.UndefinedOr[users_.User] = attr.field(hash=False, eq=False, repr=True)
@@ -424,14 +418,14 @@ class PartialMessage(snowflakes.Unique):
member: undefined.UndefinedNoneOr[guilds.Member] = attr.field(hash=False, eq=False, repr=False)
"""The member for the author who created the message.
- If the message is not in a guild, this will be `builtins.None`.
+ If the message is not in a guild, this will be `None`.
This will also be `hikari.undefined.UNDEFINED` in some cases such as when Discord
updates a message with an embed URL preview.
- !!! warning
- This will also be `builtins.None` for messages received from the REST API.
- This is a Discord limitation as stated here https://github.com/discord/discord-api-docs/issues/912
+ .. warning::
+ This will also be `None` for messages received from the REST API.
+ This is a Discord limitation as stated here
"""
content: undefined.UndefinedNoneOr[str] = attr.field(hash=False, eq=False, repr=False)
@@ -443,7 +437,7 @@ class PartialMessage(snowflakes.Unique):
edited_timestamp: undefined.UndefinedNoneOr[datetime.datetime] = attr.field(hash=False, eq=False, repr=False)
"""The timestamp that the message was last edited at.
- Will be `builtins.None` if the message wasn't ever edited, or `undefined`
+ Will be `None` if the message wasn't ever edited, or `undefined`
if the info is not available.
"""
@@ -455,7 +449,7 @@ class PartialMessage(snowflakes.Unique):
)
"""Users who were notified by their mention in the message.
- !!! warning
+ .. warning::
If the contents have not mutated and this is a message update event,
some fields that are not affected may be empty instead.
@@ -467,7 +461,7 @@ class PartialMessage(snowflakes.Unique):
)
"""IDs of roles that were notified by their mention in the message.
- !!! warning
+ .. warning::
If the contents have not mutated and this is a message update event,
some fields that are not affected may be empty instead.
@@ -481,7 +475,7 @@ class PartialMessage(snowflakes.Unique):
If the message is not crossposted, this will always be empty.
- !!! warning
+ .. warning::
If the contents have not mutated and this is a message update event,
some fields that are not affected may be empty instead.
@@ -491,7 +485,7 @@ class PartialMessage(snowflakes.Unique):
mentions_everyone: undefined.UndefinedOr[bool] = attr.field(hash=False, eq=False, repr=False)
"""Whether the message notifies using `@everyone` or `@here`.
- !!! warning
+ .. warning::
If the contents have not mutated and this is a message update event,
some fields that are not affected may be empty instead.
@@ -519,7 +513,7 @@ class PartialMessage(snowflakes.Unique):
activity: undefined.UndefinedNoneOr[MessageActivity] = attr.field(hash=False, eq=False, repr=False)
"""The message activity.
- !!! note
+ .. note::
This will only be provided for messages with rich-presence related chat
embeds.
"""
@@ -527,7 +521,7 @@ class PartialMessage(snowflakes.Unique):
application: undefined.UndefinedNoneOr[MessageApplication] = attr.field(hash=False, eq=False, repr=False)
"""The message application.
- !!! note
+ .. note::
This will only be provided for messages with rich-presence related chat
embeds.
"""
@@ -554,7 +548,7 @@ class PartialMessage(snowflakes.Unique):
If `type` is `MessageType.REPLY` and `hikari.undefined.UNDEFINED`, Discord's
backend didn't attempt to fetch the message, so the status is unknown. If
- `type` is `MessageType.REPLY` and `builtins.None`, the message was deleted.
+ `type` is `MessageType.REPLY` and `None`, the message was deleted.
"""
interaction: undefined.UndefinedNoneOr[MessageInteraction] = attr.field(hash=False, eq=False, repr=False)
@@ -563,7 +557,7 @@ class PartialMessage(snowflakes.Unique):
application_id: undefined.UndefinedNoneOr[snowflakes.Snowflake] = attr.field(hash=False, eq=False, repr=False)
"""ID of the application this message was sent by.
- !!! note
+ .. note::
This will only be provided for interaction messages.
"""
@@ -578,7 +572,7 @@ def channel_mention_ids(self) -> undefined.UndefinedOr[typing.Sequence[snowflake
If the message is not crossposted, this will always be empty.
- !!! warning
+ .. warning::
If the contents have not mutated and this is a message update event,
some fields that are not affected may be empty instead.
@@ -593,7 +587,7 @@ def channel_mention_ids(self) -> undefined.UndefinedOr[typing.Sequence[snowflake
def user_mentions_ids(self) -> undefined.UndefinedOr[typing.Sequence[snowflakes.Snowflake]]:
"""Ids of the users who were notified by their mention in the message.
- !!! warning
+ .. warning::
If the contents have not mutated and this is a message update event,
some fields that are not affected may be empty instead.
@@ -609,13 +603,13 @@ def get_member_mentions(self) -> undefined.UndefinedOr[typing.Mapping[snowflakes
If this message was sent in a DM, this will always be empty.
- !!! warning
+ .. warning::
This will only return valid results on gateway events. For REST
endpoints, this will potentially be empty. This is a limitation of
Discord's API, as they do not consistently notify of the ID of the
guild a message was sent in.
- !!! note
+ .. note::
If you are using a stateless application such as a stateless bot
or a REST-only client, this will always be empty. Furthermore,
if you are running a stateful bot and have the GUILD_MEMBERS
@@ -642,13 +636,13 @@ def get_role_mentions(self) -> undefined.UndefinedOr[typing.Mapping[snowflakes.S
If this message was sent in a DM, this will always be empty.
- !!! warning
+ .. warning::
This will only return valid results on gateway events. For REST
endpoints, this will potentially be empty. This is a limitation of
Discord's API, as they do not consistently notify of the ID of the
guild a message was sent in.
- !!! note
+ .. note::
If you are using a stateless application such as a stateless bot
or a REST-only client, this will always be empty. Furthermore,
if you are running a stateful bot and have the GUILD intent
@@ -672,18 +666,17 @@ def make_link(self, guild: typing.Optional[snowflakes.SnowflakeishOr[guilds.Part
Other Parameters
----------------
- guild : typing.Union[hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]]
- Object or ID of the guild this message is in or `builtins.None`
+ guild : typing.Optional[hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]]
+ Object or ID of the guild this message is in or `None`
to generate a DM message link.
- !!! note
- This parameter is necessary since `PartialMessage.guild_id`
- isn't returned by the REST API regardless of whether the message
- is in a DM or not.
+ This parameter is necessary since `PartialMessage.guild_id`
+ isn't returned by the REST API regardless of whether the message
+ is in a DM or not.
Returns
-------
- builtins.str
+ str
The jump link to the message.
"""
guild_id_str = "@me" if guild is None else str(int(guild))
@@ -750,14 +743,34 @@ async def edit(
) -> Message:
"""Edit an existing message in a given channel.
+ .. note::
+ Mentioning everyone, roles, or users in message edits currently
+ will not send a push notification showing a new mention to people
+ on Discord. It will still highlight in their chat as if they
+ were mentioned, however.
+
+ .. warning::
+ If you specify a text `content`, `mentions_everyone`,
+ `mentions_reply`, `user_mentions`, and `role_mentions` will default
+ to `False` as the message will be re-parsed for mentions. This will
+ also occur if only one of the four are specified
+
+ This is a limitation of Discord's design. If in doubt, specify all
+ four of them each time.
+
+ .. warning::
+ If the message was not sent by your user, the only parameter
+ you may provide to this call is the `flags` parameter. Anything
+ else will result in a `hikari.errors.ForbiddenError` being raised.
+
Parameters
----------
content : hikari.undefined.UndefinedOr[typing.Any]
If provided, the message content to update with. If
`hikari.undefined.UNDEFINED`, then the content will not
- be changed. If `builtins.None`, then the content will be removed.
+ be changed. If `None`, then the content will be removed.
- Any other value will be cast to a `builtins.str` before sending.
+ Any other value will be cast to a `str` before sending.
If this is a `hikari.embeds.Embed` and neither the `embed` or
`embeds` kwargs are provided or if this is a
@@ -771,62 +784,62 @@ async def edit(
attachment : hikari.undefined.UndefinedNoneOr[typing.Union[hikari.files.Resourceish, hikari.messages.Attachment]]
If provided, the attachment to set on the message. If
`hikari.undefined.UNDEFINED`, the previous attachment, if
- present, is not changed. If this is `builtins.None`, then the
+ present, is not changed. If this is `None`, then the
attachment is removed, if present. Otherwise, the new attachment
that was provided will be attached.
attachments : hikari.undefined.UndefinedNoneOr[typing.Sequence[typing.Union[hikari.files.Resourceish, hikari.messages.Attachment]]]
If provided, the attachments to set on the message. If
`hikari.undefined.UNDEFINED`, the previous attachments, if
- present, are not changed. If this is `builtins.None`, then the
+ present, are not changed. If this is `None`, then the
attachments is removed, if present. Otherwise, the new attachments
that were provided will be attached.
component : hikari.undefined.UndefinedNoneOr[hikari.api.special_endpoints.ComponentBuilder]
If provided, builder object of the component to set for this message.
This component will replace any previously set components and passing
- `builtins.None` will remove all components.
+ `None` will remove all components.
components : hikari.undefined.UndefinedNoneOr[typing.Sequence[hikari.api.special_endpoints.ComponentBuilder]]
If provided, a sequence of the component builder objects set for
this message. These components will replace any previously set
- components and passing `builtins.None` or an empty sequence will
+ components and passing `None` or an empty sequence will
remove all components.
embed : hikari.undefined.UndefinedNoneOr[hikari.embeds.Embed]
If provided, the embed to set on the message. If
`hikari.undefined.UNDEFINED`, the previous embed(s) are not changed.
- If this is `builtins.None` then any present embeds are removed.
+ If this is `None` then any present embeds are removed.
Otherwise, the new embed that was provided will be used as the
replacement.
embeds : hikari.undefined.UndefinedNoneOr[typing.Sequence[hikari.embeds.Embed]]
If provided, the embeds to set on the message. If
`hikari.undefined.UNDEFINED`, the previous embed(s) are not changed.
- If this is `builtins.None` then any present embeds are removed.
+ If this is `None` then any present embeds are removed.
Otherwise, the new embeds that were provided will be used as the
replacement.
- mentions_everyone : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_everyone : hikari.undefined.UndefinedOr[bool]
Sanitation for `@everyone` mentions. If
`hikari.undefined.UNDEFINED`, then the previous setting is
- not changed. If `builtins.True`, then `@everyone`/`@here` mentions
+ not changed. If `True`, then `@everyone`/`@here` mentions
in the message content will show up as mentioning everyone that can
view the chat.
- mentions_reply : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_reply : hikari.undefined.UndefinedOr[bool]
If provided, whether to mention the author of the message
that is being replied to.
This will not do anything if this is not a reply message.
- user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
+ user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], bool]]
Sanitation for user mentions. If
`hikari.undefined.UNDEFINED`, then the previous setting is
- not changed. If `builtins.True`, all valid user mentions will behave
- as mentions. If `builtins.False`, all valid user mentions will not
+ not changed. If `True`, all valid user mentions will behave
+ as mentions. If `False`, all valid user mentions will not
behave as mentions.
You may alternatively pass a collection of
`hikari.snowflakes.Snowflake` user IDs, or
`hikari.users.PartialUser`-derived objects.
- role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], builtins.bool]]
+ role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], bool]]
Sanitation for role mentions. If
`hikari.undefined.UNDEFINED`, then the previous setting is
- not changed. If `builtins.True`, all valid role mentions will behave
- as mentions. If `builtins.False`, all valid role mentions will not
+ not changed. If `True`, all valid role mentions will behave
+ as mentions. If `False`, all valid role mentions will not
behave as mentions.
You may alternatively pass a collection of
@@ -841,33 +854,6 @@ async def edit(
have `MANAGE_MESSAGES` permissions, you can use this call to
suppress embeds on another user's message.
- !!! note
- Mentioning everyone, roles, or users in message edits currently
- will not send a push notification showing a new mention to people
- on Discord. It will still highlight in their chat as if they
- were mentioned, however.
-
- !!! warning
- If you specify a non-embed `content`, `mentions_everyone`,
- `mentions_reply`, `user_mentions`, and `role_mentions` will default
- to `builtins.False` as the message will be re-parsed for mentions.
-
- This is a limitation of Discord's design. If in doubt, specify all
- four of them each time.
-
- !!! warning
- If you specify one of `mentions_everyone`, `mentions_reply`,
- `user_mentions`, or `role_mentions`, then all others will default to
- `builtins.False`, even if they were enabled previously.
-
- This is a limitation of Discord's design. If in doubt, specify all
- four of them each time.
-
- !!! warning
- If the message was not sent by your user, the only parameter
- you may provide to this call is the `flags` parameter. Anything
- else will result in a `hikari.errors.ForbiddenError` being raised.
-
Returns
-------
hikari.messages.Message
@@ -941,7 +927,7 @@ async def respond(
If provided, the message contents. If
`hikari.undefined.UNDEFINED`, then nothing will be sent
in the content. Any other value here will be cast to a
- `builtins.str`.
+ `str`.
If this is a `hikari.embeds.Embed` and no `embed` nor `embeds` kwarg
is provided, then this will instead update the embed. This allows
@@ -956,6 +942,32 @@ async def respond(
attachment : hikari.undefined.UndefinedOr[hikari.files.Resourceish],
If provided, the message attachment. This can be a resource,
or string of a path on your computer or a URL.
+
+ Attachments can be passed as many different things, to aid in
+ convenience.
+
+ - If a `pathlib.PurePath` or `str` to a valid URL, the
+ resource at the given URL will be streamed to Discord when
+ sending the message. Subclasses of
+ `hikari.files.WebResource` such as
+ `hikari.files.URL`,
+ `hikari.messages.Attachment`,
+ `hikari.emojis.Emoji`,
+ `EmbedResource`, etc will also be uploaded this way.
+ This will use bit-inception, so only a small percentage of the
+ resource will remain in memory at any one time, thus aiding in
+ scalability.
+ - If a `hikari.files.Bytes` is passed, or a `str`
+ that contains a valid data URI is passed, then this is uploaded
+ with a randomized file name if not provided.
+ - If a `hikari.files.File`, `pathlib.PurePath` or
+ `str` that is an absolute or relative path to a file
+ on your file system is passed, then this resource is uploaded
+ as an attachment using non-blocking code internally and streamed
+ using bit-inception where possible. This depends on the
+ type of `concurrent.futures.Executor` that is being used for
+ the application (default is a thread pool which supports this
+ behaviour).
attachments : hikari.undefined.UndefinedOr[typing.Sequence[hikari.files.Resourceish]],
If provided, the message attachments. These can be resources, or
strings consisting of paths on your computer or URLs.
@@ -968,28 +980,28 @@ async def respond(
If provided, the message embed.
embeds : hikari.undefined.UndefinedOr[typing.Sequence[hikari.embeds.Embed]]
If provided, the message embeds.
- tts : hikari.undefined.UndefinedOr[builtins.bool]
+ tts : hikari.undefined.UndefinedOr[bool]
If provided, whether the message will be TTS (Text To Speech).
- reply : typing.Union[hikari.undefined.UndefinedType, hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage], builtins.bool]
- If provided and `builtins.True`, reply to this message.
- If provided and not `builtins.bool`, the message to reply to.
- mentions_everyone : hikari.undefined.UndefinedOr[builtins.bool]
+ reply : typing.Union[hikari.undefined.UndefinedType, hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage], bool]
+ If provided and `True`, reply to this message.
+ If provided and not `bool`, the message to reply to.
+ mentions_everyone : hikari.undefined.UndefinedOr[bool]
If provided, whether the message should parse @everyone/@here
mentions.
- mentions_reply : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_reply : hikari.undefined.UndefinedOr[bool]
If provided, whether to mention the author of the message
that is being replied to.
This will not do anything if not being used with `reply`.
- user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
- If provided, and `builtins.True`, all mentions will be parsed.
- If provided, and `builtins.False`, no mentions will be parsed.
+ user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], bool]]
+ If provided, and `True`, all mentions will be parsed.
+ If provided, and `False`, no mentions will be parsed.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or `hikari.users.PartialUser`
derivatives to enforce mentioning specific users.
- role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], builtins.bool]]
- If provided, and `builtins.True`, all mentions will be parsed.
- If provided, and `builtins.False`, no mentions will be parsed.
+ role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], bool]]
+ If provided, and `True`, all mentions will be parsed.
+ If provided, and `False`, no mentions will be parsed.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.guilds.PartialRole` derivatives to enforce mentioning
@@ -1001,33 +1013,6 @@ async def respond(
Note that some flags may not be able to be set. Currently the only
flags that can be set are `NONE` and `SUPPRESS_EMBEDS`.
- !!! note
- Attachments can be passed as many different things, to aid in
- convenience.
-
- - If a `pathlib.PurePath` or `builtins.str` to a valid URL, the
- resource at the given URL will be streamed to Discord when
- sending the message. Subclasses of
- `hikari.files.WebResource` such as
- `hikari.files.URL`,
- `hikari.messages.Attachment`,
- `hikari.emojis.Emoji`,
- `EmbedResource`, etc will also be uploaded this way.
- This will use bit-inception, so only a small percentage of the
- resource will remain in memory at any one time, thus aiding in
- scalability.
- - If a `hikari.files.Bytes` is passed, or a `builtins.str`
- that contains a valid data URI is passed, then this is uploaded
- with a randomized file name if not provided.
- - If a `hikari.files.File`, `pathlib.PurePath` or
- `builtins.str` that is an absolute or relative path to a file
- on your file system is passed, then this resource is uploaded
- as an attachment using non-blocking code internally and streamed
- using bit-inception where possible. This depends on the
- type of `concurrent.futures.Executor` that is being used for
- the application (default is a thread pool which supports this
- behaviour).
-
Returns
-------
hikari.messages.Message
@@ -1050,10 +1035,10 @@ async def respond(
If the channel is not found.
hikari.errors.InternalServerError
If an internal error occurs on Discord while handling the request.
- builtins.ValueError
+ ValueError
If more than 100 unique objects/entities are passed for
`role_mentions` or `user_mentions`.
- builtins.TypeError
+ TypeError
If both `attachment` and `attachments` are specified.
""" # noqa: E501 - Line too long
if reply is True:
@@ -1117,7 +1102,7 @@ async def add_reaction(
Parameters
----------
- emoji: typing.Union[builtins.str, hikari.emojis.Emoji]
+ emoji : typing.Union[str, hikari.emojis.Emoji]
Object or name of the emoji to react with.
Note that if the emoji is an `hikari.emojis.CustomEmoji`
@@ -1135,19 +1120,19 @@ async def add_reaction(
Examples
--------
- ```py
- # Using a unicode emoji.
- await message.add_reaction("👌")
+ .. code-block:: python
- # Using a unicode emoji name.
- await message.add_reaction("\N{OK HAND SIGN}")
+ # Using a unicode emoji.
+ await message.add_reaction("👌")
- # Using the name and id.
- await message.add_reaction("rooAYAYA", 705837374319493284)
+ # Using a unicode emoji name.
+ await message.add_reaction("\N{OK HAND SIGN}")
- # Using an Emoji-derived object.
- await message.add_reaction(some_emoji_object)
- ```
+ # Using the name and id.
+ await message.add_reaction("rooAYAYA", 705837374319493284)
+
+ # Using an Emoji-derived object.
+ await message.add_reaction(some_emoji_object)
Raises
------
@@ -1197,7 +1182,7 @@ async def remove_reaction(
Parameters
----------
- emoji : typing.Union[builtins.str, hikari.emojis.Emoji]
+ emoji : typing.Union[str, hikari.emojis.Emoji]
Object or name of the emoji to remove the reaction for.
Other Parameters
@@ -1212,6 +1197,8 @@ async def remove_reaction(
Examples
--------
+ .. code-block:: python
+
# Using a unicode emoji and removing the bot's reaction from this
# reaction.
await message.remove_reaction("\N{OK HAND SIGN}")
@@ -1284,7 +1271,7 @@ async def remove_all_reactions(
Other Parameters
----------------
- emoji : hikari.undefined.UndefinedOr[typing.Union[builtins.str, hikari.emojis.Emoji]]
+ emoji : hikari.undefined.UndefinedOr[typing.Union[str, hikari.emojis.Emoji]]
Object or name of the emoji to get the reactions for. If not specified
then all reactions are removed.
emoji_id : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.emojis.CustomEmoji]]
@@ -1292,8 +1279,10 @@ async def remove_all_reactions(
This should only be provided when a custom emoji's name is passed
for `emoji`.
- Example
+ Examples
--------
+ .. code-block:: python
+
# Using a unicode emoji and removing all 👌 reacts from the message.
# reaction.
await message.remove_all_reactions("\N{OK HAND SIGN}")
@@ -1344,7 +1333,7 @@ class Message(PartialMessage):
edited_timestamp: typing.Optional[datetime.datetime] = attr.field(hash=False, eq=False, repr=False)
"""The timestamp that the message was last edited at.
- Will be `builtins.None` if it wasn't ever edited.
+ Will be `None` if it wasn't ever edited.
"""
is_tts: bool = attr.field(hash=False, eq=False, repr=False)
@@ -1371,7 +1360,7 @@ class Message(PartialMessage):
activity: typing.Optional[MessageActivity] = attr.field(hash=False, eq=False, repr=False)
"""The message activity.
- !!! note
+ .. note::
This will only be provided for messages with rich-presence related chat
embeds.
"""
@@ -1379,7 +1368,7 @@ class Message(PartialMessage):
application: typing.Optional[MessageApplication] = attr.field(hash=False, eq=False, repr=False)
"""The message application.
- !!! note
+ .. note::
This will only be provided for messages with rich-presence related chat
embeds.
"""
@@ -1399,7 +1388,7 @@ class Message(PartialMessage):
referenced_message: typing.Optional[PartialMessage] = attr.field(hash=False, eq=False, repr=False)
"""The message that was replied to.
- If `type` is `MessageType.REPLY` and `builtins.None`, the message was deleted.
+ If `type` is `MessageType.REPLY` and `None`, the message was deleted.
"""
interaction: typing.Optional[MessageInteraction] = attr.field(hash=False, eq=False, repr=False)
@@ -1408,7 +1397,7 @@ class Message(PartialMessage):
application_id: typing.Optional[snowflakes.Snowflake] = attr.field(hash=False, eq=False, repr=False)
"""ID of the application this message was sent by.
- !!! note
+ .. note::
This will only be provided for interaction messages.
"""
diff --git a/hikari/permissions.py b/hikari/permissions.py
index 45e846fa0f..480fb55aac 100644
--- a/hikari/permissions.py
+++ b/hikari/permissions.py
@@ -43,6 +43,8 @@ class Permissions(enums.Flag):
--------
You can create an enum which combines multiple permissions using the bitwise OR operator (`|`):
+ .. code-block:: python
+
my_perms = Permissions.MANAGE_CHANNELS | Permissions.MANAGE_GUILD
required_perms = (
@@ -57,6 +59,8 @@ class Permissions(enums.Flag):
permissions from one set are present in another set. This is useful, for instance,
for checking if a user has all the required permissions
+ .. code-block:: python
+
if (my_perms & required_perms) == required_perms:
print("I have all of the required permissions!")
else:
@@ -66,6 +70,8 @@ class Permissions(enums.Flag):
bitwise equivalent of the set difference operation, as shown below. This can be used,
for instance, to find which of a user's permissions are missing from the required permissions.
+ .. code-block:: python
+
missing_perms = ~my_perms & required_perms
if (missing_perms):
print(f"I'm missing these permissions: {missing_perms}")
@@ -73,6 +79,8 @@ class Permissions(enums.Flag):
Lastly, if you need all the permissions from a set except for a few,
you can use the bitwise NOT operator (`~`).
+ .. code-block:: python
+
# All permissions except ADMINISTRATOR.
my_perms = ~Permissions.ADMINISTRATOR
@@ -87,7 +95,7 @@ class Permissions(enums.Flag):
KICK_MEMBERS = 1 << 1
"""Allows kicking members.
- !!! note
+ .. note::
In guilds with server-wide 2FA enabled this permission can only be used
by users who have two-factor authentication enabled on their account
(or their owner's account in the case of bot users) and the guild owner.
@@ -96,7 +104,7 @@ class Permissions(enums.Flag):
BAN_MEMBERS = 1 << 2
"""Allows banning members.
- !!! note
+ .. note::
In guilds with server-wide 2FA enabled this permission can only be used
by users who have two-factor authentication enabled on their account
(or their owner's account in the case of bot users) and the guild owner.
@@ -105,7 +113,7 @@ class Permissions(enums.Flag):
ADMINISTRATOR = 1 << 3
"""Allows all permissions and bypasses channel permission overwrites.
- !!! note
+ .. note::
In guilds with server-wide 2FA enabled this permission can only be used
by users who have two-factor authentication enabled on their account
(or their owner's account in the case of bot users) and the guild owner.
@@ -114,7 +122,7 @@ class Permissions(enums.Flag):
MANAGE_CHANNELS = 1 << 4
"""Allows management and editing of channels.
- !!! note
+ .. note::
In guilds with server-wide 2FA enabled this permission can only be used
by users who have two-factor authentication enabled on their account
(or their owner's account in the case of bot users) and the guild owner.
@@ -123,7 +131,7 @@ class Permissions(enums.Flag):
MANAGE_GUILD = 1 << 5
"""Allows management and editing of the guild.
- !!! note
+ .. note::
In guilds with server-wide 2FA enabled this permission can only be used
by users who have two-factor authentication enabled on their account
(or their owner's account in the case of bot users) and the guild owner.
@@ -153,7 +161,7 @@ class Permissions(enums.Flag):
MANAGE_MESSAGES = 1 << 13
"""Allows for deletion of other users messages.
- !!! note
+ .. note::
In guilds with server-wide 2FA enabled this permission can only be used
by users who have two-factor authentication enabled on their account
(or their owner's account in the case of bot users) and the guild owner.
@@ -169,11 +177,7 @@ class Permissions(enums.Flag):
"""Allows for reading of message history."""
MENTION_ROLES = 1 << 17
- """Allows for using the `@everyone` tag to notify all users in a channel,
- and the `@here` tag to notify all online users in a channel, and the
- `@role` tag (even if the role is not mentionable) to notify all users with
- that role in a channel.
- """
+ """Allows for using the `@everyone`, `@here` and `@role` (regardless of its mention status) tag to notify users."""
USE_EXTERNAL_EMOJIS = 1 << 18
"""Allows the usage of custom emojis from other guilds."""
@@ -208,7 +212,7 @@ class Permissions(enums.Flag):
MANAGE_ROLES = 1 << 28
"""Allows management and editing of roles.
- !!! note
+ .. note::
In guilds with server-wide 2FA enabled this permission can only be used
by users who have two-factor authentication enabled on their account
(or their owner's account in the case of bot users) and the guild owner.
@@ -217,7 +221,7 @@ class Permissions(enums.Flag):
MANAGE_WEBHOOKS = 1 << 29
"""Allows management and editing of webhooks.
- !!! note
+ .. note::
In guilds with server-wide 2FA enabled this permission can only be used
by users who have two-factor authentication enabled on their account
(or their owner's account in the case of bot users) and the guild owner.
@@ -226,7 +230,7 @@ class Permissions(enums.Flag):
MANAGE_EMOJIS_AND_STICKERS = 1 << 30
"""Allows management and editing of emojis and stickers.
- !!! note
+ .. note::
In guilds with server-wide 2FA enabled this permission can only be used
by users who have two-factor authentication enabled on their account
(or their owner's account in the case of bot users) and the guild owner.
@@ -238,7 +242,7 @@ class Permissions(enums.Flag):
REQUEST_TO_SPEAK = 1 << 32
"""Allows for requesting to speak in stage channels.
- !!! warning
+ .. warning::
This permissions is currently defined as being "under active
development" by Discord meaning that "it may be changed or removed"
without warning.
@@ -250,7 +254,7 @@ class Permissions(enums.Flag):
MANAGE_THREADS = 1 << 34
"""Allows for deleting and archiving threads, and viewing all private threads.
- !!! note
+ .. note::
In guilds with server-wide 2FA enabled this permission can only be used
by users who have two-factor authentication enabled on their account
(or their owner's account in the case of bot users) and the guild owner.
diff --git a/hikari/presences.py b/hikari/presences.py
index fc8a68ea55..7a46eb3a54 100644
--- a/hikari/presences.py
+++ b/hikari/presences.py
@@ -63,12 +63,12 @@ class ActivityType(int, enums.Enum):
"""The activity type."""
PLAYING = 0
- """Shows up as `Playing `"""
+ """Shows up as `Playing `."""
STREAMING = 1
"""Shows up as `Streaming` and links to a Twitch or YouTube stream/video.
- !!! warning
+ .. warning::
You **MUST** provide a valid Twitch or YouTube stream URL to the
activity you create in order for this to be valid. If you fail to
do this, then the activity **WILL NOT** update.
@@ -86,7 +86,7 @@ class ActivityType(int, enums.Enum):
To set an emoji with the status, place a unicode emoji or Discord emoji
(`:smiley:`) as the first part of the status activity name.
- !!! warning
+ .. warning::
Bots **DO NOT** support setting custom statuses.
"""
@@ -168,8 +168,8 @@ def _make_asset_url(self, asset: typing.Optional[str], ext: str, size: int) -> t
def large_image_url(self) -> typing.Optional[files.URL]:
"""Large image asset URL.
- !!! note
- This will be `builtins.None` if no large image asset exists or if the
+ .. note::
+ This will be `None` if no large image asset exists or if the
asset's dynamic URL (indicated by a `{name}:` prefix) is not known.
"""
try:
@@ -181,30 +181,30 @@ def large_image_url(self) -> typing.Optional[files.URL]:
def make_large_image_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
"""Generate the large image asset URL for this application.
- !!! note
+ .. note::
`ext` and `size` are ignored for images hosted outside of Discord
or on Discord's media proxy.
Parameters
----------
- ext : builtins.str
+ ext : str
The extension to use for this URL, defaults to `png`.
Supports `png`, `jpeg`, `jpg` and `webp`.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Returns
-------
typing.Optional[hikari.files.URL]
- The URL, or `builtins.None` if no icon exists.
+ The URL, or `None` if no icon exists.
Raises
------
- builtins.ValueError
+ ValueError
If the size is not an integer power of 2 between 16 and 4096
(inclusive).
- builtins.RuntimeError
+ RuntimeError
If `ActivityAssets.large_image` points towards an unknown asset type.
"""
return self._make_asset_url(self.large_image, ext, size)
@@ -213,8 +213,8 @@ def make_large_image_url(self, *, ext: str = "png", size: int = 4096) -> typing.
def small_image_url(self) -> typing.Optional[files.URL]:
"""Small image asset URL.
- !!! note
- This will be `builtins.None` if no large image asset exists or if the
+ .. note::
+ This will be `None` if no large image asset exists or if the
asset's dynamic URL (indicated by a `{name}:` prefix) is not known.
"""
try:
@@ -228,24 +228,24 @@ def make_small_image_url(self, *, ext: str = "png", size: int = 4096) -> typing.
Parameters
----------
- ext : builtins.str
+ ext : str
The extension to use for this URL, defaults to `png`.
Supports `png`, `jpeg`, `jpg` and `webp`.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Returns
-------
typing.Optional[hikari.files.URL]
- The URL, or `builtins.None` if no icon exists.
+ The URL, or `None` if no icon exists.
Raises
------
- builtins.ValueError
+ ValueError
If the size is not an integer power of 2 between 16 and 4096
(inclusive).
- builtins.RuntimeError
+ RuntimeError
If `ActivityAssets.small_image` points towards an unknown asset type.
"""
return self._make_asset_url(self.small_image, ext, size)
@@ -274,22 +274,22 @@ class ActivityFlag(enums.Flag):
"""
INSTANCE = 1 << 0
- """Instance"""
+ """Instance."""
JOIN = 1 << 1
- """Join"""
+ """Join."""
SPECTATE = 1 << 2
- """Spectate"""
+ """Spectate."""
JOIN_REQUEST = 1 << 3
- """Join Request"""
+ """Join Request."""
SYNC = 1 << 4
- """Sync"""
+ """Sync."""
PLAY = 1 << 5
- """Play"""
+ """Play."""
PARTY_PRIVACY_FRIENDS = 1 << 6
"""Party privacy: friends only."""
@@ -328,9 +328,7 @@ class RichActivity(Activity):
"""When this activity was added to the user's session."""
timestamps: typing.Optional[ActivityTimestamps] = attr.field(repr=False)
- """The timestamps for when this activity's current state will start and
- end, if applicable.
- """
+ """The timestamps for when this activity's current state will start and end, if applicable."""
application_id: typing.Optional[snowflakes.Snowflake] = attr.field(repr=False)
"""The ID of the application this activity is for, if applicable."""
@@ -403,7 +401,7 @@ class MemberPresence:
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
user_id: snowflakes.Snowflake = attr.field(repr=True, hash=True)
"""The ID of the user this presence belongs to."""
diff --git a/hikari/scheduled_events.py b/hikari/scheduled_events.py
index f6d9cd0055..0c00f36908 100644
--- a/hikari/scheduled_events.py
+++ b/hikari/scheduled_events.py
@@ -103,7 +103,7 @@ class ScheduledEvent(snowflakes.Unique):
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
id: snowflakes.Snowflake = attr.field(hash=True, repr=True)
"""ID of the scheduled event."""
@@ -144,7 +144,7 @@ class ScheduledEvent(snowflakes.Unique):
user_count: typing.Optional[int] = attr.field(hash=False, repr=False)
"""The number of users that have subscribed to the event.
- This will be `builtins.None` on gateway events when creating and
+ This will be `None` on gateway events when creating and
editing a scheduled event.
"""
@@ -161,21 +161,21 @@ def make_image_url(self, *, ext: str = "png", size: int = 4096) -> typing.Option
Parameters
----------
- ext : builtins.str
+ ext : str
The extension to use for this URL, defaults to `png`.
Supports `png`, `jpeg`, `jpg` and `webp`.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Returns
-------
typing.Optional[hikari.files.URL]
- The URL, or `builtins.None` if no cover image is set.
+ The URL, or `None` if no cover image is set.
Raises
------
- builtins.ValueError
+ ValueError
If `size` is not a power of two between 16 and 4096 (inclusive).
"""
if self.image_hash is None:
@@ -198,7 +198,7 @@ class ScheduledExternalEvent(ScheduledEvent):
location: str = attr.field(hash=False, repr=False)
"""The location of the scheduled event.
- !!! note
+ .. note::
There is no strict format for this field, and it will likely be a user
friendly string.
"""
diff --git a/hikari/snowflakes.py b/hikari/snowflakes.py
index 9c6cc0335b..50155392a5 100644
--- a/hikari/snowflakes.py
+++ b/hikari/snowflakes.py
@@ -52,7 +52,7 @@
class Snowflake(int):
"""A concrete representation of a unique ID for an entity on Discord.
- This object can be treated as a regular `builtins.int` for most purposes.
+ This object can be treated as a regular `int` for most purposes.
"""
__slots__: typing.Sequence[str] = ()
@@ -109,13 +109,7 @@ class Unique(abc.ABC):
@property
@abc.abstractmethod
def id(self) -> Snowflake:
- """Return the ID of this entity.
-
- Returns
- -------
- Snowflake
- The snowflake ID of this object.
- """
+ """ID of this entity."""
@property
def created_at(self) -> datetime.datetime:
@@ -144,7 +138,7 @@ def calculate_shard_id(
Parameters
----------
- app_or_count : typing.Union[hikari.traits.ShardAware, builtins.int]
+ app_or_count : typing.Union[hikari.traits.ShardAware, int]
The shard aware app of the current application or the integer count of
the current app's shards.
guild : SnowflakeishOr[hikari.guilds.PartialGuild]
@@ -152,7 +146,7 @@ def calculate_shard_id(
Returns
-------
- builtins.int
+ int
The zero-indexed integer ID of the shard that should cover this guild.
"""
shard_count = app_or_count if isinstance(app_or_count, int) else app_or_count.shard_count
@@ -169,7 +163,7 @@ def calculate_shard_id(
The valid types for this type hint are:
-- `builtins.int`
+- `int`
- `Snowflake`
"""
@@ -181,8 +175,8 @@ def calculate_shard_id(
The valid types for this type hint are:
-- `builtins.str` containing digits.
-- `builtins.int`
+- `str` containing digits.
+- `int`
- `Snowflake`
- `datetime.datetime`
"""
@@ -195,7 +189,7 @@ def calculate_shard_id(
This is a value that is `Snowflake`-ish or a specific type covariant.
If you see `SnowflakeishOr[Foo]` anywhere as a type hint, it means the value
-may be a `Foo` instance, a `Snowflake`, a `builtins.int` or a `builtins.str`
+may be a `Foo` instance, a `Snowflake`, a `int` or a `str`
with numeric digits only.
Essentially this represents any concrete object, or ID of that object. It is
@@ -205,7 +199,7 @@ def calculate_shard_id(
The valid types for this type hint are:
-- `builtins.int`
+- `int`
- `Snowflake`
"""
@@ -222,7 +216,7 @@ def calculate_shard_id(
The valid types for this type hint are:
-- `builtins.int`
+- `int`
- `Snowflake`
- `datetime.datetime`
"""
diff --git a/hikari/stickers.py b/hikari/stickers.py
index 753214b2be..7d743b8e4a 100644
--- a/hikari/stickers.py
+++ b/hikari/stickers.py
@@ -72,7 +72,7 @@ class StickerFormatType(int, enums.Enum):
LOTTIE = 3
"""A lottie sticker.
- More information can be found here: https://airbnb.io/lottie/
+ More information can be found here:
"""
@@ -90,7 +90,7 @@ class StickerPack(snowflakes.Unique):
"""The description of the pack."""
cover_sticker_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=False)
- """The ID of a sticker in the pack which is shown as the pack's icon"""
+ """The ID of a sticker in the pack which is shown as the pack's icon."""
stickers: typing.Sequence[StandardSticker] = attr.field(eq=False, hash=False, repr=False)
"""The stickers that belong to this pack."""
@@ -112,10 +112,10 @@ def make_banner_url(self, *, ext: str = "png", size: int = 4096) -> files.URL:
Parameters
----------
- ext : builtins.str
+ ext : str
The extension to use for this URL, defaults to `png`.
Supports `png`, `jpeg`, `jpg` and `webp`.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
@@ -126,7 +126,7 @@ def make_banner_url(self, *, ext: str = "png", size: int = 4096) -> files.URL:
Raises
------
- builtins.ValueError
+ ValueError
If `size` is not a power of two or not between 16 and 4096.
"""
return routes.CDN_STICKER_PACK_BANNER.compile_to_file(
@@ -193,7 +193,7 @@ class GuildSticker(PartialSticker):
"""The description of this sticker."""
guild_id: snowflakes.Snowflake = attr.field(eq=False, hash=False)
- """The guild this sticker belongs to"""
+ """The guild this sticker belongs to."""
is_available: bool = attr.field(eq=False, hash=False)
"""Whether the sticker can be used."""
diff --git a/hikari/templates.py b/hikari/templates.py
index 616348fc32..cdbdcf6861 100644
--- a/hikari/templates.py
+++ b/hikari/templates.py
@@ -38,7 +38,6 @@
from hikari import channels as channels_
from hikari import colors
- from hikari import locales
from hikari import permissions as permissions_
from hikari import snowflakes
from hikari import users
@@ -50,7 +49,7 @@ class TemplateRole(guilds.PartialRole):
"""The partial role object attached to `Template`."""
permissions: permissions_.Permissions = attr.field(eq=False, hash=False, repr=False)
- """The guild wide permissions this role gives to the members it's attached to,
+ """The guild wide permissions this role gives to the members it's attached to.
This may be overridden by channel overwrites.
"""
@@ -64,7 +63,7 @@ class TemplateRole(guilds.PartialRole):
is_hoisted: bool = attr.field(eq=False, hash=False, repr=True)
"""Whether this role is hoisting the members it's attached to in the member list.
- members will be hoisted under their highest role where this is set to `builtins.True`.
+ members will be hoisted under their highest role where this is set to `True`.
"""
is_mentionable: bool = attr.field(eq=False, hash=False, repr=False)
@@ -92,7 +91,7 @@ class TemplateGuild(guilds.PartialGuild):
)
"""The setting for the explicit content filter in this guild."""
- preferred_locale: typing.Union[str, locales.Locale] = attr.field(eq=False, hash=False, repr=False)
+ preferred_locale: str = attr.field(eq=False, hash=False, repr=False)
"""The preferred locale to use for this guild.
This can only be change if `GuildFeature.COMMUNITY` is in `Guild.features`
@@ -109,7 +108,7 @@ class TemplateGuild(guilds.PartialGuild):
roles: typing.Mapping[snowflakes.Snowflake, TemplateRole] = attr.field(eq=False, hash=False, repr=False)
"""The roles in the guild.
- !!! note
+ .. note::
`hikari.guilds.Role.id` will be a unique placeholder on all the role
objects found attached this template guild.
"""
@@ -119,7 +118,7 @@ class TemplateGuild(guilds.PartialGuild):
)
"""The channels for the guild.
- !!! note
+ .. note::
`hikari.channels.GuildChannel.id` will be a unique placeholder on all
the channel objects found attached this template guild.
"""
@@ -127,11 +126,11 @@ class TemplateGuild(guilds.PartialGuild):
afk_channel_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=False)
"""The ID for the channel that AFK voice users get sent to.
- If `builtins.None`, then no AFK channel is set up for this guild.
+ If `None`, then no AFK channel is set up for this guild.
"""
system_channel_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=False)
- """The ID of the system channel or `builtins.None` if it is not enabled.
+ """The ID of the system channel or `None` if it is not enabled.
Welcome messages and Nitro boost messages may be sent to this channel.
"""
diff --git a/hikari/traits.py b/hikari/traits.py
index f1bd33a2d0..1ca8242111 100644
--- a/hikari/traits.py
+++ b/hikari/traits.py
@@ -76,24 +76,12 @@ class NetworkSettingsAware(fast_protocol.FastProtocolChecking, typing.Protocol):
@property
def http_settings(self) -> config.HTTPSettings:
- """Return the HTTP settings in use by this component.
-
- Returns
- -------
- hikari.config.HTTPSettings
- The HTTP settings in use.
- """
+ """HTTP settings in use by this component."""
raise NotImplementedError
@property
def proxy_settings(self) -> config.ProxySettings:
- """Return the proxy settings in use by this component.
-
- Returns
- -------
- hikari.config.ProxySettings
- The proxy settings in use.
- """
+ """Proxy settings in use by this component."""
raise NotImplementedError
@@ -108,13 +96,7 @@ class EventManagerAware(fast_protocol.FastProtocolChecking, typing.Protocol):
@property
def event_manager(self) -> event_manager_.EventManager:
- """Return the event manager for this object.
-
- Returns
- -------
- hikari.api.event_manager.EventManager
- The event manager component.
- """
+ """Event manager for this object."""
raise NotImplementedError
@@ -129,13 +111,7 @@ class EntityFactoryAware(fast_protocol.FastProtocolChecking, typing.Protocol):
@property
def entity_factory(self) -> entity_factory_.EntityFactory:
- """Return the entity factory implementation for this object.
-
- Returns
- -------
- hikari.api.entity_factory.EntityFactory
- The entity factory component.
- """
+ """Entity factory implementation for this object."""
raise NotImplementedError
@@ -144,7 +120,7 @@ class ExecutorAware(fast_protocol.FastProtocolChecking, typing.Protocol):
"""Structural supertype for an executor-aware object.
These components will contain an `executor` attribute that may return
- a `concurrent.futures.Executor` or `builtins.None` if the
+ a `concurrent.futures.Executor` or `None` if the
default `asyncio` thread pool for the event loop is used.
"""
@@ -152,16 +128,10 @@ class ExecutorAware(fast_protocol.FastProtocolChecking, typing.Protocol):
@property
def executor(self) -> typing.Optional[futures.Executor]:
- """Return the executor to use for blocking operations.
+ """Executor to use for blocking operations.
- This may return `builtins.None` if the default `asyncio` thread pool
+ This may return `None` if the default `asyncio` thread pool
should be used instead.
-
- Returns
- -------
- typing.Optional[concurrent.futures.Executor]
- The executor to use, or `builtins.None` to use the `asyncio` default
- instead.
"""
raise NotImplementedError
@@ -177,13 +147,7 @@ class EventFactoryAware(fast_protocol.FastProtocolChecking, typing.Protocol):
@property
def event_factory(self) -> event_factory_.EventFactory:
- """Return the event factory component.
-
- Returns
- -------
- hikari.api.event_factory.EventFactory
- The event factory component.
- """
+ """Event factory component."""
raise NotImplementedError
@@ -195,13 +159,7 @@ class IntentsAware(fast_protocol.FastProtocolChecking, typing.Protocol):
@property
def intents(self) -> intents_.Intents:
- """Return the intents registered for the application.
-
- Returns
- -------
- hikari.intents.Intents
- The intents registered on this application.
- """
+ """Intents registered for the application."""
raise NotImplementedError
@@ -218,13 +176,7 @@ class RESTAware(
@property
def rest(self) -> rest_.RESTClient:
- """Return the REST client to use for HTTP requests.
-
- Returns
- -------
- hikari.api.rest.RESTClient
- The REST client to use.
- """
+ """REST client to use for HTTP requests."""
raise NotImplementedError
@@ -240,13 +192,7 @@ class VoiceAware(fast_protocol.FastProtocolChecking, typing.Protocol):
@property
def voice(self) -> voice_.VoiceComponent:
- """Return the voice connection manager component for this application.
-
- Returns
- -------
- hikari.api.voice.VoiceComponent
- The voice component for the application.
- """
+ """Voice connection manager component for this application."""
raise NotImplementedError
@@ -269,61 +215,38 @@ class ShardAware(
@property
def heartbeat_latencies(self) -> typing.Mapping[int, float]:
- """Return a mapping of shard ID to heartbeat latency.
+ """Mapping of shard ID to heartbeat latency.
Any shards that are not yet started will be `float('nan')`.
-
- Returns
- -------
- typing.Mapping[builtins.int, builtins.float]
- Each shard ID mapped to the corresponding heartbeat latency.
- Each latency is measured in seconds.
- """
+ """ # noqa: D401 - Imperative mood
raise NotImplementedError
@property
def heartbeat_latency(self) -> float:
- """Return the average heartbeat latency of all started shards.
+ """Average heartbeat latency of all started shards.
If no shards are started, this will return `float('nan')`.
-
- Returns
- -------
- builtins.float
- The average heartbeat latency of all started shards, or
- `float('nan')` if no shards are started. This is measured
- in seconds.
"""
raise NotImplementedError
@property
def shards(self) -> typing.Mapping[int, gateway_shard.GatewayShard]:
- """Return a mapping of shards in this application instance.
+ """Mapping of shards in this application instance.
Each shard ID is mapped to the corresponding shard instance.
If the application has not started, it is acceptable to assume the
result of this call will be an empty mapping.
-
- Returns
- -------
- typing.Mapping[int, hikari.api.shard.GatewayShard]
- The shard mapping.
- """
+ """ # noqa: D401 - Imperative mood
raise NotImplementedError
@property
def shard_count(self) -> int:
- """Return the number of shards in the total application.
+ """Number of shards in the total application.
This may not be the same as the size of `shards`. If the application
is auto-sharded, this may be `0` until the shards are started.
-
- Returns
- -------
- builtins.int
- The number of shards in the total application.
- """
+ """ # noqa: D401 - Imperative mood
raise NotImplementedError
def get_me(self) -> typing.Optional[users_.OwnUser]:
@@ -332,20 +255,20 @@ def get_me(self) -> typing.Optional[users_.OwnUser]:
This should be available as soon as the bot has fired the
`hikari.events.lifetime_events.StartingEvent`.
- Until then, this may or may not be `builtins.None`.
+ Until then, this may or may not be `None`.
Returns
-------
typing.Optional[hikari.users.OwnUser]
- The bot user, if known, otherwise `builtins.None`.
+ The bot user, if known, otherwise `None`.
"""
raise NotImplementedError
async def update_presence(
self,
*,
- status: undefined.UndefinedOr[presences.Status] = undefined.UNDEFINED,
idle_since: undefined.UndefinedNoneOr[datetime.datetime] = undefined.UNDEFINED,
+ status: undefined.UndefinedOr[presences.Status] = undefined.UNDEFINED,
activity: undefined.UndefinedNoneOr[presences.Activity] = undefined.UNDEFINED,
afk: undefined.UndefinedOr[bool] = undefined.UNDEFINED,
) -> None:
@@ -356,13 +279,25 @@ async def update_presence(
retained. This means you do not have to track the global presence
in your code.
+ .. note::
+ This will only send the update payloads to shards that are alive.
+ Any shards that are not alive will cache the new presence for
+ when they do start.
+
+ .. note::
+ If you want to set presences per shard, access the shard you wish
+ to update (e.g. by using `GatewayBot.shards`), and call
+ `hikari.api.shard.GatewayShard.update_presence` on that shard.
+ This method is simply a facade to make performing this in bulk
+ simpler.
+
Other Parameters
----------------
idle_since : hikari.undefined.UndefinedNoneOr[datetime.datetime]
The datetime that the user started being idle. If undefined, this
will not be changed.
- afk : hikari.undefined.UndefinedOr[builtins.bool]
- If `builtins.True`, the user is marked as AFK. If `builtins.False`,
+ afk : hikari.undefined.UndefinedOr[bool]
+ If `True`, the user is marked as AFK. If `False`,
the user is marked as being active. If undefined, this will not be
changed.
activity : hikari.undefined.UndefinedNoneOr[hikari.presences.Activity]
@@ -370,19 +305,6 @@ async def update_presence(
changed.
status : hikari.undefined.UndefinedOr[hikari.presences.Status]
The web status to show. If undefined, this will not be changed.
-
- !!! note
- This will only send the update payloads to shards that are alive.
- Any shards that are not alive will cache the new presence for
- when they do start.
-
- !!! note
- If you want to set presences per shard, access the shard you wish
- to update (e.g. by using `GatewayBot.shards`), and call
- `hikari.api.shard.GatewayShard.update_presence` on that shard.
-
- This method is simply a facade to make performing this in bulk
- simpler.
"""
raise NotImplementedError
@@ -401,19 +323,19 @@ async def update_voice_state(
guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild]
The guild or guild ID to update the voice state for.
channel : typing.Optional[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildVoiceChannel]]
- The channel or channel ID to update the voice state for. If `builtins.None`
+ The channel or channel ID to update the voice state for. If `None`
then the bot will leave the voice channel that it is in for the
given guild.
- self_mute : builtins.bool
- If specified and `builtins.True`, the bot will mute itself in that
- voice channel. If `builtins.False`, then it will unmute itself.
- self_deaf : builtins.bool
- If specified and `builtins.True`, the bot will deafen itself in that
- voice channel. If `builtins.False`, then it will undeafen itself.
+ self_mute : bool
+ If specified and `True`, the bot will mute itself in that
+ voice channel. If `False`, then it will unmute itself.
+ self_deaf : bool
+ If specified and `True`, the bot will deafen itself in that
+ voice channel. If `False`, then it will undeafen itself.
Raises
------
- builtins.RuntimeError
+ RuntimeError
If the guild passed isn't covered by any of the shards in this sharded
client.
"""
@@ -430,28 +352,28 @@ async def request_guild_members(
) -> None:
"""Request for a guild chunk.
+ .. note::
+ To request the full list of members, set `query` to `""` (empty
+ string) and `limit` to `0`.
+
Parameters
----------
- guild: hikari.guilds.Guild
+ guild : hikari.guilds.Guild
The guild to request chunk for.
Other Parameters
----------------
- include_presences: hikari.undefined.UndefinedOr[builtins.bool]
+ include_presences : hikari.undefined.UndefinedOr[bool]
If provided, whether to request presences.
- query: builtins.str
+ query : str
If not `""`, request the members which username starts with the string.
- limit: builtins.int
+ limit : int
Maximum number of members to send matching the query.
- users: hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishSequence[hikari.users.User]]
+ users : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishSequence[hikari.users.User]]
If provided, the users to request for.
- nonce: hikari.undefined.UndefinedOr[builtins.str]
+ nonce : hikari.undefined.UndefinedOr[str]
If provided, the nonce to be sent with guild chunks.
- !!! note
- To request the full list of members, set `query` to `""` (empty
- string) and `limit` to `0`.
-
Raises
------
ValueError
@@ -460,7 +382,7 @@ async def request_guild_members(
hikari.errors.MissingIntentError
When trying to request presences without the `GUILD_MEMBERS` or when trying to
request the full list of members without `GUILD_PRESENCES`.
- builtins.RuntimeError
+ RuntimeError
If the guild passed isn't covered by any of the shards in this sharded
client.
"""
@@ -474,13 +396,7 @@ class InteractionServerAware(RESTAware, EntityFactoryAware, fast_protocol.FastPr
@property
def interaction_server(self) -> interaction_server_.InteractionServer:
- """Interaction server this app is bound to.
-
- Returns
- -------
- hikari.api.interaction_server.InteractionServer
- The interaction server this app is bound to.
- """
+ """Interaction server this app is bound to."""
raise NotImplementedError
@@ -495,13 +411,7 @@ class CacheAware(fast_protocol.FastProtocolChecking, typing.Protocol):
@property
def cache(self) -> cache_.Cache:
- """Return the immutable cache implementation for this object.
-
- Returns
- -------
- hikari.api.cache.Cache
- The cache component for this object.
- """
+ """Immutable cache implementation for this object."""
raise NotImplementedError
@@ -513,16 +423,11 @@ class Runnable(fast_protocol.FastProtocolChecking, typing.Protocol):
@property
def is_alive(self) -> bool:
- """Check whether the application is running or not.
+ """Whether the application is running or not.
This is useful as some functions might raise
`hikari.errors.ComponentStateConflictError` if this is
- `builtins.False`.
-
- Returns
- -------
- builtins.bool
- Whether the bot is running or not.
+ `False`.
"""
raise NotImplementedError
diff --git a/hikari/undefined.py b/hikari/undefined.py
index 4853646134..1d53496f00 100644
--- a/hikari/undefined.py
+++ b/hikari/undefined.py
@@ -91,17 +91,17 @@ def __new__(cls: UndefinedType) -> typing.NoReturn: # pragma: nocover
If you see a type with this marker, it may be `UNDEFINED` or the value it wraps.
For example, `UndefinedOr[float]` would mean the value could be a
-`builtins.float`, or the literal `UNDEFINED` value.
+`float`, or the literal `UNDEFINED` value.
On the other hand, `typing.Optional[float]` would mean the value could be
-a `builtins.float`, or the literal `builtins.None` value.
+a `float`, or the literal `None` value.
The reason for using this is in some places, there is a semantic difference
-between specifying something as being `builtins.None`, i.e. "no value", and
+between specifying something as being `None`, i.e. "no value", and
having a default to specify that the value has just not been mentioned. The
main example of this is in `edit` endpoints where the contents will only be
changed if they are explicitly mentioned in the call. Editing a message content
-and setting it to `builtins.None` would be expected to clear the content,
+and setting it to `None` would be expected to clear the content,
whereas setting it to `UNDEFINED` would be expected to leave the value as it
is without changing it.
@@ -112,13 +112,13 @@ def __new__(cls: UndefinedType) -> typing.NoReturn: # pragma: nocover
- `UNDEFINED` means there is no value present, or that it has been left to
the default value.
-- `builtins.None` means the value is present and explicitly empty/null/void,
+- `None` means the value is present and explicitly empty/null/void,
where this has a deterministic documented behaviour and no differentiation
- is made between a `builtins.None` value, and one that has been omitted.
+ is made between a `None` value, and one that has been omitted.
"""
UndefinedNoneOr = typing.Union[UndefinedOr[T], None]
-"""Type hint for a value that may be `undefined.UNDEFINED`, or `builtins.None`.
+"""Type hint for a value that may be `undefined.UNDEFINED`, or `None`.
`UndefinedNoneOr[T]` is simply an alias for
`UndefinedOr[typing.Optional[T]]`, which would expand to
diff --git a/hikari/users.py b/hikari/users.py
index 4efc7743ba..0c21eef006 100644
--- a/hikari/users.py
+++ b/hikari/users.py
@@ -55,7 +55,7 @@ class UserFlag(enums.Flag):
"""The known user flags that represent account badges."""
NONE = 0
- """None"""
+ """None."""
DISCORD_EMPLOYEE = 1 << 0
"""Discord Employee."""
@@ -143,7 +143,7 @@ def app(self) -> traits.RESTAware:
@property
@abc.abstractmethod
def avatar_hash(self) -> undefined.UndefinedNoneOr[str]:
- """Avatar hash for the user, if they have one, otherwise `builtins.None`."""
+ """Avatar hash for the user, if they have one, otherwise `None`."""
@property
@abc.abstractmethod
@@ -153,7 +153,7 @@ def banner_hash(self) -> undefined.UndefinedNoneOr[str]:
@property
@abc.abstractmethod
def accent_color(self) -> undefined.UndefinedNoneOr[colors.Color]:
- """The custom banner color for the user, if set else `builtins.None`.
+ """Custom banner color for the user if set, else `None`.
Will be `hikari.undefined.UNDEFINED` if not known.
@@ -178,12 +178,12 @@ def username(self) -> undefined.UndefinedOr[str]:
@property
@abc.abstractmethod
def is_bot(self) -> undefined.UndefinedOr[bool]:
- """`builtins.True` if this user is a bot account, `builtins.False` otherwise."""
+ """Whether this user is a bot account."""
@property
@abc.abstractmethod
def is_system(self) -> undefined.UndefinedOr[bool]:
- """`builtins.True` if this user is a system account, `builtins.False` otherwise."""
+ """Whether this user is a system account."""
@property
@abc.abstractmethod
@@ -195,18 +195,12 @@ def flags(self) -> undefined.UndefinedOr[UserFlag]:
def mention(self) -> str:
"""Return a raw mention string for the given user.
- Example
- -------
-
- ```py
- >>> some_user.mention
- '<@123456789123456789>'
- ```
+ Examples
+ --------
+ .. code-block:: python
- Returns
- -------
- builtins.str
- The mention string to use.
+ >>> some_user.mention
+ '<@123456789123456789>'
"""
async def fetch_dm_channel(self) -> channels.DMChannel:
@@ -297,7 +291,7 @@ async def send(
If provided, the message contents. If
`hikari.undefined.UNDEFINED`, then nothing will be sent
in the content. Any other value here will be cast to a
- `builtins.str`.
+ `str`.
If this is a `hikari.embeds.Embed` and no `embed` nor `embeds` kwarg
is provided, then this will instead update the embed. This allows
@@ -307,12 +301,37 @@ async def send(
content is instead treated as an attachment if no `attachment` and
no `attachments` kwargs are provided.
-
Other Parameters
----------------
attachment : hikari.undefined.UndefinedOr[hikari.files.Resourceish]
If provided, the message attachment. This can be a resource,
or string of a path on your computer or a URL.
+
+ Attachments can be passed as many different things, to aid in
+ convenience.
+
+ - If a `pathlib.PurePath` or `str` to a valid URL, the
+ resource at the given URL will be streamed to Discord when
+ sending the message. Subclasses of
+ `hikari.files.WebResource` such as
+ `hikari.files.URL`,
+ `hikari.messages.Attachment`,
+ `hikari.emojis.Emoji`,
+ `EmbedResource`, etc will also be uploaded this way.
+ This will use bit-inception, so only a small percentage of the
+ resource will remain in memory at any one time, thus aiding in
+ scalability.
+ - If a `hikari.files.Bytes` is passed, or a `str`
+ that contains a valid data URI is passed, then this is uploaded
+ with a randomized file name if not provided.
+ - If a `hikari.files.File`, `pathlib.PurePath` or
+ `str` that is an absolute or relative path to a file
+ on your file system is passed, then this resource is uploaded
+ as an attachment using non-blocking code internally and streamed
+ using bit-inception where possible. This depends on the
+ type of `concurrent.futures.Executor` that is being used for
+ the application (default is a thread pool which supports this
+ behaviour).
attachments : hikari.undefined.UndefinedOr[typing.Sequence[hikari.files.Resourceish]]
If provided, the message attachments. These can be resources, or
strings consisting of paths on your computer or URLs.
@@ -325,30 +344,30 @@ async def send(
If provided, the message embed.
embeds : hikari.undefined.UndefinedOr[typing.Sequence[hikari.embeds.Embed]]
If provided, the message embeds.
- tts : hikari.undefined.UndefinedOr[builtins.bool]
+ tts : hikari.undefined.UndefinedOr[bool]
If provided, whether the message will be read out by a screen
reader using Discord's TTS (text-to-speech) system.
reply : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage]]
If provided, the message to reply to.
- mentions_everyone : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_everyone : hikari.undefined.UndefinedOr[bool]
If provided, whether the message should parse @everyone/@here
mentions.
- mentions_reply : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_reply : hikari.undefined.UndefinedOr[bool]
If provided, whether to mention the author of the message
that is being replied to.
This will not do anything if not being used with `reply`.
- user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
- If provided, and `builtins.True`, all user mentions will be detected.
- If provided, and `builtins.False`, all user mentions will be ignored
+ user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], bool]]
+ If provided, and `True`, all user mentions will be detected.
+ If provided, and `False`, all user mentions will be ignored
if appearing in the message body.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.users.PartialUser` derivatives to enforce mentioning
specific users.
- role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], builtins.bool]]
- If provided, and `builtins.True`, all role mentions will be detected.
- If provided, and `builtins.False`, all role mentions will be ignored
+ role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], bool]]
+ If provided, and `True`, all role mentions will be detected.
+ If provided, and `False`, all role mentions will be ignored
if appearing in the message body.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
@@ -361,33 +380,6 @@ async def send(
Note that some flags may not be able to be set. Currently the only
flags that can be set are `NONE` and `SUPPRESS_EMBEDS`.
- !!! note
- Attachments can be passed as many different things, to aid in
- convenience.
-
- - If a `pathlib.PurePath` or `builtins.str` to a valid URL, the
- resource at the given URL will be streamed to Discord when
- sending the message. Subclasses of
- `hikari.files.WebResource` such as
- `hikari.files.URL`,
- `hikari.messages.Attachment`,
- `hikari.emojis.Emoji`,
- `EmbedResource`, etc will also be uploaded this way.
- This will use bit-inception, so only a small percentage of the
- resource will remain in memory at any one time, thus aiding in
- scalability.
- - If a `hikari.files.Bytes` is passed, or a `builtins.str`
- that contains a valid data URI is passed, then this is uploaded
- with a randomized file name if not provided.
- - If a `hikari.files.File`, `pathlib.PurePath` or
- `builtins.str` that is an absolute or relative path to a file
- on your file system is passed, then this resource is uploaded
- as an attachment using non-blocking code internally and streamed
- using bit-inception where possible. This depends on the
- type of `concurrent.futures.Executor` that is being used for
- the application (default is a thread pool which supports this
- behaviour).
-
Returns
-------
hikari.messages.Message
@@ -395,10 +387,10 @@ async def send(
Raises
------
- builtins.ValueError
+ ValueError
If more than 100 unique objects/entities are passed for
`role_mentions` or `user_mentions`.
- builtins.TypeError
+ TypeError
If both `attachment` and `attachments` are specified.
hikari.errors.BadRequestError
This may be raised in several discrete situations, such as messages
@@ -470,7 +462,7 @@ def app(self) -> traits.RESTAware:
@property
@abc.abstractmethod
def accent_color(self) -> typing.Optional[colors.Color]:
- """The custom banner color for the user, if set else `builtins.None`.
+ """The custom banner color for the user, if set else `None`.
The official client will decide the default color if not set.
""" # noqa: D401 - Imperative mood
@@ -483,13 +475,13 @@ def accent_colour(self) -> typing.Optional[colors.Color]:
@property
@abc.abstractmethod
def avatar_hash(self) -> typing.Optional[str]:
- """Avatar hash for the user, if they have one, otherwise `builtins.None`."""
+ """Avatar hash for the user, if they have one, otherwise `None`."""
@property
def avatar_url(self) -> typing.Optional[files.URL]:
"""Avatar URL for the user, if they have one set.
- May be `builtins.None` if no custom avatar is set. In this case, you
+ May be `None` if no custom avatar is set. In this case, you
should use `default_avatar_url` instead.
"""
return self.make_avatar_url()
@@ -503,7 +495,7 @@ def banner_hash(self) -> typing.Optional[str]:
def banner_url(self) -> typing.Optional[files.URL]:
"""Banner URL for the user, if they have one set.
- May be `builtins.None` if no custom banner is set.
+ May be `None` if no custom banner is set.
"""
return self.make_banner_url()
@@ -534,30 +526,24 @@ def flags(self) -> UserFlag:
@property
@abc.abstractmethod
def is_bot(self) -> bool:
- """`builtins.True` if this user is a bot account, `builtins.False` otherwise."""
+ """Whether this user is a bot account."""
@property
@abc.abstractmethod
def is_system(self) -> bool:
- """`builtins.True` if this user is a system account, `builtins.False` otherwise."""
+ """Whether this user is a system account."""
@property
@abc.abstractmethod
def mention(self) -> str:
"""Return a raw mention string for the given user.
- Example
- -------
-
- ```py
- >>> some_user.mention
- '<@123456789123456789>'
- ```
+ Examples
+ --------
+ .. code-block:: python
- Returns
- -------
- builtins.str
- The mention string to use.
+ >>> some_user.mention
+ '<@123456789123456789>'
"""
@property
@@ -568,21 +554,21 @@ def username(self) -> str:
def make_avatar_url(self, *, ext: typing.Optional[str] = None, size: int = 4096) -> typing.Optional[files.URL]:
"""Generate the avatar URL for this user, if set.
- If no custom avatar is set, this returns `builtins.None`. You can then
+ If no custom avatar is set, this returns `None`. You can then
use the `default_avatar_url` attribute instead to fetch the displayed
URL.
Parameters
----------
- ext : typing.Optional[builtins.str]
+ ext : typing.Optional[str]
The ext to use for this URL, defaults to `png` or `gif`.
Supports `png`, `jpeg`, `jpg`, `webp` and `gif` (when
animated). Will be ignored for default avatars which can only be
`png`.
- If `builtins.None`, then the correct default extension is
+ If `None`, then the correct default extension is
determined based on whether the icon is animated or not.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Will be ignored for default avatars.
@@ -590,11 +576,11 @@ def make_avatar_url(self, *, ext: typing.Optional[str] = None, size: int = 4096)
Returns
-------
typing.Optional[hikari.files.URL]
- The URL to the avatar, or `builtins.None` if not present.
+ The URL to the avatar, or `None` if not present.
Raises
------
- builtins.ValueError
+ ValueError
If `size` is not a power of two or not between 16 and 4096.
"""
if self.avatar_hash is None:
@@ -617,29 +603,29 @@ def make_avatar_url(self, *, ext: typing.Optional[str] = None, size: int = 4096)
def make_banner_url(self, *, ext: typing.Optional[str] = None, size: int = 4096) -> typing.Optional[files.URL]:
"""Generate the banner URL for this user, if set.
- If no custom banner is set, this returns `builtins.None`.
+ If no custom banner is set, this returns `None`.
Parameters
----------
- ext : typing.Optional[builtins.str]
+ ext : typing.Optional[str]
The ext to use for this URL, defaults to `png` or `gif`.
Supports `png`, `jpeg`, `jpg`, `webp` and `gif` (when
animated).
- If `builtins.None`, then the correct default extension is
+ If `None`, then the correct default extension is
determined based on whether the banner is animated or not.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Returns
-------
typing.Optional[hikari.files.URL]
- The URL to the banner, or `builtins.None` if not present.
+ The URL to the banner, or `None` if not present.
Raises
------
- builtins.ValueError
+ ValueError
If `size` is not a power of two or not between 16 and 4096.
"""
if self.banner_hash is None:
@@ -675,7 +661,7 @@ class PartialUserImpl(PartialUser):
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """Reference to the client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
discriminator: undefined.UndefinedOr[str] = attr.field(eq=False, hash=False, repr=True)
"""Four-digit discriminator for the user."""
@@ -708,18 +694,12 @@ class PartialUserImpl(PartialUser):
def mention(self) -> str:
"""Return a raw mention string for the given user.
- Example
- -------
+ Examples
+ --------
+ .. code-block:: python
- ```py
- >>> some_user.mention
- '<@123456789123456789>'
- ```
-
- Returns
- -------
- builtins.str
- The mention string to use.
+ >>> some_user.mention
+ '<@123456789123456789>'
"""
return f"<@{self.id}>"
@@ -740,10 +720,10 @@ class UserImpl(PartialUserImpl, User):
"""The user's username."""
avatar_hash: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
- """The user's avatar hash, if they have one, otherwise `builtins.None`."""
+ """The user's avatar hash, if they have one, otherwise `None`."""
banner_hash: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
- """Banner hash of the user, if they have one, otherwise `builtins.None`"""
+ """Banner hash of the user, if they have one, otherwise `None`"""
accent_color: typing.Optional[colors.Color] = attr.field(eq=False, hash=False, repr=False)
"""The custom banner color for the user, if set.
@@ -752,10 +732,10 @@ class UserImpl(PartialUserImpl, User):
"""
is_bot: bool = attr.field(eq=False, hash=False, repr=True)
- """`builtins.True` if this user is a bot account, `builtins.False` otherwise."""
+ """`True` if this user is a bot account, `False` otherwise."""
is_system: bool = attr.field(eq=False, hash=False, repr=True)
- """`builtins.True` if this user is a system account, `builtins.False` otherwise."""
+ """`True` if this user is a system account, `False` otherwise."""
flags: UserFlag = attr.field(eq=False, hash=False, repr=True)
"""The public flags for this user."""
@@ -777,21 +757,21 @@ class OwnUser(UserImpl):
is_verified: typing.Optional[bool] = attr.field(eq=False, hash=False, repr=False)
"""Whether the email for this user's account has been verified.
- Will be `builtins.None` if retrieved through the OAuth2 flow without the `email`
+ Will be `None` if retrieved through the OAuth2 flow without the `email`
scope.
"""
email: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
"""The user's set email.
- Will be `builtins.None` if retrieved through OAuth2 flow without the `email`
- scope. Will always be `builtins.None` for bot users.
+ Will be `None` if retrieved through OAuth2 flow without the `email`
+ scope. Will always be `None` for bot users.
"""
premium_type: typing.Union[PremiumType, int, None] = attr.field(eq=False, hash=False, repr=False)
"""The type of Nitro Subscription this user account had.
- This will always be `builtins.None` for bots.
+ This will always be `None` for bots.
"""
async def fetch_self(self) -> OwnUser:
diff --git a/hikari/voices.py b/hikari/voices.py
index 37196964c0..bf36dee9ac 100644
--- a/hikari/voices.py
+++ b/hikari/voices.py
@@ -48,12 +48,12 @@ class VoiceState:
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
channel_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False, hash=False, repr=True)
"""The ID of the channel this user is connected to.
- This will be `builtins.None` if they are leaving voice.
+ This will be `None` if they are leaving voice.
"""
guild_id: snowflakes.Snowflake = attr.field(eq=False, hash=False, repr=True)
@@ -96,7 +96,7 @@ class VoiceState:
requested_to_speak_at: typing.Optional[datetime.datetime] = attr.field(eq=False, hash=False, repr=True)
"""When the user requested to speak in a stage channel.
- Will be `builtins.None` if they have not requested to speak.
+ Will be `None` if they have not requested to speak.
"""
@@ -108,7 +108,7 @@ class VoiceRegion:
id: str = attr.field(hash=True, repr=True)
"""The string ID of this region.
- !!! note
+ .. note::
Unlike most parts of this API, this ID will always be a string type.
This is intentional.
"""
diff --git a/hikari/webhooks.py b/hikari/webhooks.py
index c5b9429073..fb4238a739 100644
--- a/hikari/webhooks.py
+++ b/hikari/webhooks.py
@@ -80,38 +80,21 @@ class ExecutableWebhook(abc.ABC):
@property
@abc.abstractmethod
def app(self) -> traits.RESTAware:
- """Client application that models may use for procedures.
-
- Returns
- -------
- hikari.traits.RESTAware
- The client application that models may use for procedures.
- """
+ """Client application that models may use for procedures."""
@property
@abc.abstractmethod
def webhook_id(self) -> snowflakes.Snowflake:
- """ID used to execute this entity as a webhook.
-
- Returns
- -------
- hikari.snowflakes.Snowflake
- The ID used to execute this entity as a webhook.
- """
+ """ID used to execute this entity as a webhook."""
@property
@abc.abstractmethod
def token(self) -> typing.Optional[str]:
"""Webhook's token.
- !!! info
- If this is `builtins.None` then the methods provided by `ExecutableWebhook`
- will always raise a `builtins.ValueError`.
-
- Returns
- -------
- typing.Optional[builtins.str]
- The token for the webhook if known, else `builtins.None`.
+ .. note::
+ If this is `None` then the methods provided by `ExecutableWebhook`
+ will always raise a `ValueError`.
"""
async def execute(
@@ -138,13 +121,21 @@ async def execute(
) -> messages_.Message:
"""Execute the webhook to create a message.
+ .. warning::
+ At the time of writing, `username` and `avatar_url` are ignored for
+ interaction webhooks.
+
+ Additionally, flags this can only be set for interaction webhooks
+ and the only settable flag is EPHEMERAL; this field is just
+ ignored for non-interaction webhooks.
+
Parameters
----------
content : hikari.undefined.UndefinedOr[typing.Any]
If provided, the message contents. If
`hikari.undefined.UNDEFINED`, then nothing will be sent
in the content. Any other value here will be cast to a
- `builtins.str`.
+ `str`.
If this is a `hikari.embeds.Embed` and no `embed` kwarg is
provided, then this will instead update the embed. This allows for
@@ -156,10 +147,10 @@ async def execute(
Other Parameters
----------------
- username : hikari.undefined.UndefinedOr[builtins.str]
+ username : hikari.undefined.UndefinedOr[str]
If provided, the username to override the webhook's username
for this request.
- avatar_url : typing.Union[hikari.undefined.UndefinedType, builtins.str, hikari.files.URL]
+ avatar_url : typing.Union[hikari.undefined.UndefinedType, hikari.files.URL, str]
If provided, the url of an image to override the webhook's
avatar with for this request.
tts : hikari.undefined.UndefinedOr[bool]
@@ -179,35 +170,26 @@ async def execute(
If provided, the message embed.
embeds : hikari.undefined.UndefinedOr[typing.Sequence[hikari.embeds.Embed]]
If provided, the message embeds.
- mentions_everyone : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_everyone : hikari.undefined.UndefinedOr[bool]
If provided, whether the message should parse @everyone/@here
mentions.
- user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
- If provided, and `builtins.True`, all mentions will be parsed.
- If provided, and `builtins.False`, no mentions will be parsed.
+ user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], bool]]
+ If provided, and `True`, all mentions will be parsed.
+ If provided, and `False`, no mentions will be parsed.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.users.PartialUser` derivatives to enforce mentioning
specific users.
- role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], builtins.bool]]
- If provided, and `builtins.True`, all mentions will be parsed.
- If provided, and `builtins.False`, no mentions will be parsed.
+ role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], bool]]
+ If provided, and `True`, all mentions will be parsed.
+ If provided, and `False`, no mentions will be parsed.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.guilds.PartialRole` derivatives to enforce mentioning
specific roles.
- flags : typing.Union[hikari.undefined.UndefinedType, builtins.int, hikari.messages.MessageFlag]
+ flags : typing.Union[hikari.undefined.UndefinedType, int, hikari.messages.MessageFlag]
The flags to set for this webhook message.
- !!! warning
- As of writing the only flags which can be passed here are
- `EPHEMERAL` (if this is an interaction response webhook) and
- `SUPPRESS_EMBEDS`.
-
- !!! warning
- As of writing, `username` and `avatar_url` are ignored for
- interaction webhooks.
-
Returns
-------
hikari.messages.Message
@@ -226,12 +208,13 @@ async def execute(
due to it being outside of the range of a 64 bit integer.
hikari.errors.UnauthorizedError
If you pass a token that's invalid for the target webhook.
- builtins.ValueError
- If either `ExecutableWebhook.token` is `builtins.None` or more than 100 unique
- objects/entities are passed for `role_mentions` or `user_mentions or
+ ValueError
+ If either `ExecutableWebhook.token` is `None` or more than 100 unique
+ objects/entities are passed for `role_mentions` or `user_mentions` or
if `token` is not available.
- builtins.TypeError
- If both `attachment` and `attachments` are specified.
+ TypeError
+ If both `attachment` and `attachments`, `component` and `components`
+ or `embed` and `embeds` are specified.
""" # noqa: E501 - Line too long
if not self.token:
raise ValueError("Cannot send a message using a webhook where we don't know the token")
@@ -271,7 +254,7 @@ async def fetch_message(self, message: snowflakes.SnowflakeishOr[messages_.Messa
Raises
------
- builtins.ValueError
+ ValueError
If `token` is not available.
hikari.errors.UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
@@ -323,6 +306,21 @@ async def edit_message(
) -> messages_.Message:
"""Edit a message sent by a webhook.
+ .. note::
+ Mentioning everyone, roles, or users in message edits currently
+ will not send a push notification showing a new mention to people
+ on Discord. It will still highlight in their chat as if they
+ were mentioned, however.
+
+ .. warning::
+ If you specify a text `content`, `mentions_everyone`,
+ `mentions_reply`, `user_mentions`, and `role_mentions` will default
+ to `False` as the message will be re-parsed for mentions. This will
+ also occur if only one of the four are specified
+
+ This is a limitation of Discord's design. If in doubt, specify all
+ four of them each time.
+
Parameters
----------
message : hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage]
@@ -332,7 +330,7 @@ async def edit_message(
If provided, the message contents. If
`hikari.undefined.UNDEFINED`, then nothing will be sent
in the content. Any other value here will be cast to a
- `builtins.str`.
+ `str`.
If this is a `hikari.embeds.Embed` and no `embed` nor
no `embeds` kwarg is provided, then this will instead
@@ -348,81 +346,59 @@ async def edit_message(
attachment : hikari.undefined.UndefinedNoneOr[typing.Union[hikari.files.Resourceish, hikari.messages.Attachment]]
If provided, the attachment to set on the message. If
`hikari.undefined.UNDEFINED`, the previous attachment, if
- present, is not changed. If this is `builtins.None`, then the
+ present, is not changed. If this is `None`, then the
attachment is removed, if present. Otherwise, the new attachment
that was provided will be attached.
attachments : hikari.undefined.UndefinedNoneOr[typing.Sequence[typing.Union[hikari.files.Resourceish, hikari.messages.Attachment]]]
If provided, the attachments to set on the message. If
`hikari.undefined.UNDEFINED`, the previous attachments, if
- present, are not changed. If this is `builtins.None`, then the
+ present, are not changed. If this is `None`, then the
attachments is removed, if present. Otherwise, the new attachments
that were provided will be attached.
component : hikari.undefined.UndefinedNoneOr[hikari.api.special_endpoints.ComponentBuilder]
If provided, builder object of the component to set for this message.
This component will replace any previously set components and passing
- `builtins.None` will remove all components.
+ `None` will remove all components.
components : hikari.undefined.UndefinedNoneOr[typing.Sequence[hikari.api.special_endpoints.ComponentBuilder]]
If provided, a sequence of the component builder objects set for
this message. These components will replace any previously set
- components and passing `builtins.None` or an empty sequence will
+ components and passing `None` or an empty sequence will
remove all components.
embed : hikari.undefined.UndefinedNoneOr[hikari.embeds.Embed]
If provided, the embed to set on the message. If
`hikari.undefined.UNDEFINED`, the previous embed(s) are not changed.
- If this is `builtins.None` then any present embeds are removed.
+ If this is `None` then any present embeds are removed.
Otherwise, the new embed that was provided will be used as the
replacement.
embeds : hikari.undefined.UndefinedNoneOr[typing.Sequence[hikari.embeds.Embed]]
If provided, the embeds to set on the message. If
`hikari.undefined.UNDEFINED`, the previous embed(s) are not changed.
- If this is `builtins.None` then any present embeds are removed.
+ If this is `None` then any present embeds are removed.
Otherwise, the new embeds that were provided will be used as the
replacement.
- mentions_everyone : hikari.undefined.UndefinedOr[builtins.bool]
+ mentions_everyone : hikari.undefined.UndefinedOr[bool]
If provided, sanitation for `@everyone` mentions. If
`hikari.undefined.UNDEFINED`, then the previous setting is
- not changed. If `builtins.True`, then `@everyone`/`@here` mentions
+ not changed. If `True`, then `@everyone`/`@here` mentions
in the message content will show up as mentioning everyone that can
view the chat.
- user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]
- If provided, and `builtins.True`, all user mentions will be detected.
- If provided, and `builtins.False`, all user mentions will be ignored
+ user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], bool]]
+ If provided, and `True`, all user mentions will be detected.
+ If provided, and `False`, all user mentions will be ignored
if appearing in the message body.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.users.PartialUser` derivatives to enforce mentioning
specific users.
- role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], builtins.bool]]
- If provided, and `builtins.True`, all role mentions will be detected.
- If provided, and `builtins.False`, all role mentions will be ignored
+ role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], bool]]
+ If provided, and `True`, all role mentions will be detected.
+ If provided, and `False`, all role mentions will be ignored
if appearing in the message body.
Alternatively this may be a collection of
`hikari.snowflakes.Snowflake`, or
`hikari.guilds.PartialRole` derivatives to enforce mentioning
specific roles.
- !!! note
- Mentioning everyone, roles, or users in message edits currently
- will not send a push notification showing a new mention to people
- on Discord. It will still highlight in their chat as if they
- were mentioned, however.
-
- !!! warning
- If you specify a non-embed `content`, `mentions_everyone`,
- `mentions_reply`, `user_mentions`, and `role_mentions` will default
- to `builtins.False` as the message will be re-parsed for mentions.
-
- This is a limitation of Discord's design. If in doubt, specify all
- three of them each time.
-
- !!! warning
- If you specify one of `mentions_everyone`, `mentions_reply`,
- `user_mentions`, or `role_mentions`, then all others will default to
- `builtins.False`, even if they were enabled previously.
-
- This is a limitation of Discord's design. If in doubt, specify all
- three of them each time.
-
Returns
-------
hikari.messages.Message
@@ -430,10 +406,10 @@ async def edit_message(
Raises
------
- builtins.ValueError
+ ValueError
If more than 100 unique objects/entities are passed for
`role_mentions` or `user_mentions` or `token` is not available.
- builtins.TypeError
+ TypeError
If both `attachment` and `attachments` are specified or if both
`embed` and `embeds` are specified.
hikari.errors.BadRequestError
@@ -490,7 +466,7 @@ async def delete_message(self, message: snowflakes.SnowflakeishOr[messages_.Mess
Raises
------
- builtins.ValueError
+ ValueError
If `token` is not available.
hikari.errors.UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
@@ -524,7 +500,7 @@ class PartialWebhook(snowflakes.Unique):
app: traits.RESTAware = attr.field(
repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
)
- """The client application that models may use for procedures."""
+ """Client application that models may use for procedures."""
id: snowflakes.Snowflake = attr.field(hash=True, repr=True)
"""The ID of this entity."""
@@ -548,23 +524,17 @@ def __str__(self) -> str:
def mention(self) -> str:
"""Return a raw mention string for the given webhook's user.
- !!! note
+ .. note::
This exists purely for consistency. Webhooks do not receive events
from the gateway, and without some bot backend to support it, will
not be able to detect mentions of their webhook.
- Example
- -------
+ Examples
+ --------
+ .. code-block:: python
- ```py
- >>> some_webhook.mention
- '<@123456789123456789>'
- ```
-
- Returns
- -------
- builtins.str
- The mention string to use.
+ >>> some_webhook.mention
+ '<@123456789123456789>'
"""
return f"<@{self.id}>"
@@ -572,18 +542,14 @@ def mention(self) -> str:
def avatar_url(self) -> typing.Optional[files_.URL]:
"""URL for this webhook's avatar, if set.
- May be `builtins.None` if no avatar is set. In this case, you should use
+ May be `None` if no avatar is set. In this case, you should use
`default_avatar_url` instead.
"""
return self.make_avatar_url()
@property
def default_avatar_url(self) -> files_.URL:
- """Avatar URL for the user, if they have one set.
-
- May be `builtins.None` if no custom avatar is set. In this case, you
- should use `default_avatar_url` instead.
- """
+ """Default avatar URL for the user.""" # noqa: D401 - Imperative mood
return routes.CDN_DEFAULT_USER_AVATAR.compile_to_file(
urls.CDN_URL,
discriminator=0,
@@ -598,10 +564,10 @@ def make_avatar_url(self, ext: str = "png", size: int = 4096) -> typing.Optional
Parameters
----------
- ext : builtins.str
+ ext : str
The extension to use for this URL, defaults to `png`.
Supports `png`, `jpeg`, `jpg` and `webp`.
- size : builtins.int
+ size : int
The size to set for the URL, defaults to `4096`.
Can be any power of two between 16 and 4096.
Will be ignored for default avatars.
@@ -609,12 +575,12 @@ def make_avatar_url(self, ext: str = "png", size: int = 4096) -> typing.Optional
Returns
-------
typing.Optional[hikari.files.URL]
- The URL of the resource. `builtins.None` if no avatar is set (in
+ The URL of the resource. `None` if no avatar is set (in
this case, use the `default_avatar` instead).
Raises
------
- builtins.ValueError
+ ValueError
If `size` is not a power of two between 16 and 4096 (inclusive).
"""
if self.avatar_hash is None:
@@ -645,17 +611,17 @@ class IncomingWebhook(PartialWebhook, ExecutableWebhook):
"""The guild ID of the webhook."""
author: typing.Optional[users_.User] = attr.field(eq=False, hash=False, repr=True)
- """The user that created the webhook
+ """The user that created the webhook.
- !!! info
- This will be `builtins.None` when fetched with the webhook's token
+ .. note::
+ This will be `None` when fetched with the webhook's token
rather than bot authorization or when received within audit logs.
"""
token: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
"""The token for the webhook.
- !!! info
+ .. note::
This is only available for incoming webhooks that are created in the
channel settings.
"""
@@ -670,9 +636,9 @@ async def delete(self, *, use_token: undefined.UndefinedOr[bool] = undefined.UND
Other Parameters
----------------
- use_token : hikari.undefined.UndefinedOr[builtins.bool]
- If set to `builtins.True` then the webhook's token will be used for
- this request; if set to `builtins.False` then bot authorization will
+ use_token : hikari.undefined.UndefinedOr[bool]
+ If set to `True` then the webhook's token will be used for
+ this request; if set to `False` then bot authorization will
be used; if not specified then the webhook's token will be used for
the request if it's set else bot authorization.
@@ -683,9 +649,9 @@ async def delete(self, *, use_token: undefined.UndefinedOr[bool] = undefined.UND
hikari.errors.ForbiddenError
If you either lack the `MANAGE_WEBHOOKS` permission or
are not a member of the guild this webhook belongs to.
- builtins.ValueError
- If `use_token` is passed as `builtins.True` when `IncomingWebhook.token` is
- `builtins.None`.
+ ValueError
+ If `use_token` is passed as `True` when `IncomingWebhook.token` is
+ `None`.
"""
token: undefined.UndefinedOr[str] = undefined.UNDEFINED
if use_token:
@@ -711,21 +677,21 @@ async def edit(
Other Parameters
----------------
- name : hikari.undefined.UndefinedOr[builtins.str]
+ name : hikari.undefined.UndefinedOr[str]
If provided, the new name string.
avatar : hikari.undefined.UndefinedOr[hikari.files.Resourceish]
- If provided, the new avatar image. If `builtins.None`, then
+ If provided, the new avatar image. If `None`, then
it is removed. If not specified, nothing is changed.
channel : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.WebhookChannelT]]
If provided, the object or ID of the new channel the given
webhook should be moved to.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the audit log reason explaining why the operation
was performed. This field will be used when using the webhook's
token rather than bot authorization.
- use_token : hikari.undefined.UndefinedOr[builtins.bool]
- If set to `builtins.True` then the webhook's token will be used for
- this request; if set to `builtins.False` then bot authorization will
+ use_token : hikari.undefined.UndefinedOr[bool]
+ If set to `True` then the webhook's token will be used for
+ this request; if set to `False` then bot authorization will
be used; if not specified then the webhook's token will be used for
the request if it's set else bot authorization.
@@ -736,8 +702,8 @@ async def edit(
Raises
------
- builtins.ValueError
- If `use_token` is passed as `builtins.True` when `IncomingWebhook.token` is `builtins.None`.
+ ValueError
+ If `use_token` is passed as `True` when `IncomingWebhook.token` is `None`.
hikari.errors.BadRequestError
If any invalid snowflake IDs are passed; a snowflake may be invalid
due to it being outside of the range of a 64 bit integer.
@@ -821,9 +787,9 @@ async def fetch_self(self, *, use_token: undefined.UndefinedOr[bool] = undefined
Other Parameters
----------------
- use_token : hikari.undefined.UndefinedOr[builtins.bool]
- If set to `builtins.True` then the webhook's token will be used for
- this request; if set to `builtins.False` then bot authorization will
+ use_token : hikari.undefined.UndefinedOr[bool]
+ If set to `True` then the webhook's token will be used for
+ this request; if set to `False` then bot authorization will
be used; if not specified then the webhook's token will be used for
the request if it's set else bot authorization.
@@ -834,9 +800,9 @@ async def fetch_self(self, *, use_token: undefined.UndefinedOr[bool] = undefined
Raises
------
- builtins.ValueError
- If `use_token` is passed as `builtins.True` when `Webhook.token`
- is `builtins.None`.
+ ValueError
+ If `use_token` is passed as `True` when `Webhook.token`
+ is `None`.
hikari.errors.ForbiddenError
If you're not in the guild that owns this webhook or
lack the `MANAGE_WEBHOOKS` permission.
@@ -883,10 +849,10 @@ class ChannelFollowerWebhook(PartialWebhook):
"""The guild ID of the webhook."""
author: typing.Optional[users_.User] = attr.field(eq=False, hash=False, repr=True)
- """The user that created the webhook
+ """The user that created the webhook.
- !!! info
- This will be `builtins.None` when received within an audit log.
+ .. note::
+ This will be `None` when received within an audit log.
"""
source_channel: channels_.PartialChannel = attr.field(eq=False, hash=False, repr=True)
@@ -920,15 +886,15 @@ async def edit(
Other Parameters
----------------
- name : hikari.undefined.UndefinedOr[builtins.str]
+ name : hikari.undefined.UndefinedOr[str]
If provided, the new name string.
avatar : hikari.undefined.UndefinedOr[hikari.files.Resourceish]
- If provided, the new avatar image. If `builtins.None`, then
+ If provided, the new avatar image. If `None`, then
it is removed. If not specified, nothing is changed.
channel : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.WebhookChannelT]]
If provided, the object or ID of the new channel the given
webhook should be moved to.
- reason : hikari.undefined.UndefinedOr[builtins.str]
+ reason : hikari.undefined.UndefinedOr[str]
If provided, the audit log reason explaining why the operation
was performed. This field will be used when using the webhook's
token rather than bot authorization.
diff --git a/pages/CNAME b/pages/CNAME
deleted file mode 100644
index feec4f389e..0000000000
--- a/pages/CNAME
+++ /dev/null
@@ -1 +0,0 @@
-www.hikari-py.dev
diff --git a/pages/index.html b/pages/index.html
deleted file mode 100644
index e4ddf7124d..0000000000
--- a/pages/index.html
+++ /dev/null
@@ -1,161 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
- Hikari
-
-
-
-
-
-
-
-
- oooo o8o oooo o8o © 2020 Nekokatt, licensed under MIT
- `888 `"' `888 `"' Installed at: /home/hikari-py/code/hikari
- 888 .oo. oooo 888 oooo .oooo. oooo d8b oooo Support: https://discord.gg/Jx4cNGG
- 888P"Y88b `888 888 .8P' `P )88b `888""8P `888 Documentation: https://hikari-py.dev/hikari
- 888 888 888 888888. .oP"888 888 888
- 888 888 888 888 `88b. d8( 888 888 888 CPython 3.8.5
- o888o o888o o888o o888o o888o `Y888""8o d888b o888o compiled with GCC 10.1.0 (default May 17 2020 18:15:42)
-
- v2.0.0
-
- I 2020-07-15 16:45:11,476 hikari: single-sharded configuration -- you have started 29/1000 sessions prior to connecting (resets at 16/07/20 11:38:05 BST)
- I 2020-07-15 16:45:11,779 hikari.gateway.0: received HELLO, heartbeat interval is 41.25s
- I 2020-07-15 16:45:11,958 hikari.gateway.0: shard is ready [session:1aa5f3fde733687ae7b41b1b55b29792, user_id:572144340277919754, tag:hikari#5863]
-
- ^C
- Terminated 13897
- [nekokatt@pc ~/hikari ] $ cat bot.py
-
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import asyncio
- import functools
- import os
-
- import hikari
-
- bot = hikari.Bot(token=os.environ["BOT_TOKEN"])
-
-
- def command(name):
- def decorator(fn):
- @functools.wraps(fn)
- async def wrapper(event):
- if event.is_human and event.message.content.startswith(name):
- await fn(event)
-
- return wrapper
-
- return decorator
-
-
- @bot.listen()
- @command("hk.ping")
- async def ping(event: hikari.MessageCreateEvent) -> None:
- await event.message.respond("Pong!")
-
-
- @bot.listen()
- @command("hk.add")
- async def add_numbers(event: hikari.MessageCreateEvent) -> None:
- def is_number_check(e):
- return (
- event.message.author == e.message.author
- and event.message.channel_id == e.message.channel_id
- and e.message.content.isdigit()
- )
-
- try:
- await event.message.respond("Please enter the first number")
- e1 = await bot.wait_for(hikari.MessageCreateEvent, predicate=is_number_check, timeout=30)
- await event.message.respond("Please enter the second number")
- e2 = await bot.wait_for(hikari.MessageCreateEvent, predicate=is_number_check, timeout=30)
-
- except asyncio.TimeoutError:
- await event.message.respond("You took too long...")
-
- else:
- val1 = int(e1.message.content)
- val2 = int(e2.message.content)
-
- embed = hikari.Embed(title="Result!", description=f"{val1} + {val2} = {val1 + val2}", color="#3f3")
-
- await event.message.respond(embed=embed)
-
-
- bot.run()
-
-
-
-
-
-
-
-
- pip install hikari
- A new, powerful, static-typed Python API for writing Discord bots.
-
- This API is still in a alpha state, and is a work in progress ! Features may change
- or undergo improvements before the design is finalized. Until then, why not join our Discord? Feel free
- to drop in to ask questions, get updates on progress, and be able to provide valuable contributions and
- feedback.
-
-
- Tutorials, tips, and additional resources will come soon!
-
-
-
- Slide into our server
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/pages/logo.png b/pages/logo.png
deleted file mode 100644
index 73392f24dd..0000000000
Binary files a/pages/logo.png and /dev/null differ
diff --git a/pages/site.css b/pages/site.css
deleted file mode 100644
index 2f26c83e22..0000000000
--- a/pages/site.css
+++ /dev/null
@@ -1,247 +0,0 @@
-@import url('https://fonts.googleapis.com/css2?family=Montserrat+Alternates:wght@100;300;400&display=swap&family=Source+Code+Pro:wght@200');
-
-:root {
- --dark-bg: #191919;
- --light-fg: #C66CB7;
- --unfocused-fg: #C66CB7;
- --dark-fg: #8F3881;
- --accent-1: #e44ecc;
-}
-/*
- * Globals
- */
-
-/* Links */
-a,
-a:focus,
-a:hover {
- color: var(--light-fg);
-}
-
-.display-1 {
- color: var(--accent-1);
- font-size: 4rem;
- font-weight: 300 !important;
-}
-
-.display-1 > small {
- font-family: monospace;
- color: var(--accent-1);
- font-size: 0.35em;
- font-weight: 100 !important;
- font-family: 'Source Code Pro', monospace;
-}
-
-.mono {
- font-family: SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace
-}
-
-/*
- * Base structure
- */
-
-html, body {
- margin: 0;
- padding: 0;
- height: 100%;
- min-width: 360px;
- background-color: var(--dark-bg);
- overflow-y: hidden;
-}
-
-header, main, footer {
- display: none;
-}
-
-html, body, .lead {
- font-family: 'Montserrat Alternates', sans-serif !important;
- font-weight: 400 !important;
-}
-
-.lead {
- font-weight: 400 !important;
-}
-
-strong {
- font-weight: 400 !important;
- text-decoration: underline;
-}
-
-body {
- display: -ms-flexbox;
- display: -webkit-box;
- display: flex;
- -ms-flex-pack: center;
- -webkit-box-pack: center;
- color: rgba(255, 255, 255, 255);
- box-shadow: inset 0 0 100rem rgba(0, 0, 0, 1);
-}
-
-.cover-container {
- overflow-y: auto;
- padding-left: 10% !important;
- padding-right: 10% !important;
- max-width: 100%;
- position: absolute;
-}
-
-/*
-* Header
-*/
-.nav-masthead .nav-link {
- padding: .25rem 0;
- font-weight: 700;
- color: rgba(255, 255, 255, 0.5);
- background-color: transparent;
- border-bottom: .25rem solid transparent;
-}
-
-.nav-masthead .nav-link:hover,
-.nav-masthead .nav-link:focus {
- border-bottom-color: var(--unfocused-bg);
-}
-
-.nav-masthead .nav-link + .nav-link {
- margin-left: 1rem;
-}
-
-.nav-masthead .active {
- color: rgba(255, 255, 255, 0.75);
- border-bottom-color: var(--light-fg);
-}
-
-/*
-* Cover
-*/
-.cover {
- padding: 0 1.5rem;
-}
-.cover .btn-lg {
- padding: .75rem 1.25rem;
- font-weight: 700;
-}
-
-/*
-* Footer
-*/
-.mastfoot {
- color: rgba(255, 255, 255, .2);
-}
-
-/*
-* Add text to the background
-*/
-.background-only-base {
- background: inherit;
- display: contents;
- position: absolute;
- top: 0;
- left: 0;
- bottom: 0;
- right: 0;
- z-index: -1;
-}
-
-.background-only {
- overflow: hidden;
- padding-top: 10vh;
- filter: blur(0.15em) contrast(45%) brightness(50%);
- font-size: 0.7vmax;
-}
-
-/*
-* highlight.js
-* https://github.com/highlightjs/highlight.js/blob/master/src/styles/monokai-sublime.css
-*/
-.hljs {
- display: block;
- overflow-x: hidden;
- overflow-y: hidden;
- background: inherit;
-}
-
-.hljs,
-.hljs-tag,
-.hljs-subst {
- color: #f8f8f2;
-}
-
-.hljs-strong,
-.hljs-emphasis {
- color: #a8a8a2;
-}
-
-.hljs-bullet,
-.hljs-quote,
-.hljs-number,
-.hljs-regexp,
-.hljs-literal,
-.hljs-link {
- color: #ae81ff;
-}
-
-.hljs-code,
-.hljs-title,
-.hljs-section,
-.hljs-selector-class {
- color: #a6e22e;
-}
-
-.hljs-strong {
- font-weight: bold;
-}
-
-.hljs-emphasis {
- font-style: italic;
-}
-
-.hljs-keyword,
-.hljs-selector-tag,
-.hljs-name,
-.hljs-attr {
- color: #f92672;
-}
-
-.hljs-symbol,
-.hljs-attribute {
- color: #66d9ef;
-}
-
-.hljs-params,
-.hljs-class .hljs-title {
- color: #f8f8f2;
-}
-
-.hljs-string,
-.hljs-type,
-.hljs-built_in,
-.hljs-builtin-name,
-.hljs-selector-id,
-.hljs-selector-attr,
-.hljs-selector-pseudo,
-.hljs-addition,
-.hljs-variable,
-.hljs-template-variable {
- color: #e6db74;
-}
-
-.hljs-comment,
-.hljs-deletion,
-.hljs-meta {
- color: #75715e;
-}
-
-.red { color: red !important; }
-.ora { color: orange !important; }
-.yel { color: yellow !important; }
-.gre { color: green !important; }
-.cya { color: cyan !important; }
-.blu { color: blue !important; }
-.pur { color: purple !important; }
-.gra { color: gray !important; }
-.whi { color: white !important; }
-.bwh { color: white !important; font-weight: bold; }
-.lin { color: aqua !important; text-decoration: underline; }
-.pre {
- white-space: pre;
-}
diff --git a/pipelines/config.py b/pipelines/config.py
index fd58b17877..15a937e475 100644
--- a/pipelines/config.py
+++ b/pipelines/config.py
@@ -28,12 +28,11 @@
# Directories
ARTIFACT_DIRECTORY = "public"
-PAGES_DIRECTORY = "pages"
DOCUMENTATION_DIRECTORY = "docs"
DEV_REQUIREMENTS_DIRECTORY = "dev-requirements"
# Linting and test configs
-FLAKE8_REPORT = "public/flake8"
+FLAKE8_REPORT = _os.path.join(ARTIFACT_DIRECTORY, "flake8")
PYPROJECT_TOML = "pyproject.toml"
COVERAGE_HTML_PATH = _os.path.join(ARTIFACT_DIRECTORY, "coverage", "html")
@@ -89,7 +88,6 @@
*PYTHON_REFORMATTING_PATHS,
*(f for f in _os.listdir(".") if _os.path.isfile(f) and f.endswith(REFORMATTING_FILE_EXTS)),
".github",
- "pages",
"docs",
"changes",
)
diff --git a/pipelines/format.nox.py b/pipelines/format.nox.py
index 81672dc3aa..5e40498ebb 100644
--- a/pipelines/format.nox.py
+++ b/pipelines/format.nox.py
@@ -43,7 +43,7 @@ def reformat_code(session: nox.Session) -> None:
session.run("black", *config.PYTHON_REFORMATTING_PATHS)
-@nox.session(reuse_venv=True)
+@nox.session(reuse_venv=True, venv_backend="none")
def check_trailing_whitespaces(session: nox.Session) -> None:
"""Check for trailing whitespaces in the project."""
remove_trailing_whitespaces(session, check_only=True)
diff --git a/pipelines/pages.nox.py b/pipelines/sphinx.nox.py
similarity index 54%
rename from pipelines/pages.nox.py
rename to pipelines/sphinx.nox.py
index 1016db3dcb..18cd0f1144 100644
--- a/pipelines/pages.nox.py
+++ b/pipelines/sphinx.nox.py
@@ -25,7 +25,6 @@
import http.server
import logging
import os
-import shutil
import socket
import threading
import webbrowser
@@ -34,66 +33,20 @@
from pipelines import nox
-def copy_from_in(src: str, dest: str) -> None:
- for parent, _, files in os.walk(src):
- sub_parent = os.path.relpath(parent, src)
-
- for file in files:
- sub_src = os.path.join(parent, file)
- sub_dest = os.path.normpath(os.path.join(dest, sub_parent, file))
- print(sub_src, "->", sub_dest)
- shutil.copy(sub_src, sub_dest)
-
-
@nox.session(reuse_venv=True)
-def pages(session: nox.Session) -> None:
- """Generate website pages."""
+def sphinx(session: nox.Session):
+ """Generate docs using sphinx."""
if not os.path.exists(config.ARTIFACT_DIRECTORY):
os.mkdir(config.ARTIFACT_DIRECTORY)
- # Static
- print("Copying static objects...")
- copy_from_in(config.PAGES_DIRECTORY, config.ARTIFACT_DIRECTORY)
+ session.install("-e", ".", *nox.dev_requirements("sphinx"))
- # Documentation
- session.install("-r", "requirements.txt", *nox.dev_requirements("pdoc"))
- session.env["PDOC3_GENERATING"] = "1"
-
- print("Building documentation...")
session.run(
- "python",
- "docs/patched_pdoc.py",
- config.MAIN_PACKAGE,
- "--html",
- "--output-dir",
- config.ARTIFACT_DIRECTORY,
- "--template-dir",
+ "sphinx-build",
+ "-M",
+ "dirhtml",
config.DOCUMENTATION_DIRECTORY,
- "--force",
- )
-
- # Rename `hikari` into `documentation`
- # print("Renaming output dir...")
- # print(f"{config.ARTIFACT_DIRECTORY}/{config.MAIN_PACKAGE} -> {config.ARTIFACT_DIRECTORY}/documentation")
- # shutil.rmtree(f"{config.ARTIFACT_DIRECTORY}/documentation", ignore_errors=True)
- # shutil.move(f"{config.ARTIFACT_DIRECTORY}/{config.MAIN_PACKAGE}", f"{config.ARTIFACT_DIRECTORY}/documentation")
-
- # Pre-generated indexes
- if shutil.which("npm") is None:
- message = "'npm' not installed, can't prebuild index"
- if "CI" in os.environ:
- session.error(message)
-
- session.skip(message)
-
- print("Prebuilding index...")
- session.run("npm", "install", "lunr@2.3.7", external=True)
- session.run(
- "node",
- "scripts/prebuild_index.js",
- f"{config.ARTIFACT_DIRECTORY}/hikari/index.json",
- f"{config.ARTIFACT_DIRECTORY}/hikari/prebuilt_index.json",
- external=True,
+ os.path.join(config.ARTIFACT_DIRECTORY, "docs"),
)
@@ -108,7 +61,8 @@ def __init__(self) -> None:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.host, self.port = sock.getsockname()
- handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=config.ARTIFACT_DIRECTORY)
+ directory = os.path.join(config.ARTIFACT_DIRECTORY, "docs", "dirhtml")
+ handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=directory)
self.server = http.server.HTTPServer((self.host, self.port), handler)
def run(self) -> None:
@@ -118,9 +72,9 @@ def close(self) -> None:
self.server.shutdown()
-@nox.session(reuse_venv=True)
-def test_pages(_: nox.Session) -> None:
- """Start an HTTP server for any generated pages in `/public`."""
+@nox.session(reuse_venv=True, venv_backend="none")
+def view_docs(_: nox.Session) -> None:
+ """Start an HTTP server for any generated pages in `/public/docs/dirhtml`."""
with contextlib.closing(HTTPServerThread()) as thread:
thread.start()
webbrowser.open(f"http://{thread.host}:{thread.port}")
diff --git a/pipelines/utils.nox.py b/pipelines/utils.nox.py
index 221433f2e2..06ca094a70 100644
--- a/pipelines/utils.nox.py
+++ b/pipelines/utils.nox.py
@@ -25,29 +25,36 @@
from pipelines import nox
-TRASH = [
+DIRECTORIES_TO_DELETE = [
".nox",
"build",
"dist",
"hikari.egg-info",
"public",
- ".coverage",
".pytest_cache",
".mypy_cache",
"node_modules",
+]
+
+FILES_TO_DELETE = [
+ ".coverage",
"package-lock.json",
]
+TO_DELETE = [
+ (shutil.rmtree, DIRECTORIES_TO_DELETE),
+ (os.remove, FILES_TO_DELETE),
+]
+
@nox.session(reuse_venv=False, venv_backend="none")
-def purge(_: nox.Session) -> None:
+def purge(session: nox.Session) -> None:
"""Delete any nox-generated files."""
- for trash in TRASH:
- print("Removing", trash)
- try:
- os.remove(trash)
- except:
- # Ignore errors
- pass
-
- shutil.rmtree(trash, ignore_errors=True)
+ for func, trash_list in TO_DELETE:
+ for trash in trash_list:
+ try:
+ func(trash)
+ except Exception as exc:
+ session.warn(f"[ FAIL ] Failed to remove {trash!r}: {exc!s}")
+ else:
+ session.log(f"[ OK ] Removed {trash!r}")
diff --git a/pyproject.toml b/pyproject.toml
index d60bea9fab..45842bba84 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -96,7 +96,6 @@ norecursedirs = [
filterwarnings = [
"error", # Treat warnings as errors
"ignore:.*assertions not in test modules or plugins will be ignored .*:pytest.PytestConfigWarning",
- "ignore::pytest.PytestUnraisableExceptionWarning",
]
required_plugins = ["pytest-asyncio"]
@@ -104,14 +103,17 @@ required_plugins = ["pytest-asyncio"]
package = "hikari"
package_dir = "hikari"
directory = "changes"
+template = "changes/.template.rst"
filename = "CHANGELOG.md"
issue_format = "[#{issue}](https://github.com/hikari-py/hikari/issues/{issue})"
+# We use this differently in the template
+underlines = [2, 3]
type = [
- { name = "Breaking Changes", directory = "breaking", showcontent = true },
- { name = "Deprecation", directory = "deprecation", showcontent = true },
- { name = "Features", directory = "feature", showcontent = true },
- { name = "Bugfixes", directory = "bugfix", showcontent = true },
- { name = "Documentation Improvements", directory = "doc", showcontent = true },
+ { name = "Breaking Changes", directory = "breaking", showcontent = true },
+ { name = "Deprecation", directory = "deprecation", showcontent = true },
+ { name = "Features", directory = "feature", showcontent = true },
+ { name = "Bugfixes", directory = "bugfix", showcontent = true },
+ { name = "Documentation Improvements", directory = "documentation", showcontent = true },
]
[tool.isort]
diff --git a/scripts/deploy-pages.sh b/scripts/deploy-pages.sh
deleted file mode 100755
index 51c0e2fb0c..0000000000
--- a/scripts/deploy-pages.sh
+++ /dev/null
@@ -1,32 +0,0 @@
-# Copyright (c) 2020 Nekokatt
-# Copyright (c) 2021-present davfsa
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in all
-# copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-# SOFTWARE.
-rm public -Rf || true
-mkdir public
-nox --sessions pages
-cd public || exit 1
-
-git init
-git remote add origin "https://git:${GITHUB_TOKEN}@github.com/${GITHUB_REPO_SLUG}"
-
-git checkout -B gh-pages
-git add -Av .
-git commit -am "Deployed documentation for ${VERSION}"
-git push origin gh-pages --force
diff --git a/scripts/prebuild_index.js b/scripts/prebuild_index.js
deleted file mode 100644
index 608dd591bf..0000000000
--- a/scripts/prebuild_index.js
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright (c) 2020 Nekokatt
-// Copyright (c) 2021-present davfsa
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in all
-// copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-// SOFTWARE.
-
-// Prebuilds the indexes for faster loading times.
-//
-// First argument must be the `index.json` file generated by pdoc.
-// Second argument is the path to save the prebuilt index to.
-
-const lunr = require('lunr');
-const fs = require('fs');
-
-const args = process.argv.slice(2);
-const data = require('./' + '../'.repeat(args[0].split("/").length - 2) + args[0]);
-
-// i: id
-// r: ref
-// n: name
-// d: docstring
-var idx = lunr(function () {
- this.ref('i');
- this.field('r', { boost: 10 });
- this.field('n', { boost: 5 });
- this.field('d');
- this.metadataWhitelist = ['position'];
- data.index.forEach((doc, i) => {
- const parts = doc.r.split('.');
- doc['n'] = parts[parts.length - 1];
- doc['i'] = i;
- this.add(doc);
- }, this);
-});
-
-fs.writeFile(args[1], JSON.stringify(idx), function (err) {
- if (err) { throw err; }
- console.log('Prebuilt index saved to ' + args[1]);
-});
diff --git a/scripts/prepare-release.sh b/scripts/prepare-release.sh
index 20cedf0b6e..092a39d7f2 100644
--- a/scripts/prepare-release.sh
+++ b/scripts/prepare-release.sh
@@ -26,8 +26,6 @@ env | grep -oP "^[^=]+" | sort
if [ -z ${VERSION+x} ]; then echo '$VERSION environment variable is missing' && exit 1; fi
if [ -z "${VERSION}" ]; then echo '$VERSION environment variable is empty' && exit 1; fi
-if [ -z ${GITHUB_TOKEN+x} ]; then echo '$GITHUB_TOKEN environment variable is missing' && exit 1; fi
-if [ -z "${GITHUB_TOKEN}" ]; then echo '$GITHUB_TOKEN environment variable is empty' && exit 1; fi
echo "===== INSTALLING DEPENDENCIES ====="
pip install -r dev-requirements/towncrier.txt -e .
@@ -38,6 +36,7 @@ git checkout -b "task/prepare-release-${VERSION}"
echo "-- Bumping repository version to ${VERSION} --"
sed "/^__version__.*/, \${s||__version__: typing.Final[str] = \"${VERSION}\"|g; b}; \$q1" -i hikari/_about.py || (echo "Variable '__version__' not found in about!" && exit 1)
+sed "/^__docs__.*/, \${s||__docs__: typing.Final[str] = \"https://docs.hikari-py.dev/en/${VERSION}\"|g; b}; \$q1" -i hikari/_about.py || (echo "Variable '__docs__' not found in about!" && exit 1)
echo "-- Running towncrier --"
towncrier --yes
diff --git a/scripts/deploy-manually.sh b/scripts/release-manually.sh
similarity index 85%
rename from scripts/deploy-manually.sh
rename to scripts/release-manually.sh
index 5204f1874a..6fa7bcd1a4 100755
--- a/scripts/deploy-manually.sh
+++ b/scripts/release-manually.sh
@@ -28,17 +28,9 @@ posix_read() {
return ${?}
}
+posix_read "Tag" VERSION
posix_read "Twine username" TWINE_USERNAME
posix_read "Twine password" TWINE_PASSWORD
-posix_read "GitHub deploy token" GITHUB_TOKEN
posix_read "Discord deployment webhook URL" DEPLOY_WEBHOOK_URL
-posix_read "Tag" VERSION
-posix_read "Repo slug (e.g. hikari-py/hikari)" GITHUB_REPO_SLUG
-
-git checkout "${GITHUB_TAG}"
-export REF=$(git rev-parse HEAD)
-echo "Detected REF to be ${REF}"
-set -x
-rm public -Rf || true
-bash scripts/deploy.sh
+bash scripts/release.sh
diff --git a/scripts/deploy-webhook.sh b/scripts/release-webhook.sh
similarity index 93%
rename from scripts/deploy-webhook.sh
rename to scripts/release-webhook.sh
index 1e651dcacc..7a3e072c53 100644
--- a/scripts/deploy-webhook.sh
+++ b/scripts/release-webhook.sh
@@ -29,7 +29,7 @@ curl \
{
"title": "'"${VERSION} has been deployed to PyPI"'",
"color": 6697881,
- "description": "'"Install it now by executing: \`\`\`pip install hikari==${VERSION}\`\`\`"'",
+ "description": "'"Install it now by executing: \`\`\`pip install hikari==${VERSION}\`\`\`\\nDocumentation can be found at https://docs.hikari-py.dev/en/${VERSION}"'",
"footer": {
"text": "'"SHA: ${REF}"'"
}
diff --git a/scripts/deploy.sh b/scripts/release.sh
similarity index 89%
rename from scripts/deploy.sh
rename to scripts/release.sh
index c50f7a1e84..797a38035e 100755
--- a/scripts/deploy.sh
+++ b/scripts/release.sh
@@ -30,10 +30,6 @@ env | grep -oP "^[^=]+" | sort
if [ -z ${VERSION+x} ]; then echo '$VERSION environment variable is missing' && exit 1; fi
if [ -z "${VERSION}" ]; then echo '$VERSION environment variable is empty' && exit 1; fi
-if [ -z ${REF+x} ]; then echo '$REF environment variable is missing' && exit 1; fi
-if [ -z "${REF}" ]; then echo '$REF environment variable is empty' && exit 1; fi
-if [ -z ${GITHUB_TOKEN+x} ]; then echo '$GITHUB_TOKEN environment variable is missing' && exit 1; fi
-if [ -z "${GITHUB_TOKEN}" ]; then echo '$GITHUB_TOKEN environment variable is empty' && exit 1; fi
if [ -z ${DEPLOY_WEBHOOK_URL+x} ]; then echo '$DEPLOY_WEBHOOK_URL environment variable is missing' && exit 1; fi
if [ -z "${DEPLOY_WEBHOOK_URL}" ]; then echo '$DEPLOY_WEBHOOK_URL environment variable is empty' && exit 1; fi
if [ -z ${TWINE_USERNAME+x} ]; then echo '$TWINE_USERNAME environment variable is missing' && exit 1; fi
@@ -44,7 +40,7 @@ if [ -z "${TWINE_PASSWORD}" ]; then echo '$TWINE_PASSWORD environment variable i
regex='__version__: typing\.Final\[str\] = "([^"]*)"'
if [[ $(cat hikari/_about.py) =~ $regex ]]; then
if [ "${BASH_REMATCH[1]}" != "${VERSION}" ]; then
- echo "Variable '__version__' does not match the version this deploy is for!" && exit 1
+ echo "Variable '__version__' does not match the version this release is for! [__version__='${BASH_REMATCH[1]}'; VERSION='${VERSION}']" && exit 1
fi
else
echo "Variable '__version__' not found in about!" && exit 1
@@ -53,12 +49,16 @@ fi
echo "===== INSTALLING DEPENDENCIES ====="
pip install -r requirements.txt -r dev-requirements/release.txt -r dev-requirements/nox.txt
+REF=$(git rev-parse HEAD)
+
echo "===== DEPLOYING TO PYPI ====="
echo "-- Setting __git_sha1__ (ref: ${REF}) --"
sed "/^__git_sha1__.*/, \${s||__git_sha1__: typing.Final[str] = \"${REF}\"|g; b}; \$q1" -i hikari/_about.py || (echo "Variable '__git_sha1__' not found in about!" && exit 1)
echo "=========================================================================="
cat hikari/_about.py
echo "=========================================================================="
+python -m hikari
+echo "=========================================================================="
python setup.py sdist bdist_wheel
echo "-- Contents of . --"
@@ -73,11 +73,8 @@ echo
echo "-- Uploading to PyPI --"
python -m twine upload --disable-progress-bar --skip-existing dist/* --non-interactive --repository-url https://upload.pypi.org/legacy/
-echo "===== DEPLOYING PAGES ====="
-bash scripts/deploy-pages.sh
-
echo "===== SENDING WEBHOOK ====="
-bash scripts/deploy-webhook.sh
+bash scripts/release-webhook.sh
echo "===== UPDATING VERSION IN REPOSITORY ====="
NEW_VERSION=$(python scripts/increase_version_number.py "${VERSION}")
@@ -88,6 +85,7 @@ git checkout -f master
echo "-- Bumping to development version (${NEW_VERSION}) --"
sed "/^__version__.*/, \${s||__version__: typing.Final[str] = \"${NEW_VERSION}\"|g; b}; \$q1" -i hikari/_about.py || (echo "Variable '__version__' not found in about!" && exit 1)
+sed "/^__docs__.*/, \${s||__docs__: typing.Final[str] = \"https://docs.hikari-py.dev/en/master\"|g; b}; \$q1" -i hikari/_about.py || (echo "Variable '__docs__' not found in about!" && exit 1)
echo "-- Pushing to repository --"
git commit -am "Bump to development version (${NEW_VERSION})"
diff --git a/tests/__init__.py b/tests/__init__.py
index adaf7da3d9..85795eeb35 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -19,8 +19,4 @@
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
-
-"""Pytest fails without this file in some cases.
-
-Fixes https://gitlab.com/nekokatt/hikari/-/issues/408.
-"""
+"""Mark this as a module to help pytest discover it."""
diff --git a/tests/hikari/__init__.py b/tests/hikari/__init__.py
index f77717f78b..696c11569e 100644
--- a/tests/hikari/__init__.py
+++ b/tests/hikari/__init__.py
@@ -33,6 +33,10 @@
#####################
class TestingPolicy(asyncio.DefaultEventLoopPolicy):
def set_event_loop(self, loop: typing.Optional[asyncio.AbstractEventLoop]) -> None:
+ # Close any old event loops to prevent them from raising warnings
+ if self._local._loop:
+ self._local._loop.close()
+
if loop is not None:
loop.set_debug(True)
diff --git a/tests/hikari/events/test_channel_events.py b/tests/hikari/events/test_channel_events.py
index e94f2cdf8e..aefeef22c9 100644
--- a/tests/hikari/events/test_channel_events.py
+++ b/tests/hikari/events/test_channel_events.py
@@ -219,41 +219,6 @@ async def test_fetch_guild_webhooks(self, event):
class TestGuildThreadEvent:
@pytest.mark.asyncio()
async def test_fetch_channel(self):
- """Perform an API call to fetch the details about this thread.
-
- !!! note
- For `GuildThreadDeleteEvent` events, this will always raise
- an exception, since the channel will have already been removed.
-
- Returns
- -------
- hikari.channels.GuildThreadChannel
- A derivative of `hikari.channels.GuildThreadChannel`. The
- actual type will vary depending on the type of channel this event
- concerns.
-
- Raises
- ------
- hikari.errors.UnauthorizedError
- If you are unauthorized to make the request (invalid/missing token).
- hikari.errors.ForbiddenError
- If you are missing the `READ_MESSAGES` permission in the channel.
- hikari.errors.NotFoundError
- If the channel is not found.
- hikari.errors.RateLimitTooLongError
- Raised in the event that a rate limit occurs that is
- longer than `max_rate_limit` when making a request.
- hikari.errors.RateLimitedError
- Usually, Hikari will handle and retry on hitting
- rate-limits automatically. This includes most bucket-specific
- rate-limits and global rate-limits. In some rare edge cases,
- however, Discord implements other undocumented rules for
- rate-limiting, such as limits per attribute. These cannot be
- detected or handled normally by Hikari due to their undocumented
- nature, and will trigger this exception if they occur.
- hikari.errors.InternalServerError
- If an internal error occurs on Discord while handling the request.
- """
mock_app = mock.AsyncMock()
mock_app.rest.fetch_channel.return_value = mock.Mock(channels.GuildThreadChannel)
event = hikari_test_helpers.mock_class_namespace(
diff --git a/tests/hikari/impl/test_rest_bot.py b/tests/hikari/impl/test_rest_bot.py
index 880696e7c0..6157dbf64a 100644
--- a/tests/hikari/impl/test_rest_bot.py
+++ b/tests/hikari/impl/test_rest_bot.py
@@ -373,47 +373,48 @@ async def test_on_interaction(self, mock_rest_bot, mock_interaction_server):
mock_interaction_server.on_interaction.assert_awaited_once_with(b"1", b"2", b"3")
def test_run(self, mock_rest_bot):
- # Dependent on test-order the current event loop may be pre-set and closed without pytest.mark.asyncio
- # therefore we need to ensure there's no pre-set event loop.
- asyncio.set_event_loop(None)
mock_socket = object()
mock_context = object()
mock_rest_bot._executor = None
- mock_rest_bot.start = mock.AsyncMock()
- mock_rest_bot.join = mock.AsyncMock()
+ mock_rest_bot.start = mock.Mock()
+ mock_rest_bot.join = mock.Mock()
- with mock.patch.object(ux, "check_for_updates") as check_for_updates:
- with mock.patch.object(
- signals, "handle_interrupts", return_value=hikari_test_helpers.ContextManagerMock()
- ) as handle_interrupts:
- mock_rest_bot.run(
- asyncio_debug=False,
- backlog=321,
- check_for_updates=False,
- close_loop=False,
- close_passed_executor=False,
- coroutine_tracking_depth=32123,
- enable_signal_handlers=True,
- propagate_interrupts=True,
- host="192.168.1.102",
- path="pathathath",
- port=4554,
- reuse_address=True,
- reuse_port=False,
- shutdown_timeout=534.534,
- socket=mock_socket,
- ssl_context=mock_context,
- )
+ stack = contextlib.ExitStack()
+ check_for_updates = stack.enter_context(mock.patch.object(ux, "check_for_updates"))
+ handle_interrupts = stack.enter_context(
+ mock.patch.object(signals, "handle_interrupts", return_value=hikari_test_helpers.ContextManagerMock())
+ )
+ get_or_make_loop = stack.enter_context(mock.patch.object(aio, "get_or_make_loop"))
+
+ with stack:
+ mock_rest_bot.run(
+ asyncio_debug=False,
+ backlog=321,
+ check_for_updates=False,
+ close_loop=False,
+ close_passed_executor=False,
+ coroutine_tracking_depth=32123,
+ enable_signal_handlers=True,
+ propagate_interrupts=True,
+ host="192.168.1.102",
+ path="pathathath",
+ port=4554,
+ reuse_address=True,
+ reuse_port=False,
+ shutdown_timeout=534.534,
+ socket=mock_socket,
+ ssl_context=mock_context,
+ )
check_for_updates.assert_not_called()
handle_interrupts.assert_called_once_with(
enabled=True,
- loop=asyncio.get_event_loop_policy().get_event_loop(),
+ loop=get_or_make_loop.return_value,
propagate_interrupts=True,
)
handle_interrupts.return_value.assert_used_once()
- mock_rest_bot.start.assert_awaited_once_with(
+ mock_rest_bot.start.assert_called_once_with(
backlog=321,
check_for_updates=False,
host="192.168.1.102",
@@ -425,8 +426,16 @@ def test_run(self, mock_rest_bot):
shutdown_timeout=534.534,
ssl_context=mock_context,
)
- mock_rest_bot.join.assert_awaited_once()
- assert asyncio.get_event_loop_policy().get_event_loop().is_closed() is False
+ mock_rest_bot.join.assert_called_once_with()
+
+ assert get_or_make_loop.return_value.run_until_complete.call_count == 2
+ get_or_make_loop.return_value.run_until_complete.assert_has_calls(
+ [
+ mock.call(mock_rest_bot.start.return_value),
+ mock.call(mock_rest_bot.join.return_value),
+ ]
+ )
+ get_or_make_loop.return_value.close.assert_not_called()
def test_run_when_close_loop(self, mock_rest_bot):
mock_rest_bot.start = mock.Mock()
@@ -434,10 +443,9 @@ def test_run_when_close_loop(self, mock_rest_bot):
with mock.patch.object(aio, "get_or_make_loop") as get_or_make_loop:
with mock.patch.object(aio, "destroy_loop") as destroy_loop:
- with mock.patch.object(rest_bot_impl, "_LOGGER") as logger:
- mock_rest_bot.run(close_loop=True)
+ mock_rest_bot.run(close_loop=True)
- destroy_loop.assert_called_once_with(get_or_make_loop.return_value, logger)
+ destroy_loop.assert_called_once_with(get_or_make_loop.return_value, rest_bot_impl._LOGGER)
def test_run_when_asyncio_debug(self, mock_rest_bot):
mock_rest_bot.start = mock.Mock()
@@ -467,55 +475,54 @@ def test_run_when_already_running(self, mock_rest_bot):
mock_rest_bot.run()
def test_run_closes_executor_when_present(self, mock_rest_bot, mock_executor):
- mock_rest_bot.join = mock.AsyncMock()
- # Dependent on test-order the current event loop may be pre-set and closed without pytest.mark.asyncio
- # therefore we need to ensure there's no pre-set event loop.
- asyncio.set_event_loop(None)
- mock_rest_bot.run(
- asyncio_debug=False,
- backlog=321,
- check_for_updates=False,
- close_loop=False,
- close_passed_executor=True,
- coroutine_tracking_depth=32123,
- enable_signal_handlers=True,
- host="192.168.1.102",
- path="pathathath",
- port=4554,
- reuse_address=True,
- reuse_port=False,
- shutdown_timeout=534.534,
- socket=object(),
- ssl_context=object(),
- )
+ mock_rest_bot.start = mock.Mock()
+ mock_rest_bot.join = mock.Mock()
+
+ with mock.patch.object(aio, "get_or_make_loop"):
+ mock_rest_bot.run(
+ asyncio_debug=False,
+ backlog=321,
+ check_for_updates=False,
+ close_loop=False,
+ close_passed_executor=True,
+ coroutine_tracking_depth=32123,
+ enable_signal_handlers=True,
+ host="192.168.1.102",
+ path="pathathath",
+ port=4554,
+ reuse_address=True,
+ reuse_port=False,
+ shutdown_timeout=534.534,
+ socket=object(),
+ ssl_context=object(),
+ )
mock_executor.shutdown.assert_called_once_with(wait=True)
assert mock_rest_bot.executor is None
def test_run_ignores_close_executor_when_not_present(self, mock_rest_bot):
- # Dependent on test-order the current event loop may be pre-filled and closed without pytest.mark.asyncio
- # therefore we need to ensure there's no pre-set event loop.
- asyncio.set_event_loop(None)
- mock_rest_bot.join = mock.AsyncMock()
+ mock_rest_bot.start = mock.Mock()
+ mock_rest_bot.join = mock.Mock()
mock_rest_bot._executor = None
- mock_rest_bot.run(
- asyncio_debug=False,
- backlog=321,
- check_for_updates=False,
- close_loop=False,
- close_passed_executor=True,
- coroutine_tracking_depth=32123,
- enable_signal_handlers=True,
- host="192.168.1.102",
- path="pathathath",
- port=4554,
- reuse_address=True,
- reuse_port=False,
- shutdown_timeout=534.534,
- socket=object(),
- ssl_context=object(),
- )
+ with mock.patch.object(aio, "get_or_make_loop"):
+ mock_rest_bot.run(
+ asyncio_debug=False,
+ backlog=321,
+ check_for_updates=False,
+ close_loop=False,
+ close_passed_executor=True,
+ coroutine_tracking_depth=32123,
+ enable_signal_handlers=True,
+ host="192.168.1.102",
+ path="pathathath",
+ port=4554,
+ reuse_address=True,
+ reuse_port=False,
+ shutdown_timeout=534.534,
+ socket=object(),
+ ssl_context=object(),
+ )
assert mock_rest_bot.executor is None
diff --git a/tests/hikari/internal/test_routes.py b/tests/hikari/internal/test_routes.py
index de5be53ef5..d6a6610fb8 100644
--- a/tests/hikari/internal/test_routes.py
+++ b/tests/hikari/internal/test_routes.py
@@ -109,10 +109,10 @@ def test_formats_converted_to_lower(self):
assert route.valid_formats == {"foo", "bar", "baz", "bork"}
def test_eq_operator__considers_path_template_only(self):
- route1 = routes.CDNRoute("/foo/bar", {"hello", "world"}, sizable=False)
- route2 = routes.CDNRoute("/foo/bar", {"i", "said", "meow"}, sizable=True)
- route3 = routes.CDNRoute("/foo/bar", {"i", "said", "meow"}, sizable=False)
- route4 = routes.CDNRoute("/foo/bar/baz", {"i", "said", "meow"}, sizable=True)
+ route1 = routes.CDNRoute("/foo/bar", {"hello", "world"}, is_sizable=False)
+ route2 = routes.CDNRoute("/foo/bar", {"i", "said", "meow"}, is_sizable=True)
+ route3 = routes.CDNRoute("/foo/bar", {"i", "said", "meow"}, is_sizable=False)
+ route4 = routes.CDNRoute("/foo/bar/baz", {"i", "said", "meow"}, is_sizable=True)
assert route1 == route2
assert route1 == route3
assert route1 != route4
@@ -121,10 +121,10 @@ def test_eq_operator__considers_path_template_only(self):
assert route3 != route4
def test_hash_operator_considers_path_template_only(self):
- route1 = routes.CDNRoute("/foo/bar", {"hello", "world"}, sizable=False)
- route2 = routes.CDNRoute("/foo/bar", {"i", "said", "meow"}, sizable=True)
- route3 = routes.CDNRoute("/foo/bar", {"i", "said", "meow"}, sizable=False)
- route4 = routes.CDNRoute("/foo/bar/baz", {"i", "said", "meow"}, sizable=True)
+ route1 = routes.CDNRoute("/foo/bar", {"hello", "world"}, is_sizable=False)
+ route2 = routes.CDNRoute("/foo/bar", {"i", "said", "meow"}, is_sizable=True)
+ route3 = routes.CDNRoute("/foo/bar", {"i", "said", "meow"}, is_sizable=False)
+ route4 = routes.CDNRoute("/foo/bar/baz", {"i", "said", "meow"}, is_sizable=True)
assert hash(route1) == hash(route2)
assert hash(route1) == hash(route3)
assert hash(route1) != hash(route4)
@@ -142,94 +142,94 @@ def test_hash_operator_considers_path_template_only(self):
],
)
def test_compile_uses_lowercase_file_format_always(self, input_file_format, expected_file_format):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg"}, sizable=False)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg"}, is_sizable=False)
compiled_url = route.compile("http://example.com", file_format=input_file_format)
assert compiled_url.endswith(f".{expected_file_format}"), f"compiled_url={compiled_url}"
def test_disallowed_file_format_raises_TypeError(self):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg"}, sizable=False)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg"}, is_sizable=False)
with pytest.raises(TypeError):
route.compile("http://example.com", file_format="gif")
def test_allowed_file_format_does_not_raise_TypeError(self):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg"}, sizable=False)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg"}, is_sizable=False)
route.compile("http://example.com", file_format="png")
def test_requesting_gif_on_non_animated_hash_raises_TypeError(self):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, sizable=False)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, is_sizable=False)
with pytest.raises(TypeError):
route.compile("http://example.com", file_format="gif", hash="boooob")
@pytest.mark.parametrize("format", ["png", "jpg", "webp"])
def test_requesting_non_gif_on_non_animated_hash_does_not_raise_TypeError(self, format):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg", "webp", "gif"}, sizable=False)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg", "webp", "gif"}, is_sizable=False)
route.compile("http://example.com", file_format=format, hash="boooob")
@pytest.mark.parametrize("format", ["png", "jpg", "webp"])
def test_requesting_non_gif_on_animated_hash_does_not_raise_TypeError(self, format):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg", "webp", "gif"}, sizable=False)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg", "webp", "gif"}, is_sizable=False)
route.compile("http://example.com", file_format=format, hash="a_boooob")
def test_requesting_gif_on_animated_hash_does_not_raise_TypeError(self):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, sizable=False)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, is_sizable=False)
route.compile("http://example.com", file_format="gif", hash="a_boooob")
def test_requesting_gif_without_passing_hash_does_not_raise_TypeError(self):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, sizable=False)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, is_sizable=False)
route.compile("http://example.com", file_format="gif")
def test_passing_size_on_non_sizable_raises_TypeError(self):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, sizable=False)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, is_sizable=False)
with pytest.raises(TypeError):
route.compile("http://example.com", file_format="png", hash="boooob", size=128)
def test_passing_size_on_sizable_does_not_raise_TypeError(self):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, sizable=True)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, is_sizable=True)
route.compile("http://example.com", file_format="png", hash="boooob", size=128)
def test_passing_no_size_on_non_sizable_does_not_raise_TypeError(self):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, sizable=False)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, is_sizable=False)
route.compile("http://example.com", file_format="png", hash="boooob")
def test_passing_no_size_on_sizable_does_not_raise_TypeError(self):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, sizable=True)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, is_sizable=True)
route.compile("http://example.com", file_format="png", hash="boooob")
@pytest.mark.parametrize("size", [*range(17, 32)])
def test_passing_non_power_of_2_sizes_to_sizable_raises_ValueError(self, size):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, sizable=True)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, is_sizable=True)
with pytest.raises(ValueError, match="size must be an integer power of 2 between 16 and 4096 inclusive"):
route.compile("http://example.com", file_format="png", hash="boooob", size=size)
@pytest.mark.parametrize("size", [int(2**size) for size in [1, *range(17, 25)]])
def test_passing_invalid_magnitude_sizes_to_sizable_raises_ValueError(self, size):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg", "png"}, sizable=True)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg", "png"}, is_sizable=True)
with pytest.raises(ValueError, match="size must be an integer power of 2 between 16 and 4096 inclusive"):
route.compile("http://example.com", file_format="png", hash="boooob", size=size)
@pytest.mark.parametrize("size", [*range(-10, 0)])
def test_passing_negative_sizes_to_sizable_raises_ValueError(self, size):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg", "png"}, sizable=True)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg", "png"}, is_sizable=True)
with pytest.raises(ValueError, match="size must be positive"):
route.compile("http://example.com", file_format="png", hash="boooob", size=size)
@pytest.mark.parametrize("size", [int(2**size) for size in range(4, 13)])
def test_passing_valid_sizes_to_sizable_does_not_raise_ValueError(self, size):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, sizable=True)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, is_sizable=True)
route.compile("http://example.com", file_format="png", hash="boooob", size=size)
def test_passing_size_adds_query_string(self):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, sizable=True)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, is_sizable=True)
compiled_url = route.compile("http://example.com", file_format="png", hash="boooob", size=128)
assert compiled_url.endswith(".png?size=128"), f"compiled_url={compiled_url}"
def test_passing_None_size_does_not_add_query_string(self):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, sizable=True)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, is_sizable=True)
compiled_url = route.compile("http://example.com", file_format="png", hash="boooob", size=None)
assert "?size=" not in compiled_url, f"compiled_url={compiled_url}"
def test_passing_no_size_does_not_add_query_string(self):
- route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, sizable=True)
+ route = routes.CDNRoute("/foo/bar", {"png", "jpg", "gif"}, is_sizable=True)
compiled_url = route.compile("http://example.com", file_format="png", hash="boooob")
assert "?size=" not in compiled_url, f"compiled_url={compiled_url}"
@@ -293,7 +293,7 @@ def test_passing_no_size_does_not_add_query_string(self):
],
)
def test_compile_generates_expected_url(self, base_url, template, format, size_kwds, foo, bar, expected_url):
- route = routes.CDNRoute(template, {"png", "gif", "jpg", "webp"}, sizable=True)
+ route = routes.CDNRoute(template, {"png", "gif", "jpg", "webp"}, is_sizable=True)
actual_url = route.compile(base_url=base_url, file_format=format, foo=foo, bar=bar, **size_kwds)
assert actual_url == expected_url
@@ -302,7 +302,7 @@ def test_compile_generates_expected_url(self, base_url, template, format, size_k
def test_compile_to_file_calls_compile(self, format, size):
with mock.patch.object(files, "URL", autospec=files.URL):
route = hikari_test_helpers.mock_class_namespace(routes.CDNRoute, slots_=False)(
- "/hello/world", {"png", "jpg"}, sizable=True
+ "/hello/world", {"png", "jpg"}, is_sizable=True
)
route.compile = mock.Mock(spec_set=route.compile)
route.compile_to_file("https://blep.com", file_format=format, size=size, boop="oyy lumo", nya="weeb")
@@ -315,7 +315,7 @@ def test_compile_to_file_passes_compile_result_to_URL_and_returns_constructed_ur
resultant_url = files.URL("http://blep.com/hello/world/weeb/oyy%20lumo")
with mock.patch.object(files, "URL", autospec=files.URL, return_value=resultant_url) as URL:
route = hikari_test_helpers.mock_class_namespace(routes.CDNRoute, slots_=False)(
- "/hello/world/{nya}/{boop}", {"png", "jpg"}, sizable=True
+ "/hello/world/{nya}/{boop}", {"png", "jpg"}, is_sizable=True
)
route.compile = mock.Mock(spec_set=route.compile, return_value=resultant_url_str)
result = route.compile_to_file("https://blep.com", file_format="png", size=64, boop="oyy lumo", nya="weeb")
diff --git a/tests/hikari/internal/test_ux.py b/tests/hikari/internal/test_ux.py
index db3091e2b8..5596a76e66 100644
--- a/tests/hikari/internal/test_ux.py
+++ b/tests/hikari/internal/test_ux.py
@@ -198,7 +198,7 @@ def mock_args(self):
stack.enter_context(mock.patch.object(_about, "__version__", new="2.2.2"))
stack.enter_context(mock.patch.object(_about, "__git_sha1__", new="12345678901234567890"))
- stack.enter_context(mock.patch.object(_about, "__copyright__", new="© 2020 Nekokatt"))
+ stack.enter_context(mock.patch.object(_about, "__copyright__", new="2020, Nekokatt"))
stack.enter_context(mock.patch.object(_about, "__license__", new="MIT"))
stack.enter_context(mock.patch.object(_about, "__file__", new="~/hikari"))
stack.enter_context(mock.patch.object(_about, "__docs__", new="https://nekokatt.github.io/hikari/docs"))
@@ -229,7 +229,7 @@ def test_when_supports_color(self, mock_args):
# Hikari stuff.
"hikari_version": "2.2.2",
"hikari_git_sha1": "12345678",
- "hikari_copyright": "© 2020 Nekokatt",
+ "hikari_copyright": "2020, Nekokatt",
"hikari_license": "MIT",
"hikari_install_location": "some path",
"hikari_documentation_url": "https://nekokatt.github.io/hikari/docs",
@@ -273,7 +273,7 @@ def test_when_doesnt_supports_color(self, mock_args):
# Hikari stuff.
"hikari_version": "2.2.2",
"hikari_git_sha1": "12345678",
- "hikari_copyright": "© 2020 Nekokatt",
+ "hikari_copyright": "2020, Nekokatt",
"hikari_license": "MIT",
"hikari_install_location": "some path",
"hikari_documentation_url": "https://nekokatt.github.io/hikari/docs",
@@ -317,7 +317,7 @@ def test_use_extra_args(self, mock_args):
# Hikari stuff.
"hikari_version": "2.2.2",
"hikari_git_sha1": "12345678",
- "hikari_copyright": "© 2020 Nekokatt",
+ "hikari_copyright": "2020, Nekokatt",
"hikari_license": "MIT",
"hikari_install_location": "some path",
"hikari_documentation_url": "https://nekokatt.github.io/hikari/docs",
@@ -634,10 +634,10 @@ async def test_when_no_new_available_releases(self, http_settings, proxy_setting
async def test_check_for_updates(self, v, http_settings, proxy_settings):
data = {
"releases": {
- "0.1.0": [{"yanked": False}],
+ v: [{"yanked": False}, {"yanked": True}],
"1.0.0": [{"yanked": False}],
"1.0.0.dev1": [{"yanked": False}],
- v: [{"yanked": False}, {"yanked": True}],
+ "0.1.0": [{"yanked": False}],
"1.0.2": [{"yanked": True}],
}
}