[ { "id": "0_0", "repo_url": "https://github.com/teamqurrent/httpx", "instruction": "Add None as default value for file parameter inside `httpx/_auth.py` class constructor", "base_commit": "4b5a92e", "test_script": "import sys\nimport unittest\nimport inspect\n\n\n\nclass TestNetRCAuthFileParam(unittest.TestCase):\n def test_netrcauth_file_param_default(self):\n from httpx._auth import NetRCAuth\n\n if hasattr(NetRCAuth, \"__init__\"):\n init_method = getattr(NetRCAuth, \"__init__\")\n method_signature = inspect.signature(init_method)\n if \"file\" in method_signature.parameters:\n param = method_signature.parameters[\"file\"]\n self.assertIs(param.default, None, \"Default value for 'file' parameter is not None\")\n else:\n self.fail(\"The 'file' parameter is not present in NetRCAuth.__init__ method.\")\n else:\n self.fail(\"NetRCAuth does not have an __init__ method.\")\n\ndef main():\n\n\n suite = unittest.TestSuite()\n suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestNetRCAuthFileParam))\n runner = unittest.TextTestRunner()\n\n if runner.run(suite).wasSuccessful():\n sys.exit(0)\n else:\n sys.exit(1)\n\nif __name__ == \"__main__\":\n\n main()\n", "testbed_environment": "python3.9", "requirements_txt": "sniffio\nrfc3986\nhttpcore>=0.18.0,<0.19.0\ncertifi\nidna", "solution_commit": "c1cc6b2", "solution_patch": "diff --git a/httpx/_auth.py b/httpx/_auth.py\n--- a/httpx/_auth.py\n+++ b/httpx/_auth.py\n@@ -147,7 +147,7 @@ class NetRCAuth(Auth):\n Use a 'netrc' file to lookup basic auth credentials based on the url host.\n \"\"\"\n \n- def __init__(self, file: typing.Optional[str]):\n+ def __init__(self, file: typing.Optional[str] = None):\n self._netrc_info = netrc.netrc(file)\n \n def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:\n", "modified_files": [ { "path": "httpx/_auth.py", "content": "import hashlib\nimport netrc\nimport os\nimport re\nimport time\nimport typing\nfrom base64 import b64encode\nfrom urllib.request import parse_http_list\n\nfrom ._exceptions import ProtocolError\nfrom ._models import Request, Response\nfrom ._utils import to_bytes, to_str, unquote\n\nif typing.TYPE_CHECKING: # pragma: no cover\n from hashlib import _Hash\n\n\nclass Auth:\n \"\"\"\n Base class for all authentication schemes.\n\n To implement a custom authentication scheme, subclass `Auth` and override\n the `.auth_flow()` method.\n\n If the authentication scheme does I/O such as disk access or network calls, or uses\n synchronization primitives such as locks, you should override `.sync_auth_flow()`\n and/or `.async_auth_flow()` instead of `.auth_flow()` to provide specialized\n implementations that will be used by `Client` and `AsyncClient` respectively.\n \"\"\"\n\n requires_request_body = False\n requires_response_body = False\n\n def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:\n \"\"\"\n Execute the authentication flow.\n\n To dispatch a request, `yield` it:\n\n ```\n yield request\n ```\n\n The client will `.send()` the response back into the flow generator. You can\n access it like so:\n\n ```\n response = yield request\n ```\n\n A `return` (or reaching the end of the generator) will result in the\n client returning the last response obtained from the server.\n\n You can dispatch as many requests as is necessary.\n \"\"\"\n yield request\n\n def sync_auth_flow(\n self, request: Request\n ) -> typing.Generator[Request, Response, None]:\n \"\"\"\n Execute the authentication flow synchronously.\n\n By default, this defers to `.auth_flow()`. You should override this method\n when the authentication scheme does I/O and/or uses concurrency primitives.\n \"\"\"\n if self.requires_request_body:\n request.read()\n\n flow = self.auth_flow(request)\n request = next(flow)\n\n while True:\n response = yield request\n if self.requires_response_body:\n response.read()\n\n try:\n request = flow.send(response)\n except StopIteration:\n break\n\n async def async_auth_flow(\n self, request: Request\n ) -> typing.AsyncGenerator[Request, Response]:\n \"\"\"\n Execute the authentication flow asynchronously.\n\n By default, this defers to `.auth_flow()`. You should override this method\n when the authentication scheme does I/O and/or uses concurrency primitives.\n \"\"\"\n if self.requires_request_body:\n await request.aread()\n\n flow = self.auth_flow(request)\n request = next(flow)\n\n while True:\n response = yield request\n if self.requires_response_body:\n await response.aread()\n\n try:\n request = flow.send(response)\n except StopIteration:\n break\n\n\nclass FunctionAuth(Auth):\n \"\"\"\n Allows the 'auth' argument to be passed as a simple callable function,\n that takes the request, and returns a new, modified request.\n \"\"\"\n\n def __init__(self, func: typing.Callable[[Request], Request]) -> None:\n self._func = func\n\n def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:\n yield self._func(request)\n\n\nclass BasicAuth(Auth):\n \"\"\"\n Allows the 'auth' argument to be passed as a (username, password) pair,\n and uses HTTP Basic authentication.\n \"\"\"\n\n def __init__(\n self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]\n ):\n self._auth_header = self._build_auth_header(username, password)\n\n def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:\n request.headers[\"Authorization\"] = self._auth_header\n yield request\n\n def _build_auth_header(\n self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]\n ) -> str:\n userpass = b\":\".join((to_bytes(username), to_bytes(password)))\n token = b64encode(userpass).decode()\n return f\"Basic {token}\"\n\n\nclass NetRCAuth(Auth):\n \"\"\"\n Use a 'netrc' file to lookup basic auth credentials based on the url host.\n \"\"\"\n\n def __init__(self, file: typing.Optional[str]):\n self._netrc_info = netrc.netrc(file)\n\n def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:\n auth_info = self._netrc_info.authenticators(request.url.host)\n if auth_info is None or not auth_info[2]:\n # The netrc file did not have authentication credentials for this host.\n yield request\n else:\n # Build a basic auth header with credentials from the netrc file.\n request.headers[\"Authorization\"] = self._build_auth_header(\n username=auth_info[0], password=auth_info[2]\n )\n yield request\n\n def _build_auth_header(\n self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]\n ) -> str:\n userpass = b\":\".join((to_bytes(username), to_bytes(password)))\n token = b64encode(userpass).decode()\n return f\"Basic {token}\"\n\n\nclass DigestAuth(Auth):\n _ALGORITHM_TO_HASH_FUNCTION: typing.Dict[str, typing.Callable[[bytes], \"_Hash\"]] = {\n \"MD5\": hashlib.md5,\n \"MD5-SESS\": hashlib.md5,\n \"SHA\": hashlib.sha1,\n \"SHA-SESS\": hashlib.sha1,\n \"SHA-256\": hashlib.sha256,\n \"SHA-256-SESS\": hashlib.sha256,\n \"SHA-512\": hashlib.sha512,\n \"SHA-512-SESS\": hashlib.sha512,\n }\n\n def __init__(\n self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]\n ) -> None:\n self._username = to_bytes(username)\n self._password = to_bytes(password)\n self._last_challenge: typing.Optional[_DigestAuthChallenge] = None\n self._nonce_count = 1\n\n def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:\n if self._last_challenge:\n request.headers[\"Authorization\"] = self._build_auth_header(\n request, self._last_challenge\n )\n\n response = yield request\n\n if response.status_code != 401 or \"www-authenticate\" not in response.headers:\n # If the response is not a 401 then we don't\n # need to build an authenticated request.\n return\n\n for auth_header in response.headers.get_list(\"www-authenticate\"):\n if auth_header.lower().startswith(\"digest \"):\n break\n else:\n # If the response does not include a 'WWW-Authenticate: Digest ...'\n # header, then we don't need to build an authenticated request.\n return\n\n self._last_challenge = self._parse_challenge(request, response, auth_header)\n self._nonce_count = 1\n\n request.headers[\"Authorization\"] = self._build_auth_header(\n request, self._last_challenge\n )\n yield request\n\n def _parse_challenge(\n self, request: Request, response: Response, auth_header: str\n ) -> \"_DigestAuthChallenge\":\n \"\"\"\n Returns a challenge from a Digest WWW-Authenticate header.\n These take the form of:\n `Digest realm=\"realm@host.com\",qop=\"auth,auth-int\",nonce=\"abc\",opaque=\"xyz\"`\n \"\"\"\n scheme, _, fields = auth_header.partition(\" \")\n\n # This method should only ever have been called with a Digest auth header.\n assert scheme.lower() == \"digest\"\n\n header_dict: typing.Dict[str, str] = {}\n for field in parse_http_list(fields):\n key, value = field.strip().split(\"=\", 1)\n header_dict[key] = unquote(value)\n\n try:\n realm = header_dict[\"realm\"].encode()\n nonce = header_dict[\"nonce\"].encode()\n algorithm = header_dict.get(\"algorithm\", \"MD5\")\n opaque = header_dict[\"opaque\"].encode() if \"opaque\" in header_dict else None\n qop = header_dict[\"qop\"].encode() if \"qop\" in header_dict else None\n return _DigestAuthChallenge(\n realm=realm, nonce=nonce, algorithm=algorithm, opaque=opaque, qop=qop\n )\n except KeyError as exc:\n message = \"Malformed Digest WWW-Authenticate header\"\n raise ProtocolError(message, request=request) from exc\n\n def _build_auth_header(\n self, request: Request, challenge: \"_DigestAuthChallenge\"\n ) -> str:\n hash_func = self._ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm.upper()]\n\n def digest(data: bytes) -> bytes:\n return hash_func(data).hexdigest().encode()\n\n A1 = b\":\".join((self._username, challenge.realm, self._password))\n\n path = request.url.raw_path\n A2 = b\":\".join((request.method.encode(), path))\n # TODO: implement auth-int\n HA2 = digest(A2)\n\n nc_value = b\"%08x\" % self._nonce_count\n cnonce = self._get_client_nonce(self._nonce_count, challenge.nonce)\n self._nonce_count += 1\n\n HA1 = digest(A1)\n if challenge.algorithm.lower().endswith(\"-sess\"):\n HA1 = digest(b\":\".join((HA1, challenge.nonce, cnonce)))\n\n qop = self._resolve_qop(challenge.qop, request=request)\n if qop is None:\n digest_data = [HA1, challenge.nonce, HA2]\n else:\n digest_data = [challenge.nonce, nc_value, cnonce, qop, HA2]\n key_digest = b\":\".join(digest_data)\n\n format_args = {\n \"username\": self._username,\n \"realm\": challenge.realm,\n \"nonce\": challenge.nonce,\n \"uri\": path,\n \"response\": digest(b\":\".join((HA1, key_digest))),\n \"algorithm\": challenge.algorithm.encode(),\n }\n if challenge.opaque:\n format_args[\"opaque\"] = challenge.opaque\n if qop:\n format_args[\"qop\"] = b\"auth\"\n format_args[\"nc\"] = nc_value\n format_args[\"cnonce\"] = cnonce\n\n return \"Digest \" + self._get_header_value(format_args)\n\n def _get_client_nonce(self, nonce_count: int, nonce: bytes) -> bytes:\n s = str(nonce_count).encode()\n s += nonce\n s += time.ctime().encode()\n s += os.urandom(8)\n\n return hashlib.sha1(s).hexdigest()[:16].encode()\n\n def _get_header_value(self, header_fields: typing.Dict[str, bytes]) -> str:\n NON_QUOTED_FIELDS = (\"algorithm\", \"qop\", \"nc\")\n QUOTED_TEMPLATE = '{}=\"{}\"'\n NON_QUOTED_TEMPLATE = \"{}={}\"\n\n header_value = \"\"\n for i, (field, value) in enumerate(header_fields.items()):\n if i > 0:\n header_value += \", \"\n template = (\n QUOTED_TEMPLATE\n if field not in NON_QUOTED_FIELDS\n else NON_QUOTED_TEMPLATE\n )\n header_value += template.format(field, to_str(value))\n\n return header_value\n\n def _resolve_qop(\n self, qop: typing.Optional[bytes], request: Request\n ) -> typing.Optional[bytes]:\n if qop is None:\n return None\n qops = re.split(b\", ?\", qop)\n if b\"auth\" in qops:\n return b\"auth\"\n\n if qops == [b\"auth-int\"]:\n raise NotImplementedError(\"Digest auth-int support is not yet implemented\")\n\n message = f'Unexpected qop value \"{qop!r}\" in digest auth'\n raise ProtocolError(message, request=request)\n\n\nclass _DigestAuthChallenge(typing.NamedTuple):\n realm: bytes\n nonce: bytes\n algorithm: str\n opaque: typing.Optional[bytes]\n qop: typing.Optional[bytes]\n" } ], "language": "python" }, { "id": "0_1", "repo_url": "https://github.com/teamqurrent/httpx", "instruction": "Allow tuple or list for multipart values inside `httpx/_multipart.py` in `_iter_fields` method", "base_commit": "ccd98b1", "test_script": "import sys\nimport unittest\nimport inspect\n\n\n\nclass TestMultipartStreamIterFields(unittest.TestCase):\n def test_iter_fields_code(self):\n from httpx._multipart import MultipartStream\n\n source_lines = inspect.getsourcelines(MultipartStream._iter_fields)\n found_isinstance_tuple = any(\"isinstance\" in line and \"tuple\" in line for line in source_lines[0])\n self.assertTrue(found_isinstance_tuple, \"The line with 'isinstance' and 'tuple' was not found in MultipartStream._iter_fields\")\n\ndef main():\n\n\n suite = unittest.TestSuite()\n suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestMultipartStreamIterFields))\n runner = unittest.TextTestRunner()\n\n if runner.run(suite).wasSuccessful():\n sys.exit(0)\n else:\n sys.exit(1)\n\nif __name__ == \"__main__\":\n\n main()\n", "testbed_environment": "python3.9", "requirements_txt": "sniffio\nrfc3986\nhttpcore>=0.18.0,<0.19.0\ncertifi\nidna", "solution_commit": "965b8ad", "solution_patch": "diff --git a/httpx/_multipart.py b/httpx/_multipart.py\n--- a/httpx/_multipart.py\n+++ b/httpx/_multipart.py\n@@ -205,7 +205,7 @@ class MultipartStream(SyncByteStream, AsyncByteStream):\n self, data: dict, files: RequestFiles\n ) -> typing.Iterator[typing.Union[FileField, DataField]]:\n for name, value in data.items():\n- if isinstance(value, list):\n+ if isinstance(value, (tuple, list)):\n for item in value:\n yield DataField(name=name, value=item)\n else:\n", "modified_files": [ { "path": "httpx/_multipart.py", "content": "import binascii\nimport io\nimport os\nimport typing\nfrom pathlib import Path\n\nfrom ._types import (\n AsyncByteStream,\n FileContent,\n FileTypes,\n RequestFiles,\n SyncByteStream,\n)\nfrom ._utils import (\n format_form_param,\n guess_content_type,\n peek_filelike_length,\n primitive_value_to_str,\n to_bytes,\n)\n\n\ndef get_multipart_boundary_from_content_type(\n content_type: typing.Optional[bytes],\n) -> typing.Optional[bytes]:\n if not content_type or not content_type.startswith(b\"multipart/form-data\"):\n return None\n # parse boundary according to\n # https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1\n if b\";\" in content_type:\n for section in content_type.split(b\";\"):\n if section.strip().lower().startswith(b\"boundary=\"):\n return section.strip()[len(b\"boundary=\") :].strip(b'\"')\n return None\n\n\nclass DataField:\n \"\"\"\n A single form field item, within a multipart form field.\n \"\"\"\n\n def __init__(\n self, name: str, value: typing.Union[str, bytes, int, float, None]\n ) -> None:\n if not isinstance(name, str):\n raise TypeError(\n f\"Invalid type for name. Expected str, got {type(name)}: {name!r}\"\n )\n if value is not None and not isinstance(value, (str, bytes, int, float)):\n raise TypeError(\n f\"Invalid type for value. Expected primitive type, got {type(value)}: {value!r}\"\n )\n self.name = name\n self.value: typing.Union[str, bytes] = (\n value if isinstance(value, bytes) else primitive_value_to_str(value)\n )\n\n def render_headers(self) -> bytes:\n if not hasattr(self, \"_headers\"):\n name = format_form_param(\"name\", self.name)\n self._headers = b\"\".join(\n [b\"Content-Disposition: form-data; \", name, b\"\\r\\n\\r\\n\"]\n )\n\n return self._headers\n\n def render_data(self) -> bytes:\n if not hasattr(self, \"_data\"):\n self._data = to_bytes(self.value)\n\n return self._data\n\n def get_length(self) -> int:\n headers = self.render_headers()\n data = self.render_data()\n return len(headers) + len(data)\n\n def render(self) -> typing.Iterator[bytes]:\n yield self.render_headers()\n yield self.render_data()\n\n\nclass FileField:\n \"\"\"\n A single file field item, within a multipart form field.\n \"\"\"\n\n CHUNK_SIZE = 64 * 1024\n\n def __init__(self, name: str, value: FileTypes) -> None:\n self.name = name\n\n fileobj: FileContent\n\n headers: typing.Dict[str, str] = {}\n content_type: typing.Optional[str] = None\n\n # This large tuple based API largely mirror's requests' API\n # It would be good to think of better APIs for this that we could include in httpx 2.0\n # since variable length tuples (especially of 4 elements) are quite unwieldly\n if isinstance(value, tuple):\n if len(value) == 2:\n # neither the 3rd parameter (content_type) nor the 4th (headers) was included\n filename, fileobj = value # type: ignore\n elif len(value) == 3:\n filename, fileobj, content_type = value # type: ignore\n else:\n # all 4 parameters included\n filename, fileobj, content_type, headers = value # type: ignore\n else:\n filename = Path(str(getattr(value, \"name\", \"upload\"))).name\n fileobj = value\n\n if content_type is None:\n content_type = guess_content_type(filename)\n\n has_content_type_header = any(\"content-type\" in key.lower() for key in headers)\n if content_type is not None and not has_content_type_header:\n # note that unlike requests, we ignore the content_type\n # provided in the 3rd tuple element if it is also included in the headers\n # requests does the opposite (it overwrites the header with the 3rd tuple element)\n headers[\"Content-Type\"] = content_type\n\n if isinstance(fileobj, (str, io.StringIO)):\n raise TypeError(f\"Expected bytes or bytes-like object got: {type(fileobj)}\")\n\n self.filename = filename\n self.file = fileobj\n self.headers = headers\n\n def get_length(self) -> int:\n headers = self.render_headers()\n\n if isinstance(self.file, (str, bytes)):\n return len(headers) + len(to_bytes(self.file))\n\n # Let's do our best not to read `file` into memory.\n file_length = peek_filelike_length(self.file)\n if file_length is None:\n # As a last resort, read file and cache contents for later.\n assert not hasattr(self, \"_data\")\n self._data = to_bytes(self.file.read())\n file_length = len(self._data)\n\n return len(headers) + file_length\n\n def render_headers(self) -> bytes:\n if not hasattr(self, \"_headers\"):\n parts = [\n b\"Content-Disposition: form-data; \",\n format_form_param(\"name\", self.name),\n ]\n if self.filename:\n filename = format_form_param(\"filename\", self.filename)\n parts.extend([b\"; \", filename])\n for header_name, header_value in self.headers.items():\n key, val = f\"\\r\\n{header_name}: \".encode(), header_value.encode()\n parts.extend([key, val])\n parts.append(b\"\\r\\n\\r\\n\")\n self._headers = b\"\".join(parts)\n\n return self._headers\n\n def render_data(self) -> typing.Iterator[bytes]:\n if isinstance(self.file, (str, bytes)):\n yield to_bytes(self.file)\n return\n\n if hasattr(self, \"_data\"):\n # Already rendered.\n yield self._data\n return\n\n if hasattr(self.file, \"seek\"):\n self.file.seek(0)\n\n chunk = self.file.read(self.CHUNK_SIZE)\n while chunk:\n yield to_bytes(chunk)\n chunk = self.file.read(self.CHUNK_SIZE)\n\n def render(self) -> typing.Iterator[bytes]:\n yield self.render_headers()\n yield from self.render_data()\n\n\nclass MultipartStream(SyncByteStream, AsyncByteStream):\n \"\"\"\n Request content as streaming multipart encoded form data.\n \"\"\"\n\n def __init__(\n self, data: dict, files: RequestFiles, boundary: typing.Optional[bytes] = None\n ) -> None:\n if boundary is None:\n boundary = binascii.hexlify(os.urandom(16))\n\n self.boundary = boundary\n self.content_type = \"multipart/form-data; boundary=%s\" % boundary.decode(\n \"ascii\"\n )\n self.fields = list(self._iter_fields(data, files))\n\n def _iter_fields(\n self, data: dict, files: RequestFiles\n ) -> typing.Iterator[typing.Union[FileField, DataField]]:\n for name, value in data.items():\n if isinstance(value, list):\n for item in value:\n yield DataField(name=name, value=item)\n else:\n yield DataField(name=name, value=value)\n\n file_items = files.items() if isinstance(files, typing.Mapping) else files\n for name, value in file_items:\n yield FileField(name=name, value=value)\n\n def iter_chunks(self) -> typing.Iterator[bytes]:\n for field in self.fields:\n yield b\"--%s\\r\\n\" % self.boundary\n yield from field.render()\n yield b\"\\r\\n\"\n yield b\"--%s--\\r\\n\" % self.boundary\n\n def iter_chunks_lengths(self) -> typing.Iterator[int]:\n boundary_length = len(self.boundary)\n # Follow closely what `.iter_chunks()` does.\n for field in self.fields:\n yield 2 + boundary_length + 2\n yield field.get_length()\n yield 2\n yield 2 + boundary_length + 4\n\n def get_content_length(self) -> int:\n return sum(self.iter_chunks_lengths())\n\n # Content stream interface.\n\n def get_headers(self) -> typing.Dict[str, str]:\n content_length = str(self.get_content_length())\n content_type = self.content_type\n return {\"Content-Length\": content_length, \"Content-Type\": content_type}\n\n def __iter__(self) -> typing.Iterator[bytes]:\n for chunk in self.iter_chunks():\n yield chunk\n\n async def __aiter__(self) -> typing.AsyncIterator[bytes]:\n for chunk in self.iter_chunks():\n yield chunk\n" } ], "language": "python" }, { "id": "0_2", "repo_url": "https://github.com/teamqurrent/httpx", "instruction": "The `primitive_value_to_str` function inside `httpx/_utils.py` returns 'true' or 'false' or '' when the value is boolean or None. It returns str(value) otherwise. Modify primitive_value_to_str function to return str(value) if value is of type str, float or int. Otherwise raise TypeError with the error message: 'Expected str, int, float, bool, or None. Got '{type}''. Update the file tests/models/test_queryparams.py to add a new test test_invalid_query_params() which expects a TypeError when bytes is passed.", "base_commit": "10a3b68", "test_script": "import sys\nimport unittest\n\n\n\nclass TestHttpxQueryParams(unittest.TestCase):\n def test_query_params_with_bytes(self):\n import httpx\n\n try:\n httpx.QueryParams({\"a\": b\"bytes\"})\n self.fail(\"TypeError not raised\")\n except TypeError as e:\n expected_message = \"Expected str, int, float, bool, or None. Got 'bytes'\"\n self.assertIn(expected_message, str(e), \"TypeError does not contain the expected message\")\n\ndef main():\n\n\n suite = unittest.TestSuite()\n suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestHttpxQueryParams))\n runner = unittest.TextTestRunner()\n\n if runner.run(suite).wasSuccessful():\n sys.exit(0)\n else:\n sys.exit(1)\n\nif __name__ == \"__main__\":\n\n main()\n", "testbed_environment": "python3.9", "requirements_txt": "sniffio\nrfc3986\nhttpcore>=0.18.0,<0.19.0\ncertifi\nidna", "solution_commit": "4cbf13e", "solution_patch": "diff --git a/httpx/_utils.py b/httpx/_utils.py\n--- a/httpx/_utils.py\n+++ b/httpx/_utils.py\n@@ -67,7 +67,11 @@ def primitive_value_to_str(value: \"PrimitiveData\") -> str:\n return \"false\"\n elif value is None:\n return \"\"\n- return str(value)\n+ elif isinstance(value, (str, float, int)):\n+ return str(value)\n+ raise TypeError(\n+ f\"Expected str, int, float, bool, or None. Got {type(value).__name__!r}.\"\n+ )\n \n \n def is_known_encoding(encoding: str) -> bool:\ndiff --git a/tests/models/test_queryparams.py b/tests/models/test_queryparams.py\n--- a/tests/models/test_queryparams.py\n+++ b/tests/models/test_queryparams.py\n@@ -87,6 +87,13 @@ def test_empty_query_params():\n assert str(q) == \"a=\"\n \n \n+def test_invalid_query_params():\n+ with pytest.raises(\n+ TypeError, match=r\"Expected str, int, float, bool, or None. Got 'bytes'.\"\n+ ):\n+ httpx.QueryParams({\"a\": b\"bytes\"})\n+\n+\n def test_queryparam_update_is_hard_deprecated():\n q = httpx.QueryParams(\"a=123\")\n with pytest.raises(RuntimeError):\n", "modified_files": [ { "path": "httpx/_utils.py", "content": "import codecs\nimport email.message\nimport logging\nimport mimetypes\nimport netrc\nimport os\nimport re\nimport sys\nimport time\nimport typing\nfrom pathlib import Path\nfrom urllib.request import getproxies\n\nimport sniffio\n\nfrom ._types import PrimitiveData\n\nif typing.TYPE_CHECKING: # pragma: no cover\n from ._urls import URL\n\n\n_HTML5_FORM_ENCODING_REPLACEMENTS = {'\"': \"%22\", \"\\\\\": \"\\\\\\\\\"}\n_HTML5_FORM_ENCODING_REPLACEMENTS.update(\n {chr(c): \"%{:02X}\".format(c) for c in range(0x1F + 1) if c != 0x1B}\n)\n_HTML5_FORM_ENCODING_RE = re.compile(\n r\"|\".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()])\n)\n\n\ndef normalize_header_key(\n value: typing.Union[str, bytes],\n lower: bool,\n encoding: typing.Optional[str] = None,\n) -> bytes:\n \"\"\"\n Coerce str/bytes into a strictly byte-wise HTTP header key.\n \"\"\"\n if isinstance(value, bytes):\n bytes_value = value\n else:\n bytes_value = value.encode(encoding or \"ascii\")\n\n return bytes_value.lower() if lower else bytes_value\n\n\ndef normalize_header_value(\n value: typing.Union[str, bytes], encoding: typing.Optional[str] = None\n) -> bytes:\n \"\"\"\n Coerce str/bytes into a strictly byte-wise HTTP header value.\n \"\"\"\n if isinstance(value, bytes):\n return value\n return value.encode(encoding or \"ascii\")\n\n\ndef primitive_value_to_str(value: \"PrimitiveData\") -> str:\n \"\"\"\n Coerce a primitive data type into a string value.\n\n Note that we prefer JSON-style 'true'/'false' for boolean values here.\n \"\"\"\n if value is True:\n return \"true\"\n elif value is False:\n return \"false\"\n elif value is None:\n return \"\"\n return str(value)\n\n\ndef is_known_encoding(encoding: str) -> bool:\n \"\"\"\n Return `True` if `encoding` is a known codec.\n \"\"\"\n try:\n codecs.lookup(encoding)\n except LookupError:\n return False\n return True\n\n\ndef format_form_param(name: str, value: str) -> bytes:\n \"\"\"\n Encode a name/value pair within a multipart form.\n \"\"\"\n\n def replacer(match: typing.Match[str]) -> str:\n return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]\n\n value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)\n return f'{name}=\"{value}\"'.encode()\n\n\n# Null bytes; no need to recreate these on each call to guess_json_utf\n_null = b\"\\x00\"\n_null2 = _null * 2\n_null3 = _null * 3\n\n\ndef guess_json_utf(data: bytes) -> typing.Optional[str]:\n # JSON always starts with two ASCII characters, so detection is as\n # easy as counting the nulls and from their location and count\n # determine the encoding. Also detect a BOM, if present.\n sample = data[:4]\n if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):\n return \"utf-32\" # BOM included\n if sample[:3] == codecs.BOM_UTF8:\n return \"utf-8-sig\" # BOM included, MS style (discouraged)\n if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):\n return \"utf-16\" # BOM included\n nullcount = sample.count(_null)\n if nullcount == 0:\n return \"utf-8\"\n if nullcount == 2:\n if sample[::2] == _null2: # 1st and 3rd are null\n return \"utf-16-be\"\n if sample[1::2] == _null2: # 2nd and 4th are null\n return \"utf-16-le\"\n # Did not detect 2 valid UTF-16 ascii-range characters\n if nullcount == 3:\n if sample[:3] == _null3:\n return \"utf-32-be\"\n if sample[1:] == _null3:\n return \"utf-32-le\"\n # Did not detect a valid UTF-32 ascii-range character\n return None\n\n\nclass NetRCInfo:\n def __init__(self, files: typing.Optional[typing.List[str]] = None) -> None:\n if files is None:\n files = [os.getenv(\"NETRC\", \"\"), \"~/.netrc\", \"~/_netrc\"]\n self.netrc_files = files\n\n @property\n def netrc_info(self) -> typing.Optional[netrc.netrc]:\n if not hasattr(self, \"_netrc_info\"):\n self._netrc_info = None\n for file_path in self.netrc_files:\n expanded_path = Path(file_path).expanduser()\n try:\n if expanded_path.is_file():\n self._netrc_info = netrc.netrc(str(expanded_path))\n break\n except (netrc.NetrcParseError, IOError): # pragma: no cover\n # Issue while reading the netrc file, ignore...\n pass\n return self._netrc_info\n\n def get_credentials(self, host: str) -> typing.Optional[typing.Tuple[str, str]]:\n if self.netrc_info is None:\n return None\n\n auth_info = self.netrc_info.authenticators(host)\n if auth_info is None or auth_info[2] is None:\n return None\n return (auth_info[0], auth_info[2])\n\n\ndef get_ca_bundle_from_env() -> typing.Optional[str]:\n if \"SSL_CERT_FILE\" in os.environ:\n ssl_file = Path(os.environ[\"SSL_CERT_FILE\"])\n if ssl_file.is_file():\n return str(ssl_file)\n if \"SSL_CERT_DIR\" in os.environ:\n ssl_path = Path(os.environ[\"SSL_CERT_DIR\"])\n if ssl_path.is_dir():\n return str(ssl_path)\n return None\n\n\ndef parse_header_links(value: str) -> typing.List[typing.Dict[str, str]]:\n \"\"\"\n Returns a list of parsed link headers, for more info see:\n https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link\n The generic syntax of those is:\n Link: < uri-reference >; param1=value1; param2=\"value2\"\n So for instance:\n Link; '; type=\"image/jpeg\",;'\n would return\n [\n {\"url\": \"http:/.../front.jpeg\", \"type\": \"image/jpeg\"},\n {\"url\": \"http://.../back.jpeg\"},\n ]\n :param value: HTTP Link entity-header field\n :return: list of parsed link headers\n \"\"\"\n links: typing.List[typing.Dict[str, str]] = []\n replace_chars = \" '\\\"\"\n value = value.strip(replace_chars)\n if not value:\n return links\n for val in re.split(\", *<\", value):\n try:\n url, params = val.split(\";\", 1)\n except ValueError:\n url, params = val, \"\"\n link = {\"url\": url.strip(\"<> '\\\"\")}\n for param in params.split(\";\"):\n try:\n key, value = param.split(\"=\")\n except ValueError:\n break\n link[key.strip(replace_chars)] = value.strip(replace_chars)\n links.append(link)\n return links\n\n\ndef parse_content_type_charset(content_type: str) -> typing.Optional[str]:\n # We used to use `cgi.parse_header()` here, but `cgi` became a dead battery.\n # See: https://peps.python.org/pep-0594/#cgi\n msg = email.message.Message()\n msg[\"content-type\"] = content_type\n return msg.get_content_charset(failobj=None)\n\n\nSENSITIVE_HEADERS = {\"authorization\", \"proxy-authorization\"}\n\n\ndef obfuscate_sensitive_headers(\n items: typing.Iterable[typing.Tuple[typing.AnyStr, typing.AnyStr]]\n) -> typing.Iterator[typing.Tuple[typing.AnyStr, typing.AnyStr]]:\n for k, v in items:\n if to_str(k.lower()) in SENSITIVE_HEADERS:\n v = to_bytes_or_str(\"[secure]\", match_type_of=v)\n yield k, v\n\n\n_LOGGER_INITIALIZED = False\nTRACE_LOG_LEVEL = 5\n\n\nclass Logger(logging.Logger):\n # Stub for type checkers.\n def trace(self, message: str, *args: typing.Any, **kwargs: typing.Any) -> None:\n ... # pragma: no cover\n\n\ndef get_logger(name: str) -> Logger:\n \"\"\"\n Get a `logging.Logger` instance, and optionally\n set up debug logging based on the HTTPX_LOG_LEVEL environment variable.\n \"\"\"\n global _LOGGER_INITIALIZED\n\n if not _LOGGER_INITIALIZED:\n _LOGGER_INITIALIZED = True\n logging.addLevelName(TRACE_LOG_LEVEL, \"TRACE\")\n\n log_level = os.environ.get(\"HTTPX_LOG_LEVEL\", \"\").upper()\n if log_level in (\"DEBUG\", \"TRACE\"):\n logger = logging.getLogger(\"httpx\")\n logger.setLevel(logging.DEBUG if log_level == \"DEBUG\" else TRACE_LOG_LEVEL)\n handler = logging.StreamHandler(sys.stderr)\n handler.setFormatter(\n logging.Formatter(\n fmt=\"%(levelname)s [%(asctime)s] %(name)s - %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n )\n )\n logger.addHandler(handler)\n\n logger = logging.getLogger(name)\n\n def trace(message: str, *args: typing.Any, **kwargs: typing.Any) -> None:\n logger.log(TRACE_LOG_LEVEL, message, *args, **kwargs)\n\n logger.trace = trace # type: ignore\n\n return typing.cast(Logger, logger)\n\n\ndef port_or_default(url: \"URL\") -> typing.Optional[int]:\n if url.port is not None:\n return url.port\n return {\"http\": 80, \"https\": 443}.get(url.scheme)\n\n\ndef same_origin(url: \"URL\", other: \"URL\") -> bool:\n \"\"\"\n Return 'True' if the given URLs share the same origin.\n \"\"\"\n return (\n url.scheme == other.scheme\n and url.host == other.host\n and port_or_default(url) == port_or_default(other)\n )\n\n\ndef is_https_redirect(url: \"URL\", location: \"URL\") -> bool:\n \"\"\"\n Return 'True' if 'location' is a HTTPS upgrade of 'url'\n \"\"\"\n if url.host != location.host:\n return False\n\n return (\n url.scheme == \"http\"\n and port_or_default(url) == 80\n and location.scheme == \"https\"\n and port_or_default(location) == 443\n )\n\n\ndef get_environment_proxies() -> typing.Dict[str, typing.Optional[str]]:\n \"\"\"Gets proxy information from the environment\"\"\"\n\n # urllib.request.getproxies() falls back on System\n # Registry and Config for proxies on Windows and macOS.\n # We don't want to propagate non-HTTP proxies into\n # our configuration such as 'TRAVIS_APT_PROXY'.\n proxy_info = getproxies()\n mounts: typing.Dict[str, typing.Optional[str]] = {}\n\n for scheme in (\"http\", \"https\", \"all\"):\n if proxy_info.get(scheme):\n hostname = proxy_info[scheme]\n mounts[f\"{scheme}://\"] = (\n hostname if \"://\" in hostname else f\"http://{hostname}\"\n )\n\n no_proxy_hosts = [host.strip() for host in proxy_info.get(\"no\", \"\").split(\",\")]\n for hostname in no_proxy_hosts:\n # See https://curl.haxx.se/libcurl/c/CURLOPT_NOPROXY.html for details\n # on how names in `NO_PROXY` are handled.\n if hostname == \"*\":\n # If NO_PROXY=* is used or if \"*\" occurs as any one of the comma\n # separated hostnames, then we should just bypass any information\n # from HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and always ignore\n # proxies.\n return {}\n elif hostname:\n # NO_PROXY=.google.com is marked as \"all://*.google.com,\n # which disables \"www.google.com\" but not \"google.com\"\n # NO_PROXY=google.com is marked as \"all://*google.com,\n # which disables \"www.google.com\" and \"google.com\".\n # (But not \"wwwgoogle.com\")\n mounts[f\"all://*{hostname}\"] = None\n\n return mounts\n\n\ndef to_bytes(value: typing.Union[str, bytes], encoding: str = \"utf-8\") -> bytes:\n return value.encode(encoding) if isinstance(value, str) else value\n\n\ndef to_str(value: typing.Union[str, bytes], encoding: str = \"utf-8\") -> str:\n return value if isinstance(value, str) else value.decode(encoding)\n\n\ndef to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr:\n return value if isinstance(match_type_of, str) else value.encode()\n\n\ndef unquote(value: str) -> str:\n return value[1:-1] if value[0] == value[-1] == '\"' else value\n\n\ndef guess_content_type(filename: typing.Optional[str]) -> typing.Optional[str]:\n if filename:\n return mimetypes.guess_type(filename)[0] or \"application/octet-stream\"\n return None\n\n\ndef peek_filelike_length(stream: typing.Any) -> typing.Optional[int]:\n \"\"\"\n Given a file-like stream object, return its length in number of bytes\n without reading it into memory.\n \"\"\"\n try:\n # Is it an actual file?\n fd = stream.fileno()\n # Yup, seems to be an actual file.\n length = os.fstat(fd).st_size\n except (AttributeError, OSError):\n # No... Maybe it's something that supports random access, like `io.BytesIO`?\n try:\n # Assuming so, go to end of stream to figure out its length,\n # then put it back in place.\n offset = stream.tell()\n length = stream.seek(0, os.SEEK_END)\n stream.seek(offset)\n except (AttributeError, OSError):\n # Not even that? Sorry, we're doomed...\n return None\n\n return length\n\n\nclass Timer:\n async def _get_time(self) -> float:\n library = sniffio.current_async_library()\n if library == \"trio\":\n import trio\n\n return trio.current_time()\n elif library == \"curio\": # pragma: no cover\n import curio\n\n return typing.cast(float, await curio.clock())\n\n import asyncio\n\n return asyncio.get_event_loop().time()\n\n def sync_start(self) -> None:\n self.started = time.perf_counter()\n\n async def async_start(self) -> None:\n self.started = await self._get_time()\n\n def sync_elapsed(self) -> float:\n now = time.perf_counter()\n return now - self.started\n\n async def async_elapsed(self) -> float:\n now = await self._get_time()\n return now - self.started\n\n\nclass URLPattern:\n \"\"\"\n A utility class currently used for making lookups against proxy keys...\n\n # Wildcard matching...\n >>> pattern = URLPattern(\"all\")\n >>> pattern.matches(httpx.URL(\"http://example.com\"))\n True\n\n # Witch scheme matching...\n >>> pattern = URLPattern(\"https\")\n >>> pattern.matches(httpx.URL(\"https://example.com\"))\n True\n >>> pattern.matches(httpx.URL(\"http://example.com\"))\n False\n\n # With domain matching...\n >>> pattern = URLPattern(\"https://example.com\")\n >>> pattern.matches(httpx.URL(\"https://example.com\"))\n True\n >>> pattern.matches(httpx.URL(\"http://example.com\"))\n False\n >>> pattern.matches(httpx.URL(\"https://other.com\"))\n False\n\n # Wildcard scheme, with domain matching...\n >>> pattern = URLPattern(\"all://example.com\")\n >>> pattern.matches(httpx.URL(\"https://example.com\"))\n True\n >>> pattern.matches(httpx.URL(\"http://example.com\"))\n True\n >>> pattern.matches(httpx.URL(\"https://other.com\"))\n False\n\n # With port matching...\n >>> pattern = URLPattern(\"https://example.com:1234\")\n >>> pattern.matches(httpx.URL(\"https://example.com:1234\"))\n True\n >>> pattern.matches(httpx.URL(\"https://example.com\"))\n False\n \"\"\"\n\n def __init__(self, pattern: str) -> None:\n from ._urls import URL\n\n if pattern and \":\" not in pattern:\n raise ValueError(\n f\"Proxy keys should use proper URL forms rather \"\n f\"than plain scheme strings. \"\n f'Instead of \"{pattern}\", use \"{pattern}://\"'\n )\n\n url = URL(pattern)\n self.pattern = pattern\n self.scheme = \"\" if url.scheme == \"all\" else url.scheme\n self.host = \"\" if url.host == \"*\" else url.host\n self.port = url.port\n if not url.host or url.host == \"*\":\n self.host_regex: typing.Optional[typing.Pattern[str]] = None\n elif url.host.startswith(\"*.\"):\n # *.example.com should match \"www.example.com\", but not \"example.com\"\n domain = re.escape(url.host[2:])\n self.host_regex = re.compile(f\"^.+\\\\.{domain}$\")\n elif url.host.startswith(\"*\"):\n # *example.com should match \"www.example.com\" and \"example.com\"\n domain = re.escape(url.host[1:])\n self.host_regex = re.compile(f\"^(.+\\\\.)?{domain}$\")\n else:\n # example.com should match \"example.com\" but not \"www.example.com\"\n domain = re.escape(url.host)\n self.host_regex = re.compile(f\"^{domain}$\")\n\n def matches(self, other: \"URL\") -> bool:\n if self.scheme and self.scheme != other.scheme:\n return False\n if (\n self.host\n and self.host_regex is not None\n and not self.host_regex.match(other.host)\n ):\n return False\n if self.port is not None and self.port != other.port:\n return False\n return True\n\n @property\n def priority(self) -> typing.Tuple[int, int, int]:\n \"\"\"\n The priority allows URLPattern instances to be sortable, so that\n we can match from most specific to least specific.\n \"\"\"\n # URLs with a port should take priority over URLs without a port.\n port_priority = 0 if self.port is not None else 1\n # Longer hostnames should match first.\n host_priority = -len(self.host)\n # Longer schemes should match first.\n scheme_priority = -len(self.scheme)\n return (port_priority, host_priority, scheme_priority)\n\n def __hash__(self) -> int:\n return hash(self.pattern)\n\n def __lt__(self, other: \"URLPattern\") -> bool:\n return self.priority < other.priority\n\n def __eq__(self, other: typing.Any) -> bool:\n return isinstance(other, URLPattern) and self.pattern == other.pattern\n" }, { "path": "tests/models/test_queryparams.py", "content": "import pytest\n\nimport httpx\n\n\n@pytest.mark.parametrize(\n \"source\",\n [\n \"a=123&a=456&b=789\",\n {\"a\": [\"123\", \"456\"], \"b\": 789},\n {\"a\": (\"123\", \"456\"), \"b\": 789},\n [(\"a\", \"123\"), (\"a\", \"456\"), (\"b\", \"789\")],\n ((\"a\", \"123\"), (\"a\", \"456\"), (\"b\", \"789\")),\n ],\n)\ndef test_queryparams(source):\n q = httpx.QueryParams(source)\n assert \"a\" in q\n assert \"A\" not in q\n assert \"c\" not in q\n assert q[\"a\"] == \"123\"\n assert q.get(\"a\") == \"123\"\n assert q.get(\"nope\", default=None) is None\n assert q.get_list(\"a\") == [\"123\", \"456\"]\n\n assert list(q.keys()) == [\"a\", \"b\"]\n assert list(q.values()) == [\"123\", \"789\"]\n assert list(q.items()) == [(\"a\", \"123\"), (\"b\", \"789\")]\n assert len(q) == 2\n assert list(q) == [\"a\", \"b\"]\n assert dict(q) == {\"a\": \"123\", \"b\": \"789\"}\n assert str(q) == \"a=123&a=456&b=789\"\n assert repr(q) == \"QueryParams('a=123&a=456&b=789')\"\n assert httpx.QueryParams({\"a\": \"123\", \"b\": \"456\"}) == httpx.QueryParams(\n [(\"a\", \"123\"), (\"b\", \"456\")]\n )\n assert httpx.QueryParams({\"a\": \"123\", \"b\": \"456\"}) == httpx.QueryParams(\n \"a=123&b=456\"\n )\n assert httpx.QueryParams({\"a\": \"123\", \"b\": \"456\"}) == httpx.QueryParams(\n {\"b\": \"456\", \"a\": \"123\"}\n )\n assert httpx.QueryParams() == httpx.QueryParams({})\n assert httpx.QueryParams([(\"a\", \"123\"), (\"a\", \"456\")]) == httpx.QueryParams(\n \"a=123&a=456\"\n )\n assert httpx.QueryParams({\"a\": \"123\", \"b\": \"456\"}) != \"invalid\"\n\n q = httpx.QueryParams([(\"a\", \"123\"), (\"a\", \"456\")])\n assert httpx.QueryParams(q) == q\n\n\ndef test_queryparam_types():\n q = httpx.QueryParams(None)\n assert str(q) == \"\"\n\n q = httpx.QueryParams({\"a\": True})\n assert str(q) == \"a=true\"\n\n q = httpx.QueryParams({\"a\": False})\n assert str(q) == \"a=false\"\n\n q = httpx.QueryParams({\"a\": \"\"})\n assert str(q) == \"a=\"\n\n q = httpx.QueryParams({\"a\": None})\n assert str(q) == \"a=\"\n\n q = httpx.QueryParams({\"a\": 1.23})\n assert str(q) == \"a=1.23\"\n\n q = httpx.QueryParams({\"a\": 123})\n assert str(q) == \"a=123\"\n\n q = httpx.QueryParams({\"a\": [1, 2]})\n assert str(q) == \"a=1&a=2\"\n\n\ndef test_empty_query_params():\n q = httpx.QueryParams({\"a\": \"\"})\n assert str(q) == \"a=\"\n\n q = httpx.QueryParams(\"a=\")\n assert str(q) == \"a=\"\n\n q = httpx.QueryParams(\"a\")\n assert str(q) == \"a=\"\n\n\ndef test_queryparam_update_is_hard_deprecated():\n q = httpx.QueryParams(\"a=123\")\n with pytest.raises(RuntimeError):\n q.update({\"a\": \"456\"})\n\n\ndef test_queryparam_setter_is_hard_deprecated():\n q = httpx.QueryParams(\"a=123\")\n with pytest.raises(RuntimeError):\n q[\"a\"] = \"456\"\n\n\ndef test_queryparam_set():\n q = httpx.QueryParams(\"a=123\")\n q = q.set(\"a\", \"456\")\n assert q == httpx.QueryParams(\"a=456\")\n\n\ndef test_queryparam_add():\n q = httpx.QueryParams(\"a=123\")\n q = q.add(\"a\", \"456\")\n assert q == httpx.QueryParams(\"a=123&a=456\")\n\n\ndef test_queryparam_remove():\n q = httpx.QueryParams(\"a=123\")\n q = q.remove(\"a\")\n assert q == httpx.QueryParams(\"\")\n\n\ndef test_queryparam_merge():\n q = httpx.QueryParams(\"a=123\")\n q = q.merge({\"b\": \"456\"})\n assert q == httpx.QueryParams(\"a=123&b=456\")\n q = q.merge({\"a\": \"000\", \"c\": \"789\"})\n assert q == httpx.QueryParams(\"a=000&b=456&c=789\")\n\n\ndef test_queryparams_are_hashable():\n params = (\n httpx.QueryParams(\"a=123\"),\n httpx.QueryParams({\"a\": 123}),\n httpx.QueryParams(\"b=456\"),\n httpx.QueryParams({\"b\": 456}),\n )\n\n assert len(set(params)) == 2\n" } ], "language": "python" }, { "id": "0_3", "repo_url": "https://github.com/teamqurrent/httpx", "instruction": "Delete `setup.py`", "base_commit": "e5bc1ea", "test_script": "import os\nimport sys\nimport unittest\n\nclass TestSetupPyExists(unittest.TestCase):\n def test_setup_py_existence(self):\n # Get the current directory path\n directory_path = os.getcwd()\n\n # List all files in the directory\n files = os.listdir(directory_path)\n\n # Check if setup.py exists in the list of files\n self.assertNotIn(\"setup.py\", files, \"setup.py exists in the directory\")\n\ndef main():\n suite = unittest.TestSuite()\n suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestSetupPyExists))\n runner = unittest.TextTestRunner()\n\n if runner.run(suite).wasSuccessful():\n sys.exit(0)\n else:\n sys.exit(1)\n\nif __name__ == \"__main__\":\n main()\n", "testbed_environment": "python3.9", "requirements_txt": "", "solution_commit": "10a3b68", "solution_patch": "diff --git a/setup.py b/setup.py\ndeleted file mode 100644\n--- a/setup.py\n+++ /dev/null\n@@ -1,31 +0,0 @@\n-import sys\n-\n-from setuptools import setup\n-\n-sys.stderr.write(\n- \"\"\"\n-===============================\n-Unsupported installation method\n-===============================\n-httpx no longer supports installation with `python setup.py install`.\n-Please use `python -m pip install .` instead.\n-\"\"\"\n-)\n-sys.exit(1)\n-\n-\n-# The below code will never execute, however GitHub is particularly\n-# picky about where it finds Python packaging metadata.\n-# See: https://github.com/github/feedback/discussions/6456\n-#\n-# To be removed once GitHub catches up.\n-\n-setup(\n- name=\"httpx\",\n- install_requires=[\n- \"certifi\",\n- \"sniffio\",\n- \"rfc3986[idna2008]>=1.3,<2\",\n- \"httpcore>=0.15.0,<0.17.0\",\n- ],\n-)\n", "modified_files": [ { "path": "setup.py", "content": "import sys\n\nfrom setuptools import setup\n\nsys.stderr.write(\n \"\"\"\n===============================\nUnsupported installation method\n===============================\nhttpx no longer supports installation with `python setup.py install`.\nPlease use `python -m pip install .` instead.\n\"\"\"\n)\nsys.exit(1)\n\n\n# The below code will never execute, however GitHub is particularly\n# picky about where it finds Python packaging metadata.\n# See: https://github.com/github/feedback/discussions/6456\n#\n# To be removed once GitHub catches up.\n\nsetup(\n name=\"httpx\",\n install_requires=[\n \"certifi\",\n \"sniffio\",\n \"rfc3986[idna2008]>=1.3,<2\",\n \"httpcore>=0.15.0,<0.17.0\",\n ],\n)\n" } ], "language": "python" }, { "id": "0_4", "repo_url": "https://github.com/teamqurrent/httpx", "instruction": "Modify the encoding setter method of the `Headers` class to throw a ValueError if the class instance already as a `_text` attribute", "base_commit": "e4241c6", "test_script": "import sys\nimport unittest\nimport inspect\n\n\n\nclass TestResponseForceEncoding(unittest.TestCase):\n def test_response_force_encoding_after_text_accessed(self):\n import httpx\n response = httpx.Response(\n 200,\n content=b\"Hello, world!\",\n )\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.reason_phrase, \"OK\")\n self.assertEqual(response.text, \"Hello, world!\")\n self.assertEqual(response.encoding, \"utf-8\")\n\n with self.assertRaises(ValueError):\n response.encoding = \"UTF8\"\n\n with self.assertRaises(ValueError):\n response.encoding = \"iso-8859-1\"\n\ndef main():\n\n\n suite = unittest.TestSuite()\n suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestResponseForceEncoding))\n runner = unittest.TextTestRunner()\n\n if runner.run(suite).wasSuccessful():\n sys.exit(0)\n else:\n sys.exit(1)\n\nif __name__ == \"__main__\":\n\n main()\n", "testbed_environment": "python3.9", "requirements_txt": "sniffio\nrfc3986\nhttpcore>=0.18.0,<0.19.0\ncertifi\nidna", "solution_commit": "59df819", "solution_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.\n \n The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).\n \n+## Unreleased\n+\n+### Fixed\n+\n+* Raise `ValueError` on `Response.encoding` being set after `Response.text` has been accessed. (#2852)\n+\n ## 0.25.0 (11th Sep, 2023)\n \n ### Removed\ndiff --git a/httpx/_models.py b/httpx/_models.py\n--- a/httpx/_models.py\n+++ b/httpx/_models.py\n@@ -603,6 +603,16 @@ class Response:\n \n @encoding.setter\n def encoding(self, value: str) -> None:\n+ \"\"\"\n+ Set the encoding to use for decoding the byte content into text.\n+\n+ If the `text` attribute has been accessed, attempting to set the\n+ encoding will throw a ValueError.\n+ \"\"\"\n+ if hasattr(self, \"_text\"):\n+ raise ValueError(\n+ \"Setting encoding after `text` has been accessed is not allowed.\"\n+ )\n self._encoding = value\n \n @property\ndiff --git a/tests/models/test_responses.py b/tests/models/test_responses.py\n--- a/tests/models/test_responses.py\n+++ b/tests/models/test_responses.py\n@@ -298,6 +298,23 @@ def test_response_force_encoding():\n assert response.encoding == \"iso-8859-1\"\n \n \n+def test_response_force_encoding_after_text_accessed():\n+ response = httpx.Response(\n+ 200,\n+ content=b\"Hello, world!\",\n+ )\n+ assert response.status_code == 200\n+ assert response.reason_phrase == \"OK\"\n+ assert response.text == \"Hello, world!\"\n+ assert response.encoding == \"utf-8\"\n+\n+ with pytest.raises(ValueError):\n+ response.encoding = \"UTF8\"\n+\n+ with pytest.raises(ValueError):\n+ response.encoding = \"iso-8859-1\"\n+\n+\n def test_read():\n response = httpx.Response(\n 200,\n", "modified_files": [ { "path": "CHANGELOG.md", "content": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).\n\n## 0.25.0 (11th Sep, 2023)\n\n### Removed\n\n* Drop support for Python 3.7. (#2813)\n\n### Added\n\n* Support HTTPS proxies. (#2845)\n* Change the type of `Extensions` from `Mapping[Str, Any]` to `MutableMapping[Str, Any]`. (#2803)\n* Add `socket_options` argument to `httpx.HTTPTransport` and `httpx.AsyncHTTPTransport` classes. (#2716)\n* The `Response.raise_for_status()` method now returns the response instance. For example: `data = httpx.get('...').raise_for_status().json()`. (#2776)\n\n### Fixed\n\n* Return `500` error response instead of exceptions when `raise_app_exceptions=False` is set on `ASGITransport`. (#2669)\n* Ensure all `WSGITransport` environs have a `SERVER_PROTOCOL`. (#2708)\n* Always encode forward slashes as `%2F` in query parameters (#2723)\n* Use Mozilla documentation instead of `httpstatuses.com` for HTTP error reference (#2768)\n\n## 0.24.1 (17th May, 2023)\n\n### Added\n\n* Provide additional context in some `InvalidURL` exceptions. (#2675)\n\n### Fixed\n\n* Fix optional percent-encoding behaviour. (#2671)\n* More robust checking for opening upload files in binary mode. (#2630)\n* Properly support IP addresses in `NO_PROXY` environment variable. (#2659)\n* Set default file for `NetRCAuth()` to `None` to use the stdlib default. (#2667)\n* Set logging request lines to INFO level for async requests, in line with sync requests. (#2656)\n* Fix which gen-delims need to be escaped for path/query/fragment components in URL. (#2701)\n\n## 0.24.0 (6th April, 2023)\n\n### Changed\n\n* The logging behaviour has been changed to be more in-line with other standard Python logging usages. We no longer have a custom `TRACE` log level, and we no longer use the `HTTPX_LOG_LEVEL` environment variable to auto-configure logging. We now have a significant amount of `DEBUG` logging available at the network level. Full documentation is available at https://www.python-httpx.org/logging/ (#2547, encode/httpcore#648)\n* The `Response.iter_lines()` method now matches the stdlib behaviour and does not include the newline characters. It also resolves a performance issue. (#2423)\n* Query parameter encoding switches from using + for spaces and %2F for forward slash, to instead using %20 for spaces and treating forward slash as a safe, unescaped character. This differs from `requests`, but is in line with browser behavior in Chrome, Safari, and Firefox. Both options are RFC valid. (#2543)\n* NetRC authentication is no longer automatically handled, but is instead supported by an explicit `httpx.NetRCAuth()` authentication class. See the documentation at https://www.python-httpx.org/advanced/#netrc-support (#2525)\n\n### Removed\n\n* The `rfc3986` dependancy has been removed. (#2252)\n\n## 0.23.3 (4th Jan, 2023)\n\n### Fixed\n\n* Version 0.23.2 accidentally included stricter type checking on query parameters. This shouldn've have been included in a minor version bump, and is now reverted. (#2523, #2539)\n\n## 0.23.2 (2nd Jan, 2023)\n\n### Added\n\n* Support digest auth nonce counting to avoid multiple auth requests. (#2463)\n\n### Fixed\n\n* Multipart file uploads where the file length cannot be determine now use chunked transfer encoding, rather than loading the entire file into memory in order to determine the `Content-Length`. (#2382)\n* Raise `TypeError` if content is passed a dict-instance. (#2495)\n* Partially revert the API breaking change in 0.23.1, which removed `RawURL`. We continue to expose a `url.raw` property which is now a plain named-tuple. This API is still expected to be deprecated, but we will do so with a major version bump. (#2481)\n\n## 0.23.1 (18th Nov, 2022)\n\n**Note**: The 0.23.1 release should have used a proper version bump, rather than a minor point release.\nThere are API surface area changes that may affect some users.\nSee the \"Removed\" section of these release notes for details.\n\n### Added\n\n* Support for Python 3.11. (#2420)\n* Allow setting an explicit multipart boundary in `Content-Type` header. (#2278)\n* Allow `tuple` or `list` for multipart values, not just `list`. (#2355)\n* Allow `str` content for multipart upload files. (#2400)\n* Support connection upgrades. See https://www.encode.io/httpcore/extensions/#upgrade-requests\n\n### Fixed\n\n* Don't drop empty query parameters. (#2354)\n\n### Removed\n\n* Upload files *must* always be opened in binary mode. (#2400)\n* Drop `.read`/`.aread` from `SyncByteStream`/`AsyncByteStream`. (#2407)\n* Drop `RawURL`. (#2241)\n\n## 0.23.0 (23rd May, 2022)\n\n### Changed\n\n* Drop support for Python 3.6. (#2097)\n* Use `utf-8` as the default character set, instead of falling back to `charset-normalizer` for auto-detection. To enable automatic character set detection, see [the documentation](https://www.python-httpx.org/advanced/#character-set-encodings-and-auto-detection). (#2165)\n\n### Fixed\n\n* Fix `URL.copy_with` for some oddly formed URL cases. (#2185)\n* Digest authentication should use case-insensitive comparison for determining which algorithm is being used. (#2204)\n* Fix console markup escaping in command line client. (#1866)\n* When files are used in multipart upload, ensure we always seek to the start of the file. (#2065)\n* Ensure that `iter_bytes` never yields zero-length chunks. (#2068)\n* Preserve `Authorization` header for redirects that are to the same origin, but are an `http`-to-`https` upgrade. (#2074)\n* When responses have binary output, don't print the output to the console in the command line client. Use output like `<16086 bytes of binary data>` instead. (#2076)\n* Fix display of `--proxies` argument in the command line client help. (#2125)\n* Close responses when task cancellations occur during stream reading. (#2156)\n* Fix type error on accessing `.request` on `HTTPError` exceptions. (#2158)\n\n## 0.22.0 (26th January, 2022)\n\n### Added\n\n* Support for [the SOCKS5 proxy protocol](https://www.python-httpx.org/advanced/#socks) via [the `socksio` package](https://github.com/sethmlarson/socksio). (#2034)\n* Support for custom headers in multipart/form-data requests (#1936)\n\n### Fixed\n\n* Don't perform unreliable close/warning on `__del__` with unclosed clients. (#2026)\n* Fix `Headers.update(...)` to correctly handle repeated headers (#2038)\n\n## 0.21.3 (6th January, 2022)\n\n### Fixed\n\n* Fix streaming uploads using `SyncByteStream` or `AsyncByteStream`. Regression in 0.21.2. (#2016)\n\n## 0.21.2 (5th January, 2022)\n\n### Fixed\n\n* HTTP/2 support for tunnelled proxy cases. (#2009)\n* Improved the speed of large file uploads. (#1948)\n\n## 0.21.1 (16th November, 2021)\n\n### Fixed\n\n* The `response.url` property is now correctly annotated as `URL`, instead of `Optional[URL]`. (#1940)\n\n## 0.21.0 (15th November, 2021)\n\nThe 0.21.0 release integrates against a newly redesigned `httpcore` backend.\n\nBoth packages ought to automatically update to the required versions, but if you are\nseeing any issues, you should ensure that you have `httpx==0.21.*` and `httpcore==0.14.*` installed.\n\n### Added\n\n* The command-line client will now display connection information when `-v/--verbose` is used.\n* The command-line client will now display server certificate information when `-v/--verbose` is used.\n* The command-line client is now able to properly detect if the outgoing request\nshould be formatted as HTTP/1.1 or HTTP/2, based on the result of the HTTP/2 negotiation.\n\n### Removed\n\n* Curio support is no longer currently included. Please get in touch if you require this, so that we can assess priorities.\n\n## 0.20.0 (13th October, 2021)\n\nThe 0.20.0 release adds an integrated command-line client, and also includes some\ndesign changes. The most notable of these is that redirect responses are no longer\nautomatically followed, unless specifically requested.\n\nThis design decision prioritises a more explicit approach to redirects, in order\nto avoid code that unintentionally issues multiple requests as a result of\nmisconfigured URLs.\n\nFor example, previously a client configured to send requests to `http://api.github.com/`\nwould end up sending every API request twice, as each request would be redirected to `https://api.github.com/`.\n\nIf you do want auto-redirect behaviour, you can enable this either by configuring\nthe client instance with `Client(follow_redirects=True)`, or on a per-request\nbasis, with `.get(..., follow_redirects=True)`.\n\nThis change is a classic trade-off between convenience and precision, with no \"right\"\nanswer. See [discussion #1785](https://github.com/encode/httpx/discussions/1785) for more\ncontext.\n\nThe other major design change is an update to the Transport API, which is the low-level\ninterface against which requests are sent. Previously this interface used only primitive\ndatastructures, like so...\n\n```python\n(status_code, headers, stream, extensions) = transport.handle_request(method, url, headers, stream, extensions)\ntry\n ...\nfinally:\n stream.close()\n```\n\nNow the interface is much simpler...\n\n```python\nresponse = transport.handle_request(request)\ntry\n ...\nfinally:\n response.close()\n```\n\n### Changed\n\n* The `allow_redirects` flag is now `follow_redirects` and defaults to `False`.\n* The `raise_for_status()` method will now raise an exception for any responses\n except those with 2xx status codes. Previously only 4xx and 5xx status codes\n would result in an exception.\n* The low-level transport API changes to the much simpler `response = transport.handle_request(request)`.\n* The `client.send()` method no longer accepts a `timeout=...` argument, but the\n `client.build_request()` does. This required by the signature change of the\n Transport API. The request timeout configuration is now stored on the request\n instance, as `request.extensions['timeout']`.\n\n### Added\n\n* Added the `httpx` command-line client.\n* Response instances now include `.is_informational`, `.is_success`, `.is_redirect`, `.is_client_error`, and `.is_server_error`\n properties for checking 1xx, 2xx, 3xx, 4xx, and 5xx response types. Note that the behaviour of `.is_redirect` is slightly different in that it now returns True for all 3xx responses, in order to allow for a consistent set of properties onto the different HTTP status code types. The `response.has_redirect_location` location may be used to determine responses with properly formed URL redirects.\n\n### Fixed\n\n* `response.iter_bytes()` no longer raises a ValueError when called on a response with no content. (Pull #1827)\n* The `'wsgi.error'` configuration now defaults to `sys.stderr`, and is corrected to be a `TextIO` interface, not a `BytesIO` interface. Additionally, the WSGITransport now accepts a `wsgi_error` configuration. (Pull #1828)\n* Follow the WSGI spec by properly closing the iterable returned by the application. (Pull #1830)\n\n## 0.19.0 (19th August, 2021)\n\n### Added\n\n* Add support for `Client(allow_redirects=)`. (Pull #1790)\n* Add automatic character set detection, when no `charset` is included in the response `Content-Type` header. (Pull #1791)\n\n### Changed\n\n* Event hooks are now also called for any additional redirect or auth requests/responses. (Pull #1806)\n* Strictly enforce that upload files must be opened in binary mode. (Pull #1736)\n* Strictly enforce that client instances can only be opened and closed once, and cannot be re-opened. (Pull #1800)\n* Drop `mode` argument from `httpx.Proxy(..., mode=...)`. (Pull #1795)\n\n## 0.18.2 (17th June, 2021)\n\n### Added\n\n* Support for Python 3.10. (Pull #1687)\n* Expose `httpx.USE_CLIENT_DEFAULT`, used as the default to `auth` and `timeout` parameters in request methods. (Pull #1634)\n* Support [HTTP/2 \"prior knowledge\"](https://python-hyper.org/projects/hyper-h2/en/v2.3.1/negotiating-http2.html#prior-knowledge), using `httpx.Client(http1=False, http2=True)`. (Pull #1624)\n\n### Fixed\n\n* Clean up some cases where warnings were being issued. (Pull #1687)\n* Prefer Content-Length over Transfer-Encoding: chunked for content= cases. (Pull #1619)\n\n## 0.18.1 (29th April, 2021)\n\n### Changed\n\n* Update brotli support to use the `brotlicffi` package (Pull #1605)\n* Ensure that `Request(..., stream=...)` does not auto-generate any headers on the request instance. (Pull #1607)\n\n### Fixed\n\n* Pass through `timeout=...` in top-level httpx.stream() function. (Pull #1613)\n* Map httpcore transport close exceptions to httpx exceptions. (Pull #1606)\n\n## 0.18.0 (27th April, 2021)\n\nThe 0.18.x release series formalises our low-level Transport API, introducing the base classes `httpx.BaseTransport` and `httpx.AsyncBaseTransport`.\n\nSee the \"[Writing custom transports](https://www.python-httpx.org/advanced/#writing-custom-transports)\" documentation and the [`httpx.BaseTransport.handle_request()`](https://github.com/encode/httpx/blob/397aad98fdc8b7580a5fc3e88f1578b4302c6382/httpx/_transports/base.py#L77-L147) docstring for more complete details on implementing custom transports.\n\nPull request #1522 includes a checklist of differences from the previous `httpcore` transport API, for developers implementing custom transports.\n\nThe following API changes have been issuing deprecation warnings since 0.17.0 onwards, and are now fully deprecated...\n\n* You should now use httpx.codes consistently instead of httpx.StatusCodes.\n* Use limits=... instead of pool_limits=....\n* Use proxies={\"http://\": ...} instead of proxies={\"http\": ...} for scheme-specific mounting.\n\n### Changed\n\n* Transport instances now inherit from `httpx.BaseTransport` or `httpx.AsyncBaseTransport`,\n and should implement either the `handle_request` method or `handle_async_request` method. (Pull #1522, #1550)\n* The `response.ext` property and `Response(ext=...)` argument are now named `extensions`. (Pull #1522)\n* The recommendation to not use `data=` in favour of `content=` has now been escalated to a deprecation warning. (Pull #1573)\n* Drop `Response(on_close=...)` from API, since it was a bit of leaking implementation detail. (Pull #1572)\n* When using a client instance, cookies should always be set on the client, rather than on a per-request basis. We prefer enforcing a stricter API here because it provides clearer expectations around cookie persistence, particularly when redirects occur. (Pull #1574)\n* The runtime exception `httpx.ResponseClosed` is now named `httpx.StreamClosed`. (#1584)\n* The `httpx.QueryParams` model now presents an immutable interface. There is a discussion on [the design and motivation here](https://github.com/encode/httpx/discussions/1599). Use `client.params = client.params.merge(...)` instead of `client.params.update(...)`. The basic query manipulation methods are `query.set(...)`, `query.add(...)`, and `query.remove()`. (#1600)\n\n### Added\n\n* The `Request` and `Response` classes can now be serialized using pickle. (#1579)\n* Handle `data={\"key\": [None|int|float|bool]}` cases. (Pull #1539)\n* Support `httpx.URL(**kwargs)`, for example `httpx.URL(scheme=\"https\", host=\"www.example.com\", path=\"/')`, or `httpx.URL(\"https://www.example.com/\", username=\"tom@gmail.com\", password=\"123 456\")`. (Pull #1601)\n* Support `url.copy_with(params=...)`. (Pull #1601)\n* Add `url.params` parameter, returning an immutable `QueryParams` instance. (Pull #1601)\n* Support query manipulation methods on the URL class. These are `url.copy_set_param()`, `url.copy_add_param()`, `url.copy_remove_param()`, `url.copy_merge_params()`. (Pull #1601)\n* The `httpx.URL` class now performs port normalization, so `:80` ports are stripped from `http` URLs and `:443` ports are stripped from `https` URLs. (Pull #1603)\n* The `URL.host` property returns unicode strings for internationalized domain names. The `URL.raw_host` property returns byte strings with IDNA escaping applied. (Pull #1590)\n\n### Fixed\n\n* Fix Content-Length for cases of `files=...` where unicode string is used as the file content. (Pull #1537)\n* Fix some cases of merging relative URLs against `Client(base_url=...)`. (Pull #1532)\n* The `request.content` attribute is now always available except for streaming content, which requires an explicit `.read()`. (Pull #1583)\n\n## 0.17.1 (March 15th, 2021)\n\n### Fixed\n\n* Type annotation on `CertTypes` allows `keyfile` and `password` to be optional. (Pull #1503)\n* Fix httpcore pinned version. (Pull #1495)\n\n## 0.17.0 (February 28th, 2021)\n\n### Added\n\n* Add `httpx.MockTransport()`, allowing to mock out a transport using pre-determined responses. (Pull #1401, Pull #1449)\n* Add `httpx.HTTPTransport()` and `httpx.AsyncHTTPTransport()` default transports. (Pull #1399)\n* Add mount API support, using `httpx.Client(mounts=...)`. (Pull #1362)\n* Add `chunk_size` parameter to `iter_raw()`, `iter_bytes()`, `iter_text()`. (Pull #1277)\n* Add `keepalive_expiry` parameter to `httpx.Limits()` configuration. (Pull #1398)\n* Add repr to `httpx.Cookies` to display available cookies. (Pull #1411)\n* Add support for `params=` (previously only `params=` was supported). (Pull #1426)\n\n### Fixed\n\n* Add missing `raw_path` to ASGI scope. (Pull #1357)\n* Tweak `create_ssl_context` defaults to use `trust_env=True`. (Pull #1447)\n* Properly URL-escape WSGI `PATH_INFO`. (Pull #1391)\n* Properly set default ports in WSGI transport. (Pull #1469)\n* Properly encode slashes when using `base_url`. (Pull #1407)\n* Properly map exceptions in `request.aclose()`. (Pull #1465)\n\n## 0.16.1 (October 8th, 2020)\n\n### Fixed\n\n* Support literal IPv6 addresses in URLs. (Pull #1349)\n* Force lowercase headers in ASGI scope dictionaries. (Pull #1351)\n\n## 0.16.0 (October 6th, 2020)\n\n### Changed\n\n* Preserve HTTP header casing. (Pull #1338, encode/httpcore#216, python-hyper/h11#104)\n* Drop `response.next()` and `response.anext()` methods in favour of `response.next_request` attribute. (Pull #1339)\n* Closed clients now raise a runtime error if attempting to send a request. (Pull #1346)\n\n### Added\n\n* Add Python 3.9 to officially supported versions.\n* Type annotate `__enter__`/`__exit__`/`__aenter__`/`__aexit__` in a way that supports subclasses of `Client` and `AsyncClient`. (Pull #1336)\n\n## 0.15.5 (October 1st, 2020)\n\n### Added\n\n* Add `response.next_request` (Pull #1334)\n\n## 0.15.4 (September 25th, 2020)\n\n### Added\n\n* Support direct comparisons between `Headers` and dicts or lists of two-tuples. Eg. `assert response.headers == {\"Content-Length\": 24}` (Pull #1326)\n\n### Fixed\n\n* Fix automatic `.read()` when `Response` instances are created with `content=` (Pull #1324)\n\n## 0.15.3 (September 24th, 2020)\n\n### Fixed\n\n* Fixed connection leak in async client due to improper closing of response streams. (Pull #1316)\n\n## 0.15.2 (September 23nd, 2020)\n\n### Fixed\n\n* Fixed `response.elapsed` property. (Pull #1313)\n* Fixed client authentication interaction with `.stream()`. (Pull #1312)\n\n## 0.15.1 (September 23nd, 2020)\n\n### Fixed\n\n* ASGITransport now properly applies URL decoding to the `path` component, as-per the ASGI spec. (Pull #1307)\n\n## 0.15.0 (September 22nd, 2020)\n\n### Added\n\n* Added support for curio. (Pull https://github.com/encode/httpcore/pull/168)\n* Added support for event hooks. (Pull #1246)\n* Added support for authentication flows which require either sync or async I/O. (Pull #1217)\n* Added support for monitoring download progress with `response.num_bytes_downloaded`. (Pull #1268)\n* Added `Request(content=...)` for byte content, instead of overloading `Request(data=...)` (Pull #1266)\n* Added support for all URL components as parameter names when using `url.copy_with(...)`. (Pull #1285)\n* Neater split between automatically populated headers on `Request` instances, vs default `client.headers`. (Pull #1248)\n* Unclosed `AsyncClient` instances will now raise warnings if garbage collected. (Pull #1197)\n* Support `Response(content=..., text=..., html=..., json=...)` for creating usable response instances in code. (Pull #1265, #1297)\n* Support instantiating requests from the low-level transport API. (Pull #1293)\n* Raise errors on invalid URL types. (Pull #1259)\n\n### Changed\n\n* Cleaned up expected behaviour for URL escaping. `url.path` is now URL escaped. (Pull #1285)\n* Cleaned up expected behaviour for bytes vs str in URL components. `url.userinfo` and `url.query` are not URL escaped, and so return bytes. (Pull #1285)\n* Drop `url.authority` property in favour of `url.netloc`, since \"authority\" was semantically incorrect. (Pull #1285)\n* Drop `url.full_path` property in favour of `url.raw_path`, for better consistency with other parts of the API. (Pull #1285)\n* No longer use the `chardet` library for auto-detecting charsets, instead defaulting to a simpler approach when no charset is specified. (#1269)\n\n### Fixed\n\n* Swapped ordering of redirects and authentication flow. (Pull #1267)\n* `.netrc` lookups should use host, not host+port. (Pull #1298)\n\n### Removed\n\n* The `URLLib3Transport` class no longer exists. We've published it instead as an example of [a custom transport class](https://gist.github.com/florimondmanca/d56764d78d748eb9f73165da388e546e). (Pull #1182)\n* Drop `request.timer` attribute, which was being used internally to set `response.elapsed`. (Pull #1249)\n* Drop `response.decoder` attribute, which was being used internally. (Pull #1276)\n* `Request.prepare()` is now a private method. (Pull #1284)\n* The `Headers.getlist()` method had previously been deprecated in favour of `Headers.get_list()`. It is now fully removed.\n* The `QueryParams.getlist()` method had previously been deprecated in favour of `QueryParams.get_list()`. It is now fully removed.\n* The `URL.is_ssl` property had previously been deprecated in favour of `URL.scheme == \"https\"`. It is now fully removed.\n* The `httpx.PoolLimits` class had previously been deprecated in favour of `httpx.Limits`. It is now fully removed.\n* The `max_keepalive` setting had previously been deprecated in favour of the more explicit `max_keepalive_connections`. It is now fully removed.\n* The verbose `httpx.Timeout(5.0, connect_timeout=60.0)` style had previously been deprecated in favour of `httpx.Timeout(5.0, connect=60.0)`. It is now fully removed.\n* Support for instantiating a timeout config missing some defaults, such as `httpx.Timeout(connect=60.0)`, had previously been deprecated in favour of enforcing a more explicit style, such as `httpx.Timeout(5.0, connect=60.0)`. This is now strictly enforced.\n\n## 0.14.3 (September 2nd, 2020)\n\n### Added\n\n* `http.Response()` may now be instantiated without a `request=...` parameter. Useful for some unit testing cases. (Pull #1238)\n* Add `103 Early Hints` and `425 Too Early` status codes. (Pull #1244)\n\n### Fixed\n\n* `DigestAuth` now handles responses that include multiple 'WWW-Authenticate' headers. (Pull #1240)\n* Call into transport `__enter__`/`__exit__` or `__aenter__`/`__aexit__` when client is used in a context manager style. (Pull #1218)\n\n## 0.14.2 (August 24th, 2020)\n\n### Added\n\n* Support `client.get(..., auth=None)` to bypass the default authentication on a clients. (Pull #1115)\n* Support `client.auth = ...` property setter. (Pull #1185)\n* Support `httpx.get(..., proxies=...)` on top-level request functions. (Pull #1198)\n* Display instances with nicer import styles. (Eg. ) (Pull #1155)\n* Support `cookies=[(key, value)]` list-of-two-tuples style usage. (Pull #1211)\n\n### Fixed\n\n* Ensure that automatically included headers on a request may be modified. (Pull #1205)\n* Allow explicit `Content-Length` header on streaming requests. (Pull #1170)\n* Handle URL quoted usernames and passwords properly. (Pull #1159)\n* Use more consistent default for `HEAD` requests, setting `allow_redirects=True`. (Pull #1183)\n* If a transport error occurs while streaming the response, raise an `httpx` exception, not the underlying `httpcore` exception. (Pull #1190)\n* Include the underlying `httpcore` traceback, when transport exceptions occur. (Pull #1199)\n\n## 0.14.1 (August 11th, 2020)\n\n### Added\n\n* The `httpx.URL(...)` class now raises `httpx.InvalidURL` on invalid URLs, rather than exposing the underlying `rfc3986` exception. If a redirect response includes an invalid 'Location' header, then a `RemoteProtocolError` exception is raised, which will be associated with the request that caused it. (Pull #1163)\n\n### Fixed\n\n* Handling multiple `Set-Cookie` headers became broken in the 0.14.0 release, and is now resolved. (Pull #1156)\n\n## 0.14.0 (August 7th, 2020)\n\nThe 0.14 release includes a range of improvements to the public API, intended on preparing for our upcoming 1.0 release.\n\n* Our HTTP/2 support is now fully optional. **You now need to use `pip install httpx[http2]` if you want to include the HTTP/2 dependencies.**\n* Our HSTS support has now been removed. Rewriting URLs from `http` to `https` if the host is on the HSTS list can be beneficial in avoiding roundtrips to incorrectly formed URLs, but on balance we've decided to remove this feature, on the principle of least surprise. Most programmatic clients do not include HSTS support, and for now we're opting to remove our support for it.\n* Our exception hierarchy has been overhauled. Most users will want to stick with their existing `httpx.HTTPError` usage, but we've got a clearer overall structure now. See https://www.python-httpx.org/exceptions/ for more details.\n\nWhen upgrading you should be aware of the following public API changes. Note that deprecated usages will currently continue to function, but will issue warnings.\n\n* You should now use `httpx.codes` consistently instead of `httpx.StatusCodes`.\n* Usage of `httpx.Timeout()` should now always include an explicit default. Eg. `httpx.Timeout(None, pool=5.0)`.\n* When using `httpx.Timeout()`, we now have more concisely named keyword arguments. Eg. `read=5.0`, instead of `read_timeout=5.0`.\n* Use `httpx.Limits()` instead of `httpx.PoolLimits()`, and `limits=...` instead of `pool_limits=...`.\n* The `httpx.Limits(max_keepalive=...)` argument is now deprecated in favour of a more explicit `httpx.Limits(max_keepalive_connections=...)`.\n* Keys used with `Client(proxies={...})` should now be in the style of `{\"http://\": ...}`, rather than `{\"http\": ...}`.\n* The multidict methods `Headers.getlist()` and `QueryParams.getlist()` are deprecated in favour of more consistent `.get_list()` variants.\n* The `URL.is_ssl` property is deprecated in favour of `URL.scheme == \"https\"`.\n* The `URL.join(relative_url=...)` method is now `URL.join(url=...)`. This change does not support warnings for the deprecated usage style.\n\nOne notable aspect of the 0.14.0 release is that it tightens up the public API for `httpx`, by ensuring that several internal attributes and methods have now become strictly private.\n\nThe following previously had nominally public names on the client, but were all undocumented and intended solely for internal usage. They are all now replaced with underscored names, and should not be relied on or accessed.\n\nThese changes should not affect users who have been working from the `httpx` documentation.\n\n* `.merge_url()`, `.merge_headers()`, `.merge_cookies()`, `.merge_queryparams()`\n* `.build_auth()`, `.build_redirect_request()`\n* `.redirect_method()`, `.redirect_url()`, `.redirect_headers()`, `.redirect_stream()`\n* `.send_handling_redirects()`, `.send_handling_auth()`, `.send_single_request()`\n* `.init_transport()`, `.init_proxy_transport()`\n* `.proxies`, `.transport`, `.netrc`, `.get_proxy_map()`\n\nSee pull requests #997, #1065, #1071.\n\nSome areas of API which were already on the deprecation path, and were raising warnings or errors in 0.13.x have now been escalated to being fully removed.\n\n* Drop `ASGIDispatch`, `WSGIDispatch`, which have been replaced by `ASGITransport`, `WSGITransport`.\n* Drop `dispatch=...`` on client, which has been replaced by `transport=...``\n* Drop `soft_limit`, `hard_limit`, which have been replaced by `max_keepalive` and `max_connections`.\n* Drop `Response.stream` and` `Response.raw`, which have been replaced by ``.aiter_bytes` and `.aiter_raw`.\n* Drop `proxies=` in favor of `proxies=httpx.Proxy(...)`.\n\nSee pull requests #1057, #1058.\n\n### Added\n\n* Added dedicated exception class `httpx.HTTPStatusError` for `.raise_for_status()` exceptions. (Pull #1072)\n* Added `httpx.create_ssl_context()` helper function. (Pull #996)\n* Support for proxy exlcusions like `proxies={\"https://www.example.com\": None}`. (Pull #1099)\n* Support `QueryParams(None)` and `client.params = None`. (Pull #1060)\n\n### Changed\n\n* Use `httpx.codes` consistently in favour of `httpx.StatusCodes` which is placed into deprecation. (Pull #1088)\n* Usage of `httpx.Timeout()` should now always include an explicit default. Eg. `httpx.Timeout(None, pool=5.0)`. (Pull #1085)\n* Switch to more concise `httpx.Timeout()` keyword arguments. Eg. `read=5.0`, instead of `read_timeout=5.0`. (Pull #1111)\n* Use `httpx.Limits()` instead of `httpx.PoolLimits()`, and `limits=...` instead of `pool_limits=...`. (Pull #1113)\n* Keys used with `Client(proxies={...})` should now be in the style of `{\"http://\": ...}`, rather than `{\"http\": ...}`. (Pull #1127)\n* The multidict methods `Headers.getlist` and `QueryParams.getlist` are deprecated in favour of more consistent `.get_list()` variants. (Pull #1089)\n* `URL.port` becomes `Optional[int]`. Now only returns a port if one is explicitly included in the URL string. (Pull #1080)\n* The `URL(..., allow_relative=[bool])` parameter no longer exists. All URL instances may be relative. (Pull #1073)\n* Drop unnecessary `url.full_path = ...` property setter. (Pull #1069)\n* The `URL.join(relative_url=...)` method is now `URL.join(url=...)`. (Pull #1129)\n* The `URL.is_ssl` property is deprecated in favour of `URL.scheme == \"https\"`. (Pull #1128)\n\n### Fixed\n\n* Add missing `Response.next()` method. (Pull #1055)\n* Ensure all exception classes are exposed as public API. (Pull #1045)\n* Support multiple items with an identical field name in multipart encodings. (Pull #777)\n* Skip HSTS preloading on single-label domains. (Pull #1074)\n* Fixes for `Response.iter_lines()`. (Pull #1033, #1075)\n* Ignore permission errors when accessing `.netrc` files. (Pull #1104)\n* Allow bare hostnames in `HTTP_PROXY` etc... environment variables. (Pull #1120)\n* Settings `app=...` or `transport=...` bypasses any environment based proxy defaults. (Pull #1122)\n* Fix handling of `.base_url` when a path component is included in the base URL. (Pull #1130)\n\n---\n\n## 0.13.3 (May 29th, 2020)\n\n### Fixed\n\n* Include missing keepalive expiry configuration. (Pull #1005)\n* Improved error message when URL redirect has a custom scheme. (Pull #1002)\n\n## 0.13.2 (May 27th, 2020)\n\n### Fixed\n\n* Include explicit \"Content-Length: 0\" on POST, PUT, PATCH if no request body is used. (Pull #995)\n* Add `http2` option to `httpx.Client`. (Pull #982)\n* Tighten up API typing in places. (Pull #992, #999)\n\n## 0.13.1 (May 22nd, 2020)\n\n### Fixed\n\n* Fix pool options deprecation warning. (Pull #980)\n* Include `httpx.URLLib3ProxyTransport` in top-level API. (Pull #979)\n\n## 0.13.0 (May 22nd, 2020)\n\nThis release switches to `httpcore` for all the internal networking, which means:\n\n* We're using the same codebase for both our sync and async clients.\n* HTTP/2 support is now available with the sync client.\n* We no longer have a `urllib3` dependency for our sync client, although there is still an *optional* `URLLib3Transport` class.\n\nIt also means we've had to remove our UDS support, since maintaining that would have meant having to push back our work towards a 1.0 release, which isn't a trade-off we wanted to make.\n\nWe also now have [a public \"Transport API\"](https://www.python-httpx.org/advanced/#custom-transports), which you can use to implement custom transport implementations against. This formalises and replaces our previously private \"Dispatch API\".\n\n### Changed\n\n* Use `httpcore` for underlying HTTP transport. Drop `urllib3` requirement. (Pull #804, #967)\n* Rename pool limit options from `soft_limit`/`hard_limit` to `max_keepalive`/`max_connections`. (Pull #968)\n* The previous private \"Dispatch API\" has now been promoted to a public \"Transport API\". When customizing the transport use `transport=...`. The `ASGIDispatch` and `WSGIDispatch` class naming is deprecated in favour of `ASGITransport` and `WSGITransport`. (Pull #963)\n\n### Added\n\n* Added `URLLib3Transport` class for optional `urllib3` transport support. (Pull #804, #963)\n* Streaming multipart uploads. (Pull #857)\n* Logging via HTTPCORE_LOG_LEVEL and HTTPX_LOG_LEVEL environment variables\nand TRACE level logging. (Pull encode/httpcore#79)\n\n### Fixed\n\n* Performance improvement in brotli decoder. (Pull #906)\n* Proper warning level of deprecation notice in `Response.stream` and `Response.raw`. (Pull #908)\n* Fix support for generator based WSGI apps. (Pull #887)\n* Reuse of connections on HTTP/2 in close concurrency situations. (Pull encode/httpcore#81)\n* Honor HTTP/2 max concurrent streams settings (Pull encode/httpcore#89, encode/httpcore#90)\n* Fix bytes support in multipart uploads. (Pull #974)\n* Improve typing support for `files=...`. (Pull #976)\n\n### Removed\n\n* Dropped support for `Client(uds=...)` (Pull #804)\n\n## 0.13.0.dev2 (May 12th, 2020)\n\nThe 0.13.0.dev2 is a *pre-release* version. To install it, use `pip install httpx --pre`.\n\n### Added\n\n* Logging via HTTPCORE_LOG_LEVEL and HTTPX_LOG_LEVEL environment variables\nand TRACE level logging. (HTTPCore Pull #79)\n\n### Fixed\n\n* Reuse of connections on HTTP/2 in close concurrency situations. (HTTPCore Pull #81)\n* When using an `app=` observe neater disconnect behaviour instead of sending empty body messages. (Pull #919)\n\n## 0.13.0.dev1 (May 6th, 2020)\n\nThe 0.13.0.dev1 is a *pre-release* version. To install it, use `pip install httpx --pre`.\n\n### Fixed\n\n* Passing `http2` flag to proxy dispatchers. (Pull #934)\n* Use [`httpcore` v0.8.3](https://github.com/encode/httpcore/releases/tag/0.8.3)\nwhich addresses problems in handling of headers when using proxies.\n\n## 0.13.0.dev0 (April 30th, 2020)\n\nThe 0.13.0.dev0 is a *pre-release* version. To install it, use `pip install httpx --pre`.\n\nThis release switches to `httpcore` for all the internal networking, which means:\n\n* We're using the same codebase for both our sync and async clients.\n* HTTP/2 support is now available with the sync client.\n* We no longer have a `urllib3` dependency for our sync client, although there is still an *optional* `URLLib3Dispatcher` class.\n\nIt also means we've had to remove our UDS support, since maintaining that would have meant having to push back our work towards a 1.0 release, which isn't a trade-off we wanted to make.\n\n### Changed\n\n* Use `httpcore` for underlying HTTP transport. Drop `urllib3` requirement. (Pull #804)\n\n### Added\n\n* Added `URLLib3Dispatcher` class for optional `urllib3` transport support. (Pull #804)\n* Streaming multipart uploads. (Pull #857)\n\n### Fixed\n\n* Performance improvement in brotli decoder. (Pull #906)\n* Proper warning level of deprecation notice in `Response.stream` and `Response.raw`. (Pull #908)\n* Fix support for generator based WSGI apps. (Pull #887)\n\n### Removed\n\n* Dropped support for `Client(uds=...)` (Pull #804)\n\n---\n\n## 0.12.1 (March 19th, 2020)\n\n### Fixed\n\n* Resolved packaging issue, where additional files were being included.\n\n## 0.12.0 (March 9th, 2020)\n\nThe 0.12 release tightens up the API expectations for `httpx` by switching to private module names to enforce better clarity around public API.\n\nAll imports of `httpx` should import from the top-level package only, such as `from httpx import Request`, rather than importing from privately namespaced modules such as `from httpx._models import Request`.\n\n### Added\n\n* Support making response body available to auth classes with `.requires_response_body`. (Pull #803)\n* Export `NetworkError` exception. (Pull #814)\n* Add support for `NO_PROXY` environment variable. (Pull #835)\n\n### Changed\n\n* Switched to private module names. (Pull #785)\n* Drop redirect looping detection and the `RedirectLoop` exception, instead using `TooManyRedirects`. (Pull #819)\n* Drop `backend=...` parameter on `AsyncClient`, in favour of always autodetecting `trio`/`asyncio`. (Pull #791)\n\n### Fixed\n\n* Support basic auth credentials in proxy URLs. (Pull #780)\n* Fix `httpx.Proxy(url, mode=\"FORWARD_ONLY\")` configuration. (Pull #788)\n* Fallback to setting headers as UTF-8 if no encoding is specified. (Pull #820)\n* Close proxy dispatches classes on client close. (Pull #826)\n* Support custom `cert` parameters even if `verify=False`. (Pull #796)\n* Don't support invalid dict-of-dicts form data in `data=...`. (Pull #811)\n\n---\n\n## 0.11.1 (January 17th, 2020)\n\n### Fixed\n\n* Fixed usage of `proxies=...` on `Client()`. (Pull #763)\n* Support both `zlib` and `deflate` style encodings on `Content-Encoding: deflate`. (Pull #758)\n* Fix for streaming a redirect response body with `allow_redirects=False`. (Pull #766)\n* Handle redirect with malformed Location headers missing host. (Pull #774)\n\n## 0.11.0 (January 9th, 2020)\n\nThe 0.11 release reintroduces our sync support, so that `httpx` now supports both a standard thread-concurrency API, and an async API.\n\nExisting async `httpx` users that are upgrading to 0.11 should ensure that:\n\n* Async codebases should always use a client instance to make requests, instead of the top-level API.\n* The async client is named as `httpx.AsyncClient()`, instead of `httpx.Client()`.\n* When instantiating proxy configurations use the `httpx.Proxy()` class, instead of the previous `httpx.HTTPProxy()`. This new configuration class works for configuring both sync and async clients.\n\nWe believe the API is now pretty much stable, and are aiming for a 1.0 release sometime on or before April 2020.\n\n### Changed\n\n- Top level API such as `httpx.get(url, ...)`, `httpx.post(url, ...)`, `httpx.request(method, url, ...)` becomes synchronous.\n- Added `httpx.Client()` for synchronous clients, with `httpx.AsyncClient` being used for async clients.\n- Switched to `proxies=httpx.Proxy(...)` for proxy configuration.\n- Network connection errors are wrapped in `httpx.NetworkError`, rather than exposing lower-level exception types directly.\n\n### Removed\n\n- The `request.url.origin` property and `httpx.Origin` class are no longer available.\n- The per-request `cert`, `verify`, and `trust_env` arguments are escalated from raising errors if used, to no longer being available. These arguments should be used on a per-client instance instead, or in the top-level API.\n- The `stream` argument has escalated from raising an error when used, to no longer being available. Use the `client.stream(...)` or `httpx.stream()` streaming API instead.\n\n### Fixed\n\n- Redirect loop detection matches against `(method, url)` rather than `url`. (Pull #734)\n\n---\n\n## 0.10.1 (December 31st, 2019)\n\n### Fixed\n\n- Fix issue with concurrent connection acquiry. (Pull #700)\n- Fix write error on closing HTTP/2 connections. (Pull #699)\n\n## 0.10.0 (December 29th, 2019)\n\nThe 0.10.0 release makes some changes that will allow us to support both sync and async interfaces.\n\nIn particular with streaming responses the `response.read()` method becomes `response.aread()`, and the `response.close()` method becomes `response.aclose()`.\n\nIf following redirects explicitly the `response.next()` method becomes `response.anext()`.\n\n### Fixed\n\n- End HTTP/2 streams immediately on no-body requests, rather than sending an empty body message. (Pull #682)\n- Improve typing for `Response.request`: switch from `Optional[Request]` to `Request`. (Pull #666)\n- `Response.elapsed` now reflects the entire download time. (Pull #687, #692)\n\n### Changed\n\n- Added `AsyncClient` as a synonym for `Client`. (Pull #680)\n- Switch to `response.aread()` for conditionally reading streaming responses. (Pull #674)\n- Switch to `response.aclose()` and `client.aclose()` for explicit closing. (Pull #674, #675)\n- Switch to `response.anext()` for resolving the next redirect response. (Pull #676)\n\n### Removed\n\n- When using a client instance, the per-request usage of `verify`, `cert`, and `trust_env` have now escalated from raising a warning to raising an error. You should set these arguments on the client instead. (Pull #617)\n- Removed the undocumented `request.read()`, since end users should not require it.\n\n---\n\n## 0.9.5 (December 20th, 2019)\n\n### Fixed\n\n- Fix Host header and HSTS rewrites when an explicit `:80` port is included in URL. (Pull #649)\n- Query Params on the URL string are merged with any `params=...` argument. (Pull #653)\n- More robust behavior when closing connections. (Pull #640)\n- More robust behavior when handling HTTP/2 headers with trailing whitespace. (Pull #637)\n- Allow any explicit `Content-Type` header to take precedence over the encoding default. (Pull #633)\n\n## 0.9.4 (December 12th, 2019)\n\n### Fixed\n\n- Added expiry to Keep-Alive connections, resolving issues with acquiring connections. (Pull #627)\n- Increased flow control windows on HTTP/2, resolving download speed issues. (Pull #629)\n\n## 0.9.3 (December 7th, 2019)\n\n### Fixed\n\n- Fixed HTTP/2 with autodetection backend. (Pull #614)\n\n## 0.9.2 (December 7th, 2019)\n\n* Released due to packaging build artifact.\n\n## 0.9.1 (December 6th, 2019)\n\n* Released due to packaging build artifact.\n\n## 0.9.0 (December 6th, 2019)\n\nThe 0.9 releases brings some major new features, including:\n\n* A new streaming API.\n* Autodetection of either asyncio or trio.\n* Nicer timeout configuration.\n* HTTP/2 support off by default, but can be enabled.\n\nWe've also removed all private types from the top-level package export.\n\nIn order to ensure you are only ever working with public API you should make\nsure to only import the top-level package eg. `import httpx`, rather than\nimporting modules within the package.\n\n### Added\n\n- Added concurrency backend autodetection. (Pull #585)\n- Added `Client(backend='trio')` and `Client(backend='asyncio')` API. (Pull #585)\n- Added `response.stream_lines()` API. (Pull #575)\n- Added `response.is_error` API. (Pull #574)\n- Added support for `timeout=Timeout(5.0, connect_timeout=60.0)` styles. (Pull #593)\n\n### Fixed\n\n- Requests or Clients with `timeout=None` now correctly always disable timeouts. (Pull #592)\n- Request 'Authorization' headers now have priority over `.netrc` authentication info. (Commit 095b691)\n- Files without a filename no longer set a Content-Type in multipart data. (Commit ed94950)\n\n### Changed\n\n- Added `httpx.stream()` API. Using `stream=True` now results in a warning. (Pull #600, #610)\n- HTTP/2 support is switched to \"off by default\", but can be enabled explicitly. (Pull #584)\n- Switched to `Client(http2=True)` API from `Client(http_versions=[\"HTTP/1.1\", \"HTTP/2\"])`. (Pull #586)\n- Removed all private types from the top-level package export. (Pull #608)\n- The SSL configuration settings of `verify`, `cert`, and `trust_env` now raise warnings if used per-request when using a Client instance. They should always be set on the Client instance itself. (Pull #597)\n- Use plain strings \"TUNNEL_ONLY\" or \"FORWARD_ONLY\" on the HTTPProxy `proxy_mode` argument. The `HTTPProxyMode` enum still exists, but its usage will raise warnings. (#610)\n- Pool timeouts are now on the timeout configuration, not the pool limits configuration. (Pull #563)\n- The timeout configuration is now named `httpx.Timeout(...)`, not `httpx.TimeoutConfig(...)`. The old version currently remains as a synonym for backwards compatibility. (Pull #591)\n\n---\n\n## 0.8.0 (November 27, 2019)\n\n### Removed\n\n- The synchronous API has been removed, in order to allow us to fundamentally change how we approach supporting both sync and async variants. (See #588 for more details.)\n\n---\n\n## 0.7.8 (November 17, 2019)\n\n### Added\n\n- Add support for proxy tunnels for Python 3.6 + asyncio. (Pull #521)\n\n## 0.7.7 (November 15, 2019)\n\n### Fixed\n\n- Resolve an issue with cookies behavior on redirect requests. (Pull #529)\n\n### Added\n\n- Add request/response DEBUG logs. (Pull #502)\n- Use TRACE log level for low level info. (Pull #500)\n\n## 0.7.6 (November 2, 2019)\n\n### Removed\n\n- Drop `proxies` parameter from the high-level API. (Pull #485)\n\n### Fixed\n\n- Tweak multipart files: omit null filenames, add support for `str` file contents. (Pull #482)\n- Cache NETRC authentication per-client. (Pull #400)\n- Rely on `getproxies` for all proxy environment variables. (Pull #470)\n- Wait for the `asyncio` stream to close when closing a connection. (Pull #494)\n\n## 0.7.5 (October 10, 2019)\n\n### Added\n\n- Allow lists of values to be passed to `params`. (Pull #386)\n- `ASGIDispatch`, `WSGIDispatch` are now available in the `httpx.dispatch` namespace. (Pull #407)\n- `HTTPError` is now available in the `httpx` namespace. (Pull #421)\n- Add support for `start_tls()` to the Trio concurrency backend. (Pull #467)\n\n### Fixed\n\n- Username and password are no longer included in the `Host` header when basic authentication\n credentials are supplied via the URL. (Pull #417)\n\n### Removed\n\n- The `.delete()` function no longer has `json`, `data`, or `files` parameters\n to match the expected semantics of the `DELETE` method. (Pull #408)\n- Removed the `trio` extra. Trio support is detected automatically. (Pull #390)\n\n## 0.7.4 (September 25, 2019)\n\n### Added\n\n- Add Trio concurrency backend. (Pull #276)\n- Add `params` parameter to `Client` for setting default query parameters. (Pull #372)\n- Add support for `SSL_CERT_FILE` and `SSL_CERT_DIR` environment variables. (Pull #307)\n- Add debug logging to calls into ASGI apps. (Pull #371)\n- Add debug logging to SSL configuration. (Pull #378)\n\n### Fixed\n\n- Fix a bug when using `Client` without timeouts in Python 3.6. (Pull #383)\n- Propagate `Client` configuration to HTTP proxies. (Pull #377)\n\n## 0.7.3 (September 20, 2019)\n\n### Added\n\n- HTTP Proxy support. (Pulls #259, #353)\n- Add Digest authentication. (Pull #332)\n- Add `.build_request()` method to `Client` and `AsyncClient`. (Pull #319)\n- Add `.elapsed` property on responses. (Pull #351)\n- Add support for `SSLKEYLOGFILE` in Python 3.8b4+. (Pull #301)\n\n### Removed\n\n- Drop NPN support for HTTP version negotiation. (Pull #314)\n\n### Fixed\n\n- Fix distribution of type annotations for mypy (Pull #361).\n- Set `Host` header when redirecting cross-origin. (Pull #321)\n- Drop `Content-Length` headers on `GET` redirects. (Pull #310)\n- Raise `KeyError` if header isn't found in `Headers`. (Pull #324)\n- Raise `NotRedirectResponse` in `response.next()` if there is no redirection to perform. (Pull #297)\n- Fix bug in calculating the HTTP/2 maximum frame size. (Pull #153)\n\n## 0.7.2 (August 28, 2019)\n\n- Enforce using `httpx.AsyncioBackend` for the synchronous client. (Pull #232)\n- `httpx.ConnectionPool` will properly release a dropped connection. (Pull #230)\n- Remove the `raise_app_exceptions` argument from `Client`. (Pull #238)\n- `DecodeError` will no longer be raised for an empty body encoded with Brotli. (Pull #237)\n- Added `http_versions` parameter to `Client`. (Pull #250)\n- Only use HTTP/1.1 on short-lived connections like `httpx.get()`. (Pull #284)\n- Convert `Client.cookies` and `Client.headers` when set as a property. (Pull #274)\n- Setting `HTTPX_DEBUG=1` enables debug logging on all requests. (Pull #277)\n\n## 0.7.1 (August 18, 2019)\n\n- Include files with source distribution to be installable. (Pull #233)\n\n## 0.7.0 (August 17, 2019)\n\n- Add the `trust_env` property to `BaseClient`. (Pull #187)\n- Add the `links` property to `BaseResponse`. (Pull #211)\n- Accept `ssl.SSLContext` instances into `SSLConfig(verify=...)`. (Pull #215)\n- Add `Response.stream_text()` with incremental encoding detection. (Pull #183)\n- Properly updated the `Host` header when a redirect changes the origin. (Pull #199)\n- Ignore invalid `Content-Encoding` headers. (Pull #196)\n- Use `~/.netrc` and `~/_netrc` files by default when `trust_env=True`. (Pull #189)\n- Create exception base class `HTTPError` with `request` and `response` properties. (Pull #162)\n- Add HSTS preload list checking within `BaseClient` to upgrade HTTP URLs to HTTPS. (Pull #184)\n- Switch IDNA encoding from IDNA 2003 to IDNA 2008. (Pull #161)\n- Expose base classes for alternate concurrency backends. (Pull #178)\n- Improve Multipart parameter encoding. (Pull #167)\n- Add the `headers` property to `BaseClient`. (Pull #159)\n- Add support for Google's `brotli` library. (Pull #156)\n- Remove deprecated TLS versions (TLSv1 and TLSv1.1) from default `SSLConfig`. (Pull #155)\n- Fix `URL.join(...)` to work similarly to RFC 3986 URL joining. (Pull #144)\n\n---\n\n## 0.6.8 (July 25, 2019)\n\n- Check for disconnections when searching for an available\n connection in `ConnectionPool.keepalive_connections` (Pull #145)\n- Allow string comparison for `URL` objects (Pull #139)\n- Add HTTP status codes 418 and 451 (Pull #135)\n- Add support for client certificate passwords (Pull #118)\n- Enable post-handshake client cert authentication for TLSv1.3 (Pull #118)\n- Disable using `commonName` for hostname checking for OpenSSL 1.1.0+ (Pull #118)\n- Detect encoding for `Response.json()` (Pull #116)\n\n## 0.6.7 (July 8, 2019)\n\n- Check for connection aliveness on re-acquiry (Pull #111)\n\n## 0.6.6 (July 3, 2019)\n\n- Improve `USER_AGENT` (Pull #110)\n- Add `Connection: keep-alive` by default to HTTP/1.1 connections. (Pull #110)\n\n## 0.6.5 (June 27, 2019)\n\n- Include `Host` header by default. (Pull #109)\n- Improve HTTP protocol detection. (Pull #107)\n\n## 0.6.4 (June 25, 2019)\n\n- Implement read and write timeouts (Pull #104)\n\n## 0.6.3 (June 24, 2019)\n\n- Handle early connection closes (Pull #103)\n\n## 0.6.2 (June 23, 2019)\n\n- Use urllib3's `DEFAULT_CIPHERS` for the `SSLConfig` object. (Pull #100)\n\n## 0.6.1 (June 21, 2019)\n\n- Add support for setting a `base_url` on the `Client`.\n\n## 0.6.0 (June 21, 2019)\n\n- Honor `local_flow_control_window` for HTTP/2 connections (Pull #98)\n" }, { "path": "httpx/_models.py", "content": "import datetime\nimport email.message\nimport json as jsonlib\nimport typing\nimport urllib.request\nfrom collections.abc import Mapping\nfrom http.cookiejar import Cookie, CookieJar\n\nfrom ._content import ByteStream, UnattachedStream, encode_request, encode_response\nfrom ._decoders import (\n SUPPORTED_DECODERS,\n ByteChunker,\n ContentDecoder,\n IdentityDecoder,\n LineDecoder,\n MultiDecoder,\n TextChunker,\n TextDecoder,\n)\nfrom ._exceptions import (\n CookieConflict,\n HTTPStatusError,\n RequestNotRead,\n ResponseNotRead,\n StreamClosed,\n StreamConsumed,\n request_context,\n)\nfrom ._multipart import get_multipart_boundary_from_content_type\nfrom ._status_codes import codes\nfrom ._types import (\n AsyncByteStream,\n CookieTypes,\n HeaderTypes,\n QueryParamTypes,\n RequestContent,\n RequestData,\n RequestExtensions,\n RequestFiles,\n ResponseContent,\n ResponseExtensions,\n SyncByteStream,\n)\nfrom ._urls import URL\nfrom ._utils import (\n guess_json_utf,\n is_known_encoding,\n normalize_header_key,\n normalize_header_value,\n obfuscate_sensitive_headers,\n parse_content_type_charset,\n parse_header_links,\n)\n\n\nclass Headers(typing.MutableMapping[str, str]):\n \"\"\"\n HTTP headers, as a case-insensitive multi-dict.\n \"\"\"\n\n def __init__(\n self,\n headers: typing.Optional[HeaderTypes] = None,\n encoding: typing.Optional[str] = None,\n ) -> None:\n if headers is None:\n self._list = [] # type: typing.List[typing.Tuple[bytes, bytes, bytes]]\n elif isinstance(headers, Headers):\n self._list = list(headers._list)\n elif isinstance(headers, Mapping):\n self._list = [\n (\n normalize_header_key(k, lower=False, encoding=encoding),\n normalize_header_key(k, lower=True, encoding=encoding),\n normalize_header_value(v, encoding),\n )\n for k, v in headers.items()\n ]\n else:\n self._list = [\n (\n normalize_header_key(k, lower=False, encoding=encoding),\n normalize_header_key(k, lower=True, encoding=encoding),\n normalize_header_value(v, encoding),\n )\n for k, v in headers\n ]\n\n self._encoding = encoding\n\n @property\n def encoding(self) -> str:\n \"\"\"\n Header encoding is mandated as ascii, but we allow fallbacks to utf-8\n or iso-8859-1.\n \"\"\"\n if self._encoding is None:\n for encoding in [\"ascii\", \"utf-8\"]:\n for key, value in self.raw:\n try:\n key.decode(encoding)\n value.decode(encoding)\n except UnicodeDecodeError:\n break\n else:\n # The else block runs if 'break' did not occur, meaning\n # all values fitted the encoding.\n self._encoding = encoding\n break\n else:\n # The ISO-8859-1 encoding covers all 256 code points in a byte,\n # so will never raise decode errors.\n self._encoding = \"iso-8859-1\"\n return self._encoding\n\n @encoding.setter\n def encoding(self, value: str) -> None:\n self._encoding = value\n\n @property\n def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:\n \"\"\"\n Returns a list of the raw header items, as byte pairs.\n \"\"\"\n return [(raw_key, value) for raw_key, _, value in self._list]\n\n def keys(self) -> typing.KeysView[str]:\n return {key.decode(self.encoding): None for _, key, value in self._list}.keys()\n\n def values(self) -> typing.ValuesView[str]:\n values_dict: typing.Dict[str, str] = {}\n for _, key, value in self._list:\n str_key = key.decode(self.encoding)\n str_value = value.decode(self.encoding)\n if str_key in values_dict:\n values_dict[str_key] += f\", {str_value}\"\n else:\n values_dict[str_key] = str_value\n return values_dict.values()\n\n def items(self) -> typing.ItemsView[str, str]:\n \"\"\"\n Return `(key, value)` items of headers. Concatenate headers\n into a single comma separated value when a key occurs multiple times.\n \"\"\"\n values_dict: typing.Dict[str, str] = {}\n for _, key, value in self._list:\n str_key = key.decode(self.encoding)\n str_value = value.decode(self.encoding)\n if str_key in values_dict:\n values_dict[str_key] += f\", {str_value}\"\n else:\n values_dict[str_key] = str_value\n return values_dict.items()\n\n def multi_items(self) -> typing.List[typing.Tuple[str, str]]:\n \"\"\"\n Return a list of `(key, value)` pairs of headers. Allow multiple\n occurrences of the same key without concatenating into a single\n comma separated value.\n \"\"\"\n return [\n (key.decode(self.encoding), value.decode(self.encoding))\n for _, key, value in self._list\n ]\n\n def get(self, key: str, default: typing.Any = None) -> typing.Any:\n \"\"\"\n Return a header value. If multiple occurrences of the header occur\n then concatenate them together with commas.\n \"\"\"\n try:\n return self[key]\n except KeyError:\n return default\n\n def get_list(self, key: str, split_commas: bool = False) -> typing.List[str]:\n \"\"\"\n Return a list of all header values for a given key.\n If `split_commas=True` is passed, then any comma separated header\n values are split into multiple return strings.\n \"\"\"\n get_header_key = key.lower().encode(self.encoding)\n\n values = [\n item_value.decode(self.encoding)\n for _, item_key, item_value in self._list\n if item_key.lower() == get_header_key\n ]\n\n if not split_commas:\n return values\n\n split_values = []\n for value in values:\n split_values.extend([item.strip() for item in value.split(\",\")])\n return split_values\n\n def update(self, headers: typing.Optional[HeaderTypes] = None) -> None: # type: ignore\n headers = Headers(headers)\n for key in headers.keys():\n if key in self:\n self.pop(key)\n self._list.extend(headers._list)\n\n def copy(self) -> \"Headers\":\n return Headers(self, encoding=self.encoding)\n\n def __getitem__(self, key: str) -> str:\n \"\"\"\n Return a single header value.\n\n If there are multiple headers with the same key, then we concatenate\n them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2\n \"\"\"\n normalized_key = key.lower().encode(self.encoding)\n\n items = [\n header_value.decode(self.encoding)\n for _, header_key, header_value in self._list\n if header_key == normalized_key\n ]\n\n if items:\n return \", \".join(items)\n\n raise KeyError(key)\n\n def __setitem__(self, key: str, value: str) -> None:\n \"\"\"\n Set the header `key` to `value`, removing any duplicate entries.\n Retains insertion order.\n \"\"\"\n set_key = key.encode(self._encoding or \"utf-8\")\n set_value = value.encode(self._encoding or \"utf-8\")\n lookup_key = set_key.lower()\n\n found_indexes = [\n idx\n for idx, (_, item_key, _) in enumerate(self._list)\n if item_key == lookup_key\n ]\n\n for idx in reversed(found_indexes[1:]):\n del self._list[idx]\n\n if found_indexes:\n idx = found_indexes[0]\n self._list[idx] = (set_key, lookup_key, set_value)\n else:\n self._list.append((set_key, lookup_key, set_value))\n\n def __delitem__(self, key: str) -> None:\n \"\"\"\n Remove the header `key`.\n \"\"\"\n del_key = key.lower().encode(self.encoding)\n\n pop_indexes = [\n idx\n for idx, (_, item_key, _) in enumerate(self._list)\n if item_key.lower() == del_key\n ]\n\n if not pop_indexes:\n raise KeyError(key)\n\n for idx in reversed(pop_indexes):\n del self._list[idx]\n\n def __contains__(self, key: typing.Any) -> bool:\n header_key = key.lower().encode(self.encoding)\n return header_key in [key for _, key, _ in self._list]\n\n def __iter__(self) -> typing.Iterator[typing.Any]:\n return iter(self.keys())\n\n def __len__(self) -> int:\n return len(self._list)\n\n def __eq__(self, other: typing.Any) -> bool:\n try:\n other_headers = Headers(other)\n except ValueError:\n return False\n\n self_list = [(key, value) for _, key, value in self._list]\n other_list = [(key, value) for _, key, value in other_headers._list]\n return sorted(self_list) == sorted(other_list)\n\n def __repr__(self) -> str:\n class_name = self.__class__.__name__\n\n encoding_str = \"\"\n if self.encoding != \"ascii\":\n encoding_str = f\", encoding={self.encoding!r}\"\n\n as_list = list(obfuscate_sensitive_headers(self.multi_items()))\n as_dict = dict(as_list)\n\n no_duplicate_keys = len(as_dict) == len(as_list)\n if no_duplicate_keys:\n return f\"{class_name}({as_dict!r}{encoding_str})\"\n return f\"{class_name}({as_list!r}{encoding_str})\"\n\n\nclass Request:\n def __init__(\n self,\n method: typing.Union[str, bytes],\n url: typing.Union[\"URL\", str],\n *,\n params: typing.Optional[QueryParamTypes] = None,\n headers: typing.Optional[HeaderTypes] = None,\n cookies: typing.Optional[CookieTypes] = None,\n content: typing.Optional[RequestContent] = None,\n data: typing.Optional[RequestData] = None,\n files: typing.Optional[RequestFiles] = None,\n json: typing.Optional[typing.Any] = None,\n stream: typing.Union[SyncByteStream, AsyncByteStream, None] = None,\n extensions: typing.Optional[RequestExtensions] = None,\n ):\n self.method = (\n method.decode(\"ascii\").upper()\n if isinstance(method, bytes)\n else method.upper()\n )\n self.url = URL(url)\n if params is not None:\n self.url = self.url.copy_merge_params(params=params)\n self.headers = Headers(headers)\n self.extensions = {} if extensions is None else extensions\n\n if cookies:\n Cookies(cookies).set_cookie_header(self)\n\n if stream is None:\n content_type: typing.Optional[str] = self.headers.get(\"content-type\")\n headers, stream = encode_request(\n content=content,\n data=data,\n files=files,\n json=json,\n boundary=get_multipart_boundary_from_content_type(\n content_type=content_type.encode(self.headers.encoding)\n if content_type\n else None\n ),\n )\n self._prepare(headers)\n self.stream = stream\n # Load the request body, except for streaming content.\n if isinstance(stream, ByteStream):\n self.read()\n else:\n # There's an important distinction between `Request(content=...)`,\n # and `Request(stream=...)`.\n #\n # Using `content=...` implies automatically populated `Host` and content\n # headers, of either `Content-Length: ...` or `Transfer-Encoding: chunked`.\n #\n # Using `stream=...` will not automatically include *any* auto-populated headers.\n #\n # As an end-user you don't really need `stream=...`. It's only\n # useful when:\n #\n # * Preserving the request stream when copying requests, eg for redirects.\n # * Creating request instances on the *server-side* of the transport API.\n self.stream = stream\n\n def _prepare(self, default_headers: typing.Dict[str, str]) -> None:\n for key, value in default_headers.items():\n # Ignore Transfer-Encoding if the Content-Length has been set explicitly.\n if key.lower() == \"transfer-encoding\" and \"Content-Length\" in self.headers:\n continue\n self.headers.setdefault(key, value)\n\n auto_headers: typing.List[typing.Tuple[bytes, bytes]] = []\n\n has_host = \"Host\" in self.headers\n has_content_length = (\n \"Content-Length\" in self.headers or \"Transfer-Encoding\" in self.headers\n )\n\n if not has_host and self.url.host:\n auto_headers.append((b\"Host\", self.url.netloc))\n if not has_content_length and self.method in (\"POST\", \"PUT\", \"PATCH\"):\n auto_headers.append((b\"Content-Length\", b\"0\"))\n\n self.headers = Headers(auto_headers + self.headers.raw)\n\n @property\n def content(self) -> bytes:\n if not hasattr(self, \"_content\"):\n raise RequestNotRead()\n return self._content\n\n def read(self) -> bytes:\n \"\"\"\n Read and return the request content.\n \"\"\"\n if not hasattr(self, \"_content\"):\n assert isinstance(self.stream, typing.Iterable)\n self._content = b\"\".join(self.stream)\n if not isinstance(self.stream, ByteStream):\n # If a streaming request has been read entirely into memory, then\n # we can replace the stream with a raw bytes implementation,\n # to ensure that any non-replayable streams can still be used.\n self.stream = ByteStream(self._content)\n return self._content\n\n async def aread(self) -> bytes:\n \"\"\"\n Read and return the request content.\n \"\"\"\n if not hasattr(self, \"_content\"):\n assert isinstance(self.stream, typing.AsyncIterable)\n self._content = b\"\".join([part async for part in self.stream])\n if not isinstance(self.stream, ByteStream):\n # If a streaming request has been read entirely into memory, then\n # we can replace the stream with a raw bytes implementation,\n # to ensure that any non-replayable streams can still be used.\n self.stream = ByteStream(self._content)\n return self._content\n\n def __repr__(self) -> str:\n class_name = self.__class__.__name__\n url = str(self.url)\n return f\"<{class_name}({self.method!r}, {url!r})>\"\n\n def __getstate__(self) -> typing.Dict[str, typing.Any]:\n return {\n name: value\n for name, value in self.__dict__.items()\n if name not in [\"extensions\", \"stream\"]\n }\n\n def __setstate__(self, state: typing.Dict[str, typing.Any]) -> None:\n for name, value in state.items():\n setattr(self, name, value)\n self.extensions = {}\n self.stream = UnattachedStream()\n\n\nclass Response:\n def __init__(\n self,\n status_code: int,\n *,\n headers: typing.Optional[HeaderTypes] = None,\n content: typing.Optional[ResponseContent] = None,\n text: typing.Optional[str] = None,\n html: typing.Optional[str] = None,\n json: typing.Any = None,\n stream: typing.Union[SyncByteStream, AsyncByteStream, None] = None,\n request: typing.Optional[Request] = None,\n extensions: typing.Optional[ResponseExtensions] = None,\n history: typing.Optional[typing.List[\"Response\"]] = None,\n default_encoding: typing.Union[str, typing.Callable[[bytes], str]] = \"utf-8\",\n ):\n self.status_code = status_code\n self.headers = Headers(headers)\n\n self._request: typing.Optional[Request] = request\n\n # When follow_redirects=False and a redirect is received,\n # the client will set `response.next_request`.\n self.next_request: typing.Optional[Request] = None\n\n self.extensions: ResponseExtensions = {} if extensions is None else extensions\n self.history = [] if history is None else list(history)\n\n self.is_closed = False\n self.is_stream_consumed = False\n\n self.default_encoding = default_encoding\n\n if stream is None:\n headers, stream = encode_response(content, text, html, json)\n self._prepare(headers)\n self.stream = stream\n if isinstance(stream, ByteStream):\n # Load the response body, except for streaming content.\n self.read()\n else:\n # There's an important distinction between `Response(content=...)`,\n # and `Response(stream=...)`.\n #\n # Using `content=...` implies automatically populated content headers,\n # of either `Content-Length: ...` or `Transfer-Encoding: chunked`.\n #\n # Using `stream=...` will not automatically include any content headers.\n #\n # As an end-user you don't really need `stream=...`. It's only\n # useful when creating response instances having received a stream\n # from the transport API.\n self.stream = stream\n\n self._num_bytes_downloaded = 0\n\n def _prepare(self, default_headers: typing.Dict[str, str]) -> None:\n for key, value in default_headers.items():\n # Ignore Transfer-Encoding if the Content-Length has been set explicitly.\n if key.lower() == \"transfer-encoding\" and \"content-length\" in self.headers:\n continue\n self.headers.setdefault(key, value)\n\n @property\n def elapsed(self) -> datetime.timedelta:\n \"\"\"\n Returns the time taken for the complete request/response\n cycle to complete.\n \"\"\"\n if not hasattr(self, \"_elapsed\"):\n raise RuntimeError(\n \"'.elapsed' may only be accessed after the response \"\n \"has been read or closed.\"\n )\n return self._elapsed\n\n @elapsed.setter\n def elapsed(self, elapsed: datetime.timedelta) -> None:\n self._elapsed = elapsed\n\n @property\n def request(self) -> Request:\n \"\"\"\n Returns the request instance associated to the current response.\n \"\"\"\n if self._request is None:\n raise RuntimeError(\n \"The request instance has not been set on this response.\"\n )\n return self._request\n\n @request.setter\n def request(self, value: Request) -> None:\n self._request = value\n\n @property\n def http_version(self) -> str:\n try:\n http_version: bytes = self.extensions[\"http_version\"]\n except KeyError:\n return \"HTTP/1.1\"\n else:\n return http_version.decode(\"ascii\", errors=\"ignore\")\n\n @property\n def reason_phrase(self) -> str:\n try:\n reason_phrase: bytes = self.extensions[\"reason_phrase\"]\n except KeyError:\n return codes.get_reason_phrase(self.status_code)\n else:\n return reason_phrase.decode(\"ascii\", errors=\"ignore\")\n\n @property\n def url(self) -> URL:\n \"\"\"\n Returns the URL for which the request was made.\n \"\"\"\n return self.request.url\n\n @property\n def content(self) -> bytes:\n if not hasattr(self, \"_content\"):\n raise ResponseNotRead()\n return self._content\n\n @property\n def text(self) -> str:\n if not hasattr(self, \"_text\"):\n content = self.content\n if not content:\n self._text = \"\"\n else:\n decoder = TextDecoder(encoding=self.encoding or \"utf-8\")\n self._text = \"\".join([decoder.decode(self.content), decoder.flush()])\n return self._text\n\n @property\n def encoding(self) -> typing.Optional[str]:\n \"\"\"\n Return an encoding to use for decoding the byte content into text.\n The priority for determining this is given by...\n\n * `.encoding = <>` has been set explicitly.\n * The encoding as specified by the charset parameter in the Content-Type header.\n * The encoding as determined by `default_encoding`, which may either be\n a string like \"utf-8\" indicating the encoding to use, or may be a callable\n which enables charset autodetection.\n \"\"\"\n if not hasattr(self, \"_encoding\"):\n encoding = self.charset_encoding\n if encoding is None or not is_known_encoding(encoding):\n if isinstance(self.default_encoding, str):\n encoding = self.default_encoding\n elif hasattr(self, \"_content\"):\n encoding = self.default_encoding(self._content)\n self._encoding = encoding or \"utf-8\"\n return self._encoding\n\n @encoding.setter\n def encoding(self, value: str) -> None:\n self._encoding = value\n\n @property\n def charset_encoding(self) -> typing.Optional[str]:\n \"\"\"\n Return the encoding, as specified by the Content-Type header.\n \"\"\"\n content_type = self.headers.get(\"Content-Type\")\n if content_type is None:\n return None\n\n return parse_content_type_charset(content_type)\n\n def _get_content_decoder(self) -> ContentDecoder:\n \"\"\"\n Returns a decoder instance which can be used to decode the raw byte\n content, depending on the Content-Encoding used in the response.\n \"\"\"\n if not hasattr(self, \"_decoder\"):\n decoders: typing.List[ContentDecoder] = []\n values = self.headers.get_list(\"content-encoding\", split_commas=True)\n for value in values:\n value = value.strip().lower()\n try:\n decoder_cls = SUPPORTED_DECODERS[value]\n decoders.append(decoder_cls())\n except KeyError:\n continue\n\n if len(decoders) == 1:\n self._decoder = decoders[0]\n elif len(decoders) > 1:\n self._decoder = MultiDecoder(children=decoders)\n else:\n self._decoder = IdentityDecoder()\n\n return self._decoder\n\n @property\n def is_informational(self) -> bool:\n \"\"\"\n A property which is `True` for 1xx status codes, `False` otherwise.\n \"\"\"\n return codes.is_informational(self.status_code)\n\n @property\n def is_success(self) -> bool:\n \"\"\"\n A property which is `True` for 2xx status codes, `False` otherwise.\n \"\"\"\n return codes.is_success(self.status_code)\n\n @property\n def is_redirect(self) -> bool:\n \"\"\"\n A property which is `True` for 3xx status codes, `False` otherwise.\n\n Note that not all responses with a 3xx status code indicate a URL redirect.\n\n Use `response.has_redirect_location` to determine responses with a properly\n formed URL redirection.\n \"\"\"\n return codes.is_redirect(self.status_code)\n\n @property\n def is_client_error(self) -> bool:\n \"\"\"\n A property which is `True` for 4xx status codes, `False` otherwise.\n \"\"\"\n return codes.is_client_error(self.status_code)\n\n @property\n def is_server_error(self) -> bool:\n \"\"\"\n A property which is `True` for 5xx status codes, `False` otherwise.\n \"\"\"\n return codes.is_server_error(self.status_code)\n\n @property\n def is_error(self) -> bool:\n \"\"\"\n A property which is `True` for 4xx and 5xx status codes, `False` otherwise.\n \"\"\"\n return codes.is_error(self.status_code)\n\n @property\n def has_redirect_location(self) -> bool:\n \"\"\"\n Returns True for 3xx responses with a properly formed URL redirection,\n `False` otherwise.\n \"\"\"\n return (\n self.status_code\n in (\n # 301 (Cacheable redirect. Method may change to GET.)\n codes.MOVED_PERMANENTLY,\n # 302 (Uncacheable redirect. Method may change to GET.)\n codes.FOUND,\n # 303 (Client should make a GET or HEAD request.)\n codes.SEE_OTHER,\n # 307 (Equiv. 302, but retain method)\n codes.TEMPORARY_REDIRECT,\n # 308 (Equiv. 301, but retain method)\n codes.PERMANENT_REDIRECT,\n )\n and \"Location\" in self.headers\n )\n\n def raise_for_status(self) -> \"Response\":\n \"\"\"\n Raise the `HTTPStatusError` if one occurred.\n \"\"\"\n request = self._request\n if request is None:\n raise RuntimeError(\n \"Cannot call `raise_for_status` as the request \"\n \"instance has not been set on this response.\"\n )\n\n if self.is_success:\n return self\n\n if self.has_redirect_location:\n message = (\n \"{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\\n\"\n \"Redirect location: '{0.headers[location]}'\\n\"\n \"For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}\"\n )\n else:\n message = (\n \"{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\\n\"\n \"For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}\"\n )\n\n status_class = self.status_code // 100\n error_types = {\n 1: \"Informational response\",\n 3: \"Redirect response\",\n 4: \"Client error\",\n 5: \"Server error\",\n }\n error_type = error_types.get(status_class, \"Invalid status code\")\n message = message.format(self, error_type=error_type)\n raise HTTPStatusError(message, request=request, response=self)\n\n def json(self, **kwargs: typing.Any) -> typing.Any:\n if self.charset_encoding is None and self.content and len(self.content) > 3:\n encoding = guess_json_utf(self.content)\n if encoding is not None:\n return jsonlib.loads(self.content.decode(encoding), **kwargs)\n return jsonlib.loads(self.text, **kwargs)\n\n @property\n def cookies(self) -> \"Cookies\":\n if not hasattr(self, \"_cookies\"):\n self._cookies = Cookies()\n self._cookies.extract_cookies(self)\n return self._cookies\n\n @property\n def links(self) -> typing.Dict[typing.Optional[str], typing.Dict[str, str]]:\n \"\"\"\n Returns the parsed header links of the response, if any\n \"\"\"\n header = self.headers.get(\"link\")\n ldict = {}\n if header:\n links = parse_header_links(header)\n for link in links:\n key = link.get(\"rel\") or link.get(\"url\")\n ldict[key] = link\n return ldict\n\n @property\n def num_bytes_downloaded(self) -> int:\n return self._num_bytes_downloaded\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __getstate__(self) -> typing.Dict[str, typing.Any]:\n return {\n name: value\n for name, value in self.__dict__.items()\n if name not in [\"extensions\", \"stream\", \"is_closed\", \"_decoder\"]\n }\n\n def __setstate__(self, state: typing.Dict[str, typing.Any]) -> None:\n for name, value in state.items():\n setattr(self, name, value)\n self.is_closed = True\n self.extensions = {}\n self.stream = UnattachedStream()\n\n def read(self) -> bytes:\n \"\"\"\n Read and return the response content.\n \"\"\"\n if not hasattr(self, \"_content\"):\n self._content = b\"\".join(self.iter_bytes())\n return self._content\n\n def iter_bytes(\n self, chunk_size: typing.Optional[int] = None\n ) -> typing.Iterator[bytes]:\n \"\"\"\n A byte-iterator over the decoded response content.\n This allows us to handle gzip, deflate, and brotli encoded responses.\n \"\"\"\n if hasattr(self, \"_content\"):\n chunk_size = len(self._content) if chunk_size is None else chunk_size\n for i in range(0, len(self._content), max(chunk_size, 1)):\n yield self._content[i : i + chunk_size]\n else:\n decoder = self._get_content_decoder()\n chunker = ByteChunker(chunk_size=chunk_size)\n with request_context(request=self._request):\n for raw_bytes in self.iter_raw():\n decoded = decoder.decode(raw_bytes)\n for chunk in chunker.decode(decoded):\n yield chunk\n decoded = decoder.flush()\n for chunk in chunker.decode(decoded):\n yield chunk # pragma: no cover\n for chunk in chunker.flush():\n yield chunk\n\n def iter_text(\n self, chunk_size: typing.Optional[int] = None\n ) -> typing.Iterator[str]:\n \"\"\"\n A str-iterator over the decoded response content\n that handles both gzip, deflate, etc but also detects the content's\n string encoding.\n \"\"\"\n decoder = TextDecoder(encoding=self.encoding or \"utf-8\")\n chunker = TextChunker(chunk_size=chunk_size)\n with request_context(request=self._request):\n for byte_content in self.iter_bytes():\n text_content = decoder.decode(byte_content)\n for chunk in chunker.decode(text_content):\n yield chunk\n text_content = decoder.flush()\n for chunk in chunker.decode(text_content):\n yield chunk\n for chunk in chunker.flush():\n yield chunk\n\n def iter_lines(self) -> typing.Iterator[str]:\n decoder = LineDecoder()\n with request_context(request=self._request):\n for text in self.iter_text():\n for line in decoder.decode(text):\n yield line\n for line in decoder.flush():\n yield line\n\n def iter_raw(\n self, chunk_size: typing.Optional[int] = None\n ) -> typing.Iterator[bytes]:\n \"\"\"\n A byte-iterator over the raw response content.\n \"\"\"\n if self.is_stream_consumed:\n raise StreamConsumed()\n if self.is_closed:\n raise StreamClosed()\n if not isinstance(self.stream, SyncByteStream):\n raise RuntimeError(\"Attempted to call a sync iterator on an async stream.\")\n\n self.is_stream_consumed = True\n self._num_bytes_downloaded = 0\n chunker = ByteChunker(chunk_size=chunk_size)\n\n with request_context(request=self._request):\n for raw_stream_bytes in self.stream:\n self._num_bytes_downloaded += len(raw_stream_bytes)\n for chunk in chunker.decode(raw_stream_bytes):\n yield chunk\n\n for chunk in chunker.flush():\n yield chunk\n\n self.close()\n\n def close(self) -> None:\n \"\"\"\n Close the response and release the connection.\n Automatically called if the response body is read to completion.\n \"\"\"\n if not isinstance(self.stream, SyncByteStream):\n raise RuntimeError(\"Attempted to call an sync close on an async stream.\")\n\n if not self.is_closed:\n self.is_closed = True\n with request_context(request=self._request):\n self.stream.close()\n\n async def aread(self) -> bytes:\n \"\"\"\n Read and return the response content.\n \"\"\"\n if not hasattr(self, \"_content\"):\n self._content = b\"\".join([part async for part in self.aiter_bytes()])\n return self._content\n\n async def aiter_bytes(\n self, chunk_size: typing.Optional[int] = None\n ) -> typing.AsyncIterator[bytes]:\n \"\"\"\n A byte-iterator over the decoded response content.\n This allows us to handle gzip, deflate, and brotli encoded responses.\n \"\"\"\n if hasattr(self, \"_content\"):\n chunk_size = len(self._content) if chunk_size is None else chunk_size\n for i in range(0, len(self._content), max(chunk_size, 1)):\n yield self._content[i : i + chunk_size]\n else:\n decoder = self._get_content_decoder()\n chunker = ByteChunker(chunk_size=chunk_size)\n with request_context(request=self._request):\n async for raw_bytes in self.aiter_raw():\n decoded = decoder.decode(raw_bytes)\n for chunk in chunker.decode(decoded):\n yield chunk\n decoded = decoder.flush()\n for chunk in chunker.decode(decoded):\n yield chunk # pragma: no cover\n for chunk in chunker.flush():\n yield chunk\n\n async def aiter_text(\n self, chunk_size: typing.Optional[int] = None\n ) -> typing.AsyncIterator[str]:\n \"\"\"\n A str-iterator over the decoded response content\n that handles both gzip, deflate, etc but also detects the content's\n string encoding.\n \"\"\"\n decoder = TextDecoder(encoding=self.encoding or \"utf-8\")\n chunker = TextChunker(chunk_size=chunk_size)\n with request_context(request=self._request):\n async for byte_content in self.aiter_bytes():\n text_content = decoder.decode(byte_content)\n for chunk in chunker.decode(text_content):\n yield chunk\n text_content = decoder.flush()\n for chunk in chunker.decode(text_content):\n yield chunk\n for chunk in chunker.flush():\n yield chunk\n\n async def aiter_lines(self) -> typing.AsyncIterator[str]:\n decoder = LineDecoder()\n with request_context(request=self._request):\n async for text in self.aiter_text():\n for line in decoder.decode(text):\n yield line\n for line in decoder.flush():\n yield line\n\n async def aiter_raw(\n self, chunk_size: typing.Optional[int] = None\n ) -> typing.AsyncIterator[bytes]:\n \"\"\"\n A byte-iterator over the raw response content.\n \"\"\"\n if self.is_stream_consumed:\n raise StreamConsumed()\n if self.is_closed:\n raise StreamClosed()\n if not isinstance(self.stream, AsyncByteStream):\n raise RuntimeError(\"Attempted to call an async iterator on an sync stream.\")\n\n self.is_stream_consumed = True\n self._num_bytes_downloaded = 0\n chunker = ByteChunker(chunk_size=chunk_size)\n\n with request_context(request=self._request):\n async for raw_stream_bytes in self.stream:\n self._num_bytes_downloaded += len(raw_stream_bytes)\n for chunk in chunker.decode(raw_stream_bytes):\n yield chunk\n\n for chunk in chunker.flush():\n yield chunk\n\n await self.aclose()\n\n async def aclose(self) -> None:\n \"\"\"\n Close the response and release the connection.\n Automatically called if the response body is read to completion.\n \"\"\"\n if not isinstance(self.stream, AsyncByteStream):\n raise RuntimeError(\"Attempted to call an async close on an sync stream.\")\n\n if not self.is_closed:\n self.is_closed = True\n with request_context(request=self._request):\n await self.stream.aclose()\n\n\nclass Cookies(typing.MutableMapping[str, str]):\n \"\"\"\n HTTP Cookies, as a mutable mapping.\n \"\"\"\n\n def __init__(self, cookies: typing.Optional[CookieTypes] = None) -> None:\n if cookies is None or isinstance(cookies, dict):\n self.jar = CookieJar()\n if isinstance(cookies, dict):\n for key, value in cookies.items():\n self.set(key, value)\n elif isinstance(cookies, list):\n self.jar = CookieJar()\n for key, value in cookies:\n self.set(key, value)\n elif isinstance(cookies, Cookies):\n self.jar = CookieJar()\n for cookie in cookies.jar:\n self.jar.set_cookie(cookie)\n else:\n self.jar = cookies\n\n def extract_cookies(self, response: Response) -> None:\n \"\"\"\n Loads any cookies based on the response `Set-Cookie` headers.\n \"\"\"\n urllib_response = self._CookieCompatResponse(response)\n urllib_request = self._CookieCompatRequest(response.request)\n\n self.jar.extract_cookies(urllib_response, urllib_request) # type: ignore\n\n def set_cookie_header(self, request: Request) -> None:\n \"\"\"\n Sets an appropriate 'Cookie:' HTTP header on the `Request`.\n \"\"\"\n urllib_request = self._CookieCompatRequest(request)\n self.jar.add_cookie_header(urllib_request)\n\n def set(self, name: str, value: str, domain: str = \"\", path: str = \"/\") -> None:\n \"\"\"\n Set a cookie value by name. May optionally include domain and path.\n \"\"\"\n kwargs = {\n \"version\": 0,\n \"name\": name,\n \"value\": value,\n \"port\": None,\n \"port_specified\": False,\n \"domain\": domain,\n \"domain_specified\": bool(domain),\n \"domain_initial_dot\": domain.startswith(\".\"),\n \"path\": path,\n \"path_specified\": bool(path),\n \"secure\": False,\n \"expires\": None,\n \"discard\": True,\n \"comment\": None,\n \"comment_url\": None,\n \"rest\": {\"HttpOnly\": None},\n \"rfc2109\": False,\n }\n cookie = Cookie(**kwargs) # type: ignore\n self.jar.set_cookie(cookie)\n\n def get( # type: ignore\n self,\n name: str,\n default: typing.Optional[str] = None,\n domain: typing.Optional[str] = None,\n path: typing.Optional[str] = None,\n ) -> typing.Optional[str]:\n \"\"\"\n Get a cookie by name. May optionally include domain and path\n in order to specify exactly which cookie to retrieve.\n \"\"\"\n value = None\n for cookie in self.jar:\n if cookie.name == name:\n if domain is None or cookie.domain == domain:\n if path is None or cookie.path == path:\n if value is not None:\n message = f\"Multiple cookies exist with name={name}\"\n raise CookieConflict(message)\n value = cookie.value\n\n if value is None:\n return default\n return value\n\n def delete(\n self,\n name: str,\n domain: typing.Optional[str] = None,\n path: typing.Optional[str] = None,\n ) -> None:\n \"\"\"\n Delete a cookie by name. May optionally include domain and path\n in order to specify exactly which cookie to delete.\n \"\"\"\n if domain is not None and path is not None:\n return self.jar.clear(domain, path, name)\n\n remove = [\n cookie\n for cookie in self.jar\n if cookie.name == name\n and (domain is None or cookie.domain == domain)\n and (path is None or cookie.path == path)\n ]\n\n for cookie in remove:\n self.jar.clear(cookie.domain, cookie.path, cookie.name)\n\n def clear(\n self, domain: typing.Optional[str] = None, path: typing.Optional[str] = None\n ) -> None:\n \"\"\"\n Delete all cookies. Optionally include a domain and path in\n order to only delete a subset of all the cookies.\n \"\"\"\n args = []\n if domain is not None:\n args.append(domain)\n if path is not None:\n assert domain is not None\n args.append(path)\n self.jar.clear(*args)\n\n def update(self, cookies: typing.Optional[CookieTypes] = None) -> None: # type: ignore\n cookies = Cookies(cookies)\n for cookie in cookies.jar:\n self.jar.set_cookie(cookie)\n\n def __setitem__(self, name: str, value: str) -> None:\n return self.set(name, value)\n\n def __getitem__(self, name: str) -> str:\n value = self.get(name)\n if value is None:\n raise KeyError(name)\n return value\n\n def __delitem__(self, name: str) -> None:\n return self.delete(name)\n\n def __len__(self) -> int:\n return len(self.jar)\n\n def __iter__(self) -> typing.Iterator[str]:\n return (cookie.name for cookie in self.jar)\n\n def __bool__(self) -> bool:\n for _ in self.jar:\n return True\n return False\n\n def __repr__(self) -> str:\n cookies_repr = \", \".join(\n [\n f\"\"\n for cookie in self.jar\n ]\n )\n\n return f\"\"\n\n class _CookieCompatRequest(urllib.request.Request):\n \"\"\"\n Wraps a `Request` instance up in a compatibility interface suitable\n for use with `CookieJar` operations.\n \"\"\"\n\n def __init__(self, request: Request) -> None:\n super().__init__(\n url=str(request.url),\n headers=dict(request.headers),\n method=request.method,\n )\n self.request = request\n\n def add_unredirected_header(self, key: str, value: str) -> None:\n super().add_unredirected_header(key, value)\n self.request.headers[key] = value\n\n class _CookieCompatResponse:\n \"\"\"\n Wraps a `Request` instance up in a compatibility interface suitable\n for use with `CookieJar` operations.\n \"\"\"\n\n def __init__(self, response: Response):\n self.response = response\n\n def info(self) -> email.message.Message:\n info = email.message.Message()\n for key, value in self.response.headers.multi_items():\n # Note that setting `info[key]` here is an \"append\" operation,\n # not a \"replace\" operation.\n # https://docs.python.org/3/library/email.compat32-message.html#email.message.Message.__setitem__\n info[key] = value\n return info\n" }, { "path": "tests/models/test_responses.py", "content": "import json\nimport pickle\nimport typing\n\nimport chardet\nimport pytest\n\nimport httpx\n\n\nclass StreamingBody:\n def __iter__(self):\n yield b\"Hello, \"\n yield b\"world!\"\n\n\ndef streaming_body() -> typing.Iterator[bytes]:\n yield b\"Hello, \"\n yield b\"world!\"\n\n\nasync def async_streaming_body() -> typing.AsyncIterator[bytes]:\n yield b\"Hello, \"\n yield b\"world!\"\n\n\ndef autodetect(content):\n return chardet.detect(content).get(\"encoding\")\n\n\ndef test_response():\n response = httpx.Response(\n 200,\n content=b\"Hello, world!\",\n request=httpx.Request(\"GET\", \"https://example.org\"),\n )\n\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.text == \"Hello, world!\"\n assert response.request.method == \"GET\"\n assert response.request.url == \"https://example.org\"\n assert not response.is_error\n\n\ndef test_response_content():\n response = httpx.Response(200, content=\"Hello, world!\")\n\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.text == \"Hello, world!\"\n assert response.headers == {\"Content-Length\": \"13\"}\n\n\ndef test_response_text():\n response = httpx.Response(200, text=\"Hello, world!\")\n\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.text == \"Hello, world!\"\n assert response.headers == {\n \"Content-Length\": \"13\",\n \"Content-Type\": \"text/plain; charset=utf-8\",\n }\n\n\ndef test_response_html():\n response = httpx.Response(200, html=\"Hello, world!\")\n\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.text == \"Hello, world!\"\n assert response.headers == {\n \"Content-Length\": \"39\",\n \"Content-Type\": \"text/html; charset=utf-8\",\n }\n\n\ndef test_response_json():\n response = httpx.Response(200, json={\"hello\": \"world\"})\n\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.json() == {\"hello\": \"world\"}\n assert response.headers == {\n \"Content-Length\": \"18\",\n \"Content-Type\": \"application/json\",\n }\n\n\ndef test_raise_for_status():\n request = httpx.Request(\"GET\", \"https://example.org\")\n\n # 2xx status codes are not an error.\n response = httpx.Response(200, request=request)\n response.raise_for_status()\n\n # 1xx status codes are informational responses.\n response = httpx.Response(101, request=request)\n assert response.is_informational\n with pytest.raises(httpx.HTTPStatusError) as exc_info:\n response.raise_for_status()\n assert str(exc_info.value) == (\n \"Informational response '101 Switching Protocols' for url 'https://example.org'\\n\"\n \"For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/101\"\n )\n\n # 3xx status codes are redirections.\n headers = {\"location\": \"https://other.org\"}\n response = httpx.Response(303, headers=headers, request=request)\n assert response.is_redirect\n with pytest.raises(httpx.HTTPStatusError) as exc_info:\n response.raise_for_status()\n assert str(exc_info.value) == (\n \"Redirect response '303 See Other' for url 'https://example.org'\\n\"\n \"Redirect location: 'https://other.org'\\n\"\n \"For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/303\"\n )\n\n # 4xx status codes are a client error.\n response = httpx.Response(403, request=request)\n assert response.is_client_error\n assert response.is_error\n with pytest.raises(httpx.HTTPStatusError) as exc_info:\n response.raise_for_status()\n assert str(exc_info.value) == (\n \"Client error '403 Forbidden' for url 'https://example.org'\\n\"\n \"For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403\"\n )\n\n # 5xx status codes are a server error.\n response = httpx.Response(500, request=request)\n assert response.is_server_error\n assert response.is_error\n with pytest.raises(httpx.HTTPStatusError) as exc_info:\n response.raise_for_status()\n assert str(exc_info.value) == (\n \"Server error '500 Internal Server Error' for url 'https://example.org'\\n\"\n \"For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500\"\n )\n\n # Calling .raise_for_status without setting a request instance is\n # not valid. Should raise a runtime error.\n response = httpx.Response(200)\n with pytest.raises(RuntimeError):\n response.raise_for_status()\n\n\ndef test_response_repr():\n response = httpx.Response(\n 200,\n content=b\"Hello, world!\",\n )\n assert repr(response) == \"\"\n\n\ndef test_response_content_type_encoding():\n \"\"\"\n Use the charset encoding in the Content-Type header if possible.\n \"\"\"\n headers = {\"Content-Type\": \"text-plain; charset=latin-1\"}\n content = \"Latin 1: \u00ff\".encode(\"latin-1\")\n response = httpx.Response(\n 200,\n content=content,\n headers=headers,\n )\n assert response.text == \"Latin 1: \u00ff\"\n assert response.encoding == \"latin-1\"\n\n\ndef test_response_default_to_utf8_encoding():\n \"\"\"\n Default to utf-8 encoding if there is no Content-Type header.\n \"\"\"\n content = \"\u304a\u306f\u3088\u3046\u3054\u3056\u3044\u307e\u3059\u3002\".encode(\"utf-8\")\n response = httpx.Response(\n 200,\n content=content,\n )\n assert response.text == \"\u304a\u306f\u3088\u3046\u3054\u3056\u3044\u307e\u3059\u3002\"\n assert response.encoding == \"utf-8\"\n\n\ndef test_response_fallback_to_utf8_encoding():\n \"\"\"\n Fallback to utf-8 if we get an invalid charset in the Content-Type header.\n \"\"\"\n headers = {\"Content-Type\": \"text-plain; charset=invalid-codec-name\"}\n content = \"\u304a\u306f\u3088\u3046\u3054\u3056\u3044\u307e\u3059\u3002\".encode(\"utf-8\")\n response = httpx.Response(\n 200,\n content=content,\n headers=headers,\n )\n assert response.text == \"\u304a\u306f\u3088\u3046\u3054\u3056\u3044\u307e\u3059\u3002\"\n assert response.encoding == \"utf-8\"\n\n\ndef test_response_no_charset_with_ascii_content():\n \"\"\"\n A response with ascii encoded content should decode correctly,\n even with no charset specified.\n \"\"\"\n content = b\"Hello, world!\"\n headers = {\"Content-Type\": \"text/plain\"}\n response = httpx.Response(\n 200,\n content=content,\n headers=headers,\n )\n assert response.status_code == 200\n assert response.encoding == \"utf-8\"\n assert response.text == \"Hello, world!\"\n\n\ndef test_response_no_charset_with_utf8_content():\n \"\"\"\n A response with UTF-8 encoded content should decode correctly,\n even with no charset specified.\n \"\"\"\n content = \"Unicode Snowman: \u2603\".encode(\"utf-8\")\n headers = {\"Content-Type\": \"text/plain\"}\n response = httpx.Response(\n 200,\n content=content,\n headers=headers,\n )\n assert response.text == \"Unicode Snowman: \u2603\"\n assert response.encoding == \"utf-8\"\n\n\ndef test_response_no_charset_with_iso_8859_1_content():\n \"\"\"\n A response with ISO 8859-1 encoded content should decode correctly,\n even with no charset specified, if autodetect is enabled.\n \"\"\"\n content = \"Accented: \u00d6sterreich abcdefghijklmnopqrstuzwxyz\".encode(\"iso-8859-1\")\n headers = {\"Content-Type\": \"text/plain\"}\n response = httpx.Response(\n 200, content=content, headers=headers, default_encoding=autodetect\n )\n assert response.text == \"Accented: \u00d6sterreich abcdefghijklmnopqrstuzwxyz\"\n assert response.charset_encoding is None\n\n\ndef test_response_no_charset_with_cp_1252_content():\n \"\"\"\n A response with Windows 1252 encoded content should decode correctly,\n even with no charset specified, if autodetect is enabled.\n \"\"\"\n content = \"Euro Currency: \u20ac abcdefghijklmnopqrstuzwxyz\".encode(\"cp1252\")\n headers = {\"Content-Type\": \"text/plain\"}\n response = httpx.Response(\n 200, content=content, headers=headers, default_encoding=autodetect\n )\n assert response.text == \"Euro Currency: \u20ac abcdefghijklmnopqrstuzwxyz\"\n assert response.charset_encoding is None\n\n\ndef test_response_non_text_encoding():\n \"\"\"\n Default to attempting utf-8 encoding for non-text content-type headers.\n \"\"\"\n headers = {\"Content-Type\": \"image/png\"}\n response = httpx.Response(\n 200,\n content=b\"xyz\",\n headers=headers,\n )\n assert response.text == \"xyz\"\n assert response.encoding == \"utf-8\"\n\n\ndef test_response_set_explicit_encoding():\n headers = {\n \"Content-Type\": \"text-plain; charset=utf-8\"\n } # Deliberately incorrect charset\n response = httpx.Response(\n 200,\n content=\"Latin 1: \u00ff\".encode(\"latin-1\"),\n headers=headers,\n )\n response.encoding = \"latin-1\"\n assert response.text == \"Latin 1: \u00ff\"\n assert response.encoding == \"latin-1\"\n\n\ndef test_response_force_encoding():\n response = httpx.Response(\n 200,\n content=\"Snowman: \u2603\".encode(\"utf-8\"),\n )\n response.encoding = \"iso-8859-1\"\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.text == \"Snowman: \u00e2\\x98\\x83\"\n assert response.encoding == \"iso-8859-1\"\n\n\ndef test_read():\n response = httpx.Response(\n 200,\n content=b\"Hello, world!\",\n )\n\n assert response.status_code == 200\n assert response.text == \"Hello, world!\"\n assert response.encoding == \"utf-8\"\n assert response.is_closed\n\n content = response.read()\n\n assert content == b\"Hello, world!\"\n assert response.content == b\"Hello, world!\"\n assert response.is_closed\n\n\ndef test_empty_read():\n response = httpx.Response(200)\n\n assert response.status_code == 200\n assert response.text == \"\"\n assert response.encoding == \"utf-8\"\n assert response.is_closed\n\n content = response.read()\n\n assert content == b\"\"\n assert response.content == b\"\"\n assert response.is_closed\n\n\n@pytest.mark.anyio\nasync def test_aread():\n response = httpx.Response(\n 200,\n content=b\"Hello, world!\",\n )\n\n assert response.status_code == 200\n assert response.text == \"Hello, world!\"\n assert response.encoding == \"utf-8\"\n assert response.is_closed\n\n content = await response.aread()\n\n assert content == b\"Hello, world!\"\n assert response.content == b\"Hello, world!\"\n assert response.is_closed\n\n\n@pytest.mark.anyio\nasync def test_empty_aread():\n response = httpx.Response(200)\n\n assert response.status_code == 200\n assert response.text == \"\"\n assert response.encoding == \"utf-8\"\n assert response.is_closed\n\n content = await response.aread()\n\n assert content == b\"\"\n assert response.content == b\"\"\n assert response.is_closed\n\n\ndef test_iter_raw():\n response = httpx.Response(\n 200,\n content=streaming_body(),\n )\n\n raw = b\"\"\n for part in response.iter_raw():\n raw += part\n assert raw == b\"Hello, world!\"\n\n\ndef test_iter_raw_with_chunksize():\n response = httpx.Response(200, content=streaming_body())\n parts = [part for part in response.iter_raw(chunk_size=5)]\n assert parts == [b\"Hello\", b\", wor\", b\"ld!\"]\n\n response = httpx.Response(200, content=streaming_body())\n parts = [part for part in response.iter_raw(chunk_size=7)]\n assert parts == [b\"Hello, \", b\"world!\"]\n\n response = httpx.Response(200, content=streaming_body())\n parts = [part for part in response.iter_raw(chunk_size=13)]\n assert parts == [b\"Hello, world!\"]\n\n response = httpx.Response(200, content=streaming_body())\n parts = [part for part in response.iter_raw(chunk_size=20)]\n assert parts == [b\"Hello, world!\"]\n\n\ndef test_iter_raw_doesnt_return_empty_chunks():\n def streaming_body_with_empty_chunks() -> typing.Iterator[bytes]:\n yield b\"Hello, \"\n yield b\"\"\n yield b\"world!\"\n yield b\"\"\n\n response = httpx.Response(200, content=streaming_body_with_empty_chunks())\n\n parts = [part for part in response.iter_raw()]\n assert parts == [b\"Hello, \", b\"world!\"]\n\n\ndef test_iter_raw_on_iterable():\n response = httpx.Response(\n 200,\n content=StreamingBody(),\n )\n\n raw = b\"\"\n for part in response.iter_raw():\n raw += part\n assert raw == b\"Hello, world!\"\n\n\ndef test_iter_raw_on_async():\n response = httpx.Response(\n 200,\n content=async_streaming_body(),\n )\n\n with pytest.raises(RuntimeError):\n [part for part in response.iter_raw()]\n\n\ndef test_close_on_async():\n response = httpx.Response(\n 200,\n content=async_streaming_body(),\n )\n\n with pytest.raises(RuntimeError):\n response.close()\n\n\ndef test_iter_raw_increments_updates_counter():\n response = httpx.Response(200, content=streaming_body())\n\n num_downloaded = response.num_bytes_downloaded\n for part in response.iter_raw():\n assert len(part) == (response.num_bytes_downloaded - num_downloaded)\n num_downloaded = response.num_bytes_downloaded\n\n\n@pytest.mark.anyio\nasync def test_aiter_raw():\n response = httpx.Response(200, content=async_streaming_body())\n\n raw = b\"\"\n async for part in response.aiter_raw():\n raw += part\n assert raw == b\"Hello, world!\"\n\n\n@pytest.mark.anyio\nasync def test_aiter_raw_with_chunksize():\n response = httpx.Response(200, content=async_streaming_body())\n\n parts = [part async for part in response.aiter_raw(chunk_size=5)]\n assert parts == [b\"Hello\", b\", wor\", b\"ld!\"]\n\n response = httpx.Response(200, content=async_streaming_body())\n\n parts = [part async for part in response.aiter_raw(chunk_size=13)]\n assert parts == [b\"Hello, world!\"]\n\n response = httpx.Response(200, content=async_streaming_body())\n\n parts = [part async for part in response.aiter_raw(chunk_size=20)]\n assert parts == [b\"Hello, world!\"]\n\n\n@pytest.mark.anyio\nasync def test_aiter_raw_on_sync():\n response = httpx.Response(\n 200,\n content=streaming_body(),\n )\n\n with pytest.raises(RuntimeError):\n [part async for part in response.aiter_raw()]\n\n\n@pytest.mark.anyio\nasync def test_aclose_on_sync():\n response = httpx.Response(\n 200,\n content=streaming_body(),\n )\n\n with pytest.raises(RuntimeError):\n await response.aclose()\n\n\n@pytest.mark.anyio\nasync def test_aiter_raw_increments_updates_counter():\n response = httpx.Response(200, content=async_streaming_body())\n\n num_downloaded = response.num_bytes_downloaded\n async for part in response.aiter_raw():\n assert len(part) == (response.num_bytes_downloaded - num_downloaded)\n num_downloaded = response.num_bytes_downloaded\n\n\ndef test_iter_bytes():\n response = httpx.Response(200, content=b\"Hello, world!\")\n\n content = b\"\"\n for part in response.iter_bytes():\n content += part\n assert content == b\"Hello, world!\"\n\n\ndef test_iter_bytes_with_chunk_size():\n response = httpx.Response(200, content=streaming_body())\n parts = [part for part in response.iter_bytes(chunk_size=5)]\n assert parts == [b\"Hello\", b\", wor\", b\"ld!\"]\n\n response = httpx.Response(200, content=streaming_body())\n parts = [part for part in response.iter_bytes(chunk_size=13)]\n assert parts == [b\"Hello, world!\"]\n\n response = httpx.Response(200, content=streaming_body())\n parts = [part for part in response.iter_bytes(chunk_size=20)]\n assert parts == [b\"Hello, world!\"]\n\n\ndef test_iter_bytes_with_empty_response():\n response = httpx.Response(200, content=b\"\")\n parts = [part for part in response.iter_bytes()]\n assert parts == []\n\n\ndef test_iter_bytes_doesnt_return_empty_chunks():\n def streaming_body_with_empty_chunks() -> typing.Iterator[bytes]:\n yield b\"Hello, \"\n yield b\"\"\n yield b\"world!\"\n yield b\"\"\n\n response = httpx.Response(200, content=streaming_body_with_empty_chunks())\n\n parts = [part for part in response.iter_bytes()]\n assert parts == [b\"Hello, \", b\"world!\"]\n\n\n@pytest.mark.anyio\nasync def test_aiter_bytes():\n response = httpx.Response(\n 200,\n content=b\"Hello, world!\",\n )\n\n content = b\"\"\n async for part in response.aiter_bytes():\n content += part\n assert content == b\"Hello, world!\"\n\n\n@pytest.mark.anyio\nasync def test_aiter_bytes_with_chunk_size():\n response = httpx.Response(200, content=async_streaming_body())\n parts = [part async for part in response.aiter_bytes(chunk_size=5)]\n assert parts == [b\"Hello\", b\", wor\", b\"ld!\"]\n\n response = httpx.Response(200, content=async_streaming_body())\n parts = [part async for part in response.aiter_bytes(chunk_size=13)]\n assert parts == [b\"Hello, world!\"]\n\n response = httpx.Response(200, content=async_streaming_body())\n parts = [part async for part in response.aiter_bytes(chunk_size=20)]\n assert parts == [b\"Hello, world!\"]\n\n\ndef test_iter_text():\n response = httpx.Response(\n 200,\n content=b\"Hello, world!\",\n )\n\n content = \"\"\n for part in response.iter_text():\n content += part\n assert content == \"Hello, world!\"\n\n\ndef test_iter_text_with_chunk_size():\n response = httpx.Response(200, content=b\"Hello, world!\")\n parts = [part for part in response.iter_text(chunk_size=5)]\n assert parts == [\"Hello\", \", wor\", \"ld!\"]\n\n response = httpx.Response(200, content=b\"Hello, world!!\")\n parts = [part for part in response.iter_text(chunk_size=7)]\n assert parts == [\"Hello, \", \"world!!\"]\n\n response = httpx.Response(200, content=b\"Hello, world!\")\n parts = [part for part in response.iter_text(chunk_size=7)]\n assert parts == [\"Hello, \", \"world!\"]\n\n response = httpx.Response(200, content=b\"Hello, world!\")\n parts = [part for part in response.iter_text(chunk_size=13)]\n assert parts == [\"Hello, world!\"]\n\n response = httpx.Response(200, content=b\"Hello, world!\")\n parts = [part for part in response.iter_text(chunk_size=20)]\n assert parts == [\"Hello, world!\"]\n\n\n@pytest.mark.anyio\nasync def test_aiter_text():\n response = httpx.Response(\n 200,\n content=b\"Hello, world!\",\n )\n\n content = \"\"\n async for part in response.aiter_text():\n content += part\n assert content == \"Hello, world!\"\n\n\n@pytest.mark.anyio\nasync def test_aiter_text_with_chunk_size():\n response = httpx.Response(200, content=b\"Hello, world!\")\n parts = [part async for part in response.aiter_text(chunk_size=5)]\n assert parts == [\"Hello\", \", wor\", \"ld!\"]\n\n response = httpx.Response(200, content=b\"Hello, world!\")\n parts = [part async for part in response.aiter_text(chunk_size=13)]\n assert parts == [\"Hello, world!\"]\n\n response = httpx.Response(200, content=b\"Hello, world!\")\n parts = [part async for part in response.aiter_text(chunk_size=20)]\n assert parts == [\"Hello, world!\"]\n\n\ndef test_iter_lines():\n response = httpx.Response(\n 200,\n content=b\"Hello,\\nworld!\",\n )\n content = [line for line in response.iter_lines()]\n assert content == [\"Hello,\", \"world!\"]\n\n\n@pytest.mark.anyio\nasync def test_aiter_lines():\n response = httpx.Response(\n 200,\n content=b\"Hello,\\nworld!\",\n )\n\n content = []\n async for line in response.aiter_lines():\n content.append(line)\n assert content == [\"Hello,\", \"world!\"]\n\n\ndef test_sync_streaming_response():\n response = httpx.Response(\n 200,\n content=streaming_body(),\n )\n\n assert response.status_code == 200\n assert not response.is_closed\n\n content = response.read()\n\n assert content == b\"Hello, world!\"\n assert response.content == b\"Hello, world!\"\n assert response.is_closed\n\n\n@pytest.mark.anyio\nasync def test_async_streaming_response():\n response = httpx.Response(\n 200,\n content=async_streaming_body(),\n )\n\n assert response.status_code == 200\n assert not response.is_closed\n\n content = await response.aread()\n\n assert content == b\"Hello, world!\"\n assert response.content == b\"Hello, world!\"\n assert response.is_closed\n\n\ndef test_cannot_read_after_stream_consumed():\n response = httpx.Response(\n 200,\n content=streaming_body(),\n )\n\n content = b\"\"\n for part in response.iter_bytes():\n content += part\n\n with pytest.raises(httpx.StreamConsumed):\n response.read()\n\n\n@pytest.mark.anyio\nasync def test_cannot_aread_after_stream_consumed():\n response = httpx.Response(\n 200,\n content=async_streaming_body(),\n )\n\n content = b\"\"\n async for part in response.aiter_bytes():\n content += part\n\n with pytest.raises(httpx.StreamConsumed):\n await response.aread()\n\n\ndef test_cannot_read_after_response_closed():\n response = httpx.Response(\n 200,\n content=streaming_body(),\n )\n\n response.close()\n with pytest.raises(httpx.StreamClosed):\n response.read()\n\n\n@pytest.mark.anyio\nasync def test_cannot_aread_after_response_closed():\n response = httpx.Response(\n 200,\n content=async_streaming_body(),\n )\n\n await response.aclose()\n with pytest.raises(httpx.StreamClosed):\n await response.aread()\n\n\n@pytest.mark.anyio\nasync def test_elapsed_not_available_until_closed():\n response = httpx.Response(\n 200,\n content=async_streaming_body(),\n )\n\n with pytest.raises(RuntimeError):\n response.elapsed # noqa: B018\n\n\ndef test_unknown_status_code():\n response = httpx.Response(\n 600,\n )\n assert response.status_code == 600\n assert response.reason_phrase == \"\"\n assert response.text == \"\"\n\n\ndef test_json_with_specified_encoding():\n data = {\"greeting\": \"hello\", \"recipient\": \"world\"}\n content = json.dumps(data).encode(\"utf-16\")\n headers = {\"Content-Type\": \"application/json, charset=utf-16\"}\n response = httpx.Response(\n 200,\n content=content,\n headers=headers,\n )\n assert response.json() == data\n\n\ndef test_json_with_options():\n data = {\"greeting\": \"hello\", \"recipient\": \"world\", \"amount\": 1}\n content = json.dumps(data).encode(\"utf-16\")\n headers = {\"Content-Type\": \"application/json, charset=utf-16\"}\n response = httpx.Response(\n 200,\n content=content,\n headers=headers,\n )\n assert response.json(parse_int=str)[\"amount\"] == \"1\"\n\n\n@pytest.mark.parametrize(\n \"encoding\",\n [\n \"utf-8\",\n \"utf-8-sig\",\n \"utf-16\",\n \"utf-16-be\",\n \"utf-16-le\",\n \"utf-32\",\n \"utf-32-be\",\n \"utf-32-le\",\n ],\n)\ndef test_json_without_specified_charset(encoding):\n data = {\"greeting\": \"hello\", \"recipient\": \"world\"}\n content = json.dumps(data).encode(encoding)\n headers = {\"Content-Type\": \"application/json\"}\n response = httpx.Response(\n 200,\n content=content,\n headers=headers,\n )\n assert response.json() == data\n\n\n@pytest.mark.parametrize(\n \"encoding\",\n [\n \"utf-8\",\n \"utf-8-sig\",\n \"utf-16\",\n \"utf-16-be\",\n \"utf-16-le\",\n \"utf-32\",\n \"utf-32-be\",\n \"utf-32-le\",\n ],\n)\ndef test_json_with_specified_charset(encoding):\n data = {\"greeting\": \"hello\", \"recipient\": \"world\"}\n content = json.dumps(data).encode(encoding)\n headers = {\"Content-Type\": f\"application/json; charset={encoding}\"}\n response = httpx.Response(\n 200,\n content=content,\n headers=headers,\n )\n assert response.json() == data\n\n\n@pytest.mark.parametrize(\n \"headers, expected\",\n [\n (\n {\"Link\": \"; rel='preload'\"},\n {\"preload\": {\"rel\": \"preload\", \"url\": \"https://example.com\"}},\n ),\n (\n {\"Link\": '; rel=\"hub\", ; rel=\"self\"'},\n {\n \"hub\": {\"url\": \"/hub\", \"rel\": \"hub\"},\n \"self\": {\"url\": \"/resource\", \"rel\": \"self\"},\n },\n ),\n ],\n)\ndef test_link_headers(headers, expected):\n response = httpx.Response(\n 200,\n content=None,\n headers=headers,\n )\n assert response.links == expected\n\n\n@pytest.mark.parametrize(\"header_value\", (b\"deflate\", b\"gzip\", b\"br\"))\ndef test_decode_error_with_request(header_value):\n headers = [(b\"Content-Encoding\", header_value)]\n broken_compressed_body = b\"xxxxxxxxxxxxxx\"\n with pytest.raises(httpx.DecodingError):\n httpx.Response(\n 200,\n headers=headers,\n content=broken_compressed_body,\n )\n\n with pytest.raises(httpx.DecodingError):\n httpx.Response(\n 200,\n headers=headers,\n content=broken_compressed_body,\n request=httpx.Request(\"GET\", \"https://www.example.org/\"),\n )\n\n\n@pytest.mark.parametrize(\"header_value\", (b\"deflate\", b\"gzip\", b\"br\"))\ndef test_value_error_without_request(header_value):\n headers = [(b\"Content-Encoding\", header_value)]\n broken_compressed_body = b\"xxxxxxxxxxxxxx\"\n with pytest.raises(httpx.DecodingError):\n httpx.Response(200, headers=headers, content=broken_compressed_body)\n\n\ndef test_response_with_unset_request():\n response = httpx.Response(200, content=b\"Hello, world!\")\n\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.text == \"Hello, world!\"\n assert not response.is_error\n\n\ndef test_set_request_after_init():\n response = httpx.Response(200, content=b\"Hello, world!\")\n\n response.request = httpx.Request(\"GET\", \"https://www.example.org\")\n\n assert response.request.method == \"GET\"\n assert response.request.url == \"https://www.example.org\"\n\n\ndef test_cannot_access_unset_request():\n response = httpx.Response(200, content=b\"Hello, world!\")\n\n with pytest.raises(RuntimeError):\n response.request # noqa: B018\n\n\ndef test_generator_with_transfer_encoding_header():\n def content() -> typing.Iterator[bytes]:\n yield b\"test 123\" # pragma: no cover\n\n response = httpx.Response(200, content=content())\n assert response.headers == {\"Transfer-Encoding\": \"chunked\"}\n\n\ndef test_generator_with_content_length_header():\n def content() -> typing.Iterator[bytes]:\n yield b\"test 123\" # pragma: no cover\n\n headers = {\"Content-Length\": \"8\"}\n response = httpx.Response(200, content=content(), headers=headers)\n assert response.headers == {\"Content-Length\": \"8\"}\n\n\ndef test_response_picklable():\n response = httpx.Response(\n 200,\n content=b\"Hello, world!\",\n request=httpx.Request(\"GET\", \"https://example.org\"),\n )\n pickle_response = pickle.loads(pickle.dumps(response))\n assert pickle_response.is_closed is True\n assert pickle_response.is_stream_consumed is True\n assert pickle_response.next_request is None\n assert pickle_response.stream is not None\n assert pickle_response.content == b\"Hello, world!\"\n assert pickle_response.status_code == 200\n assert pickle_response.request.url == response.request.url\n assert pickle_response.extensions == {}\n assert pickle_response.history == []\n\n\n@pytest.mark.anyio\nasync def test_response_async_streaming_picklable():\n response = httpx.Response(200, content=async_streaming_body())\n pickle_response = pickle.loads(pickle.dumps(response))\n with pytest.raises(httpx.ResponseNotRead):\n pickle_response.content # noqa: B018\n with pytest.raises(httpx.StreamClosed):\n await pickle_response.aread()\n assert pickle_response.is_stream_consumed is False\n assert pickle_response.num_bytes_downloaded == 0\n assert pickle_response.headers == {\"Transfer-Encoding\": \"chunked\"}\n\n response = httpx.Response(200, content=async_streaming_body())\n await response.aread()\n pickle_response = pickle.loads(pickle.dumps(response))\n assert pickle_response.is_stream_consumed is True\n assert pickle_response.content == b\"Hello, world!\"\n assert pickle_response.num_bytes_downloaded == 13\n\n\ndef test_response_decode_text_using_autodetect():\n # Ensure that a 'default_encoding=\"autodetect\"' on the response allows for\n # encoding autodetection to be used when no \"Content-Type: text/plain; charset=...\"\n # info is present.\n #\n # Here we have some french text encoded with ISO-8859-1, rather than UTF-8.\n text = (\n \"Non-seulement Despr\u00e9aux ne se trompait pas, mais de tous les \u00e9crivains \"\n \"que la France a produits, sans excepter Voltaire lui-m\u00eame, impr\u00e9gn\u00e9 de \"\n \"l'esprit anglais par son s\u00e9jour \u00e0 Londres, c'est incontestablement \"\n \"Moli\u00e8re ou Poquelin qui reproduit avec l'exactitude la plus vive et la \"\n \"plus compl\u00e8te le fond du g\u00e9nie fran\u00e7ais.\"\n )\n content = text.encode(\"ISO-8859-1\")\n response = httpx.Response(200, content=content, default_encoding=autodetect)\n\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.encoding == \"ISO-8859-1\"\n assert response.text == text\n\n\ndef test_response_decode_text_using_explicit_encoding():\n # Ensure that a 'default_encoding=\"...\"' on the response is used for text decoding\n # when no \"Content-Type: text/plain; charset=...\"\" info is present.\n #\n # Here we have some french text encoded with Windows-1252, rather than UTF-8.\n # https://en.wikipedia.org/wiki/Windows-1252\n text = (\n \"Non-seulement Despr\u00e9aux ne se trompait pas, mais de tous les \u00e9crivains \"\n \"que la France a produits, sans excepter Voltaire lui-m\u00eame, impr\u00e9gn\u00e9 de \"\n \"l'esprit anglais par son s\u00e9jour \u00e0 Londres, c'est incontestablement \"\n \"Moli\u00e8re ou Poquelin qui reproduit avec l'exactitude la plus vive et la \"\n \"plus compl\u00e8te le fond du g\u00e9nie fran\u00e7ais.\"\n )\n content = text.encode(\"cp1252\")\n response = httpx.Response(200, content=content, default_encoding=\"cp1252\")\n\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.encoding == \"cp1252\"\n assert response.text == text\n" } ], "language": "python" }, { "id": "10_0", "repo_url": "https://github.com/teamqurrent/discord.py", "instruction": "Your task is to add support for the Latin American Spanish locale to the discord.py library. This involves updating the `Locale` enumeration in the `enums.py` file to include the new locale. The locale code is es-419", "base_commit": "08ef42f", "test_script": "import unittest\nimport sys\n\n\n\nclass TestLocaleAddition(unittest.TestCase):\n def test_latin_american_spanish_locale(self):\n from discord.enums import Locale\n # Check if the Latin American Spanish locale is present in the Locale enumeration\n self.assertTrue(hasattr(Locale, 'latin_american_spanish'), \"Locale for Latin American Spanish is missing\")\n\n def test_locale_code_correct(self):\n from discord.enums import Locale\n # Verify that the value of the Latin American Spanish locale is correctly set to 'es-419'\n self.assertEqual(Locale.latin_american_spanish.value, 'es-419', \"Latin American Spanish locale should be 'es-419'\")\n\ndef main():\n\n\n suite = unittest.TestSuite()\n suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestLocaleAddition))\n runner = unittest.TextTestRunner()\n\n if runner.run(suite).wasSuccessful():\n sys.exit(0)\n else:\n sys.exit(1)\n\nif __name__ == '__main__':\n\n main()\n", "testbed_environment": "python3.9", "requirements_txt": "discord", "solution_commit": "2a59e028", "solution_patch": "diff --git a/discord/enums.py b/discord/enums.py\n--- a/discord/enums.py\n+++ b/discord/enums.py\n@@ -690,6 +690,7 @@ class Locale(Enum):\n italian = 'it'\n japanese = 'ja'\n korean = 'ko'\n+ latin_american_spanish = 'es-419'\n lithuanian = 'lt'\n norwegian = 'no'\n polish = 'pl'\ndiff --git a/docs/api.rst b/docs/api.rst\n--- a/docs/api.rst\n+++ b/docs/api.rst\n@@ -3236,6 +3236,12 @@ of :class:`enum.Enum`.\n \n The ``ko`` locale.\n \n+ .. attribute:: latin_american_spanish\n+\n+ The ``es-419`` locale.\n+\n+ .. versionadded:: 2.4\n+\n .. attribute:: lithuanian\n \n The ``lt`` locale.\n", "modified_files": [ { "path": "discord/enums.py", "content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\nfrom __future__ import annotations\n\nimport types\nfrom collections import namedtuple\nfrom typing import Any, ClassVar, Dict, List, Optional, TYPE_CHECKING, Tuple, Type, TypeVar, Iterator, Mapping\n\n__all__ = (\n 'Enum',\n 'ChannelType',\n 'MessageType',\n 'SpeakingState',\n 'VerificationLevel',\n 'ContentFilter',\n 'Status',\n 'DefaultAvatar',\n 'AuditLogAction',\n 'AuditLogActionCategory',\n 'UserFlags',\n 'ActivityType',\n 'NotificationLevel',\n 'TeamMembershipState',\n 'TeamMemberRole',\n 'WebhookType',\n 'ExpireBehaviour',\n 'ExpireBehavior',\n 'StickerType',\n 'StickerFormatType',\n 'InviteTarget',\n 'VideoQualityMode',\n 'ComponentType',\n 'ButtonStyle',\n 'TextStyle',\n 'PrivacyLevel',\n 'InteractionType',\n 'InteractionResponseType',\n 'NSFWLevel',\n 'MFALevel',\n 'Locale',\n 'EntityType',\n 'EventStatus',\n 'AppCommandType',\n 'AppCommandOptionType',\n 'AppCommandPermissionType',\n 'AutoModRuleTriggerType',\n 'AutoModRuleEventType',\n 'AutoModRuleActionType',\n 'ForumLayoutType',\n 'ForumOrderType',\n 'SelectDefaultValueType',\n 'SKUType',\n 'EntitlementType',\n 'EntitlementOwnerType',\n)\n\nif TYPE_CHECKING:\n from typing_extensions import Self\n\n\ndef _create_value_cls(name: str, comparable: bool):\n # All the type ignores here are due to the type checker being unable to recognise\n # Runtime type creation without exploding.\n cls = namedtuple('_EnumValue_' + name, 'name value')\n cls.__repr__ = lambda self: f'<{name}.{self.name}: {self.value!r}>' # type: ignore\n cls.__str__ = lambda self: f'{name}.{self.name}' # type: ignore\n if comparable:\n cls.__le__ = lambda self, other: isinstance(other, self.__class__) and self.value <= other.value # type: ignore\n cls.__ge__ = lambda self, other: isinstance(other, self.__class__) and self.value >= other.value # type: ignore\n cls.__lt__ = lambda self, other: isinstance(other, self.__class__) and self.value < other.value # type: ignore\n cls.__gt__ = lambda self, other: isinstance(other, self.__class__) and self.value > other.value # type: ignore\n return cls\n\n\ndef _is_descriptor(obj):\n return hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__')\n\n\nclass EnumMeta(type):\n if TYPE_CHECKING:\n __name__: ClassVar[str]\n _enum_member_names_: ClassVar[List[str]]\n _enum_member_map_: ClassVar[Dict[str, Any]]\n _enum_value_map_: ClassVar[Dict[Any, Any]]\n\n def __new__(cls, name: str, bases: Tuple[type, ...], attrs: Dict[str, Any], *, comparable: bool = False) -> Self:\n value_mapping = {}\n member_mapping = {}\n member_names = []\n\n value_cls = _create_value_cls(name, comparable)\n for key, value in list(attrs.items()):\n is_descriptor = _is_descriptor(value)\n if key[0] == '_' and not is_descriptor:\n continue\n\n # Special case classmethod to just pass through\n if isinstance(value, classmethod):\n continue\n\n if is_descriptor:\n setattr(value_cls, key, value)\n del attrs[key]\n continue\n\n try:\n new_value = value_mapping[value]\n except KeyError:\n new_value = value_cls(name=key, value=value)\n value_mapping[value] = new_value\n member_names.append(key)\n\n member_mapping[key] = new_value\n attrs[key] = new_value\n\n attrs['_enum_value_map_'] = value_mapping\n attrs['_enum_member_map_'] = member_mapping\n attrs['_enum_member_names_'] = member_names\n attrs['_enum_value_cls_'] = value_cls\n actual_cls = super().__new__(cls, name, bases, attrs)\n value_cls._actual_enum_cls_ = actual_cls # type: ignore # Runtime attribute isn't understood\n return actual_cls\n\n def __iter__(cls) -> Iterator[Any]:\n return (cls._enum_member_map_[name] for name in cls._enum_member_names_)\n\n def __reversed__(cls) -> Iterator[Any]:\n return (cls._enum_member_map_[name] for name in reversed(cls._enum_member_names_))\n\n def __len__(cls) -> int:\n return len(cls._enum_member_names_)\n\n def __repr__(cls) -> str:\n return f''\n\n @property\n def __members__(cls) -> Mapping[str, Any]:\n return types.MappingProxyType(cls._enum_member_map_)\n\n def __call__(cls, value: str) -> Any:\n try:\n return cls._enum_value_map_[value]\n except (KeyError, TypeError):\n raise ValueError(f\"{value!r} is not a valid {cls.__name__}\")\n\n def __getitem__(cls, key: str) -> Any:\n return cls._enum_member_map_[key]\n\n def __setattr__(cls, name: str, value: Any) -> None:\n raise TypeError('Enums are immutable.')\n\n def __delattr__(cls, attr: str) -> None:\n raise TypeError('Enums are immutable')\n\n def __instancecheck__(self, instance: Any) -> bool:\n # isinstance(x, Y)\n # -> __instancecheck__(Y, x)\n try:\n return instance._actual_enum_cls_ is self\n except AttributeError:\n return False\n\n\nif TYPE_CHECKING:\n from enum import Enum\nelse:\n\n class Enum(metaclass=EnumMeta):\n @classmethod\n def try_value(cls, value):\n try:\n return cls._enum_value_map_[value]\n except (KeyError, TypeError):\n return value\n\n\nclass ChannelType(Enum):\n text = 0\n private = 1\n voice = 2\n group = 3\n category = 4\n news = 5\n news_thread = 10\n public_thread = 11\n private_thread = 12\n stage_voice = 13\n forum = 15\n media = 16\n\n def __str__(self) -> str:\n return self.name\n\n\nclass MessageType(Enum):\n default = 0\n recipient_add = 1\n recipient_remove = 2\n call = 3\n channel_name_change = 4\n channel_icon_change = 5\n pins_add = 6\n new_member = 7\n premium_guild_subscription = 8\n premium_guild_tier_1 = 9\n premium_guild_tier_2 = 10\n premium_guild_tier_3 = 11\n channel_follow_add = 12\n guild_stream = 13\n guild_discovery_disqualified = 14\n guild_discovery_requalified = 15\n guild_discovery_grace_period_initial_warning = 16\n guild_discovery_grace_period_final_warning = 17\n thread_created = 18\n reply = 19\n chat_input_command = 20\n thread_starter_message = 21\n guild_invite_reminder = 22\n context_menu_command = 23\n auto_moderation_action = 24\n role_subscription_purchase = 25\n interaction_premium_upsell = 26\n stage_start = 27\n stage_end = 28\n stage_speaker = 29\n stage_raise_hand = 30\n stage_topic = 31\n guild_application_premium_subscription = 32\n guild_incident_alert_mode_enabled = 36\n guild_incident_alert_mode_disabled = 37\n guild_incident_report_raid = 38\n guild_incident_report_false_alarm = 39\n\n\nclass SpeakingState(Enum):\n none = 0\n voice = 1\n soundshare = 2\n priority = 4\n\n def __str__(self) -> str:\n return self.name\n\n def __int__(self) -> int:\n return self.value\n\n\nclass VerificationLevel(Enum, comparable=True):\n none = 0\n low = 1\n medium = 2\n high = 3\n highest = 4\n\n def __str__(self) -> str:\n return self.name\n\n\nclass ContentFilter(Enum, comparable=True):\n disabled = 0\n no_role = 1\n all_members = 2\n\n def __str__(self) -> str:\n return self.name\n\n\nclass Status(Enum):\n online = 'online'\n offline = 'offline'\n idle = 'idle'\n dnd = 'dnd'\n do_not_disturb = 'dnd'\n invisible = 'invisible'\n\n def __str__(self) -> str:\n return self.value\n\n\nclass DefaultAvatar(Enum):\n blurple = 0\n grey = 1\n gray = 1\n green = 2\n orange = 3\n red = 4\n pink = 5\n\n def __str__(self) -> str:\n return self.name\n\n\nclass NotificationLevel(Enum, comparable=True):\n all_messages = 0\n only_mentions = 1\n\n\nclass AuditLogActionCategory(Enum):\n create = 1\n delete = 2\n update = 3\n\n\nclass AuditLogAction(Enum):\n # fmt: off\n guild_update = 1\n channel_create = 10\n channel_update = 11\n channel_delete = 12\n overwrite_create = 13\n overwrite_update = 14\n overwrite_delete = 15\n kick = 20\n member_prune = 21\n ban = 22\n unban = 23\n member_update = 24\n member_role_update = 25\n member_move = 26\n member_disconnect = 27\n bot_add = 28\n role_create = 30\n role_update = 31\n role_delete = 32\n invite_create = 40\n invite_update = 41\n invite_delete = 42\n webhook_create = 50\n webhook_update = 51\n webhook_delete = 52\n emoji_create = 60\n emoji_update = 61\n emoji_delete = 62\n message_delete = 72\n message_bulk_delete = 73\n message_pin = 74\n message_unpin = 75\n integration_create = 80\n integration_update = 81\n integration_delete = 82\n stage_instance_create = 83\n stage_instance_update = 84\n stage_instance_delete = 85\n sticker_create = 90\n sticker_update = 91\n sticker_delete = 92\n scheduled_event_create = 100\n scheduled_event_update = 101\n scheduled_event_delete = 102\n thread_create = 110\n thread_update = 111\n thread_delete = 112\n app_command_permission_update = 121\n automod_rule_create = 140\n automod_rule_update = 141\n automod_rule_delete = 142\n automod_block_message = 143\n automod_flag_message = 144\n automod_timeout_member = 145\n creator_monetization_request_created = 150\n creator_monetization_terms_accepted = 151\n # fmt: on\n\n @property\n def category(self) -> Optional[AuditLogActionCategory]:\n # fmt: off\n lookup: Dict[AuditLogAction, Optional[AuditLogActionCategory]] = {\n AuditLogAction.guild_update: AuditLogActionCategory.update,\n AuditLogAction.channel_create: AuditLogActionCategory.create,\n AuditLogAction.channel_update: AuditLogActionCategory.update,\n AuditLogAction.channel_delete: AuditLogActionCategory.delete,\n AuditLogAction.overwrite_create: AuditLogActionCategory.create,\n AuditLogAction.overwrite_update: AuditLogActionCategory.update,\n AuditLogAction.overwrite_delete: AuditLogActionCategory.delete,\n AuditLogAction.kick: None,\n AuditLogAction.member_prune: None,\n AuditLogAction.ban: None,\n AuditLogAction.unban: None,\n AuditLogAction.member_update: AuditLogActionCategory.update,\n AuditLogAction.member_role_update: AuditLogActionCategory.update,\n AuditLogAction.member_move: None,\n AuditLogAction.member_disconnect: None,\n AuditLogAction.bot_add: None,\n AuditLogAction.role_create: AuditLogActionCategory.create,\n AuditLogAction.role_update: AuditLogActionCategory.update,\n AuditLogAction.role_delete: AuditLogActionCategory.delete,\n AuditLogAction.invite_create: AuditLogActionCategory.create,\n AuditLogAction.invite_update: AuditLogActionCategory.update,\n AuditLogAction.invite_delete: AuditLogActionCategory.delete,\n AuditLogAction.webhook_create: AuditLogActionCategory.create,\n AuditLogAction.webhook_update: AuditLogActionCategory.update,\n AuditLogAction.webhook_delete: AuditLogActionCategory.delete,\n AuditLogAction.emoji_create: AuditLogActionCategory.create,\n AuditLogAction.emoji_update: AuditLogActionCategory.update,\n AuditLogAction.emoji_delete: AuditLogActionCategory.delete,\n AuditLogAction.message_delete: AuditLogActionCategory.delete,\n AuditLogAction.message_bulk_delete: AuditLogActionCategory.delete,\n AuditLogAction.message_pin: None,\n AuditLogAction.message_unpin: None,\n AuditLogAction.integration_create: AuditLogActionCategory.create,\n AuditLogAction.integration_update: AuditLogActionCategory.update,\n AuditLogAction.integration_delete: AuditLogActionCategory.delete,\n AuditLogAction.stage_instance_create: AuditLogActionCategory.create,\n AuditLogAction.stage_instance_update: AuditLogActionCategory.update,\n AuditLogAction.stage_instance_delete: AuditLogActionCategory.delete,\n AuditLogAction.sticker_create: AuditLogActionCategory.create,\n AuditLogAction.sticker_update: AuditLogActionCategory.update,\n AuditLogAction.sticker_delete: AuditLogActionCategory.delete,\n AuditLogAction.scheduled_event_create: AuditLogActionCategory.create,\n AuditLogAction.scheduled_event_update: AuditLogActionCategory.update,\n AuditLogAction.scheduled_event_delete: AuditLogActionCategory.delete,\n AuditLogAction.thread_create: AuditLogActionCategory.create,\n AuditLogAction.thread_delete: AuditLogActionCategory.delete,\n AuditLogAction.thread_update: AuditLogActionCategory.update,\n AuditLogAction.app_command_permission_update: AuditLogActionCategory.update,\n AuditLogAction.automod_rule_create: AuditLogActionCategory.create,\n AuditLogAction.automod_rule_update: AuditLogActionCategory.update,\n AuditLogAction.automod_rule_delete: AuditLogActionCategory.delete,\n AuditLogAction.automod_block_message: None,\n AuditLogAction.automod_flag_message: None,\n AuditLogAction.automod_timeout_member: None,\n AuditLogAction.creator_monetization_request_created: None,\n AuditLogAction.creator_monetization_terms_accepted: None,\n }\n # fmt: on\n return lookup[self]\n\n @property\n def target_type(self) -> Optional[str]:\n v = self.value\n if v == -1:\n return 'all'\n elif v < 10:\n return 'guild'\n elif v < 20:\n return 'channel'\n elif v < 30:\n return 'user'\n elif v < 40:\n return 'role'\n elif v < 50:\n return 'invite'\n elif v < 60:\n return 'webhook'\n elif v < 70:\n return 'emoji'\n elif v == 73:\n return 'channel'\n elif v < 80:\n return 'message'\n elif v < 83:\n return 'integration'\n elif v < 90:\n return 'stage_instance'\n elif v < 93:\n return 'sticker'\n elif v < 103:\n return 'guild_scheduled_event'\n elif v < 113:\n return 'thread'\n elif v < 122:\n return 'integration_or_app_command'\n elif v < 143:\n return 'auto_moderation'\n elif v < 146:\n return 'user'\n elif v < 152:\n return 'creator_monetization'\n\n\nclass UserFlags(Enum):\n staff = 1\n partner = 2\n hypesquad = 4\n bug_hunter = 8\n mfa_sms = 16\n premium_promo_dismissed = 32\n hypesquad_bravery = 64\n hypesquad_brilliance = 128\n hypesquad_balance = 256\n early_supporter = 512\n team_user = 1024\n system = 4096\n has_unread_urgent_messages = 8192\n bug_hunter_level_2 = 16384\n verified_bot = 65536\n verified_bot_developer = 131072\n discord_certified_moderator = 262144\n bot_http_interactions = 524288\n spammer = 1048576\n active_developer = 4194304\n\n\nclass ActivityType(Enum):\n unknown = -1\n playing = 0\n streaming = 1\n listening = 2\n watching = 3\n custom = 4\n competing = 5\n\n def __int__(self) -> int:\n return self.value\n\n\nclass TeamMembershipState(Enum):\n invited = 1\n accepted = 2\n\n\nclass TeamMemberRole(Enum):\n admin = 'admin'\n developer = 'developer'\n read_only = 'read_only'\n\n\nclass WebhookType(Enum):\n incoming = 1\n channel_follower = 2\n application = 3\n\n\nclass ExpireBehaviour(Enum):\n remove_role = 0\n kick = 1\n\n\nExpireBehavior = ExpireBehaviour\n\n\nclass StickerType(Enum):\n standard = 1\n guild = 2\n\n\nclass StickerFormatType(Enum):\n png = 1\n apng = 2\n lottie = 3\n gif = 4\n\n @property\n def file_extension(self) -> str:\n # fmt: off\n lookup: Dict[StickerFormatType, str] = {\n StickerFormatType.png: 'png',\n StickerFormatType.apng: 'png',\n StickerFormatType.lottie: 'json',\n StickerFormatType.gif: 'gif',\n }\n # fmt: on\n return lookup.get(self, 'png')\n\n\nclass InviteTarget(Enum):\n unknown = 0\n stream = 1\n embedded_application = 2\n\n\nclass InteractionType(Enum):\n ping = 1\n application_command = 2\n component = 3\n autocomplete = 4\n modal_submit = 5\n\n\nclass InteractionResponseType(Enum):\n pong = 1\n # ack = 2 (deprecated)\n # channel_message = 3 (deprecated)\n channel_message = 4 # (with source)\n deferred_channel_message = 5 # (with source)\n deferred_message_update = 6 # for components\n message_update = 7 # for components\n autocomplete_result = 8\n modal = 9 # for modals\n premium_required = 10\n\n\nclass VideoQualityMode(Enum):\n auto = 1\n full = 2\n\n def __int__(self) -> int:\n return self.value\n\n\nclass ComponentType(Enum):\n action_row = 1\n button = 2\n select = 3\n string_select = 3\n text_input = 4\n user_select = 5\n role_select = 6\n mentionable_select = 7\n channel_select = 8\n\n def __int__(self) -> int:\n return self.value\n\n\nclass ButtonStyle(Enum):\n primary = 1\n secondary = 2\n success = 3\n danger = 4\n link = 5\n\n # Aliases\n blurple = 1\n grey = 2\n gray = 2\n green = 3\n red = 4\n url = 5\n\n def __int__(self) -> int:\n return self.value\n\n\nclass TextStyle(Enum):\n short = 1\n paragraph = 2\n\n # Aliases\n long = 2\n\n def __int__(self) -> int:\n return self.value\n\n\nclass PrivacyLevel(Enum):\n guild_only = 2\n\n\nclass NSFWLevel(Enum, comparable=True):\n default = 0\n explicit = 1\n safe = 2\n age_restricted = 3\n\n\nclass MFALevel(Enum, comparable=True):\n disabled = 0\n require_2fa = 1\n\n\nclass Locale(Enum):\n american_english = 'en-US'\n british_english = 'en-GB'\n bulgarian = 'bg'\n chinese = 'zh-CN'\n taiwan_chinese = 'zh-TW'\n croatian = 'hr'\n czech = 'cs'\n indonesian = 'id'\n danish = 'da'\n dutch = 'nl'\n finnish = 'fi'\n french = 'fr'\n german = 'de'\n greek = 'el'\n hindi = 'hi'\n hungarian = 'hu'\n italian = 'it'\n japanese = 'ja'\n korean = 'ko'\n lithuanian = 'lt'\n norwegian = 'no'\n polish = 'pl'\n brazil_portuguese = 'pt-BR'\n romanian = 'ro'\n russian = 'ru'\n spain_spanish = 'es-ES'\n swedish = 'sv-SE'\n thai = 'th'\n turkish = 'tr'\n ukrainian = 'uk'\n vietnamese = 'vi'\n\n def __str__(self) -> str:\n return self.value\n\n\nE = TypeVar('E', bound='Enum')\n\n\nclass EntityType(Enum):\n stage_instance = 1\n voice = 2\n external = 3\n\n\nclass EventStatus(Enum):\n scheduled = 1\n active = 2\n completed = 3\n canceled = 4\n\n ended = 3\n cancelled = 4\n\n\nclass AppCommandOptionType(Enum):\n subcommand = 1\n subcommand_group = 2\n string = 3\n integer = 4\n boolean = 5\n user = 6\n channel = 7\n role = 8\n mentionable = 9\n number = 10\n attachment = 11\n\n\nclass AppCommandType(Enum):\n chat_input = 1\n user = 2\n message = 3\n\n\nclass AppCommandPermissionType(Enum):\n role = 1\n user = 2\n channel = 3\n\n\nclass AutoModRuleTriggerType(Enum):\n keyword = 1\n harmful_link = 2\n spam = 3\n keyword_preset = 4\n mention_spam = 5\n member_profile = 6\n\n\nclass AutoModRuleEventType(Enum):\n message_send = 1\n member_update = 2\n\n\nclass AutoModRuleActionType(Enum):\n block_message = 1\n send_alert_message = 2\n timeout = 3\n block_member_interactions = 4\n\n\nclass ForumLayoutType(Enum):\n not_set = 0\n list_view = 1\n gallery_view = 2\n\n\nclass ForumOrderType(Enum):\n latest_activity = 0\n creation_date = 1\n\n\nclass SelectDefaultValueType(Enum):\n user = 'user'\n role = 'role'\n channel = 'channel'\n\n\nclass SKUType(Enum):\n subscription = 5\n subscription_group = 6\n\n\nclass EntitlementType(Enum):\n application_subscription = 8\n\n\nclass EntitlementOwnerType(Enum):\n guild = 1\n user = 2\n\n\ndef create_unknown_value(cls: Type[E], val: Any) -> E:\n value_cls = cls._enum_value_cls_ # type: ignore # This is narrowed below\n name = f'unknown_{val}'\n return value_cls(name=name, value=val)\n\n\ndef try_enum(cls: Type[E], val: Any) -> E:\n \"\"\"A function that tries to turn the value into enum ``cls``.\n\n If it fails it returns a proxy invalid value instead.\n \"\"\"\n\n try:\n return cls._enum_value_map_[val] # type: ignore # All errors are caught below\n except (KeyError, TypeError, AttributeError):\n return create_unknown_value(cls, val)\n" }, { "path": "docs/api.rst", "content": ".. currentmodule:: discord\n\nAPI Reference\n===============\n\nThe following section outlines the API of discord.py.\n\n.. note::\n\n This module uses the Python logging module to log diagnostic and errors\n in an output independent way. If the logging module is not configured,\n these logs will not be output anywhere. See :ref:`logging_setup` for\n more information on how to set up and use the logging module with\n discord.py.\n\nVersion Related Info\n---------------------\n\nThere are two main ways to query version information about the library. For guarantees, check :ref:`version_guarantees`.\n\n.. data:: version_info\n\n A named tuple that is similar to :obj:`py:sys.version_info`.\n\n Just like :obj:`py:sys.version_info` the valid values for ``releaselevel`` are\n 'alpha', 'beta', 'candidate' and 'final'.\n\n.. data:: __version__\n\n A string representation of the version. e.g. ``'1.0.0rc1'``. This is based\n off of :pep:`440`.\n\nClients\n--------\n\nClient\n~~~~~~~\n\n.. attributetable:: Client\n\n.. autoclass:: Client\n :members:\n :exclude-members: event\n\n .. automethod:: Client.event()\n :decorator:\n\nAutoShardedClient\n~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: AutoShardedClient\n\n.. autoclass:: AutoShardedClient\n :members:\n\nApplication Info\n------------------\n\nAppInfo\n~~~~~~~~\n\n.. attributetable:: AppInfo\n\n.. autoclass:: AppInfo()\n :members:\n\nPartialAppInfo\n~~~~~~~~~~~~~~~\n\n.. attributetable:: PartialAppInfo\n\n.. autoclass:: PartialAppInfo()\n :members:\n\nAppInstallParams\n~~~~~~~~~~~~~~~~\n\n.. attributetable:: AppInstallParams\n\n.. autoclass:: AppInstallParams()\n :members:\n\nTeam\n~~~~~\n\n.. attributetable:: Team\n\n.. autoclass:: Team()\n :members:\n\nTeamMember\n~~~~~~~~~~~\n\n.. attributetable:: TeamMember\n\n.. autoclass:: TeamMember()\n :members:\n :inherited-members:\n\nVoice Related\n---------------\n\nVoiceClient\n~~~~~~~~~~~~\n\n.. attributetable:: VoiceClient\n\n.. autoclass:: VoiceClient()\n :members:\n :exclude-members: connect, on_voice_state_update, on_voice_server_update\n\nVoiceProtocol\n~~~~~~~~~~~~~~~\n\n.. attributetable:: VoiceProtocol\n\n.. autoclass:: VoiceProtocol\n :members:\n\nAudioSource\n~~~~~~~~~~~~\n\n.. attributetable:: AudioSource\n\n.. autoclass:: AudioSource\n :members:\n\nPCMAudio\n~~~~~~~~~\n\n.. attributetable:: PCMAudio\n\n.. autoclass:: PCMAudio\n :members:\n\nFFmpegAudio\n~~~~~~~~~~~~\n\n.. attributetable:: FFmpegAudio\n\n.. autoclass:: FFmpegAudio\n :members:\n\nFFmpegPCMAudio\n~~~~~~~~~~~~~~~\n\n.. attributetable:: FFmpegPCMAudio\n\n.. autoclass:: FFmpegPCMAudio\n :members:\n\nFFmpegOpusAudio\n~~~~~~~~~~~~~~~~\n\n.. attributetable:: FFmpegOpusAudio\n\n.. autoclass:: FFmpegOpusAudio\n :members:\n\nPCMVolumeTransformer\n~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: PCMVolumeTransformer\n\n.. autoclass:: PCMVolumeTransformer\n :members:\n\nOpus Library\n~~~~~~~~~~~~~\n\n.. autofunction:: discord.opus.load_opus\n\n.. autofunction:: discord.opus.is_loaded\n\n.. _discord-api-events:\n\nEvent Reference\n---------------\n\nThis section outlines the different types of events listened by :class:`Client`.\n\nThere are two ways to register an event, the first way is through the use of\n:meth:`Client.event`. The second way is through subclassing :class:`Client` and\noverriding the specific events. For example: ::\n\n import discord\n\n class MyClient(discord.Client):\n async def on_message(self, message):\n if message.author == self.user:\n return\n\n if message.content.startswith('$hello'):\n await message.channel.send('Hello World!')\n\n\nIf an event handler raises an exception, :func:`on_error` will be called\nto handle it, which defaults to logging the traceback and ignoring the exception.\n\n.. warning::\n\n All the events must be a |coroutine_link|_. If they aren't, then you might get unexpected\n errors. In order to turn a function into a coroutine they must be ``async def``\n functions.\n\nApp Commands\n~~~~~~~~~~~~~\n\n.. function:: on_raw_app_command_permissions_update(payload)\n\n Called when application command permissions are updated.\n\n .. versionadded:: 2.0\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawAppCommandPermissionsUpdateEvent`\n\n.. function:: on_app_command_completion(interaction, command)\n\n Called when a :class:`app_commands.Command` or :class:`app_commands.ContextMenu` has\n successfully completed without error.\n\n .. versionadded:: 2.0\n\n :param interaction: The interaction of the command.\n :type interaction: :class:`Interaction`\n :param command: The command that completed successfully\n :type command: Union[:class:`app_commands.Command`, :class:`app_commands.ContextMenu`]\n\nAutoMod\n~~~~~~~~\n\n.. function:: on_automod_rule_create(rule)\n\n Called when a :class:`AutoModRule` is created.\n You must have :attr:`~Permissions.manage_guild` to receive this.\n\n This requires :attr:`Intents.auto_moderation_configuration` to be enabled.\n\n .. versionadded:: 2.0\n\n :param rule: The rule that was created.\n :type rule: :class:`AutoModRule`\n\n.. function:: on_automod_rule_update(rule)\n\n Called when a :class:`AutoModRule` is updated.\n You must have :attr:`~Permissions.manage_guild` to receive this.\n\n This requires :attr:`Intents.auto_moderation_configuration` to be enabled.\n\n .. versionadded:: 2.0\n\n :param rule: The rule that was updated.\n :type rule: :class:`AutoModRule`\n\n.. function:: on_automod_rule_delete(rule)\n\n Called when a :class:`AutoModRule` is deleted.\n You must have :attr:`~Permissions.manage_guild` to receive this.\n\n This requires :attr:`Intents.auto_moderation_configuration` to be enabled.\n\n .. versionadded:: 2.0\n\n :param rule: The rule that was deleted.\n :type rule: :class:`AutoModRule`\n\n.. function:: on_automod_action(execution)\n\n Called when a :class:`AutoModAction` is created/performed.\n You must have :attr:`~Permissions.manage_guild` to receive this.\n\n This requires :attr:`Intents.auto_moderation_execution` to be enabled.\n\n .. versionadded:: 2.0\n\n :param execution: The rule execution that was performed.\n :type execution: :class:`AutoModAction`\n\nChannels\n~~~~~~~~~\n\n.. function:: on_guild_channel_delete(channel)\n on_guild_channel_create(channel)\n\n Called whenever a guild channel is deleted or created.\n\n Note that you can get the guild from :attr:`~abc.GuildChannel.guild`.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n :param channel: The guild channel that got created or deleted.\n :type channel: :class:`abc.GuildChannel`\n\n.. function:: on_guild_channel_update(before, after)\n\n Called whenever a guild channel is updated. e.g. changed name, topic, permissions.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n :param before: The updated guild channel's old info.\n :type before: :class:`abc.GuildChannel`\n :param after: The updated guild channel's new info.\n :type after: :class:`abc.GuildChannel`\n\n.. function:: on_guild_channel_pins_update(channel, last_pin)\n\n Called whenever a message is pinned or unpinned from a guild channel.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n :param channel: The guild channel that had its pins updated.\n :type channel: Union[:class:`abc.GuildChannel`, :class:`Thread`]\n :param last_pin: The latest message that was pinned as an aware datetime in UTC. Could be ``None``.\n :type last_pin: Optional[:class:`datetime.datetime`]\n\n.. function:: on_private_channel_update(before, after)\n\n Called whenever a private group DM is updated. e.g. changed name or topic.\n\n This requires :attr:`Intents.messages` to be enabled.\n\n :param before: The updated group channel's old info.\n :type before: :class:`GroupChannel`\n :param after: The updated group channel's new info.\n :type after: :class:`GroupChannel`\n\n.. function:: on_private_channel_pins_update(channel, last_pin)\n\n Called whenever a message is pinned or unpinned from a private channel.\n\n :param channel: The private channel that had its pins updated.\n :type channel: :class:`abc.PrivateChannel`\n :param last_pin: The latest message that was pinned as an aware datetime in UTC. Could be ``None``.\n :type last_pin: Optional[:class:`datetime.datetime`]\n\n.. function:: on_typing(channel, user, when)\n\n Called when someone begins typing a message.\n\n The ``channel`` parameter can be a :class:`abc.Messageable` instance.\n Which could either be :class:`TextChannel`, :class:`GroupChannel`, or\n :class:`DMChannel`.\n\n If the ``channel`` is a :class:`TextChannel` then the ``user`` parameter\n is a :class:`Member`, otherwise it is a :class:`User`.\n\n If the channel or user could not be found in the internal cache this event\n will not be called, you may use :func:`on_raw_typing` instead.\n\n This requires :attr:`Intents.typing` to be enabled.\n\n :param channel: The location where the typing originated from.\n :type channel: :class:`abc.Messageable`\n :param user: The user that started typing.\n :type user: Union[:class:`User`, :class:`Member`]\n :param when: When the typing started as an aware datetime in UTC.\n :type when: :class:`datetime.datetime`\n\n.. function:: on_raw_typing(payload)\n\n Called when someone begins typing a message. Unlike :func:`on_typing` this\n is called regardless of the channel and user being in the internal cache.\n\n This requires :attr:`Intents.typing` to be enabled.\n\n .. versionadded:: 2.0\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawTypingEvent`\n\nConnection\n~~~~~~~~~~~\n\n.. function:: on_connect()\n\n Called when the client has successfully connected to Discord. This is not\n the same as the client being fully prepared, see :func:`on_ready` for that.\n\n The warnings on :func:`on_ready` also apply.\n\n.. function:: on_disconnect()\n\n Called when the client has disconnected from Discord, or a connection attempt to Discord has failed.\n This could happen either through the internet being disconnected, explicit calls to close,\n or Discord terminating the connection one way or the other.\n\n This function can be called many times without a corresponding :func:`on_connect` call.\n\n.. function:: on_shard_connect(shard_id)\n\n Similar to :func:`on_connect` except used by :class:`AutoShardedClient`\n to denote when a particular shard ID has connected to Discord.\n\n .. versionadded:: 1.4\n\n :param shard_id: The shard ID that has connected.\n :type shard_id: :class:`int`\n\n\n.. function:: on_shard_disconnect(shard_id)\n\n Similar to :func:`on_disconnect` except used by :class:`AutoShardedClient`\n to denote when a particular shard ID has disconnected from Discord.\n\n .. versionadded:: 1.4\n\n :param shard_id: The shard ID that has disconnected.\n :type shard_id: :class:`int`\n\nDebug\n~~~~~~\n\n.. function:: on_error(event, *args, **kwargs)\n\n Usually when an event raises an uncaught exception, a traceback is\n logged to stderr and the exception is ignored. If you want to\n change this behaviour and handle the exception for whatever reason\n yourself, this event can be overridden. Which, when done, will\n suppress the default action of printing the traceback.\n\n The information of the exception raised and the exception itself can\n be retrieved with a standard call to :func:`sys.exc_info`.\n\n .. note::\n\n ``on_error`` will only be dispatched to :meth:`Client.event`.\n\n It will not be received by :meth:`Client.wait_for`, or, if used,\n :ref:`ext_commands_api_bot` listeners such as\n :meth:`~ext.commands.Bot.listen` or :meth:`~ext.commands.Cog.listener`.\n\n .. versionchanged:: 2.0\n\n The traceback is now logged rather than printed.\n\n :param event: The name of the event that raised the exception.\n :type event: :class:`str`\n\n :param args: The positional arguments for the event that raised the\n exception.\n :param kwargs: The keyword arguments for the event that raised the\n exception.\n\n.. function:: on_socket_event_type(event_type)\n\n Called whenever a websocket event is received from the WebSocket.\n\n This is mainly useful for logging how many events you are receiving\n from the Discord gateway.\n\n .. versionadded:: 2.0\n\n :param event_type: The event type from Discord that is received, e.g. ``'READY'``.\n :type event_type: :class:`str`\n\n.. function:: on_socket_raw_receive(msg)\n\n Called whenever a message is completely received from the WebSocket, before\n it's processed and parsed. This event is always dispatched when a\n complete message is received and the passed data is not parsed in any way.\n\n This is only really useful for grabbing the WebSocket stream and\n debugging purposes.\n\n This requires setting the ``enable_debug_events`` setting in the :class:`Client`.\n\n .. note::\n\n This is only for the messages received from the client\n WebSocket. The voice WebSocket will not trigger this event.\n\n :param msg: The message passed in from the WebSocket library.\n :type msg: :class:`str`\n\n.. function:: on_socket_raw_send(payload)\n\n Called whenever a send operation is done on the WebSocket before the\n message is sent. The passed parameter is the message that is being\n sent to the WebSocket.\n\n This is only really useful for grabbing the WebSocket stream and\n debugging purposes.\n\n This requires setting the ``enable_debug_events`` setting in the :class:`Client`.\n\n .. note::\n\n This is only for the messages sent from the client\n WebSocket. The voice WebSocket will not trigger this event.\n\n :param payload: The message that is about to be passed on to the\n WebSocket library. It can be :class:`bytes` to denote a binary\n message or :class:`str` to denote a regular text message.\n :type payload: Union[:class:`bytes`, :class:`str`]\n\n\nEntitlements\n~~~~~~~~~~~~\n\n.. function:: on_entitlement_create(entitlement)\n\n Called when a user subscribes to a SKU.\n\n .. versionadded:: 2.4\n\n :param entitlement: The entitlement that was created.\n :type entitlement: :class:`Entitlement`\n\n.. function:: on_entitlement_update(entitlement)\n\n Called when a user updates their subscription to a SKU. This is usually called when\n the user renews or cancels their subscription.\n\n .. versionadded:: 2.4\n\n :param entitlement: The entitlement that was updated.\n :type entitlement: :class:`Entitlement`\n\n.. function:: on_entitlement_delete(entitlement)\n\n Called when a users subscription to a SKU is cancelled. This is typically only called when:\n\n - Discord issues a refund for the subscription.\n - Discord removes an entitlement from a user.\n\n .. warning::\n\n This event won't be called if the user cancels their subscription manually, instead\n :func:`on_entitlement_update` will be called with :attr:`Entitlement.ends_at` set to the end of the\n current billing period.\n\n .. versionadded:: 2.4\n\n :param entitlement: The entitlement that was deleted.\n :type entitlement: :class:`Entitlement`\n\n\nGateway\n~~~~~~~~\n\n.. function:: on_ready()\n\n Called when the client is done preparing the data received from Discord. Usually after login is successful\n and the :attr:`Client.guilds` and co. are filled up.\n\n .. warning::\n\n This function is not guaranteed to be the first event called.\n Likewise, this function is **not** guaranteed to only be called\n once. This library implements reconnection logic and thus will\n end up calling this event whenever a RESUME request fails.\n\n.. function:: on_resumed()\n\n Called when the client has resumed a session.\n\n.. function:: on_shard_ready(shard_id)\n\n Similar to :func:`on_ready` except used by :class:`AutoShardedClient`\n to denote when a particular shard ID has become ready.\n\n :param shard_id: The shard ID that is ready.\n :type shard_id: :class:`int`\n\n\n.. function:: on_shard_resumed(shard_id)\n\n Similar to :func:`on_resumed` except used by :class:`AutoShardedClient`\n to denote when a particular shard ID has resumed a session.\n\n .. versionadded:: 1.4\n\n :param shard_id: The shard ID that has resumed.\n :type shard_id: :class:`int`\n\nGuilds\n~~~~~~~\n\n.. function:: on_guild_available(guild)\n on_guild_unavailable(guild)\n\n Called when a guild becomes available or unavailable. The guild must have\n existed in the :attr:`Client.guilds` cache.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n :param guild: The :class:`Guild` that has changed availability.\n\n.. function:: on_guild_join(guild)\n\n Called when a :class:`Guild` is either created by the :class:`Client` or when the\n :class:`Client` joins a guild.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n :param guild: The guild that was joined.\n :type guild: :class:`Guild`\n\n.. function:: on_guild_remove(guild)\n\n Called when a :class:`Guild` is removed from the :class:`Client`.\n\n This happens through, but not limited to, these circumstances:\n\n - The client got banned.\n - The client got kicked.\n - The client left the guild.\n - The client or the guild owner deleted the guild.\n\n In order for this event to be invoked then the :class:`Client` must have\n been part of the guild to begin with. (i.e. it is part of :attr:`Client.guilds`)\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n :param guild: The guild that got removed.\n :type guild: :class:`Guild`\n\n.. function:: on_guild_update(before, after)\n\n Called when a :class:`Guild` updates, for example:\n\n - Changed name\n - Changed AFK channel\n - Changed AFK timeout\n - etc\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n :param before: The guild prior to being updated.\n :type before: :class:`Guild`\n :param after: The guild after being updated.\n :type after: :class:`Guild`\n\n.. function:: on_guild_emojis_update(guild, before, after)\n\n Called when a :class:`Guild` adds or removes :class:`Emoji`.\n\n This requires :attr:`Intents.emojis_and_stickers` to be enabled.\n\n :param guild: The guild who got their emojis updated.\n :type guild: :class:`Guild`\n :param before: A list of emojis before the update.\n :type before: Sequence[:class:`Emoji`]\n :param after: A list of emojis after the update.\n :type after: Sequence[:class:`Emoji`]\n\n.. function:: on_guild_stickers_update(guild, before, after)\n\n Called when a :class:`Guild` updates its stickers.\n\n This requires :attr:`Intents.emojis_and_stickers` to be enabled.\n\n .. versionadded:: 2.0\n\n :param guild: The guild who got their stickers updated.\n :type guild: :class:`Guild`\n :param before: A list of stickers before the update.\n :type before: Sequence[:class:`GuildSticker`]\n :param after: A list of stickers after the update.\n :type after: Sequence[:class:`GuildSticker`]\n\n.. function:: on_audit_log_entry_create(entry)\n\n Called when a :class:`Guild` gets a new audit log entry.\n You must have :attr:`~Permissions.view_audit_log` to receive this.\n\n This requires :attr:`Intents.moderation` to be enabled.\n\n .. versionadded:: 2.2\n\n .. warning::\n\n Audit log entries received through the gateway are subject to data retrieval\n from cache rather than REST. This means that some data might not be present\n when you expect it to be. For example, the :attr:`AuditLogEntry.target`\n attribute will usually be a :class:`discord.Object` and the\n :attr:`AuditLogEntry.user` attribute will depend on user and member cache.\n\n To get the user ID of entry, :attr:`AuditLogEntry.user_id` can be used instead.\n\n :param entry: The audit log entry that was created.\n :type entry: :class:`AuditLogEntry`\n\n.. function:: on_invite_create(invite)\n\n Called when an :class:`Invite` is created.\n You must have :attr:`~Permissions.manage_channels` to receive this.\n\n .. versionadded:: 1.3\n\n .. note::\n\n There is a rare possibility that the :attr:`Invite.guild` and :attr:`Invite.channel`\n attributes will be of :class:`Object` rather than the respective models.\n\n This requires :attr:`Intents.invites` to be enabled.\n\n :param invite: The invite that was created.\n :type invite: :class:`Invite`\n\n.. function:: on_invite_delete(invite)\n\n Called when an :class:`Invite` is deleted.\n You must have :attr:`~Permissions.manage_channels` to receive this.\n\n .. versionadded:: 1.3\n\n .. note::\n\n There is a rare possibility that the :attr:`Invite.guild` and :attr:`Invite.channel`\n attributes will be of :class:`Object` rather than the respective models.\n\n Outside of those two attributes, the only other attribute guaranteed to be\n filled by the Discord gateway for this event is :attr:`Invite.code`.\n\n This requires :attr:`Intents.invites` to be enabled.\n\n :param invite: The invite that was deleted.\n :type invite: :class:`Invite`\n\n\nIntegrations\n~~~~~~~~~~~~~\n\n.. function:: on_integration_create(integration)\n\n Called when an integration is created.\n\n This requires :attr:`Intents.integrations` to be enabled.\n\n .. versionadded:: 2.0\n\n :param integration: The integration that was created.\n :type integration: :class:`Integration`\n\n.. function:: on_integration_update(integration)\n\n Called when an integration is updated.\n\n This requires :attr:`Intents.integrations` to be enabled.\n\n .. versionadded:: 2.0\n\n :param integration: The integration that was updated.\n :type integration: :class:`Integration`\n\n.. function:: on_guild_integrations_update(guild)\n\n Called whenever an integration is created, modified, or removed from a guild.\n\n This requires :attr:`Intents.integrations` to be enabled.\n\n .. versionadded:: 1.4\n\n :param guild: The guild that had its integrations updated.\n :type guild: :class:`Guild`\n\n.. function:: on_webhooks_update(channel)\n\n Called whenever a webhook is created, modified, or removed from a guild channel.\n\n This requires :attr:`Intents.webhooks` to be enabled.\n\n :param channel: The channel that had its webhooks updated.\n :type channel: :class:`abc.GuildChannel`\n\n.. function:: on_raw_integration_delete(payload)\n\n Called when an integration is deleted.\n\n This requires :attr:`Intents.integrations` to be enabled.\n\n .. versionadded:: 2.0\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawIntegrationDeleteEvent`\n\nInteractions\n~~~~~~~~~~~~~\n\n.. function:: on_interaction(interaction)\n\n Called when an interaction happened.\n\n This currently happens due to slash command invocations or components being used.\n\n .. warning::\n\n This is a low level function that is not generally meant to be used.\n If you are working with components, consider using the callbacks associated\n with the :class:`~discord.ui.View` instead as it provides a nicer user experience.\n\n .. versionadded:: 2.0\n\n :param interaction: The interaction data.\n :type interaction: :class:`Interaction`\n\nMembers\n~~~~~~~~\n\n.. function:: on_member_join(member)\n\n Called when a :class:`Member` joins a :class:`Guild`.\n\n This requires :attr:`Intents.members` to be enabled.\n\n :param member: The member who joined.\n :type member: :class:`Member`\n\n.. function:: on_member_remove(member)\n\n Called when a :class:`Member` leaves a :class:`Guild`.\n\n If the guild or member could not be found in the internal cache this event\n will not be called, you may use :func:`on_raw_member_remove` instead.\n\n This requires :attr:`Intents.members` to be enabled.\n\n :param member: The member who left.\n :type member: :class:`Member`\n\n.. function:: on_raw_member_remove(payload)\n\n Called when a :class:`Member` leaves a :class:`Guild`.\n\n Unlike :func:`on_member_remove`\n this is called regardless of the guild or member being in the internal cache.\n\n This requires :attr:`Intents.members` to be enabled.\n\n .. versionadded:: 2.0\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawMemberRemoveEvent`\n\n.. function:: on_member_update(before, after)\n\n Called when a :class:`Member` updates their profile.\n\n This is called when one or more of the following things change:\n\n - nickname\n - roles\n - pending\n - timeout\n - guild avatar\n - flags\n\n Due to a Discord limitation, this event is not dispatched when a member's timeout expires.\n\n This requires :attr:`Intents.members` to be enabled.\n\n :param before: The updated member's old info.\n :type before: :class:`Member`\n :param after: The updated member's updated info.\n :type after: :class:`Member`\n\n.. function:: on_user_update(before, after)\n\n Called when a :class:`User` updates their profile.\n\n This is called when one or more of the following things change:\n\n - avatar\n - username\n - discriminator\n\n This requires :attr:`Intents.members` to be enabled.\n\n :param before: The updated user's old info.\n :type before: :class:`User`\n :param after: The updated user's updated info.\n :type after: :class:`User`\n\n.. function:: on_member_ban(guild, user)\n\n Called when a user gets banned from a :class:`Guild`.\n\n This requires :attr:`Intents.moderation` to be enabled.\n\n :param guild: The guild the user got banned from.\n :type guild: :class:`Guild`\n :param user: The user that got banned.\n Can be either :class:`User` or :class:`Member` depending if\n the user was in the guild or not at the time of removal.\n :type user: Union[:class:`User`, :class:`Member`]\n\n.. function:: on_member_unban(guild, user)\n\n Called when a :class:`User` gets unbanned from a :class:`Guild`.\n\n This requires :attr:`Intents.moderation` to be enabled.\n\n :param guild: The guild the user got unbanned from.\n :type guild: :class:`Guild`\n :param user: The user that got unbanned.\n :type user: :class:`User`\n\n.. function:: on_presence_update(before, after)\n\n Called when a :class:`Member` updates their presence.\n\n This is called when one or more of the following things change:\n\n - status\n - activity\n\n This requires :attr:`Intents.presences` and :attr:`Intents.members` to be enabled.\n\n .. versionadded:: 2.0\n\n :param before: The updated member's old info.\n :type before: :class:`Member`\n :param after: The updated member's updated info.\n :type after: :class:`Member`\n\nMessages\n~~~~~~~~~\n\n.. function:: on_message(message)\n\n Called when a :class:`Message` is created and sent.\n\n This requires :attr:`Intents.messages` to be enabled.\n\n .. warning::\n\n Your bot's own messages and private messages are sent through this\n event. This can lead cases of 'recursion' depending on how your bot was\n programmed. If you want the bot to not reply to itself, consider\n checking the user IDs. Note that :class:`~ext.commands.Bot` does not\n have this problem.\n\n :param message: The current message.\n :type message: :class:`Message`\n\n.. function:: on_message_edit(before, after)\n\n Called when a :class:`Message` receives an update event. If the message is not found\n in the internal message cache, then these events will not be called.\n Messages might not be in cache if the message is too old\n or the client is participating in high traffic guilds.\n\n If this occurs increase the :class:`max_messages ` parameter\n or use the :func:`on_raw_message_edit` event instead.\n\n The following non-exhaustive cases trigger this event:\n\n - A message has been pinned or unpinned.\n - The message content has been changed.\n - The message has received an embed.\n\n - For performance reasons, the embed server does not do this in a \"consistent\" manner.\n\n - The message's embeds were suppressed or unsuppressed.\n - A call message has received an update to its participants or ending time.\n\n This requires :attr:`Intents.messages` to be enabled.\n\n :param before: The previous version of the message.\n :type before: :class:`Message`\n :param after: The current version of the message.\n :type after: :class:`Message`\n\n.. function:: on_message_delete(message)\n\n Called when a message is deleted. If the message is not found in the\n internal message cache, then this event will not be called.\n Messages might not be in cache if the message is too old\n or the client is participating in high traffic guilds.\n\n If this occurs increase the :class:`max_messages ` parameter\n or use the :func:`on_raw_message_delete` event instead.\n\n This requires :attr:`Intents.messages` to be enabled.\n\n :param message: The deleted message.\n :type message: :class:`Message`\n\n.. function:: on_bulk_message_delete(messages)\n\n Called when messages are bulk deleted. If none of the messages deleted\n are found in the internal message cache, then this event will not be called.\n If individual messages were not found in the internal message cache,\n this event will still be called, but the messages not found will not be included in\n the messages list. Messages might not be in cache if the message is too old\n or the client is participating in high traffic guilds.\n\n If this occurs increase the :class:`max_messages ` parameter\n or use the :func:`on_raw_bulk_message_delete` event instead.\n\n This requires :attr:`Intents.messages` to be enabled.\n\n :param messages: The messages that have been deleted.\n :type messages: List[:class:`Message`]\n\n.. function:: on_raw_message_edit(payload)\n\n Called when a message is edited. Unlike :func:`on_message_edit`, this is called\n regardless of the state of the internal message cache.\n\n If the message is found in the message cache,\n it can be accessed via :attr:`RawMessageUpdateEvent.cached_message`. The cached message represents\n the message before it has been edited. For example, if the content of a message is modified and\n triggers the :func:`on_raw_message_edit` coroutine, the :attr:`RawMessageUpdateEvent.cached_message`\n will return a :class:`Message` object that represents the message before the content was modified.\n\n Due to the inherently raw nature of this event, the data parameter coincides with\n the raw data given by the :ddocs:`gateway `.\n\n Since the data payload can be partial, care must be taken when accessing stuff in the dictionary.\n One example of a common case of partial data is when the ``'content'`` key is inaccessible. This\n denotes an \"embed\" only edit, which is an edit in which only the embeds are updated by the Discord\n embed server.\n\n This requires :attr:`Intents.messages` to be enabled.\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawMessageUpdateEvent`\n\n\n.. function:: on_raw_message_delete(payload)\n\n Called when a message is deleted. Unlike :func:`on_message_delete`, this is\n called regardless of the message being in the internal message cache or not.\n\n If the message is found in the message cache,\n it can be accessed via :attr:`RawMessageDeleteEvent.cached_message`\n\n This requires :attr:`Intents.messages` to be enabled.\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawMessageDeleteEvent`\n\n.. function:: on_raw_bulk_message_delete(payload)\n\n Called when a bulk delete is triggered. Unlike :func:`on_bulk_message_delete`, this is\n called regardless of the messages being in the internal message cache or not.\n\n If the messages are found in the message cache,\n they can be accessed via :attr:`RawBulkMessageDeleteEvent.cached_messages`\n\n This requires :attr:`Intents.messages` to be enabled.\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawBulkMessageDeleteEvent`\n\nReactions\n~~~~~~~~~~\n\n.. function:: on_reaction_add(reaction, user)\n\n Called when a message has a reaction added to it. Similar to :func:`on_message_edit`,\n if the message is not found in the internal message cache, then this\n event will not be called. Consider using :func:`on_raw_reaction_add` instead.\n\n .. note::\n\n To get the :class:`Message` being reacted, access it via :attr:`Reaction.message`.\n\n This requires :attr:`Intents.reactions` to be enabled.\n\n .. note::\n\n This doesn't require :attr:`Intents.members` within a guild context,\n but due to Discord not providing updated user information in a direct message\n it's required for direct messages to receive this event.\n Consider using :func:`on_raw_reaction_add` if you need this and do not otherwise want\n to enable the members intent.\n\n .. warning::\n\n This event does not have a way of differentiating whether a reaction is a\n burst reaction (also known as \"super reaction\") or not. If you need this,\n consider using :func:`on_raw_reaction_add` instead.\n\n :param reaction: The current state of the reaction.\n :type reaction: :class:`Reaction`\n :param user: The user who added the reaction.\n :type user: Union[:class:`Member`, :class:`User`]\n\n.. function:: on_reaction_remove(reaction, user)\n\n Called when a message has a reaction removed from it. Similar to on_message_edit,\n if the message is not found in the internal message cache, then this event\n will not be called.\n\n .. note::\n\n To get the message being reacted, access it via :attr:`Reaction.message`.\n\n This requires both :attr:`Intents.reactions` and :attr:`Intents.members` to be enabled.\n\n .. note::\n\n Consider using :func:`on_raw_reaction_remove` if you need this and do not want\n to enable the members intent.\n\n .. warning::\n\n This event does not have a way of differentiating whether a reaction is a\n burst reaction (also known as \"super reaction\") or not. If you need this,\n consider using :func:`on_raw_reaction_remove` instead.\n\n :param reaction: The current state of the reaction.\n :type reaction: :class:`Reaction`\n :param user: The user whose reaction was removed.\n :type user: Union[:class:`Member`, :class:`User`]\n\n.. function:: on_reaction_clear(message, reactions)\n\n Called when a message has all its reactions removed from it. Similar to :func:`on_message_edit`,\n if the message is not found in the internal message cache, then this event\n will not be called. Consider using :func:`on_raw_reaction_clear` instead.\n\n This requires :attr:`Intents.reactions` to be enabled.\n\n :param message: The message that had its reactions cleared.\n :type message: :class:`Message`\n :param reactions: The reactions that were removed.\n :type reactions: List[:class:`Reaction`]\n\n.. function:: on_reaction_clear_emoji(reaction)\n\n Called when a message has a specific reaction removed from it. Similar to :func:`on_message_edit`,\n if the message is not found in the internal message cache, then this event\n will not be called. Consider using :func:`on_raw_reaction_clear_emoji` instead.\n\n This requires :attr:`Intents.reactions` to be enabled.\n\n .. versionadded:: 1.3\n\n :param reaction: The reaction that got cleared.\n :type reaction: :class:`Reaction`\n\n\n.. function:: on_raw_reaction_add(payload)\n\n Called when a message has a reaction added. Unlike :func:`on_reaction_add`, this is\n called regardless of the state of the internal message cache.\n\n This requires :attr:`Intents.reactions` to be enabled.\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawReactionActionEvent`\n\n.. function:: on_raw_reaction_remove(payload)\n\n Called when a message has a reaction removed. Unlike :func:`on_reaction_remove`, this is\n called regardless of the state of the internal message cache.\n\n This requires :attr:`Intents.reactions` to be enabled.\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawReactionActionEvent`\n\n.. function:: on_raw_reaction_clear(payload)\n\n Called when a message has all its reactions removed. Unlike :func:`on_reaction_clear`,\n this is called regardless of the state of the internal message cache.\n\n This requires :attr:`Intents.reactions` to be enabled.\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawReactionClearEvent`\n\n.. function:: on_raw_reaction_clear_emoji(payload)\n\n Called when a message has a specific reaction removed from it. Unlike :func:`on_reaction_clear_emoji` this is called\n regardless of the state of the internal message cache.\n\n This requires :attr:`Intents.reactions` to be enabled.\n\n .. versionadded:: 1.3\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawReactionClearEmojiEvent`\n\n\nRoles\n~~~~~~\n\n.. function:: on_guild_role_create(role)\n on_guild_role_delete(role)\n\n Called when a :class:`Guild` creates or deletes a new :class:`Role`.\n\n To get the guild it belongs to, use :attr:`Role.guild`.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n :param role: The role that was created or deleted.\n :type role: :class:`Role`\n\n.. function:: on_guild_role_update(before, after)\n\n Called when a :class:`Role` is changed guild-wide.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n :param before: The updated role's old info.\n :type before: :class:`Role`\n :param after: The updated role's updated info.\n :type after: :class:`Role`\n\n\nScheduled Events\n~~~~~~~~~~~~~~~~~\n\n.. function:: on_scheduled_event_create(event)\n on_scheduled_event_delete(event)\n\n Called when a :class:`ScheduledEvent` is created or deleted.\n\n This requires :attr:`Intents.guild_scheduled_events` to be enabled.\n\n .. versionadded:: 2.0\n\n :param event: The scheduled event that was created or deleted.\n :type event: :class:`ScheduledEvent`\n\n.. function:: on_scheduled_event_update(before, after)\n\n Called when a :class:`ScheduledEvent` is updated.\n\n This requires :attr:`Intents.guild_scheduled_events` to be enabled.\n\n The following, but not limited to, examples illustrate when this event is called:\n\n - The scheduled start/end times are changed.\n - The channel is changed.\n - The description is changed.\n - The status is changed.\n - The image is changed.\n\n .. versionadded:: 2.0\n\n :param before: The scheduled event before the update.\n :type before: :class:`ScheduledEvent`\n :param after: The scheduled event after the update.\n :type after: :class:`ScheduledEvent`\n\n.. function:: on_scheduled_event_user_add(event, user)\n on_scheduled_event_user_remove(event, user)\n\n Called when a user is added or removed from a :class:`ScheduledEvent`.\n\n This requires :attr:`Intents.guild_scheduled_events` to be enabled.\n\n .. versionadded:: 2.0\n\n :param event: The scheduled event that the user was added or removed from.\n :type event: :class:`ScheduledEvent`\n :param user: The user that was added or removed.\n :type user: :class:`User`\n\n\nStages\n~~~~~~~\n\n.. function:: on_stage_instance_create(stage_instance)\n on_stage_instance_delete(stage_instance)\n\n Called when a :class:`StageInstance` is created or deleted for a :class:`StageChannel`.\n\n .. versionadded:: 2.0\n\n :param stage_instance: The stage instance that was created or deleted.\n :type stage_instance: :class:`StageInstance`\n\n.. function:: on_stage_instance_update(before, after)\n\n Called when a :class:`StageInstance` is updated.\n\n The following, but not limited to, examples illustrate when this event is called:\n\n - The topic is changed.\n - The privacy level is changed.\n\n .. versionadded:: 2.0\n\n :param before: The stage instance before the update.\n :type before: :class:`StageInstance`\n :param after: The stage instance after the update.\n :type after: :class:`StageInstance`\n\nThreads\n~~~~~~~~\n\n.. function:: on_thread_create(thread)\n\n Called whenever a thread is created.\n\n Note that you can get the guild from :attr:`Thread.guild`.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n .. versionadded:: 2.0\n\n :param thread: The thread that was created.\n :type thread: :class:`Thread`\n\n.. function:: on_thread_join(thread)\n\n Called whenever a thread is joined.\n\n Note that you can get the guild from :attr:`Thread.guild`.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n .. versionadded:: 2.0\n\n :param thread: The thread that got joined.\n :type thread: :class:`Thread`\n\n.. function:: on_thread_update(before, after)\n\n Called whenever a thread is updated. If the thread could\n not be found in the internal cache this event will not be called.\n Threads will not be in the cache if they are archived.\n\n If you need this information use :func:`on_raw_thread_update` instead.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n .. versionadded:: 2.0\n\n :param before: The updated thread's old info.\n :type before: :class:`Thread`\n :param after: The updated thread's new info.\n :type after: :class:`Thread`\n\n.. function:: on_thread_remove(thread)\n\n Called whenever a thread is removed. This is different from a thread being deleted.\n\n Note that you can get the guild from :attr:`Thread.guild`.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n .. warning::\n\n Due to technical limitations, this event might not be called\n as soon as one expects. Since the library tracks thread membership\n locally, the API only sends updated thread membership status upon being\n synced by joining a thread.\n\n .. versionadded:: 2.0\n\n :param thread: The thread that got removed.\n :type thread: :class:`Thread`\n\n.. function:: on_thread_delete(thread)\n\n Called whenever a thread is deleted. If the thread could\n not be found in the internal cache this event will not be called.\n Threads will not be in the cache if they are archived.\n\n If you need this information use :func:`on_raw_thread_delete` instead.\n\n Note that you can get the guild from :attr:`Thread.guild`.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n .. versionadded:: 2.0\n\n :param thread: The thread that got deleted.\n :type thread: :class:`Thread`\n\n.. function:: on_raw_thread_update(payload)\n\n Called whenever a thread is updated. Unlike :func:`on_thread_update` this\n is called regardless of the thread being in the internal thread cache or not.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n .. versionadded:: 2.0\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawThreadUpdateEvent`\n\n.. function:: on_raw_thread_delete(payload)\n\n Called whenever a thread is deleted. Unlike :func:`on_thread_delete` this\n is called regardless of the thread being in the internal thread cache or not.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n .. versionadded:: 2.0\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawThreadDeleteEvent`\n\n.. function:: on_thread_member_join(member)\n on_thread_member_remove(member)\n\n Called when a :class:`ThreadMember` leaves or joins a :class:`Thread`.\n\n You can get the thread a member belongs in by accessing :attr:`ThreadMember.thread`.\n\n This requires :attr:`Intents.members` to be enabled.\n\n .. versionadded:: 2.0\n\n :param member: The member who joined or left.\n :type member: :class:`ThreadMember`\n\n.. function:: on_raw_thread_member_remove(payload)\n\n Called when a :class:`ThreadMember` leaves a :class:`Thread`. Unlike :func:`on_thread_member_remove` this\n is called regardless of the member being in the internal thread's members cache or not.\n\n This requires :attr:`Intents.members` to be enabled.\n\n .. versionadded:: 2.0\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawThreadMembersUpdate`\n\nVoice\n~~~~~~\n\n.. function:: on_voice_state_update(member, before, after)\n\n Called when a :class:`Member` changes their :class:`VoiceState`.\n\n The following, but not limited to, examples illustrate when this event is called:\n\n - A member joins a voice or stage channel.\n - A member leaves a voice or stage channel.\n - A member is muted or deafened by their own accord.\n - A member is muted or deafened by a guild administrator.\n\n This requires :attr:`Intents.voice_states` to be enabled.\n\n :param member: The member whose voice states changed.\n :type member: :class:`Member`\n :param before: The voice state prior to the changes.\n :type before: :class:`VoiceState`\n :param after: The voice state after the changes.\n :type after: :class:`VoiceState`\n\n.. _discord-api-utils:\n\nUtility Functions\n-----------------\n\n.. autofunction:: discord.utils.find\n\n.. autofunction:: discord.utils.get\n\n.. autofunction:: discord.utils.setup_logging\n\n.. autofunction:: discord.utils.maybe_coroutine\n\n.. autofunction:: discord.utils.snowflake_time\n\n.. autofunction:: discord.utils.time_snowflake\n\n.. autofunction:: discord.utils.oauth_url\n\n.. autofunction:: discord.utils.remove_markdown\n\n.. autofunction:: discord.utils.escape_markdown\n\n.. autofunction:: discord.utils.escape_mentions\n\n.. class:: ResolvedInvite\n\n A data class which represents a resolved invite returned from :func:`discord.utils.resolve_invite`.\n\n .. attribute:: code\n\n The invite code.\n\n :type: :class:`str`\n\n .. attribute:: event\n\n The id of the scheduled event that the invite refers to.\n\n :type: Optional[:class:`int`]\n\n.. autofunction:: discord.utils.resolve_invite\n\n.. autofunction:: discord.utils.resolve_template\n\n.. autofunction:: discord.utils.sleep_until\n\n.. autofunction:: discord.utils.utcnow\n\n.. autofunction:: discord.utils.format_dt\n\n.. autofunction:: discord.utils.as_chunks\n\n.. data:: MISSING\n :module: discord.utils\n\n A type safe sentinel used in the library to represent something as missing. Used to distinguish from ``None`` values.\n\n .. versionadded:: 2.0\n\n.. _discord-api-enums:\n\nEnumerations\n-------------\n\nThe API provides some enumerations for certain types of strings to avoid the API\nfrom being stringly typed in case the strings change in the future.\n\nAll enumerations are subclasses of an internal class which mimics the behaviour\nof :class:`enum.Enum`.\n\n.. class:: ChannelType\n\n Specifies the type of channel.\n\n .. attribute:: text\n\n A text channel.\n .. attribute:: voice\n\n A voice channel.\n .. attribute:: private\n\n A private text channel. Also called a direct message.\n .. attribute:: group\n\n A private group text channel.\n .. attribute:: category\n\n A category channel.\n .. attribute:: news\n\n A guild news channel.\n\n .. attribute:: stage_voice\n\n A guild stage voice channel.\n\n .. versionadded:: 1.7\n\n .. attribute:: news_thread\n\n A news thread\n\n .. versionadded:: 2.0\n\n .. attribute:: public_thread\n\n A public thread\n\n .. versionadded:: 2.0\n\n .. attribute:: private_thread\n\n A private thread\n\n .. versionadded:: 2.0\n\n .. attribute:: forum\n\n A forum channel.\n\n .. versionadded:: 2.0\n\n .. attribute:: media\n\n A media channel.\n\n .. versionadded:: 2.4\n\n.. class:: MessageType\n\n Specifies the type of :class:`Message`. This is used to denote if a message\n is to be interpreted as a system message or a regular message.\n\n .. container:: operations\n\n .. describe:: x == y\n\n Checks if two messages are equal.\n .. describe:: x != y\n\n Checks if two messages are not equal.\n\n .. attribute:: default\n\n The default message type. This is the same as regular messages.\n .. attribute:: recipient_add\n\n The system message when a user is added to a group private\n message or a thread.\n .. attribute:: recipient_remove\n\n The system message when a user is removed from a group private\n message or a thread.\n .. attribute:: call\n\n The system message denoting call state, e.g. missed call, started call,\n etc.\n .. attribute:: channel_name_change\n\n The system message denoting that a channel's name has been changed.\n .. attribute:: channel_icon_change\n\n The system message denoting that a channel's icon has been changed.\n .. attribute:: pins_add\n\n The system message denoting that a pinned message has been added to a channel.\n .. attribute:: new_member\n\n The system message denoting that a new member has joined a Guild.\n\n .. attribute:: premium_guild_subscription\n\n The system message denoting that a member has \"nitro boosted\" a guild.\n .. attribute:: premium_guild_tier_1\n\n The system message denoting that a member has \"nitro boosted\" a guild\n and it achieved level 1.\n .. attribute:: premium_guild_tier_2\n\n The system message denoting that a member has \"nitro boosted\" a guild\n and it achieved level 2.\n .. attribute:: premium_guild_tier_3\n\n The system message denoting that a member has \"nitro boosted\" a guild\n and it achieved level 3.\n .. attribute:: channel_follow_add\n\n The system message denoting that an announcement channel has been followed.\n\n .. versionadded:: 1.3\n .. attribute:: guild_stream\n\n The system message denoting that a member is streaming in the guild.\n\n .. versionadded:: 1.7\n .. attribute:: guild_discovery_disqualified\n\n The system message denoting that the guild is no longer eligible for Server\n Discovery.\n\n .. versionadded:: 1.7\n .. attribute:: guild_discovery_requalified\n\n The system message denoting that the guild has become eligible again for Server\n Discovery.\n\n .. versionadded:: 1.7\n .. attribute:: guild_discovery_grace_period_initial_warning\n\n The system message denoting that the guild has failed to meet the Server\n Discovery requirements for one week.\n\n .. versionadded:: 1.7\n .. attribute:: guild_discovery_grace_period_final_warning\n\n The system message denoting that the guild has failed to meet the Server\n Discovery requirements for 3 weeks in a row.\n\n .. versionadded:: 1.7\n .. attribute:: thread_created\n\n The system message denoting that a thread has been created. This is only\n sent if the thread has been created from an older message. The period of time\n required for a message to be considered old cannot be relied upon and is up to\n Discord.\n\n .. versionadded:: 2.0\n .. attribute:: reply\n\n The system message denoting that the author is replying to a message.\n\n .. versionadded:: 2.0\n .. attribute:: chat_input_command\n\n The system message denoting that a slash command was executed.\n\n .. versionadded:: 2.0\n .. attribute:: guild_invite_reminder\n\n The system message sent as a reminder to invite people to the guild.\n\n .. versionadded:: 2.0\n .. attribute:: thread_starter_message\n\n The system message denoting the message in the thread that is the one that started the\n thread's conversation topic.\n\n .. versionadded:: 2.0\n .. attribute:: context_menu_command\n\n The system message denoting that a context menu command was executed.\n\n .. versionadded:: 2.0\n .. attribute:: auto_moderation_action\n\n The system message sent when an AutoMod rule is triggered. This is only\n sent if the rule is configured to sent an alert when triggered.\n\n .. versionadded:: 2.0\n .. attribute:: role_subscription_purchase\n\n The system message sent when a user purchases or renews a role subscription.\n\n .. versionadded:: 2.2\n .. attribute:: interaction_premium_upsell\n\n The system message sent when a user is given an advertisement to purchase a premium tier for\n an application during an interaction.\n\n .. versionadded:: 2.2\n .. attribute:: stage_start\n\n The system message sent when the stage starts.\n\n .. versionadded:: 2.2\n .. attribute:: stage_end\n\n The system message sent when the stage ends.\n\n .. versionadded:: 2.2\n .. attribute:: stage_speaker\n\n The system message sent when the stage speaker changes.\n\n .. versionadded:: 2.2\n .. attribute:: stage_raise_hand\n\n The system message sent when a user is requesting to speak by raising their hands.\n\n .. versionadded:: 2.2\n .. attribute:: stage_topic\n\n The system message sent when the stage topic changes.\n\n .. versionadded:: 2.2\n .. attribute:: guild_application_premium_subscription\n\n The system message sent when an application's premium subscription is purchased for the guild.\n\n .. versionadded:: 2.2\n\n .. attribute:: guild_incident_alert_mode_enabled\n\n The system message sent when security actions is enabled.\n\n .. versionadded:: 2.4\n\n .. attribute:: guild_incident_alert_mode_disabled\n\n The system message sent when security actions is disabled.\n\n .. versionadded:: 2.4\n\n .. attribute:: guild_incident_report_raid\n\n The system message sent when a raid is reported.\n\n .. versionadded:: 2.4\n\n .. attribute:: guild_incident_report_false_alarm\n\n The system message sent when a false alarm is reported.\n\n .. versionadded:: 2.4\n\n.. class:: UserFlags\n\n Represents Discord User flags.\n\n .. attribute:: staff\n\n The user is a Discord Employee.\n .. attribute:: partner\n\n The user is a Discord Partner.\n .. attribute:: hypesquad\n\n The user is a HypeSquad Events member.\n .. attribute:: bug_hunter\n\n The user is a Bug Hunter.\n .. attribute:: mfa_sms\n\n The user has SMS recovery for Multi Factor Authentication enabled.\n .. attribute:: premium_promo_dismissed\n\n The user has dismissed the Discord Nitro promotion.\n .. attribute:: hypesquad_bravery\n\n The user is a HypeSquad Bravery member.\n .. attribute:: hypesquad_brilliance\n\n The user is a HypeSquad Brilliance member.\n .. attribute:: hypesquad_balance\n\n The user is a HypeSquad Balance member.\n .. attribute:: early_supporter\n\n The user is an Early Supporter.\n .. attribute:: team_user\n\n The user is a Team User.\n .. attribute:: system\n\n The user is a system user (i.e. represents Discord officially).\n .. attribute:: has_unread_urgent_messages\n\n The user has an unread system message.\n .. attribute:: bug_hunter_level_2\n\n The user is a Bug Hunter Level 2.\n .. attribute:: verified_bot\n\n The user is a Verified Bot.\n .. attribute:: verified_bot_developer\n\n The user is an Early Verified Bot Developer.\n .. attribute:: discord_certified_moderator\n\n The user is a Moderator Programs Alumni.\n .. attribute:: bot_http_interactions\n\n The user is a bot that only uses HTTP interactions and is shown in the online member list.\n\n .. versionadded:: 2.0\n .. attribute:: spammer\n\n The user is flagged as a spammer by Discord.\n\n .. versionadded:: 2.0\n\n .. attribute:: active_developer\n\n The user is an active developer.\n\n .. versionadded:: 2.1\n\n.. class:: ActivityType\n\n Specifies the type of :class:`Activity`. This is used to check how to\n interpret the activity itself.\n\n .. attribute:: unknown\n\n An unknown activity type. This should generally not happen.\n .. attribute:: playing\n\n A \"Playing\" activity type.\n .. attribute:: streaming\n\n A \"Streaming\" activity type.\n .. attribute:: listening\n\n A \"Listening\" activity type.\n .. attribute:: watching\n\n A \"Watching\" activity type.\n .. attribute:: custom\n\n A custom activity type.\n .. attribute:: competing\n\n A competing activity type.\n\n .. versionadded:: 1.5\n\n.. class:: VerificationLevel\n\n Specifies a :class:`Guild`\\'s verification level, which is the criteria in\n which a member must meet before being able to send messages to the guild.\n\n .. container:: operations\n\n .. versionadded:: 2.0\n\n .. describe:: x == y\n\n Checks if two verification levels are equal.\n .. describe:: x != y\n\n Checks if two verification levels are not equal.\n .. describe:: x > y\n\n Checks if a verification level is higher than another.\n .. describe:: x < y\n\n Checks if a verification level is lower than another.\n .. describe:: x >= y\n\n Checks if a verification level is higher or equal to another.\n .. describe:: x <= y\n\n Checks if a verification level is lower or equal to another.\n\n .. attribute:: none\n\n No criteria set.\n .. attribute:: low\n\n Member must have a verified email on their Discord account.\n .. attribute:: medium\n\n Member must have a verified email and be registered on Discord for more\n than five minutes.\n .. attribute:: high\n\n Member must have a verified email, be registered on Discord for more\n than five minutes, and be a member of the guild itself for more than\n ten minutes.\n .. attribute:: highest\n\n Member must have a verified phone on their Discord account.\n\n.. class:: NotificationLevel\n\n Specifies whether a :class:`Guild` has notifications on for all messages or mentions only by default.\n\n .. container:: operations\n\n .. versionadded:: 2.0\n\n .. describe:: x == y\n\n Checks if two notification levels are equal.\n .. describe:: x != y\n\n Checks if two notification levels are not equal.\n .. describe:: x > y\n\n Checks if a notification level is higher than another.\n .. describe:: x < y\n\n Checks if a notification level is lower than another.\n .. describe:: x >= y\n\n Checks if a notification level is higher or equal to another.\n .. describe:: x <= y\n\n Checks if a notification level is lower or equal to another.\n\n .. attribute:: all_messages\n\n Members receive notifications for every message regardless of them being mentioned.\n .. attribute:: only_mentions\n\n Members receive notifications for messages they are mentioned in.\n\n.. class:: ContentFilter\n\n Specifies a :class:`Guild`\\'s explicit content filter, which is the machine\n learning algorithms that Discord uses to detect if an image contains\n pornography or otherwise explicit content.\n\n .. container:: operations\n\n .. versionadded:: 2.0\n\n .. describe:: x == y\n\n Checks if two content filter levels are equal.\n .. describe:: x != y\n\n Checks if two content filter levels are not equal.\n .. describe:: x > y\n\n Checks if a content filter level is higher than another.\n .. describe:: x < y\n\n Checks if a content filter level is lower than another.\n .. describe:: x >= y\n\n Checks if a content filter level is higher or equal to another.\n .. describe:: x <= y\n\n Checks if a content filter level is lower or equal to another.\n\n .. attribute:: disabled\n\n The guild does not have the content filter enabled.\n .. attribute:: no_role\n\n The guild has the content filter enabled for members without a role.\n .. attribute:: all_members\n\n The guild has the content filter enabled for every member.\n\n.. class:: Status\n\n Specifies a :class:`Member` 's status.\n\n .. attribute:: online\n\n The member is online.\n .. attribute:: offline\n\n The member is offline.\n .. attribute:: idle\n\n The member is idle.\n .. attribute:: dnd\n\n The member is \"Do Not Disturb\".\n .. attribute:: do_not_disturb\n\n An alias for :attr:`dnd`.\n .. attribute:: invisible\n\n The member is \"invisible\". In reality, this is only used when sending\n a presence a la :meth:`Client.change_presence`. When you receive a\n user's presence this will be :attr:`offline` instead.\n\n\n.. class:: AuditLogAction\n\n Represents the type of action being done for a :class:`AuditLogEntry`\\,\n which is retrievable via :meth:`Guild.audit_logs`.\n\n .. attribute:: guild_update\n\n The guild has updated. Things that trigger this include:\n\n - Changing the guild vanity URL\n - Changing the guild invite splash\n - Changing the guild AFK channel or timeout\n - Changing the guild voice server region\n - Changing the guild icon, banner, or discovery splash\n - Changing the guild moderation settings\n - Changing things related to the guild widget\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Guild`.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.afk_channel`\n - :attr:`~AuditLogDiff.system_channel`\n - :attr:`~AuditLogDiff.afk_timeout`\n - :attr:`~AuditLogDiff.default_notifications`\n - :attr:`~AuditLogDiff.explicit_content_filter`\n - :attr:`~AuditLogDiff.mfa_level`\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.owner`\n - :attr:`~AuditLogDiff.splash`\n - :attr:`~AuditLogDiff.discovery_splash`\n - :attr:`~AuditLogDiff.icon`\n - :attr:`~AuditLogDiff.banner`\n - :attr:`~AuditLogDiff.vanity_url_code`\n - :attr:`~AuditLogDiff.description`\n - :attr:`~AuditLogDiff.preferred_locale`\n - :attr:`~AuditLogDiff.prune_delete_days`\n - :attr:`~AuditLogDiff.public_updates_channel`\n - :attr:`~AuditLogDiff.rules_channel`\n - :attr:`~AuditLogDiff.verification_level`\n - :attr:`~AuditLogDiff.widget_channel`\n - :attr:`~AuditLogDiff.widget_enabled`\n - :attr:`~AuditLogDiff.premium_progress_bar_enabled`\n - :attr:`~AuditLogDiff.system_channel_flags`\n\n .. attribute:: channel_create\n\n A new channel was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n either a :class:`abc.GuildChannel` or :class:`Object` with an ID.\n\n A more filled out object in the :class:`Object` case can be found\n by using :attr:`~AuditLogEntry.after`.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.type`\n - :attr:`~AuditLogDiff.overwrites`\n\n .. attribute:: channel_update\n\n A channel was updated. Things that trigger this include:\n\n - The channel name or topic was changed\n - The channel bitrate was changed\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`abc.GuildChannel` or :class:`Object` with an ID.\n\n A more filled out object in the :class:`Object` case can be found\n by using :attr:`~AuditLogEntry.after` or :attr:`~AuditLogEntry.before`.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.type`\n - :attr:`~AuditLogDiff.position`\n - :attr:`~AuditLogDiff.overwrites`\n - :attr:`~AuditLogDiff.topic`\n - :attr:`~AuditLogDiff.bitrate`\n - :attr:`~AuditLogDiff.rtc_region`\n - :attr:`~AuditLogDiff.video_quality_mode`\n - :attr:`~AuditLogDiff.default_auto_archive_duration`\n - :attr:`~AuditLogDiff.nsfw`\n - :attr:`~AuditLogDiff.slowmode_delay`\n - :attr:`~AuditLogDiff.user_limit`\n\n .. attribute:: channel_delete\n\n A channel was deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n an :class:`Object` with an ID.\n\n A more filled out object can be found by using the\n :attr:`~AuditLogEntry.before` object.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.type`\n - :attr:`~AuditLogDiff.overwrites`\n - :attr:`~AuditLogDiff.flags`\n - :attr:`~AuditLogDiff.nsfw`\n - :attr:`~AuditLogDiff.slowmode_delay`\n\n .. attribute:: overwrite_create\n\n A channel permission overwrite was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`abc.GuildChannel` or :class:`Object` with an ID.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n either a :class:`Role` or :class:`Member`. If the object is not found\n then it is a :class:`Object` with an ID being filled, a name, and a\n ``type`` attribute set to either ``'role'`` or ``'member'`` to help\n dictate what type of ID it is.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.deny`\n - :attr:`~AuditLogDiff.allow`\n - :attr:`~AuditLogDiff.id`\n - :attr:`~AuditLogDiff.type`\n\n .. attribute:: overwrite_update\n\n A channel permission overwrite was changed, this is typically\n when the permission values change.\n\n See :attr:`overwrite_create` for more information on how the\n :attr:`~AuditLogEntry.target` and :attr:`~AuditLogEntry.extra` fields\n are set.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.deny`\n - :attr:`~AuditLogDiff.allow`\n - :attr:`~AuditLogDiff.id`\n - :attr:`~AuditLogDiff.type`\n\n .. attribute:: overwrite_delete\n\n A channel permission overwrite was deleted.\n\n See :attr:`overwrite_create` for more information on how the\n :attr:`~AuditLogEntry.target` and :attr:`~AuditLogEntry.extra` fields\n are set.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.deny`\n - :attr:`~AuditLogDiff.allow`\n - :attr:`~AuditLogDiff.id`\n - :attr:`~AuditLogDiff.type`\n\n .. attribute:: kick\n\n A member was kicked.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`User` or :class:`Object` who got kicked.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with one attribute:\n\n - ``integration_type``: An optional string that denotes the type of integration that did the action.\n\n When this is the action, :attr:`~AuditLogEntry.changes` is empty.\n\n .. attribute:: member_prune\n\n A member prune was triggered.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n set to ``None``.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with two attributes:\n\n - ``delete_member_days``: An integer specifying how far the prune was.\n - ``members_removed``: An integer specifying how many members were removed.\n\n When this is the action, :attr:`~AuditLogEntry.changes` is empty.\n\n .. attribute:: ban\n\n A member was banned.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`User` or :class:`Object` who got banned.\n\n When this is the action, :attr:`~AuditLogEntry.changes` is empty.\n\n .. attribute:: unban\n\n A member was unbanned.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`User` or :class:`Object` who got unbanned.\n\n When this is the action, :attr:`~AuditLogEntry.changes` is empty.\n\n .. attribute:: member_update\n\n A member has updated. This triggers in the following situations:\n\n - A nickname was changed\n - They were server muted or deafened (or it was undo'd)\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Member`, :class:`User`, or :class:`Object` who got updated.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.nick`\n - :attr:`~AuditLogDiff.mute`\n - :attr:`~AuditLogDiff.deaf`\n - :attr:`~AuditLogDiff.timed_out_until`\n\n .. attribute:: member_role_update\n\n A member's role has been updated. This triggers when a member\n either gains a role or loses a role.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Member`, :class:`User`, or :class:`Object` who got the role.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with one attribute:\n\n - ``integration_type``: An optional string that denotes the type of integration that did the action.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.roles`\n\n .. attribute:: member_move\n\n A member's voice channel has been updated. This triggers when a\n member is moved to a different voice channel.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with two attributes:\n\n - ``channel``: A :class:`TextChannel` or :class:`Object` with the channel ID where the members were moved.\n - ``count``: An integer specifying how many members were moved.\n\n .. versionadded:: 1.3\n\n .. attribute:: member_disconnect\n\n A member's voice state has changed. This triggers when a\n member is force disconnected from voice.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with one attribute:\n\n - ``count``: An integer specifying how many members were disconnected.\n\n .. versionadded:: 1.3\n\n .. attribute:: bot_add\n\n A bot was added to the guild.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Member`, :class:`User`, or :class:`Object` which was added to the guild.\n\n .. versionadded:: 1.3\n\n .. attribute:: role_create\n\n A new role was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Role` or a :class:`Object` with the ID.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.colour`\n - :attr:`~AuditLogDiff.mentionable`\n - :attr:`~AuditLogDiff.hoist`\n - :attr:`~AuditLogDiff.icon`\n - :attr:`~AuditLogDiff.unicode_emoji`\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.permissions`\n\n .. attribute:: role_update\n\n A role was updated. This triggers in the following situations:\n\n - The name has changed\n - The permissions have changed\n - The colour has changed\n - The role icon (or unicode emoji) has changed\n - Its hoist/mentionable state has changed\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Role` or a :class:`Object` with the ID.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.colour`\n - :attr:`~AuditLogDiff.mentionable`\n - :attr:`~AuditLogDiff.hoist`\n - :attr:`~AuditLogDiff.icon`\n - :attr:`~AuditLogDiff.unicode_emoji`\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.permissions`\n\n .. attribute:: role_delete\n\n A role was deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Role` or a :class:`Object` with the ID.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.colour`\n - :attr:`~AuditLogDiff.mentionable`\n - :attr:`~AuditLogDiff.hoist`\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.permissions`\n\n .. attribute:: invite_create\n\n An invite was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Invite` that was created.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.max_age`\n - :attr:`~AuditLogDiff.code`\n - :attr:`~AuditLogDiff.temporary`\n - :attr:`~AuditLogDiff.inviter`\n - :attr:`~AuditLogDiff.channel`\n - :attr:`~AuditLogDiff.uses`\n - :attr:`~AuditLogDiff.max_uses`\n\n .. attribute:: invite_update\n\n An invite was updated.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Invite` that was updated.\n\n .. attribute:: invite_delete\n\n An invite was deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Invite` that was deleted.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.max_age`\n - :attr:`~AuditLogDiff.code`\n - :attr:`~AuditLogDiff.temporary`\n - :attr:`~AuditLogDiff.inviter`\n - :attr:`~AuditLogDiff.channel`\n - :attr:`~AuditLogDiff.uses`\n - :attr:`~AuditLogDiff.max_uses`\n\n .. attribute:: webhook_create\n\n A webhook was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Object` with the webhook ID.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.channel`\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.type` (always set to ``1`` if so)\n\n .. attribute:: webhook_update\n\n A webhook was updated. This trigger in the following situations:\n\n - The webhook name changed\n - The webhook channel changed\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Object` with the webhook ID.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.channel`\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.avatar`\n\n .. attribute:: webhook_delete\n\n A webhook was deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Object` with the webhook ID.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.channel`\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.type` (always set to ``1`` if so)\n\n .. attribute:: emoji_create\n\n An emoji was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Emoji` or :class:`Object` with the emoji ID.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n\n .. attribute:: emoji_update\n\n An emoji was updated. This triggers when the name has changed.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Emoji` or :class:`Object` with the emoji ID.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n\n .. attribute:: emoji_delete\n\n An emoji was deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Object` with the emoji ID.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n\n .. attribute:: message_delete\n\n A message was deleted by a moderator. Note that this\n only triggers if the message was deleted by someone other than the author.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Member`, :class:`User`, or :class:`Object` who had their message deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with two attributes:\n\n - ``count``: An integer specifying how many messages were deleted.\n - ``channel``: A :class:`TextChannel` or :class:`Object` with the channel ID where the message got deleted.\n\n .. attribute:: message_bulk_delete\n\n Messages were bulk deleted by a moderator.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`TextChannel` or :class:`Object` with the ID of the channel that was purged.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with one attribute:\n\n - ``count``: An integer specifying how many messages were deleted.\n\n .. versionadded:: 1.3\n\n .. attribute:: message_pin\n\n A message was pinned in a channel.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Member`, :class:`User`, or :class:`Object` who had their message pinned.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with two attributes:\n\n - ``channel``: A :class:`TextChannel` or :class:`Object` with the channel ID where the message was pinned.\n - ``message_id``: the ID of the message which was pinned.\n\n .. versionadded:: 1.3\n\n .. attribute:: message_unpin\n\n A message was unpinned in a channel.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Member`, :class:`User`, or :class:`Object` who had their message unpinned.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with two attributes:\n\n - ``channel``: A :class:`TextChannel` or :class:`Object` with the channel ID where the message was unpinned.\n - ``message_id``: the ID of the message which was unpinned.\n\n .. versionadded:: 1.3\n\n .. attribute:: integration_create\n\n A guild integration was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`PartialIntegration` or :class:`Object` with the\n integration ID of the integration which was created.\n\n .. versionadded:: 1.3\n\n .. attribute:: integration_update\n\n A guild integration was updated.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`PartialIntegration` or :class:`Object` with the\n integration ID of the integration which was updated.\n\n .. versionadded:: 1.3\n\n .. attribute:: integration_delete\n\n A guild integration was deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`PartialIntegration` or :class:`Object` with the\n integration ID of the integration which was deleted.\n\n .. versionadded:: 1.3\n\n .. attribute:: stage_instance_create\n\n A stage instance was started.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`StageInstance` or :class:`Object` with the ID of the stage\n instance which was created.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.topic`\n - :attr:`~AuditLogDiff.privacy_level`\n\n .. versionadded:: 2.0\n\n .. attribute:: stage_instance_update\n\n A stage instance was updated.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`StageInstance` or :class:`Object` with the ID of the stage\n instance which was updated.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.topic`\n - :attr:`~AuditLogDiff.privacy_level`\n\n .. versionadded:: 2.0\n\n .. attribute:: stage_instance_delete\n\n A stage instance was ended.\n\n .. versionadded:: 2.0\n\n .. attribute:: sticker_create\n\n A sticker was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`GuildSticker` or :class:`Object` with the ID of the sticker\n which was created.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.emoji`\n - :attr:`~AuditLogDiff.type`\n - :attr:`~AuditLogDiff.format_type`\n - :attr:`~AuditLogDiff.description`\n - :attr:`~AuditLogDiff.available`\n\n .. versionadded:: 2.0\n\n .. attribute:: sticker_update\n\n A sticker was updated.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`GuildSticker` or :class:`Object` with the ID of the sticker\n which was updated.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.emoji`\n - :attr:`~AuditLogDiff.type`\n - :attr:`~AuditLogDiff.format_type`\n - :attr:`~AuditLogDiff.description`\n - :attr:`~AuditLogDiff.available`\n\n .. versionadded:: 2.0\n\n .. attribute:: sticker_delete\n\n A sticker was deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`GuildSticker` or :class:`Object` with the ID of the sticker\n which was updated.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.emoji`\n - :attr:`~AuditLogDiff.type`\n - :attr:`~AuditLogDiff.format_type`\n - :attr:`~AuditLogDiff.description`\n - :attr:`~AuditLogDiff.available`\n\n .. versionadded:: 2.0\n\n .. attribute:: scheduled_event_create\n\n A scheduled event was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`ScheduledEvent` or :class:`Object` with the ID of the event\n which was created.\n\n Possible attributes for :class:`AuditLogDiff`:\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.channel`\n - :attr:`~AuditLogDiff.description`\n - :attr:`~AuditLogDiff.privacy_level`\n - :attr:`~AuditLogDiff.status`\n - :attr:`~AuditLogDiff.entity_type`\n - :attr:`~AuditLogDiff.cover_image`\n\n .. versionadded:: 2.0\n\n .. attribute:: scheduled_event_update\n\n A scheduled event was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`ScheduledEvent` or :class:`Object` with the ID of the event\n which was updated.\n\n Possible attributes for :class:`AuditLogDiff`:\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.channel`\n - :attr:`~AuditLogDiff.description`\n - :attr:`~AuditLogDiff.privacy_level`\n - :attr:`~AuditLogDiff.status`\n - :attr:`~AuditLogDiff.entity_type`\n - :attr:`~AuditLogDiff.cover_image`\n\n .. versionadded:: 2.0\n\n .. attribute:: scheduled_event_delete\n\n A scheduled event was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`ScheduledEvent` or :class:`Object` with the ID of the event\n which was deleted.\n\n Possible attributes for :class:`AuditLogDiff`:\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.channel`\n - :attr:`~AuditLogDiff.description`\n - :attr:`~AuditLogDiff.privacy_level`\n - :attr:`~AuditLogDiff.status`\n - :attr:`~AuditLogDiff.entity_type`\n - :attr:`~AuditLogDiff.cover_image`\n\n .. versionadded:: 2.0\n\n .. attribute:: thread_create\n\n A thread was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Thread` or :class:`Object` with the ID of the thread which\n was created.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.archived`\n - :attr:`~AuditLogDiff.locked`\n - :attr:`~AuditLogDiff.auto_archive_duration`\n - :attr:`~AuditLogDiff.invitable`\n\n .. versionadded:: 2.0\n\n .. attribute:: thread_update\n\n A thread was updated.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Thread` or :class:`Object` with the ID of the thread which\n was updated.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.archived`\n - :attr:`~AuditLogDiff.locked`\n - :attr:`~AuditLogDiff.auto_archive_duration`\n - :attr:`~AuditLogDiff.invitable`\n\n .. versionadded:: 2.0\n\n .. attribute:: thread_delete\n\n A thread was deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Thread` or :class:`Object` with the ID of the thread which\n was deleted.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.archived`\n - :attr:`~AuditLogDiff.locked`\n - :attr:`~AuditLogDiff.auto_archive_duration`\n - :attr:`~AuditLogDiff.invitable`\n\n .. versionadded:: 2.0\n\n .. attribute:: app_command_permission_update\n\n An application command or integrations application command permissions\n were updated.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`PartialIntegration` for an integrations general permissions,\n :class:`~discord.app_commands.AppCommand` for a specific commands permissions,\n or :class:`Object` with the ID of the command or integration which\n was updated.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an :class:`PartialIntegration` or :class:`Object` with the ID of\n application that command or integration belongs to.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.app_command_permissions`\n\n .. versionadded:: 2.0\n\n .. attribute:: automod_rule_create\n\n An automod rule was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`AutoModRule` or :class:`Object` with the ID of the automod\n rule that was created.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.enabled`\n - :attr:`~AuditLogDiff.event_type`\n - :attr:`~AuditLogDiff.trigger_type`\n - :attr:`~AuditLogDiff.trigger`\n - :attr:`~AuditLogDiff.actions`\n - :attr:`~AuditLogDiff.exempt_roles`\n - :attr:`~AuditLogDiff.exempt_channels`\n\n .. versionadded:: 2.0\n\n .. attribute:: automod_rule_update\n\n An automod rule was updated.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`AutoModRule` or :class:`Object` with the ID of the automod\n rule that was created.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.enabled`\n - :attr:`~AuditLogDiff.event_type`\n - :attr:`~AuditLogDiff.trigger_type`\n - :attr:`~AuditLogDiff.trigger`\n - :attr:`~AuditLogDiff.actions`\n - :attr:`~AuditLogDiff.exempt_roles`\n - :attr:`~AuditLogDiff.exempt_channels`\n\n .. versionadded:: 2.0\n\n .. attribute:: automod_rule_delete\n\n An automod rule was deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`AutoModRule` or :class:`Object` with the ID of the automod\n rule that was created.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.enabled`\n - :attr:`~AuditLogDiff.event_type`\n - :attr:`~AuditLogDiff.trigger_type`\n - :attr:`~AuditLogDiff.trigger`\n - :attr:`~AuditLogDiff.actions`\n - :attr:`~AuditLogDiff.exempt_roles`\n - :attr:`~AuditLogDiff.exempt_channels`\n\n .. versionadded:: 2.0\n\n .. attribute:: automod_block_message\n\n An automod rule blocked a message from being sent.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`Member` with the ID of the person who triggered the automod rule.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with 3 attributes:\n\n - ``automod_rule_name``: The name of the automod rule that was triggered.\n - ``automod_rule_trigger_type``: A :class:`AutoModRuleTriggerType` representation of the rule type that was triggered.\n - ``channel``: The channel in which the automod rule was triggered.\n\n When this is the action, :attr:`AuditLogEntry.changes` is empty.\n\n .. versionadded:: 2.0\n\n .. attribute:: automod_flag_message\n\n An automod rule flagged a message.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`Member` with the ID of the person who triggered the automod rule.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with 3 attributes:\n\n - ``automod_rule_name``: The name of the automod rule that was triggered.\n - ``automod_rule_trigger_type``: A :class:`AutoModRuleTriggerType` representation of the rule type that was triggered.\n - ``channel``: The channel in which the automod rule was triggered.\n\n When this is the action, :attr:`AuditLogEntry.changes` is empty.\n\n .. versionadded:: 2.1\n\n .. attribute:: automod_timeout_member\n\n An automod rule timed-out a member.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`Member` with the ID of the person who triggered the automod rule.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with 3 attributes:\n\n - ``automod_rule_name``: The name of the automod rule that was triggered.\n - ``automod_rule_trigger_type``: A :class:`AutoModRuleTriggerType` representation of the rule type that was triggered.\n - ``channel``: The channel in which the automod rule was triggered.\n\n When this is the action, :attr:`AuditLogEntry.changes` is empty.\n\n .. versionadded:: 2.1\n\n .. attribute:: creator_monetization_request_created\n\n A request to monetize the server was created.\n\n .. versionadded:: 2.4\n\n .. attribute:: creator_monetization_terms_accepted\n\n The terms and conditions for creator monetization were accepted.\n\n .. versionadded:: 2.4\n\n.. class:: AuditLogActionCategory\n\n Represents the category that the :class:`AuditLogAction` belongs to.\n\n This can be retrieved via :attr:`AuditLogEntry.category`.\n\n .. attribute:: create\n\n The action is the creation of something.\n\n .. attribute:: delete\n\n The action is the deletion of something.\n\n .. attribute:: update\n\n The action is the update of something.\n\n.. class:: TeamMembershipState\n\n Represents the membership state of a team member retrieved through :func:`Client.application_info`.\n\n .. versionadded:: 1.3\n\n .. attribute:: invited\n\n Represents an invited member.\n\n .. attribute:: accepted\n\n Represents a member currently in the team.\n\n.. class:: TeamMemberRole\n\n Represents the type of role of a team member retrieved through :func:`Client.application_info`.\n\n .. versionadded:: 2.4\n\n .. attribute:: admin\n\n The team member is an admin. This allows them to invite members to the team, access credentials, edit the application,\n and do most things the owner can do. However they cannot do destructive actions.\n\n .. attribute:: developer\n\n The team member is a developer. This allows them to access information, like the client secret or public key.\n They can also configure interaction endpoints or reset the bot token. Developers cannot invite anyone to the team\n nor can they do destructive actions.\n\n .. attribute:: read_only\n\n The team member is a read-only member. This allows them to access information, but not edit anything.\n\n.. class:: WebhookType\n\n Represents the type of webhook that can be received.\n\n .. versionadded:: 1.3\n\n .. attribute:: incoming\n\n Represents a webhook that can post messages to channels with a token.\n\n .. attribute:: channel_follower\n\n Represents a webhook that is internally managed by Discord, used for following channels.\n\n .. attribute:: application\n\n Represents a webhook that is used for interactions or applications.\n\n .. versionadded:: 2.0\n\n.. class:: ExpireBehaviour\n\n Represents the behaviour the :class:`Integration` should perform\n when a user's subscription has finished.\n\n There is an alias for this called ``ExpireBehavior``.\n\n .. versionadded:: 1.4\n\n .. attribute:: remove_role\n\n This will remove the :attr:`StreamIntegration.role` from the user\n when their subscription is finished.\n\n .. attribute:: kick\n\n This will kick the user when their subscription is finished.\n\n.. class:: DefaultAvatar\n\n Represents the default avatar of a Discord :class:`User`\n\n .. attribute:: blurple\n\n Represents the default avatar with the colour blurple.\n See also :attr:`Colour.blurple`\n .. attribute:: grey\n\n Represents the default avatar with the colour grey.\n See also :attr:`Colour.greyple`\n .. attribute:: gray\n\n An alias for :attr:`grey`.\n .. attribute:: green\n\n Represents the default avatar with the colour green.\n See also :attr:`Colour.green`\n .. attribute:: orange\n\n Represents the default avatar with the colour orange.\n See also :attr:`Colour.orange`\n .. attribute:: red\n\n Represents the default avatar with the colour red.\n See also :attr:`Colour.red`\n .. attribute:: pink\n\n Represents the default avatar with the colour pink.\n See also :attr:`Colour.pink`\n\n .. versionadded:: 2.3\n\n.. class:: StickerType\n\n Represents the type of sticker.\n\n .. versionadded:: 2.0\n\n .. attribute:: standard\n\n Represents a standard sticker that all Nitro users can use.\n\n .. attribute:: guild\n\n Represents a custom sticker created in a guild.\n\n.. class:: StickerFormatType\n\n Represents the type of sticker images.\n\n .. versionadded:: 1.6\n\n .. attribute:: png\n\n Represents a sticker with a png image.\n\n .. attribute:: apng\n\n Represents a sticker with an apng image.\n\n .. attribute:: lottie\n\n Represents a sticker with a lottie image.\n\n .. attribute:: gif\n\n Represents a sticker with a gif image.\n\n .. versionadded:: 2.2\n\n.. class:: InviteTarget\n\n Represents the invite type for voice channel invites.\n\n .. versionadded:: 2.0\n\n .. attribute:: unknown\n\n The invite doesn't target anyone or anything.\n\n .. attribute:: stream\n\n A stream invite that targets a user.\n\n .. attribute:: embedded_application\n\n A stream invite that targets an embedded application.\n\n.. class:: VideoQualityMode\n\n Represents the camera video quality mode for voice channel participants.\n\n .. versionadded:: 2.0\n\n .. attribute:: auto\n\n Represents auto camera video quality.\n\n .. attribute:: full\n\n Represents full camera video quality.\n\n.. class:: PrivacyLevel\n\n Represents the privacy level of a stage instance or scheduled event.\n\n .. versionadded:: 2.0\n\n .. attribute:: guild_only\n\n The stage instance or scheduled event is only accessible within the guild.\n\n.. class:: NSFWLevel\n\n Represents the NSFW level of a guild.\n\n .. versionadded:: 2.0\n\n .. container:: operations\n\n .. describe:: x == y\n\n Checks if two NSFW levels are equal.\n .. describe:: x != y\n\n Checks if two NSFW levels are not equal.\n .. describe:: x > y\n\n Checks if a NSFW level is higher than another.\n .. describe:: x < y\n\n Checks if a NSFW level is lower than another.\n .. describe:: x >= y\n\n Checks if a NSFW level is higher or equal to another.\n .. describe:: x <= y\n\n Checks if a NSFW level is lower or equal to another.\n\n .. attribute:: default\n\n The guild has not been categorised yet.\n\n .. attribute:: explicit\n\n The guild contains NSFW content.\n\n .. attribute:: safe\n\n The guild does not contain any NSFW content.\n\n .. attribute:: age_restricted\n\n The guild may contain NSFW content.\n\n.. class:: Locale\n\n Supported locales by Discord. Mainly used for application command localisation.\n\n .. versionadded:: 2.0\n\n .. attribute:: american_english\n\n The ``en-US`` locale.\n\n .. attribute:: british_english\n\n The ``en-GB`` locale.\n\n .. attribute:: bulgarian\n\n The ``bg`` locale.\n\n .. attribute:: chinese\n\n The ``zh-CN`` locale.\n\n .. attribute:: taiwan_chinese\n\n The ``zh-TW`` locale.\n\n .. attribute:: croatian\n\n The ``hr`` locale.\n\n .. attribute:: czech\n\n The ``cs`` locale.\n\n .. attribute:: indonesian\n\n The ``id`` locale.\n\n .. versionadded:: 2.2\n\n .. attribute:: danish\n\n The ``da`` locale.\n\n .. attribute:: dutch\n\n The ``nl`` locale.\n\n .. attribute:: finnish\n\n The ``fi`` locale.\n\n .. attribute:: french\n\n The ``fr`` locale.\n\n .. attribute:: german\n\n The ``de`` locale.\n\n .. attribute:: greek\n\n The ``el`` locale.\n\n .. attribute:: hindi\n\n The ``hi`` locale.\n\n .. attribute:: hungarian\n\n The ``hu`` locale.\n\n .. attribute:: italian\n\n The ``it`` locale.\n\n .. attribute:: japanese\n\n The ``ja`` locale.\n\n .. attribute:: korean\n\n The ``ko`` locale.\n\n .. attribute:: lithuanian\n\n The ``lt`` locale.\n\n .. attribute:: norwegian\n\n The ``no`` locale.\n\n .. attribute:: polish\n\n The ``pl`` locale.\n\n .. attribute:: brazil_portuguese\n\n The ``pt-BR`` locale.\n\n .. attribute:: romanian\n\n The ``ro`` locale.\n\n .. attribute:: russian\n\n The ``ru`` locale.\n\n .. attribute:: spain_spanish\n\n The ``es-ES`` locale.\n\n .. attribute:: swedish\n\n The ``sv-SE`` locale.\n\n .. attribute:: thai\n\n The ``th`` locale.\n\n .. attribute:: turkish\n\n The ``tr`` locale.\n\n .. attribute:: ukrainian\n\n The ``uk`` locale.\n\n .. attribute:: vietnamese\n\n The ``vi`` locale.\n\n\n.. class:: MFALevel\n\n Represents the Multi-Factor Authentication requirement level of a guild.\n\n .. versionadded:: 2.0\n\n .. container:: operations\n\n .. describe:: x == y\n\n Checks if two MFA levels are equal.\n .. describe:: x != y\n\n Checks if two MFA levels are not equal.\n .. describe:: x > y\n\n Checks if a MFA level is higher than another.\n .. describe:: x < y\n\n Checks if a MFA level is lower than another.\n .. describe:: x >= y\n\n Checks if a MFA level is higher or equal to another.\n .. describe:: x <= y\n\n Checks if a MFA level is lower or equal to another.\n\n .. attribute:: disabled\n\n The guild has no MFA requirement.\n\n .. attribute:: require_2fa\n\n The guild requires 2 factor authentication.\n\n.. class:: EntityType\n\n Represents the type of entity that a scheduled event is for.\n\n .. versionadded:: 2.0\n\n .. attribute:: stage_instance\n\n The scheduled event will occur in a stage instance.\n\n .. attribute:: voice\n\n The scheduled event will occur in a voice channel.\n\n .. attribute:: external\n\n The scheduled event will occur externally.\n\n.. class:: EventStatus\n\n Represents the status of an event.\n\n .. versionadded:: 2.0\n\n .. attribute:: scheduled\n\n The event is scheduled.\n\n .. attribute:: active\n\n The event is active.\n\n .. attribute:: completed\n\n The event has ended.\n\n .. attribute:: cancelled\n\n The event has been cancelled.\n\n .. attribute:: canceled\n\n An alias for :attr:`cancelled`.\n\n .. attribute:: ended\n\n An alias for :attr:`completed`.\n\n.. class:: AutoModRuleTriggerType\n\n Represents the trigger type of an automod rule.\n\n .. versionadded:: 2.0\n\n .. attribute:: keyword\n\n The rule will trigger when a keyword is mentioned.\n\n .. attribute:: harmful_link\n\n The rule will trigger when a harmful link is posted.\n\n .. attribute:: spam\n\n The rule will trigger when a spam message is posted.\n\n .. attribute:: keyword_preset\n\n The rule will trigger when something triggers based on the set keyword preset types.\n\n .. attribute:: mention_spam\n\n The rule will trigger when combined number of role and user mentions\n is greater than the set limit.\n\n .. attribute:: member_profile\n\n The rule will trigger when a user's profile contains a keyword.\n\n .. versionadded:: 2.4\n\n.. class:: AutoModRuleEventType\n\n Represents the event type of an automod rule.\n\n .. versionadded:: 2.0\n\n .. attribute:: message_send\n\n The rule will trigger when a message is sent.\n\n .. attribute:: member_update\n\n The rule will trigger when a member's profile is updated.\n\n .. versionadded:: 2.4\n\n.. class:: AutoModRuleActionType\n\n Represents the action type of an automod rule.\n\n .. versionadded:: 2.0\n\n .. attribute:: block_message\n\n The rule will block a message from being sent.\n\n .. attribute:: send_alert_message\n\n The rule will send an alert message to a predefined channel.\n\n .. attribute:: timeout\n\n The rule will timeout a user.\n\n .. attribute:: block_member_interactions\n\n Similar to :attr:`timeout`, except the user will be timed out indefinitely.\n This will request the user to edit it's profile.\n\n .. versionadded:: 2.4\n\n.. class:: ForumLayoutType\n\n Represents how a forum's posts are layed out in the client.\n\n .. versionadded:: 2.2\n\n .. attribute:: not_set\n\n No default has been set, so it is up to the client to know how to lay it out.\n\n .. attribute:: list_view\n\n Displays posts as a list.\n\n .. attribute:: gallery_view\n\n Displays posts as a collection of tiles.\n\n\n.. class:: ForumOrderType\n\n Represents how a forum's posts are sorted in the client.\n\n .. versionadded:: 2.3\n\n .. attribute:: latest_activity\n\n Sort forum posts by activity.\n\n .. attribute:: creation_date\n\n Sort forum posts by creation time (from most recent to oldest).\n\n.. class:: SelectDefaultValueType\n\n Represents the default value of a select menu.\n\n .. versionadded:: 2.4\n\n .. attribute:: user\n\n The underlying type of the ID is a user.\n\n .. attribute:: role\n\n The underlying type of the ID is a role.\n\n .. attribute:: channel\n\n The underlying type of the ID is a channel or thread.\n\n\n.. class:: SKUType\n\n Represents the type of a SKU.\n\n .. versionadded:: 2.4\n\n .. attribute:: subscription\n\n The SKU is a recurring subscription.\n\n .. attribute:: subscription_group\n\n The SKU is a system-generated group which is created for each :attr:`SKUType.subscription`.\n\n\n.. class:: EntitlementType\n\n Represents the type of an entitlement.\n\n .. versionadded:: 2.4\n\n .. attribute:: application_subscription\n\n The entitlement was purchased as an app subscription.\n\n\n.. class:: EntitlementOwnerType\n\n Represents the type of an entitlement owner.\n\n .. versionadded:: 2.4\n\n .. attribute:: guild\n\n The entitlement owner is a guild.\n\n .. attribute:: user\n\n The entitlement owner is a user.\n\n\n.. _discord-api-audit-logs:\n\nAudit Log Data\n----------------\n\nWorking with :meth:`Guild.audit_logs` is a complicated process with a lot of machinery\ninvolved. The library attempts to make it easy to use and friendly. In order to accomplish\nthis goal, it must make use of a couple of data classes that aid in this goal.\n\nAuditLogEntry\n~~~~~~~~~~~~~~~\n\n.. attributetable:: AuditLogEntry\n\n.. autoclass:: AuditLogEntry\n :members:\n\nAuditLogChanges\n~~~~~~~~~~~~~~~~~\n\n.. attributetable:: AuditLogChanges\n\n.. class:: AuditLogChanges\n\n An audit log change set.\n\n .. attribute:: before\n\n The old value. The attribute has the type of :class:`AuditLogDiff`.\n\n Depending on the :class:`AuditLogActionCategory` retrieved by\n :attr:`~AuditLogEntry.category`\\, the data retrieved by this\n attribute differs:\n\n +----------------------------------------+---------------------------------------------------+\n | Category | Description |\n +----------------------------------------+---------------------------------------------------+\n | :attr:`~AuditLogActionCategory.create` | All attributes are set to ``None``. |\n +----------------------------------------+---------------------------------------------------+\n | :attr:`~AuditLogActionCategory.delete` | All attributes are set the value before deletion. |\n +----------------------------------------+---------------------------------------------------+\n | :attr:`~AuditLogActionCategory.update` | All attributes are set the value before updating. |\n +----------------------------------------+---------------------------------------------------+\n | ``None`` | No attributes are set. |\n +----------------------------------------+---------------------------------------------------+\n\n .. attribute:: after\n\n The new value. The attribute has the type of :class:`AuditLogDiff`.\n\n Depending on the :class:`AuditLogActionCategory` retrieved by\n :attr:`~AuditLogEntry.category`\\, the data retrieved by this\n attribute differs:\n\n +----------------------------------------+--------------------------------------------------+\n | Category | Description |\n +----------------------------------------+--------------------------------------------------+\n | :attr:`~AuditLogActionCategory.create` | All attributes are set to the created value |\n +----------------------------------------+--------------------------------------------------+\n | :attr:`~AuditLogActionCategory.delete` | All attributes are set to ``None`` |\n +----------------------------------------+--------------------------------------------------+\n | :attr:`~AuditLogActionCategory.update` | All attributes are set the value after updating. |\n +----------------------------------------+--------------------------------------------------+\n | ``None`` | No attributes are set. |\n +----------------------------------------+--------------------------------------------------+\n\nAuditLogDiff\n~~~~~~~~~~~~~\n\n.. attributetable:: AuditLogDiff\n\n.. class:: AuditLogDiff\n\n Represents an audit log \"change\" object. A change object has dynamic\n attributes that depend on the type of action being done. Certain actions\n map to certain attributes being set.\n\n Note that accessing an attribute that does not match the specified action\n will lead to an attribute error.\n\n To get a list of attributes that have been set, you can iterate over\n them. To see a list of all possible attributes that could be set based\n on the action being done, check the documentation for :class:`AuditLogAction`,\n otherwise check the documentation below for all attributes that are possible.\n\n .. container:: operations\n\n .. describe:: iter(diff)\n\n Returns an iterator over (attribute, value) tuple of this diff.\n\n .. attribute:: name\n\n A name of something.\n\n :type: :class:`str`\n\n .. attribute:: guild\n\n The guild of something.\n\n :type: :class:`Guild`\n\n .. attribute:: icon\n\n A guild's or role's icon. See also :attr:`Guild.icon` or :attr:`Role.icon`.\n\n :type: :class:`Asset`\n\n .. attribute:: splash\n\n The guild's invite splash. See also :attr:`Guild.splash`.\n\n :type: :class:`Asset`\n\n .. attribute:: discovery_splash\n\n The guild's discovery splash. See also :attr:`Guild.discovery_splash`.\n\n :type: :class:`Asset`\n\n .. attribute:: banner\n\n The guild's banner. See also :attr:`Guild.banner`.\n\n :type: :class:`Asset`\n\n .. attribute:: owner\n\n The guild's owner. See also :attr:`Guild.owner`\n\n :type: Union[:class:`Member`, :class:`User`]\n\n .. attribute:: afk_channel\n\n The guild's AFK channel.\n\n If this could not be found, then it falls back to a :class:`Object`\n with the ID being set.\n\n See :attr:`Guild.afk_channel`.\n\n :type: Union[:class:`VoiceChannel`, :class:`Object`]\n\n .. attribute:: system_channel\n\n The guild's system channel.\n\n If this could not be found, then it falls back to a :class:`Object`\n with the ID being set.\n\n See :attr:`Guild.system_channel`.\n\n :type: Union[:class:`TextChannel`, :class:`Object`]\n\n\n .. attribute:: rules_channel\n\n The guild's rules channel.\n\n If this could not be found then it falls back to a :class:`Object`\n with the ID being set.\n\n See :attr:`Guild.rules_channel`.\n\n :type: Union[:class:`TextChannel`, :class:`Object`]\n\n\n .. attribute:: public_updates_channel\n\n The guild's public updates channel.\n\n If this could not be found then it falls back to a :class:`Object`\n with the ID being set.\n\n See :attr:`Guild.public_updates_channel`.\n\n :type: Union[:class:`TextChannel`, :class:`Object`]\n\n .. attribute:: afk_timeout\n\n The guild's AFK timeout. See :attr:`Guild.afk_timeout`.\n\n :type: :class:`int`\n\n .. attribute:: mfa_level\n\n The guild's MFA level. See :attr:`Guild.mfa_level`.\n\n :type: :class:`MFALevel`\n\n .. attribute:: widget_enabled\n\n The guild's widget has been enabled or disabled.\n\n :type: :class:`bool`\n\n .. attribute:: widget_channel\n\n The widget's channel.\n\n If this could not be found then it falls back to a :class:`Object`\n with the ID being set.\n\n :type: Union[:class:`TextChannel`, :class:`Object`]\n\n .. attribute:: verification_level\n\n The guild's verification level.\n\n See also :attr:`Guild.verification_level`.\n\n :type: :class:`VerificationLevel`\n\n .. attribute:: default_notifications\n\n The guild's default notification level.\n\n See also :attr:`Guild.default_notifications`.\n\n :type: :class:`NotificationLevel`\n\n .. attribute:: explicit_content_filter\n\n The guild's content filter.\n\n See also :attr:`Guild.explicit_content_filter`.\n\n :type: :class:`ContentFilter`\n\n .. attribute:: vanity_url_code\n\n The guild's vanity URL.\n\n See also :meth:`Guild.vanity_invite` and :meth:`Guild.edit`.\n\n :type: :class:`str`\n\n .. attribute:: position\n\n The position of a :class:`Role` or :class:`abc.GuildChannel`.\n\n :type: :class:`int`\n\n .. attribute:: type\n\n The type of channel, sticker, webhook or integration.\n\n :type: Union[:class:`ChannelType`, :class:`StickerType`, :class:`WebhookType`, :class:`str`]\n\n .. attribute:: topic\n\n The topic of a :class:`TextChannel` or :class:`StageChannel`.\n\n See also :attr:`TextChannel.topic` or :attr:`StageChannel.topic`.\n\n :type: :class:`str`\n\n .. attribute:: bitrate\n\n The bitrate of a :class:`VoiceChannel`.\n\n See also :attr:`VoiceChannel.bitrate`.\n\n :type: :class:`int`\n\n .. attribute:: overwrites\n\n A list of permission overwrite tuples that represents a target and a\n :class:`PermissionOverwrite` for said target.\n\n The first element is the object being targeted, which can either\n be a :class:`Member` or :class:`User` or :class:`Role`. If this object\n is not found then it is a :class:`Object` with an ID being filled and\n a ``type`` attribute set to either ``'role'`` or ``'member'`` to help\n decide what type of ID it is.\n\n :type: List[Tuple[target, :class:`PermissionOverwrite`]]\n\n .. attribute:: privacy_level\n\n The privacy level of the stage instance or scheduled event\n\n :type: :class:`PrivacyLevel`\n\n .. attribute:: roles\n\n A list of roles being added or removed from a member.\n\n If a role is not found then it is a :class:`Object` with the ID and name being\n filled in.\n\n :type: List[Union[:class:`Role`, :class:`Object`]]\n\n .. attribute:: nick\n\n The nickname of a member.\n\n See also :attr:`Member.nick`\n\n :type: Optional[:class:`str`]\n\n .. attribute:: deaf\n\n Whether the member is being server deafened.\n\n See also :attr:`VoiceState.deaf`.\n\n :type: :class:`bool`\n\n .. attribute:: mute\n\n Whether the member is being server muted.\n\n See also :attr:`VoiceState.mute`.\n\n :type: :class:`bool`\n\n .. attribute:: permissions\n\n The permissions of a role.\n\n See also :attr:`Role.permissions`.\n\n :type: :class:`Permissions`\n\n .. attribute:: colour\n color\n\n The colour of a role.\n\n See also :attr:`Role.colour`\n\n :type: :class:`Colour`\n\n .. attribute:: hoist\n\n Whether the role is being hoisted or not.\n\n See also :attr:`Role.hoist`\n\n :type: :class:`bool`\n\n .. attribute:: mentionable\n\n Whether the role is mentionable or not.\n\n See also :attr:`Role.mentionable`\n\n :type: :class:`bool`\n\n .. attribute:: code\n\n The invite's code.\n\n See also :attr:`Invite.code`\n\n :type: :class:`str`\n\n .. attribute:: channel\n\n A guild channel.\n\n If the channel is not found then it is a :class:`Object` with the ID\n being set. In some cases the channel name is also set.\n\n :type: Union[:class:`abc.GuildChannel`, :class:`Object`]\n\n .. attribute:: inviter\n\n The user who created the invite.\n\n See also :attr:`Invite.inviter`.\n\n :type: Optional[:class:`User`]\n\n .. attribute:: max_uses\n\n The invite's max uses.\n\n See also :attr:`Invite.max_uses`.\n\n :type: :class:`int`\n\n .. attribute:: uses\n\n The invite's current uses.\n\n See also :attr:`Invite.uses`.\n\n :type: :class:`int`\n\n .. attribute:: max_age\n\n The invite's max age in seconds.\n\n See also :attr:`Invite.max_age`.\n\n :type: :class:`int`\n\n .. attribute:: temporary\n\n If the invite is a temporary invite.\n\n See also :attr:`Invite.temporary`.\n\n :type: :class:`bool`\n\n .. attribute:: allow\n deny\n\n The permissions being allowed or denied.\n\n :type: :class:`Permissions`\n\n .. attribute:: id\n\n The ID of the object being changed.\n\n :type: :class:`int`\n\n .. attribute:: avatar\n\n The avatar of a member.\n\n See also :attr:`User.avatar`.\n\n :type: :class:`Asset`\n\n .. attribute:: slowmode_delay\n\n The number of seconds members have to wait before\n sending another message in the channel.\n\n See also :attr:`TextChannel.slowmode_delay`.\n\n :type: :class:`int`\n\n .. attribute:: rtc_region\n\n The region for the voice channel\u2019s voice communication.\n A value of ``None`` indicates automatic voice region detection.\n\n See also :attr:`VoiceChannel.rtc_region`.\n\n :type: :class:`str`\n\n .. attribute:: video_quality_mode\n\n The camera video quality for the voice channel's participants.\n\n See also :attr:`VoiceChannel.video_quality_mode`.\n\n :type: :class:`VideoQualityMode`\n\n .. attribute:: format_type\n\n The format type of a sticker being changed.\n\n See also :attr:`GuildSticker.format`\n\n :type: :class:`StickerFormatType`\n\n .. attribute:: emoji\n\n The name of the emoji that represents a sticker being changed.\n\n See also :attr:`GuildSticker.emoji`.\n\n :type: :class:`str`\n\n .. attribute:: unicode_emoji\n\n The unicode emoji that is used as an icon for the role being changed.\n\n See also :attr:`Role.unicode_emoji`.\n\n :type: :class:`str`\n\n .. attribute:: description\n\n The description of a guild, a sticker, or a scheduled event.\n\n See also :attr:`Guild.description`, :attr:`GuildSticker.description`, or\n :attr:`ScheduledEvent.description`.\n\n :type: :class:`str`\n\n .. attribute:: available\n\n The availability of a sticker being changed.\n\n See also :attr:`GuildSticker.available`\n\n :type: :class:`bool`\n\n .. attribute:: archived\n\n The thread is now archived.\n\n :type: :class:`bool`\n\n .. attribute:: locked\n\n The thread is being locked or unlocked.\n\n :type: :class:`bool`\n\n .. attribute:: auto_archive_duration\n\n The thread's auto archive duration being changed.\n\n See also :attr:`Thread.auto_archive_duration`\n\n :type: :class:`int`\n\n .. attribute:: default_auto_archive_duration\n\n The default auto archive duration for newly created threads being changed.\n\n :type: :class:`int`\n\n .. attribute:: invitable\n\n Whether non-moderators can add users to this private thread.\n\n :type: :class:`bool`\n\n .. attribute:: timed_out_until\n\n Whether the user is timed out, and if so until when.\n\n :type: Optional[:class:`datetime.datetime`]\n\n .. attribute:: enable_emoticons\n\n Integration emoticons were enabled or disabled.\n\n See also :attr:`StreamIntegration.enable_emoticons`\n\n :type: :class:`bool`\n\n .. attribute:: expire_behaviour\n expire_behavior\n\n The behaviour of expiring subscribers changed.\n\n See also :attr:`StreamIntegration.expire_behaviour`\n\n :type: :class:`ExpireBehaviour`\n\n .. attribute:: expire_grace_period\n\n The grace period before expiring subscribers changed.\n\n See also :attr:`StreamIntegration.expire_grace_period`\n\n :type: :class:`int`\n\n .. attribute:: preferred_locale\n\n The preferred locale for the guild changed.\n\n See also :attr:`Guild.preferred_locale`\n\n :type: :class:`Locale`\n\n .. attribute:: prune_delete_days\n\n The number of days after which inactive and role-unassigned members are kicked has been changed.\n\n :type: :class:`int`\n\n .. attribute:: status\n\n The status of the scheduled event.\n\n :type: :class:`EventStatus`\n\n .. attribute:: entity_type\n\n The type of entity this scheduled event is for.\n\n :type: :class:`EntityType`\n\n .. attribute:: cover_image\n\n The scheduled event's cover image.\n\n See also :attr:`ScheduledEvent.cover_image`.\n\n :type: :class:`Asset`\n\n .. attribute:: app_command_permissions\n\n List of permissions for the app command.\n\n :type: List[:class:`~discord.app_commands.AppCommandPermissions`]\n\n .. attribute:: enabled\n\n Whether the automod rule is active or not.\n\n :type: :class:`bool`\n\n .. attribute:: event_type\n\n The event type for triggering the automod rule.\n\n :type: :class:`AutoModRuleEventType`\n\n .. attribute:: trigger_type\n\n The trigger type for the automod rule.\n\n :type: :class:`AutoModRuleTriggerType`\n\n .. attribute:: trigger\n\n The trigger for the automod rule.\n\n .. note ::\n\n The :attr:`~AutoModTrigger.type` of the trigger may be incorrect.\n Some attributes such as :attr:`~AutoModTrigger.keyword_filter`, :attr:`~AutoModTrigger.regex_patterns`,\n and :attr:`~AutoModTrigger.allow_list` will only have the added or removed values.\n\n :type: :class:`AutoModTrigger`\n\n .. attribute:: actions\n\n The actions to take when an automod rule is triggered.\n\n :type: List[AutoModRuleAction]\n\n .. attribute:: exempt_roles\n\n The list of roles that are exempt from the automod rule.\n\n :type: List[Union[:class:`Role`, :class:`Object`]]\n\n .. attribute:: exempt_channels\n\n The list of channels or threads that are exempt from the automod rule.\n\n :type: List[:class:`abc.GuildChannel`, :class:`Thread`, :class:`Object`]\n\n .. attribute:: premium_progress_bar_enabled\n\n The guild\u2019s display setting to show boost progress bar.\n\n :type: :class:`bool`\n\n .. attribute:: system_channel_flags\n\n The guild\u2019s system channel settings.\n\n See also :attr:`Guild.system_channel_flags`\n\n :type: :class:`SystemChannelFlags`\n\n .. attribute:: nsfw\n\n Whether the channel is marked as \u201cnot safe for work\u201d or \u201cage restricted\u201d.\n\n :type: :class:`bool`\n\n .. attribute:: user_limit\n\n The channel\u2019s limit for number of members that can be in a voice or stage channel.\n\n See also :attr:`VoiceChannel.user_limit` and :attr:`StageChannel.user_limit`\n\n :type: :class:`int`\n\n .. attribute:: flags\n\n The channel flags associated with this thread or forum post.\n\n See also :attr:`ForumChannel.flags` and :attr:`Thread.flags`\n\n :type: :class:`ChannelFlags`\n\n .. attribute:: default_thread_slowmode_delay\n\n The default slowmode delay for threads created in this text channel or forum.\n\n See also :attr:`TextChannel.default_thread_slowmode_delay` and :attr:`ForumChannel.default_thread_slowmode_delay`\n\n :type: :class:`int`\n\n .. attribute:: applied_tags\n\n The applied tags of a forum post.\n\n See also :attr:`Thread.applied_tags`\n\n :type: List[Union[:class:`ForumTag`, :class:`Object`]]\n\n .. attribute:: available_tags\n\n The available tags of a forum.\n\n See also :attr:`ForumChannel.available_tags`\n\n :type: Sequence[:class:`ForumTag`]\n\n .. attribute:: default_reaction_emoji\n\n The default_reaction_emoji for forum posts.\n\n See also :attr:`ForumChannel.default_reaction_emoji`\n\n :type: Optional[:class:`PartialEmoji`]\n\n.. this is currently missing the following keys: reason and application_id\n I'm not sure how to port these\n\nWebhook Support\n------------------\n\ndiscord.py offers support for creating, editing, and executing webhooks through the :class:`Webhook` class.\n\nWebhook\n~~~~~~~~~\n\n.. attributetable:: Webhook\n\n.. autoclass:: Webhook()\n :members:\n :inherited-members:\n\nWebhookMessage\n~~~~~~~~~~~~~~~~\n\n.. attributetable:: WebhookMessage\n\n.. autoclass:: WebhookMessage()\n :members:\n :inherited-members:\n\nSyncWebhook\n~~~~~~~~~~~~\n\n.. attributetable:: SyncWebhook\n\n.. autoclass:: SyncWebhook()\n :members:\n :inherited-members:\n\nSyncWebhookMessage\n~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: SyncWebhookMessage\n\n.. autoclass:: SyncWebhookMessage()\n :members:\n\n.. _discord_api_abcs:\n\nAbstract Base Classes\n-----------------------\n\nAn :term:`abstract base class` (also known as an ``abc``) is a class that models can inherit\nto get their behaviour. **Abstract base classes should not be instantiated**.\nThey are mainly there for usage with :func:`isinstance` and :func:`issubclass`\\.\n\nThis library has a module related to abstract base classes, in which all the ABCs are subclasses of\n:class:`typing.Protocol`.\n\nSnowflake\n~~~~~~~~~~\n\n.. attributetable:: discord.abc.Snowflake\n\n.. autoclass:: discord.abc.Snowflake()\n :members:\n\nUser\n~~~~~\n\n.. attributetable:: discord.abc.User\n\n.. autoclass:: discord.abc.User()\n :members:\n\nPrivateChannel\n~~~~~~~~~~~~~~~\n\n.. attributetable:: discord.abc.PrivateChannel\n\n.. autoclass:: discord.abc.PrivateChannel()\n :members:\n\nGuildChannel\n~~~~~~~~~~~~~\n\n.. attributetable:: discord.abc.GuildChannel\n\n.. autoclass:: discord.abc.GuildChannel()\n :members:\n\nMessageable\n~~~~~~~~~~~~\n\n.. attributetable:: discord.abc.Messageable\n\n.. autoclass:: discord.abc.Messageable()\n :members:\n :exclude-members: typing\n\n .. automethod:: discord.abc.Messageable.typing\n :async-with:\n\nConnectable\n~~~~~~~~~~~~\n\n.. attributetable:: discord.abc.Connectable\n\n.. autoclass:: discord.abc.Connectable()\n :members:\n\n.. _discord_api_models:\n\nDiscord Models\n---------------\n\nModels are classes that are received from Discord and are not meant to be created by\nthe user of the library.\n\n.. danger::\n\n The classes listed below are **not intended to be created by users** and are also\n **read-only**.\n\n For example, this means that you should not make your own :class:`User` instances\n nor should you modify the :class:`User` instance yourself.\n\n If you want to get one of these model classes instances they'd have to be through\n the cache, and a common way of doing so is through the :func:`utils.find` function\n or attributes of model classes that you receive from the events specified in the\n :ref:`discord-api-events`.\n\n.. note::\n\n Nearly all classes here have :ref:`py:slots` defined which means that it is\n impossible to have dynamic attributes to the data classes.\n\n\nClientUser\n~~~~~~~~~~~~\n\n.. attributetable:: ClientUser\n\n.. autoclass:: ClientUser()\n :members:\n :inherited-members:\n\nUser\n~~~~~\n\n.. attributetable:: User\n\n.. autoclass:: User()\n :members:\n :inherited-members:\n :exclude-members: typing\n\n .. automethod:: typing\n :async-with:\n\nAutoMod\n~~~~~~~\n\n.. attributetable:: AutoModRule\n\n.. autoclass:: AutoModRule()\n :members:\n\n.. attributetable:: AutoModAction\n\n.. autoclass:: AutoModAction()\n :members:\n\nAttachment\n~~~~~~~~~~~\n\n.. attributetable:: Attachment\n\n.. autoclass:: Attachment()\n :members:\n\nAsset\n~~~~~\n\n.. attributetable:: Asset\n\n.. autoclass:: Asset()\n :members:\n :inherited-members:\n\nMessage\n~~~~~~~\n\n.. attributetable:: Message\n\n.. autoclass:: Message()\n :members:\n :inherited-members:\n\nDeletedReferencedMessage\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: DeletedReferencedMessage\n\n.. autoclass:: DeletedReferencedMessage()\n :members:\n\n\nReaction\n~~~~~~~~~\n\n.. attributetable:: Reaction\n\n.. autoclass:: Reaction()\n :members:\n\nGuild\n~~~~~~\n\n.. attributetable:: Guild\n\n.. autoclass:: Guild()\n :members:\n\n.. class:: BanEntry\n\n A namedtuple which represents a ban returned from :meth:`~Guild.bans`.\n\n .. attribute:: reason\n\n The reason this user was banned.\n\n :type: Optional[:class:`str`]\n .. attribute:: user\n\n The :class:`User` that was banned.\n\n :type: :class:`User`\n\n\nScheduledEvent\n~~~~~~~~~~~~~~\n\n.. attributetable:: ScheduledEvent\n\n.. autoclass:: ScheduledEvent()\n :members:\n\n\nIntegration\n~~~~~~~~~~~~\n\n.. attributetable:: Integration\n\n.. autoclass:: Integration()\n :members:\n\n.. attributetable:: IntegrationAccount\n\n.. autoclass:: IntegrationAccount()\n :members:\n\n.. attributetable:: BotIntegration\n\n.. autoclass:: BotIntegration()\n :members:\n\n.. attributetable:: IntegrationApplication\n\n.. autoclass:: IntegrationApplication()\n :members:\n\n.. attributetable:: StreamIntegration\n\n.. autoclass:: StreamIntegration()\n :members:\n\n.. attributetable:: PartialIntegration\n\n.. autoclass:: PartialIntegration()\n :members:\n\nMember\n~~~~~~\n\n.. attributetable:: Member\n\n.. autoclass:: Member()\n :members:\n :inherited-members:\n :exclude-members: typing\n\n .. automethod:: typing\n :async-with:\n\nSpotify\n~~~~~~~~\n\n.. attributetable:: Spotify\n\n.. autoclass:: Spotify()\n :members:\n\nVoiceState\n~~~~~~~~~~~\n\n.. attributetable:: VoiceState\n\n.. autoclass:: VoiceState()\n :members:\n\nEmoji\n~~~~~\n\n.. attributetable:: Emoji\n\n.. autoclass:: Emoji()\n :members:\n :inherited-members:\n\nPartialEmoji\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: PartialEmoji\n\n.. autoclass:: PartialEmoji()\n :members:\n :inherited-members:\n\nRole\n~~~~~\n\n.. attributetable:: Role\n\n.. autoclass:: Role()\n :members:\n\nRoleTags\n~~~~~~~~~~\n\n.. attributetable:: RoleTags\n\n.. autoclass:: RoleTags()\n :members:\n\nPartialMessageable\n~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: PartialMessageable\n\n.. autoclass:: PartialMessageable()\n :members:\n :inherited-members:\n\nTextChannel\n~~~~~~~~~~~~\n\n.. attributetable:: TextChannel\n\n.. autoclass:: TextChannel()\n :members:\n :inherited-members:\n :exclude-members: typing\n\n .. automethod:: typing\n :async-with:\n\nForumChannel\n~~~~~~~~~~~~~\n\n.. attributetable:: ForumChannel\n\n.. autoclass:: ForumChannel()\n :members:\n :inherited-members:\n\nThread\n~~~~~~~~\n\n.. attributetable:: Thread\n\n.. autoclass:: Thread()\n :members:\n :inherited-members:\n :exclude-members: typing\n\n .. automethod:: typing\n :async-with:\n\nThreadMember\n~~~~~~~~~~~~~\n\n.. attributetable:: ThreadMember\n\n.. autoclass:: ThreadMember()\n :members:\n\nVoiceChannel\n~~~~~~~~~~~~~\n\n.. attributetable:: VoiceChannel\n\n.. autoclass:: VoiceChannel()\n :members:\n :inherited-members:\n\nStageChannel\n~~~~~~~~~~~~~\n\n.. attributetable:: StageChannel\n\n.. autoclass:: StageChannel()\n :members:\n :inherited-members:\n\n\nStageInstance\n~~~~~~~~~~~~~~\n\n.. attributetable:: StageInstance\n\n.. autoclass:: StageInstance()\n :members:\n\nCategoryChannel\n~~~~~~~~~~~~~~~~~\n\n.. attributetable:: CategoryChannel\n\n.. autoclass:: CategoryChannel()\n :members:\n :inherited-members:\n\nDMChannel\n~~~~~~~~~\n\n.. attributetable:: DMChannel\n\n.. autoclass:: DMChannel()\n :members:\n :inherited-members:\n :exclude-members: typing\n\n .. automethod:: typing\n :async-with:\n\nGroupChannel\n~~~~~~~~~~~~\n\n.. attributetable:: GroupChannel\n\n.. autoclass:: GroupChannel()\n :members:\n :inherited-members:\n :exclude-members: typing\n\n .. automethod:: typing\n :async-with:\n\nPartialInviteGuild\n~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: PartialInviteGuild\n\n.. autoclass:: PartialInviteGuild()\n :members:\n\nPartialInviteChannel\n~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: PartialInviteChannel\n\n.. autoclass:: PartialInviteChannel()\n :members:\n\nInvite\n~~~~~~~\n\n.. attributetable:: Invite\n\n.. autoclass:: Invite()\n :members:\n\nTemplate\n~~~~~~~~~\n\n.. attributetable:: Template\n\n.. autoclass:: Template()\n :members:\n\nWelcomeScreen\n~~~~~~~~~~~~~~~\n\n.. attributetable:: WelcomeScreen\n\n.. autoclass:: WelcomeScreen()\n :members:\n\nWelcomeChannel\n~~~~~~~~~~~~~~~\n\n.. attributetable:: WelcomeChannel\n\n.. autoclass:: WelcomeChannel()\n :members:\n\nWidgetChannel\n~~~~~~~~~~~~~~~\n\n.. attributetable:: WidgetChannel\n\n.. autoclass:: WidgetChannel()\n :members:\n\nWidgetMember\n~~~~~~~~~~~~~\n\n.. attributetable:: WidgetMember\n\n.. autoclass:: WidgetMember()\n :members:\n :inherited-members:\n\nWidget\n~~~~~~~\n\n.. attributetable:: Widget\n\n.. autoclass:: Widget()\n :members:\n\nStickerPack\n~~~~~~~~~~~~~\n\n.. attributetable:: StickerPack\n\n.. autoclass:: StickerPack()\n :members:\n\nStickerItem\n~~~~~~~~~~~~~\n\n.. attributetable:: StickerItem\n\n.. autoclass:: StickerItem()\n :members:\n\nSticker\n~~~~~~~~~~~~~~~\n\n.. attributetable:: Sticker\n\n.. autoclass:: Sticker()\n :members:\n\nStandardSticker\n~~~~~~~~~~~~~~~~\n\n.. attributetable:: StandardSticker\n\n.. autoclass:: StandardSticker()\n :members:\n\nGuildSticker\n~~~~~~~~~~~~~\n\n.. attributetable:: GuildSticker\n\n.. autoclass:: GuildSticker()\n :members:\n\nShardInfo\n~~~~~~~~~~~\n\n.. attributetable:: ShardInfo\n\n.. autoclass:: ShardInfo()\n :members:\n\nSKU\n~~~~~~~~~~~\n\n.. attributetable:: SKU\n\n.. autoclass:: SKU()\n :members:\n\nEntitlement\n~~~~~~~~~~~\n\n.. attributetable:: Entitlement\n\n.. autoclass:: Entitlement()\n :members:\n\nRawMessageDeleteEvent\n~~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawMessageDeleteEvent\n\n.. autoclass:: RawMessageDeleteEvent()\n :members:\n\nRawBulkMessageDeleteEvent\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawBulkMessageDeleteEvent\n\n.. autoclass:: RawBulkMessageDeleteEvent()\n :members:\n\nRawMessageUpdateEvent\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawMessageUpdateEvent\n\n.. autoclass:: RawMessageUpdateEvent()\n :members:\n\nRawReactionActionEvent\n~~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawReactionActionEvent\n\n.. autoclass:: RawReactionActionEvent()\n :members:\n\nRawReactionClearEvent\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawReactionClearEvent\n\n.. autoclass:: RawReactionClearEvent()\n :members:\n\nRawReactionClearEmojiEvent\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawReactionClearEmojiEvent\n\n.. autoclass:: RawReactionClearEmojiEvent()\n :members:\n\nRawIntegrationDeleteEvent\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawIntegrationDeleteEvent\n\n.. autoclass:: RawIntegrationDeleteEvent()\n :members:\n\nRawThreadUpdateEvent\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawThreadUpdateEvent\n\n.. autoclass:: RawThreadUpdateEvent()\n :members:\n\nRawThreadMembersUpdate\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawThreadMembersUpdate\n\n.. autoclass:: RawThreadMembersUpdate()\n :members:\n\nRawThreadDeleteEvent\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawThreadDeleteEvent\n\n.. autoclass:: RawThreadDeleteEvent()\n :members:\n\nRawTypingEvent\n~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawTypingEvent\n\n.. autoclass:: RawTypingEvent()\n :members:\n\nRawMemberRemoveEvent\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawMemberRemoveEvent\n\n.. autoclass:: RawMemberRemoveEvent()\n :members:\n\nRawAppCommandPermissionsUpdateEvent\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawAppCommandPermissionsUpdateEvent\n\n.. autoclass:: RawAppCommandPermissionsUpdateEvent()\n :members:\n\nPartialWebhookGuild\n~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: PartialWebhookGuild\n\n.. autoclass:: PartialWebhookGuild()\n :members:\n\nPartialWebhookChannel\n~~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: PartialWebhookChannel\n\n.. autoclass:: PartialWebhookChannel()\n :members:\n\n.. _discord_api_data:\n\nData Classes\n--------------\n\nSome classes are just there to be data containers, this lists them.\n\nUnlike :ref:`models ` you are allowed to create\nmost of these yourself, even if they can also be used to hold attributes.\n\nNearly all classes here have :ref:`py:slots` defined which means that it is\nimpossible to have dynamic attributes to the data classes.\n\nThe only exception to this rule is :class:`Object`, which is made with\ndynamic attributes in mind.\n\n\nObject\n~~~~~~~\n\n.. attributetable:: Object\n\n.. autoclass:: Object\n :members:\n\nEmbed\n~~~~~~\n\n.. attributetable:: Embed\n\n.. autoclass:: Embed\n :members:\n\nAllowedMentions\n~~~~~~~~~~~~~~~~~\n\n.. attributetable:: AllowedMentions\n\n.. autoclass:: AllowedMentions\n :members:\n\nMessageReference\n~~~~~~~~~~~~~~~~~\n\n.. attributetable:: MessageReference\n\n.. autoclass:: MessageReference\n :members:\n\nPartialMessage\n~~~~~~~~~~~~~~~~~\n\n.. attributetable:: PartialMessage\n\n.. autoclass:: PartialMessage\n :members:\n\nMessageApplication\n~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: MessageApplication\n\n.. autoclass:: MessageApplication\n :members:\n\nRoleSubscriptionInfo\n~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RoleSubscriptionInfo\n\n.. autoclass:: RoleSubscriptionInfo\n :members:\n\nIntents\n~~~~~~~~~~\n\n.. attributetable:: Intents\n\n.. autoclass:: Intents\n :members:\n\nMemberCacheFlags\n~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: MemberCacheFlags\n\n.. autoclass:: MemberCacheFlags\n :members:\n\nApplicationFlags\n~~~~~~~~~~~~~~~~~\n\n.. attributetable:: ApplicationFlags\n\n.. autoclass:: ApplicationFlags\n :members:\n\nChannelFlags\n~~~~~~~~~~~~~~\n\n.. attributetable:: ChannelFlags\n\n.. autoclass:: ChannelFlags\n :members:\n\nAutoModPresets\n~~~~~~~~~~~~~~\n\n.. attributetable:: AutoModPresets\n\n.. autoclass:: AutoModPresets\n :members:\n\nAutoModRuleAction\n~~~~~~~~~~~~~~~~~\n\n.. attributetable:: AutoModRuleAction\n\n.. autoclass:: AutoModRuleAction\n :members:\n\nAutoModTrigger\n~~~~~~~~~~~~~~\n\n.. attributetable:: AutoModTrigger\n\n.. autoclass:: AutoModTrigger\n :members:\n\nFile\n~~~~~\n\n.. attributetable:: File\n\n.. autoclass:: File\n :members:\n\nColour\n~~~~~~\n\n.. attributetable:: Colour\n\n.. autoclass:: Colour\n :members:\n\nBaseActivity\n~~~~~~~~~~~~~~\n\n.. attributetable:: BaseActivity\n\n.. autoclass:: BaseActivity\n :members:\n\nActivity\n~~~~~~~~~\n\n.. attributetable:: Activity\n\n.. autoclass:: Activity\n :members:\n\nGame\n~~~~~\n\n.. attributetable:: Game\n\n.. autoclass:: Game\n :members:\n\nStreaming\n~~~~~~~~~~~\n\n.. attributetable:: Streaming\n\n.. autoclass:: Streaming\n :members:\n\nCustomActivity\n~~~~~~~~~~~~~~~\n\n.. attributetable:: CustomActivity\n\n.. autoclass:: CustomActivity\n :members:\n\nPermissions\n~~~~~~~~~~~~\n\n.. attributetable:: Permissions\n\n.. autoclass:: Permissions\n :members:\n\nPermissionOverwrite\n~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: PermissionOverwrite\n\n.. autoclass:: PermissionOverwrite\n :members:\n\nSystemChannelFlags\n~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: SystemChannelFlags\n\n.. autoclass:: SystemChannelFlags\n :members:\n\nMessageFlags\n~~~~~~~~~~~~\n\n.. attributetable:: MessageFlags\n\n.. autoclass:: MessageFlags\n :members:\n\nPublicUserFlags\n~~~~~~~~~~~~~~~\n\n.. attributetable:: PublicUserFlags\n\n.. autoclass:: PublicUserFlags\n :members:\n\nMemberFlags\n~~~~~~~~~~~~\n\n.. attributetable:: MemberFlags\n\n.. autoclass:: MemberFlags\n :members:\n\nAttachmentFlags\n~~~~~~~~~~~~~~~~\n\n.. attributetable:: AttachmentFlags\n\n.. autoclass:: AttachmentFlags\n :members:\n\nRoleFlags\n~~~~~~~~~~\n\n.. attributetable:: RoleFlags\n\n.. autoclass:: RoleFlags\n :members:\n\nSKUFlags\n~~~~~~~~~~~\n\n.. attributetable:: SKUFlags\n\n.. autoclass:: SKUFlags()\n :members:\n\nForumTag\n~~~~~~~~~\n\n.. attributetable:: ForumTag\n\n.. autoclass:: ForumTag\n :members:\n\n\nExceptions\n------------\n\nThe following exceptions are thrown by the library.\n\n.. autoexception:: DiscordException\n\n.. autoexception:: ClientException\n\n.. autoexception:: LoginFailure\n\n.. autoexception:: HTTPException\n :members:\n\n.. autoexception:: RateLimited\n :members:\n\n.. autoexception:: Forbidden\n\n.. autoexception:: NotFound\n\n.. autoexception:: DiscordServerError\n\n.. autoexception:: InvalidData\n\n.. autoexception:: GatewayNotFound\n\n.. autoexception:: ConnectionClosed\n\n.. autoexception:: PrivilegedIntentsRequired\n\n.. autoexception:: InteractionResponded\n\n.. autoexception:: discord.opus.OpusError\n\n.. autoexception:: discord.opus.OpusNotLoaded\n\nException Hierarchy\n~~~~~~~~~~~~~~~~~~~~~\n\n.. exception_hierarchy::\n\n - :exc:`Exception`\n - :exc:`DiscordException`\n - :exc:`ClientException`\n - :exc:`InvalidData`\n - :exc:`LoginFailure`\n - :exc:`ConnectionClosed`\n - :exc:`PrivilegedIntentsRequired`\n - :exc:`InteractionResponded`\n - :exc:`GatewayNotFound`\n - :exc:`HTTPException`\n - :exc:`Forbidden`\n - :exc:`NotFound`\n - :exc:`DiscordServerError`\n - :exc:`app_commands.CommandSyncFailure`\n - :exc:`RateLimited`\n" } ], "language": "python" }, { "id": "10_1", "repo_url": "https://github.com/teamqurrent/discord.py", "instruction": "Your task is to introduce new message types related to guild incidents in the discord.py library. Specifically, add the message types guild_incident_alert_mode_enabled, guild_incident_alert_mode_disabled, guild_incident_report_raid, and guild_incident_report_false_alarm with respective values 36, 37, 38, and 39. These changes should be made in the `enums.py` file to update the `MessageType` enumeration. Additionally, update the `message.py` file to handle these new types appropriately.", "base_commit": "9db0dad", "test_script": "import unittest\nimport sys\n\n\n\nclass TestNewIncidentMessageTypes(unittest.TestCase):\n def setUp(self):\n from unittest.mock import Mock\n\n # Mock data for testing\n self.mock_state = Mock()\n self.mock_channel = Mock()\n self.mock_data = {'type': 0, 'content': '', 'author': {'id': 123, 'username': 'TestUser', 'avatar': None, 'discriminator': '0001'}, 'channel_id': 123456789}\n\n def test_incident_message_types(self):\n from discord import MessageType\n # Check if new incident message types are present in the MessageType enumeration\n new_types = [\n 'guild_incident_alert_mode_enabled',\n 'guild_incident_alert_mode_disabled',\n 'guild_incident_report_raid',\n 'guild_incident_report_false_alarm'\n ]\n\n # Verify the presence of each new message type\n for type_name in new_types:\n with self.subTest(type_name=type_name):\n self.assertTrue(any(mt.name == type_name for mt in MessageType), f\"{type_name} is missing\")\n\n def test_incident_message_type_values(self):\n from discord import MessageType \n # Check if new incident message type values are correctly added\n new_type_values = [36, 37, 38, 39]\n\n # Verify the presence of each new message type value\n for value in new_type_values:\n with self.subTest(value=value):\n self.assertIn(value, [mt.value for mt in MessageType], f\"Message type value {value} is missing\")\n \ndef main():\n\n\n suite = unittest.TestSuite()\n suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestNewIncidentMessageTypes))\n runner = unittest.TextTestRunner()\n\n if runner.run(suite).wasSuccessful():\n sys.exit(0)\n else:\n sys.exit(1)\n\nif __name__ == '__main__':\n\n main()\n", "testbed_environment": "python3.9", "requirements_txt": "discord", "solution_commit": "08ef42fe", "solution_patch": "diff --git a/discord/enums.py b/discord/enums.py\n--- a/discord/enums.py\n+++ b/discord/enums.py\n@@ -247,6 +247,10 @@ class MessageType(Enum):\n stage_raise_hand = 30\n stage_topic = 31\n guild_application_premium_subscription = 32\n+ guild_incident_alert_mode_enabled = 36\n+ guild_incident_alert_mode_disabled = 37\n+ guild_incident_report_raid = 38\n+ guild_incident_report_false_alarm = 39\n \n \n class SpeakingState(Enum):\ndiff --git a/discord/message.py b/discord/message.py\n--- a/discord/message.py\n+++ b/discord/message.py\n@@ -2216,6 +2216,20 @@ class Message(PartialMessage, Hashable):\n if self.type is MessageType.stage_topic:\n return f'{self.author.name} changed Stage topic: **{self.content}**.'\n \n+ if self.type is MessageType.guild_incident_alert_mode_enabled:\n+ dt = utils.parse_time(self.content)\n+ dt_content = utils.format_dt(dt)\n+ return f'{self.author.name} enabled security actions until {dt_content}.'\n+\n+ if self.type is MessageType.guild_incident_alert_mode_disabled:\n+ return f'{self.author.name} disabled security actions.'\n+\n+ if self.type is MessageType.guild_incident_report_raid:\n+ return f'{self.author.name} reported a raid in {self.guild}.'\n+\n+ if self.type is MessageType.guild_incident_report_false_alarm:\n+ return f'{self.author.name} reported a false alarm in {self.guild}.'\n+\n # Fallback for unknown message types\n return ''\n \ndiff --git a/discord/types/message.py b/discord/types/message.py\n--- a/discord/types/message.py\n+++ b/discord/types/message.py\n@@ -113,7 +113,40 @@ class RoleSubscriptionData(TypedDict):\n \n \n MessageType = Literal[\n- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32\n+ 0,\n+ 1,\n+ 2,\n+ 3,\n+ 4,\n+ 5,\n+ 6,\n+ 7,\n+ 8,\n+ 9,\n+ 10,\n+ 11,\n+ 12,\n+ 14,\n+ 15,\n+ 18,\n+ 19,\n+ 20,\n+ 21,\n+ 22,\n+ 23,\n+ 24,\n+ 25,\n+ 26,\n+ 27,\n+ 28,\n+ 29,\n+ 30,\n+ 31,\n+ 32,\n+ 36,\n+ 37,\n+ 38,\n+ 39,\n ]\n \n \ndiff --git a/docs/api.rst b/docs/api.rst\n--- a/docs/api.rst\n+++ b/docs/api.rst\n@@ -1745,6 +1745,30 @@ of :class:`enum.Enum`.\n \n .. versionadded:: 2.2\n \n+ .. attribute:: guild_incident_alert_mode_enabled\n+\n+ The system message sent when security actions is enabled.\n+\n+ .. versionadded:: 2.4\n+\n+ .. attribute:: guild_incident_alert_mode_disabled\n+\n+ The system message sent when security actions is disabled.\n+\n+ .. versionadded:: 2.4\n+\n+ .. attribute:: guild_incident_report_raid\n+\n+ The system message sent when a raid is reported.\n+\n+ .. versionadded:: 2.4\n+\n+ .. attribute:: guild_incident_report_false_alarm\n+\n+ The system message sent when a false alarm is reported.\n+\n+ .. versionadded:: 2.4\n+\n .. class:: UserFlags\n \n Represents Discord User flags.\n", "modified_files": [ { "path": "discord/enums.py", "content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\nfrom __future__ import annotations\n\nimport types\nfrom collections import namedtuple\nfrom typing import Any, ClassVar, Dict, List, Optional, TYPE_CHECKING, Tuple, Type, TypeVar, Iterator, Mapping\n\n__all__ = (\n 'Enum',\n 'ChannelType',\n 'MessageType',\n 'SpeakingState',\n 'VerificationLevel',\n 'ContentFilter',\n 'Status',\n 'DefaultAvatar',\n 'AuditLogAction',\n 'AuditLogActionCategory',\n 'UserFlags',\n 'ActivityType',\n 'NotificationLevel',\n 'TeamMembershipState',\n 'TeamMemberRole',\n 'WebhookType',\n 'ExpireBehaviour',\n 'ExpireBehavior',\n 'StickerType',\n 'StickerFormatType',\n 'InviteTarget',\n 'VideoQualityMode',\n 'ComponentType',\n 'ButtonStyle',\n 'TextStyle',\n 'PrivacyLevel',\n 'InteractionType',\n 'InteractionResponseType',\n 'NSFWLevel',\n 'MFALevel',\n 'Locale',\n 'EntityType',\n 'EventStatus',\n 'AppCommandType',\n 'AppCommandOptionType',\n 'AppCommandPermissionType',\n 'AutoModRuleTriggerType',\n 'AutoModRuleEventType',\n 'AutoModRuleActionType',\n 'ForumLayoutType',\n 'ForumOrderType',\n 'SelectDefaultValueType',\n 'SKUType',\n 'EntitlementType',\n 'EntitlementOwnerType',\n)\n\nif TYPE_CHECKING:\n from typing_extensions import Self\n\n\ndef _create_value_cls(name: str, comparable: bool):\n # All the type ignores here are due to the type checker being unable to recognise\n # Runtime type creation without exploding.\n cls = namedtuple('_EnumValue_' + name, 'name value')\n cls.__repr__ = lambda self: f'<{name}.{self.name}: {self.value!r}>' # type: ignore\n cls.__str__ = lambda self: f'{name}.{self.name}' # type: ignore\n if comparable:\n cls.__le__ = lambda self, other: isinstance(other, self.__class__) and self.value <= other.value # type: ignore\n cls.__ge__ = lambda self, other: isinstance(other, self.__class__) and self.value >= other.value # type: ignore\n cls.__lt__ = lambda self, other: isinstance(other, self.__class__) and self.value < other.value # type: ignore\n cls.__gt__ = lambda self, other: isinstance(other, self.__class__) and self.value > other.value # type: ignore\n return cls\n\n\ndef _is_descriptor(obj):\n return hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__')\n\n\nclass EnumMeta(type):\n if TYPE_CHECKING:\n __name__: ClassVar[str]\n _enum_member_names_: ClassVar[List[str]]\n _enum_member_map_: ClassVar[Dict[str, Any]]\n _enum_value_map_: ClassVar[Dict[Any, Any]]\n\n def __new__(cls, name: str, bases: Tuple[type, ...], attrs: Dict[str, Any], *, comparable: bool = False) -> Self:\n value_mapping = {}\n member_mapping = {}\n member_names = []\n\n value_cls = _create_value_cls(name, comparable)\n for key, value in list(attrs.items()):\n is_descriptor = _is_descriptor(value)\n if key[0] == '_' and not is_descriptor:\n continue\n\n # Special case classmethod to just pass through\n if isinstance(value, classmethod):\n continue\n\n if is_descriptor:\n setattr(value_cls, key, value)\n del attrs[key]\n continue\n\n try:\n new_value = value_mapping[value]\n except KeyError:\n new_value = value_cls(name=key, value=value)\n value_mapping[value] = new_value\n member_names.append(key)\n\n member_mapping[key] = new_value\n attrs[key] = new_value\n\n attrs['_enum_value_map_'] = value_mapping\n attrs['_enum_member_map_'] = member_mapping\n attrs['_enum_member_names_'] = member_names\n attrs['_enum_value_cls_'] = value_cls\n actual_cls = super().__new__(cls, name, bases, attrs)\n value_cls._actual_enum_cls_ = actual_cls # type: ignore # Runtime attribute isn't understood\n return actual_cls\n\n def __iter__(cls) -> Iterator[Any]:\n return (cls._enum_member_map_[name] for name in cls._enum_member_names_)\n\n def __reversed__(cls) -> Iterator[Any]:\n return (cls._enum_member_map_[name] for name in reversed(cls._enum_member_names_))\n\n def __len__(cls) -> int:\n return len(cls._enum_member_names_)\n\n def __repr__(cls) -> str:\n return f''\n\n @property\n def __members__(cls) -> Mapping[str, Any]:\n return types.MappingProxyType(cls._enum_member_map_)\n\n def __call__(cls, value: str) -> Any:\n try:\n return cls._enum_value_map_[value]\n except (KeyError, TypeError):\n raise ValueError(f\"{value!r} is not a valid {cls.__name__}\")\n\n def __getitem__(cls, key: str) -> Any:\n return cls._enum_member_map_[key]\n\n def __setattr__(cls, name: str, value: Any) -> None:\n raise TypeError('Enums are immutable.')\n\n def __delattr__(cls, attr: str) -> None:\n raise TypeError('Enums are immutable')\n\n def __instancecheck__(self, instance: Any) -> bool:\n # isinstance(x, Y)\n # -> __instancecheck__(Y, x)\n try:\n return instance._actual_enum_cls_ is self\n except AttributeError:\n return False\n\n\nif TYPE_CHECKING:\n from enum import Enum\nelse:\n\n class Enum(metaclass=EnumMeta):\n @classmethod\n def try_value(cls, value):\n try:\n return cls._enum_value_map_[value]\n except (KeyError, TypeError):\n return value\n\n\nclass ChannelType(Enum):\n text = 0\n private = 1\n voice = 2\n group = 3\n category = 4\n news = 5\n news_thread = 10\n public_thread = 11\n private_thread = 12\n stage_voice = 13\n forum = 15\n media = 16\n\n def __str__(self) -> str:\n return self.name\n\n\nclass MessageType(Enum):\n default = 0\n recipient_add = 1\n recipient_remove = 2\n call = 3\n channel_name_change = 4\n channel_icon_change = 5\n pins_add = 6\n new_member = 7\n premium_guild_subscription = 8\n premium_guild_tier_1 = 9\n premium_guild_tier_2 = 10\n premium_guild_tier_3 = 11\n channel_follow_add = 12\n guild_stream = 13\n guild_discovery_disqualified = 14\n guild_discovery_requalified = 15\n guild_discovery_grace_period_initial_warning = 16\n guild_discovery_grace_period_final_warning = 17\n thread_created = 18\n reply = 19\n chat_input_command = 20\n thread_starter_message = 21\n guild_invite_reminder = 22\n context_menu_command = 23\n auto_moderation_action = 24\n role_subscription_purchase = 25\n interaction_premium_upsell = 26\n stage_start = 27\n stage_end = 28\n stage_speaker = 29\n stage_raise_hand = 30\n stage_topic = 31\n guild_application_premium_subscription = 32\n\n\nclass SpeakingState(Enum):\n none = 0\n voice = 1\n soundshare = 2\n priority = 4\n\n def __str__(self) -> str:\n return self.name\n\n def __int__(self) -> int:\n return self.value\n\n\nclass VerificationLevel(Enum, comparable=True):\n none = 0\n low = 1\n medium = 2\n high = 3\n highest = 4\n\n def __str__(self) -> str:\n return self.name\n\n\nclass ContentFilter(Enum, comparable=True):\n disabled = 0\n no_role = 1\n all_members = 2\n\n def __str__(self) -> str:\n return self.name\n\n\nclass Status(Enum):\n online = 'online'\n offline = 'offline'\n idle = 'idle'\n dnd = 'dnd'\n do_not_disturb = 'dnd'\n invisible = 'invisible'\n\n def __str__(self) -> str:\n return self.value\n\n\nclass DefaultAvatar(Enum):\n blurple = 0\n grey = 1\n gray = 1\n green = 2\n orange = 3\n red = 4\n pink = 5\n\n def __str__(self) -> str:\n return self.name\n\n\nclass NotificationLevel(Enum, comparable=True):\n all_messages = 0\n only_mentions = 1\n\n\nclass AuditLogActionCategory(Enum):\n create = 1\n delete = 2\n update = 3\n\n\nclass AuditLogAction(Enum):\n # fmt: off\n guild_update = 1\n channel_create = 10\n channel_update = 11\n channel_delete = 12\n overwrite_create = 13\n overwrite_update = 14\n overwrite_delete = 15\n kick = 20\n member_prune = 21\n ban = 22\n unban = 23\n member_update = 24\n member_role_update = 25\n member_move = 26\n member_disconnect = 27\n bot_add = 28\n role_create = 30\n role_update = 31\n role_delete = 32\n invite_create = 40\n invite_update = 41\n invite_delete = 42\n webhook_create = 50\n webhook_update = 51\n webhook_delete = 52\n emoji_create = 60\n emoji_update = 61\n emoji_delete = 62\n message_delete = 72\n message_bulk_delete = 73\n message_pin = 74\n message_unpin = 75\n integration_create = 80\n integration_update = 81\n integration_delete = 82\n stage_instance_create = 83\n stage_instance_update = 84\n stage_instance_delete = 85\n sticker_create = 90\n sticker_update = 91\n sticker_delete = 92\n scheduled_event_create = 100\n scheduled_event_update = 101\n scheduled_event_delete = 102\n thread_create = 110\n thread_update = 111\n thread_delete = 112\n app_command_permission_update = 121\n automod_rule_create = 140\n automod_rule_update = 141\n automod_rule_delete = 142\n automod_block_message = 143\n automod_flag_message = 144\n automod_timeout_member = 145\n creator_monetization_request_created = 150\n creator_monetization_terms_accepted = 151\n # fmt: on\n\n @property\n def category(self) -> Optional[AuditLogActionCategory]:\n # fmt: off\n lookup: Dict[AuditLogAction, Optional[AuditLogActionCategory]] = {\n AuditLogAction.guild_update: AuditLogActionCategory.update,\n AuditLogAction.channel_create: AuditLogActionCategory.create,\n AuditLogAction.channel_update: AuditLogActionCategory.update,\n AuditLogAction.channel_delete: AuditLogActionCategory.delete,\n AuditLogAction.overwrite_create: AuditLogActionCategory.create,\n AuditLogAction.overwrite_update: AuditLogActionCategory.update,\n AuditLogAction.overwrite_delete: AuditLogActionCategory.delete,\n AuditLogAction.kick: None,\n AuditLogAction.member_prune: None,\n AuditLogAction.ban: None,\n AuditLogAction.unban: None,\n AuditLogAction.member_update: AuditLogActionCategory.update,\n AuditLogAction.member_role_update: AuditLogActionCategory.update,\n AuditLogAction.member_move: None,\n AuditLogAction.member_disconnect: None,\n AuditLogAction.bot_add: None,\n AuditLogAction.role_create: AuditLogActionCategory.create,\n AuditLogAction.role_update: AuditLogActionCategory.update,\n AuditLogAction.role_delete: AuditLogActionCategory.delete,\n AuditLogAction.invite_create: AuditLogActionCategory.create,\n AuditLogAction.invite_update: AuditLogActionCategory.update,\n AuditLogAction.invite_delete: AuditLogActionCategory.delete,\n AuditLogAction.webhook_create: AuditLogActionCategory.create,\n AuditLogAction.webhook_update: AuditLogActionCategory.update,\n AuditLogAction.webhook_delete: AuditLogActionCategory.delete,\n AuditLogAction.emoji_create: AuditLogActionCategory.create,\n AuditLogAction.emoji_update: AuditLogActionCategory.update,\n AuditLogAction.emoji_delete: AuditLogActionCategory.delete,\n AuditLogAction.message_delete: AuditLogActionCategory.delete,\n AuditLogAction.message_bulk_delete: AuditLogActionCategory.delete,\n AuditLogAction.message_pin: None,\n AuditLogAction.message_unpin: None,\n AuditLogAction.integration_create: AuditLogActionCategory.create,\n AuditLogAction.integration_update: AuditLogActionCategory.update,\n AuditLogAction.integration_delete: AuditLogActionCategory.delete,\n AuditLogAction.stage_instance_create: AuditLogActionCategory.create,\n AuditLogAction.stage_instance_update: AuditLogActionCategory.update,\n AuditLogAction.stage_instance_delete: AuditLogActionCategory.delete,\n AuditLogAction.sticker_create: AuditLogActionCategory.create,\n AuditLogAction.sticker_update: AuditLogActionCategory.update,\n AuditLogAction.sticker_delete: AuditLogActionCategory.delete,\n AuditLogAction.scheduled_event_create: AuditLogActionCategory.create,\n AuditLogAction.scheduled_event_update: AuditLogActionCategory.update,\n AuditLogAction.scheduled_event_delete: AuditLogActionCategory.delete,\n AuditLogAction.thread_create: AuditLogActionCategory.create,\n AuditLogAction.thread_delete: AuditLogActionCategory.delete,\n AuditLogAction.thread_update: AuditLogActionCategory.update,\n AuditLogAction.app_command_permission_update: AuditLogActionCategory.update,\n AuditLogAction.automod_rule_create: AuditLogActionCategory.create,\n AuditLogAction.automod_rule_update: AuditLogActionCategory.update,\n AuditLogAction.automod_rule_delete: AuditLogActionCategory.delete,\n AuditLogAction.automod_block_message: None,\n AuditLogAction.automod_flag_message: None,\n AuditLogAction.automod_timeout_member: None,\n AuditLogAction.creator_monetization_request_created: None,\n AuditLogAction.creator_monetization_terms_accepted: None,\n }\n # fmt: on\n return lookup[self]\n\n @property\n def target_type(self) -> Optional[str]:\n v = self.value\n if v == -1:\n return 'all'\n elif v < 10:\n return 'guild'\n elif v < 20:\n return 'channel'\n elif v < 30:\n return 'user'\n elif v < 40:\n return 'role'\n elif v < 50:\n return 'invite'\n elif v < 60:\n return 'webhook'\n elif v < 70:\n return 'emoji'\n elif v == 73:\n return 'channel'\n elif v < 80:\n return 'message'\n elif v < 83:\n return 'integration'\n elif v < 90:\n return 'stage_instance'\n elif v < 93:\n return 'sticker'\n elif v < 103:\n return 'guild_scheduled_event'\n elif v < 113:\n return 'thread'\n elif v < 122:\n return 'integration_or_app_command'\n elif v < 143:\n return 'auto_moderation'\n elif v < 146:\n return 'user'\n elif v < 152:\n return 'creator_monetization'\n\n\nclass UserFlags(Enum):\n staff = 1\n partner = 2\n hypesquad = 4\n bug_hunter = 8\n mfa_sms = 16\n premium_promo_dismissed = 32\n hypesquad_bravery = 64\n hypesquad_brilliance = 128\n hypesquad_balance = 256\n early_supporter = 512\n team_user = 1024\n system = 4096\n has_unread_urgent_messages = 8192\n bug_hunter_level_2 = 16384\n verified_bot = 65536\n verified_bot_developer = 131072\n discord_certified_moderator = 262144\n bot_http_interactions = 524288\n spammer = 1048576\n active_developer = 4194304\n\n\nclass ActivityType(Enum):\n unknown = -1\n playing = 0\n streaming = 1\n listening = 2\n watching = 3\n custom = 4\n competing = 5\n\n def __int__(self) -> int:\n return self.value\n\n\nclass TeamMembershipState(Enum):\n invited = 1\n accepted = 2\n\n\nclass TeamMemberRole(Enum):\n admin = 'admin'\n developer = 'developer'\n read_only = 'read_only'\n\n\nclass WebhookType(Enum):\n incoming = 1\n channel_follower = 2\n application = 3\n\n\nclass ExpireBehaviour(Enum):\n remove_role = 0\n kick = 1\n\n\nExpireBehavior = ExpireBehaviour\n\n\nclass StickerType(Enum):\n standard = 1\n guild = 2\n\n\nclass StickerFormatType(Enum):\n png = 1\n apng = 2\n lottie = 3\n gif = 4\n\n @property\n def file_extension(self) -> str:\n # fmt: off\n lookup: Dict[StickerFormatType, str] = {\n StickerFormatType.png: 'png',\n StickerFormatType.apng: 'png',\n StickerFormatType.lottie: 'json',\n StickerFormatType.gif: 'gif',\n }\n # fmt: on\n return lookup.get(self, 'png')\n\n\nclass InviteTarget(Enum):\n unknown = 0\n stream = 1\n embedded_application = 2\n\n\nclass InteractionType(Enum):\n ping = 1\n application_command = 2\n component = 3\n autocomplete = 4\n modal_submit = 5\n\n\nclass InteractionResponseType(Enum):\n pong = 1\n # ack = 2 (deprecated)\n # channel_message = 3 (deprecated)\n channel_message = 4 # (with source)\n deferred_channel_message = 5 # (with source)\n deferred_message_update = 6 # for components\n message_update = 7 # for components\n autocomplete_result = 8\n modal = 9 # for modals\n premium_required = 10\n\n\nclass VideoQualityMode(Enum):\n auto = 1\n full = 2\n\n def __int__(self) -> int:\n return self.value\n\n\nclass ComponentType(Enum):\n action_row = 1\n button = 2\n select = 3\n string_select = 3\n text_input = 4\n user_select = 5\n role_select = 6\n mentionable_select = 7\n channel_select = 8\n\n def __int__(self) -> int:\n return self.value\n\n\nclass ButtonStyle(Enum):\n primary = 1\n secondary = 2\n success = 3\n danger = 4\n link = 5\n\n # Aliases\n blurple = 1\n grey = 2\n gray = 2\n green = 3\n red = 4\n url = 5\n\n def __int__(self) -> int:\n return self.value\n\n\nclass TextStyle(Enum):\n short = 1\n paragraph = 2\n\n # Aliases\n long = 2\n\n def __int__(self) -> int:\n return self.value\n\n\nclass PrivacyLevel(Enum):\n guild_only = 2\n\n\nclass NSFWLevel(Enum, comparable=True):\n default = 0\n explicit = 1\n safe = 2\n age_restricted = 3\n\n\nclass MFALevel(Enum, comparable=True):\n disabled = 0\n require_2fa = 1\n\n\nclass Locale(Enum):\n american_english = 'en-US'\n british_english = 'en-GB'\n bulgarian = 'bg'\n chinese = 'zh-CN'\n taiwan_chinese = 'zh-TW'\n croatian = 'hr'\n czech = 'cs'\n indonesian = 'id'\n danish = 'da'\n dutch = 'nl'\n finnish = 'fi'\n french = 'fr'\n german = 'de'\n greek = 'el'\n hindi = 'hi'\n hungarian = 'hu'\n italian = 'it'\n japanese = 'ja'\n korean = 'ko'\n lithuanian = 'lt'\n norwegian = 'no'\n polish = 'pl'\n brazil_portuguese = 'pt-BR'\n romanian = 'ro'\n russian = 'ru'\n spain_spanish = 'es-ES'\n swedish = 'sv-SE'\n thai = 'th'\n turkish = 'tr'\n ukrainian = 'uk'\n vietnamese = 'vi'\n\n def __str__(self) -> str:\n return self.value\n\n\nE = TypeVar('E', bound='Enum')\n\n\nclass EntityType(Enum):\n stage_instance = 1\n voice = 2\n external = 3\n\n\nclass EventStatus(Enum):\n scheduled = 1\n active = 2\n completed = 3\n canceled = 4\n\n ended = 3\n cancelled = 4\n\n\nclass AppCommandOptionType(Enum):\n subcommand = 1\n subcommand_group = 2\n string = 3\n integer = 4\n boolean = 5\n user = 6\n channel = 7\n role = 8\n mentionable = 9\n number = 10\n attachment = 11\n\n\nclass AppCommandType(Enum):\n chat_input = 1\n user = 2\n message = 3\n\n\nclass AppCommandPermissionType(Enum):\n role = 1\n user = 2\n channel = 3\n\n\nclass AutoModRuleTriggerType(Enum):\n keyword = 1\n harmful_link = 2\n spam = 3\n keyword_preset = 4\n mention_spam = 5\n member_profile = 6\n\n\nclass AutoModRuleEventType(Enum):\n message_send = 1\n member_update = 2\n\n\nclass AutoModRuleActionType(Enum):\n block_message = 1\n send_alert_message = 2\n timeout = 3\n block_member_interactions = 4\n\n\nclass ForumLayoutType(Enum):\n not_set = 0\n list_view = 1\n gallery_view = 2\n\n\nclass ForumOrderType(Enum):\n latest_activity = 0\n creation_date = 1\n\n\nclass SelectDefaultValueType(Enum):\n user = 'user'\n role = 'role'\n channel = 'channel'\n\n\nclass SKUType(Enum):\n subscription = 5\n subscription_group = 6\n\n\nclass EntitlementType(Enum):\n application_subscription = 8\n\n\nclass EntitlementOwnerType(Enum):\n guild = 1\n user = 2\n\n\ndef create_unknown_value(cls: Type[E], val: Any) -> E:\n value_cls = cls._enum_value_cls_ # type: ignore # This is narrowed below\n name = f'unknown_{val}'\n return value_cls(name=name, value=val)\n\n\ndef try_enum(cls: Type[E], val: Any) -> E:\n \"\"\"A function that tries to turn the value into enum ``cls``.\n\n If it fails it returns a proxy invalid value instead.\n \"\"\"\n\n try:\n return cls._enum_value_map_[val] # type: ignore # All errors are caught below\n except (KeyError, TypeError, AttributeError):\n return create_unknown_value(cls, val)\n" }, { "path": "discord/message.py", "content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\nimport datetime\nimport re\nimport io\nfrom os import PathLike\nfrom typing import (\n Dict,\n TYPE_CHECKING,\n Sequence,\n Union,\n List,\n Optional,\n Any,\n Callable,\n Tuple,\n ClassVar,\n Type,\n overload,\n)\n\nfrom . import utils\nfrom .asset import Asset\nfrom .reaction import Reaction\nfrom .emoji import Emoji\nfrom .partial_emoji import PartialEmoji\nfrom .enums import InteractionType, MessageType, ChannelType, try_enum\nfrom .errors import HTTPException\nfrom .components import _component_factory\nfrom .embeds import Embed\nfrom .member import Member\nfrom .flags import MessageFlags, AttachmentFlags\nfrom .file import File\nfrom .utils import escape_mentions, MISSING\nfrom .http import handle_message_parameters\nfrom .guild import Guild\nfrom .mixins import Hashable\nfrom .sticker import StickerItem, GuildSticker\nfrom .threads import Thread\nfrom .channel import PartialMessageable\n\nif TYPE_CHECKING:\n from typing_extensions import Self\n\n from .types.message import (\n Message as MessagePayload,\n Attachment as AttachmentPayload,\n MessageReference as MessageReferencePayload,\n MessageApplication as MessageApplicationPayload,\n MessageActivity as MessageActivityPayload,\n RoleSubscriptionData as RoleSubscriptionDataPayload,\n )\n\n from .types.interactions import MessageInteraction as MessageInteractionPayload\n\n from .types.components import Component as ComponentPayload\n from .types.threads import ThreadArchiveDuration\n from .types.member import (\n Member as MemberPayload,\n UserWithMember as UserWithMemberPayload,\n )\n from .types.user import User as UserPayload\n from .types.embed import Embed as EmbedPayload\n from .types.gateway import MessageReactionRemoveEvent, MessageUpdateEvent\n from .abc import Snowflake\n from .abc import GuildChannel, MessageableChannel\n from .components import ActionRow, ActionRowChildComponentType\n from .state import ConnectionState\n from .mentions import AllowedMentions\n from .user import User\n from .role import Role\n from .ui.view import View\n\n EmojiInputType = Union[Emoji, PartialEmoji, str]\n MessageComponentType = Union[ActionRow, ActionRowChildComponentType]\n\n\n__all__ = (\n 'Attachment',\n 'Message',\n 'PartialMessage',\n 'MessageInteraction',\n 'MessageReference',\n 'DeletedReferencedMessage',\n 'MessageApplication',\n 'RoleSubscriptionInfo',\n)\n\n\ndef convert_emoji_reaction(emoji: Union[EmojiInputType, Reaction]) -> str:\n if isinstance(emoji, Reaction):\n emoji = emoji.emoji\n\n if isinstance(emoji, Emoji):\n return f'{emoji.name}:{emoji.id}'\n if isinstance(emoji, PartialEmoji):\n return emoji._as_reaction()\n if isinstance(emoji, str):\n # Reactions can be in :name:id format, but not <:name:id>.\n # No existing emojis have <> in them, so this should be okay.\n return emoji.strip('<>')\n\n raise TypeError(f'emoji argument must be str, Emoji, or Reaction not {emoji.__class__.__name__}.')\n\n\nclass Attachment(Hashable):\n \"\"\"Represents an attachment from Discord.\n\n .. container:: operations\n\n .. describe:: str(x)\n\n Returns the URL of the attachment.\n\n .. describe:: x == y\n\n Checks if the attachment is equal to another attachment.\n\n .. describe:: x != y\n\n Checks if the attachment is not equal to another attachment.\n\n .. describe:: hash(x)\n\n Returns the hash of the attachment.\n\n .. versionchanged:: 1.7\n Attachment can now be casted to :class:`str` and is hashable.\n\n Attributes\n ------------\n id: :class:`int`\n The attachment ID.\n size: :class:`int`\n The attachment size in bytes.\n height: Optional[:class:`int`]\n The attachment's height, in pixels. Only applicable to images and videos.\n width: Optional[:class:`int`]\n The attachment's width, in pixels. Only applicable to images and videos.\n filename: :class:`str`\n The attachment's filename.\n url: :class:`str`\n The attachment URL. If the message this attachment was attached\n to is deleted, then this will 404.\n proxy_url: :class:`str`\n The proxy URL. This is a cached version of the :attr:`~Attachment.url` in the\n case of images. When the message is deleted, this URL might be valid for a few\n minutes or not valid at all.\n content_type: Optional[:class:`str`]\n The attachment's `media type `_\n\n .. versionadded:: 1.7\n description: Optional[:class:`str`]\n The attachment's description. Only applicable to images.\n\n .. versionadded:: 2.0\n ephemeral: :class:`bool`\n Whether the attachment is ephemeral.\n\n .. versionadded:: 2.0\n duration: Optional[:class:`float`]\n The duration of the audio file in seconds. Returns ``None`` if it's not a voice message.\n\n .. versionadded:: 2.3\n waveform: Optional[:class:`bytes`]\n The waveform (amplitudes) of the audio in bytes. Returns ``None`` if it's not a voice message.\n\n .. versionadded:: 2.3\n \"\"\"\n\n __slots__ = (\n 'id',\n 'size',\n 'height',\n 'width',\n 'filename',\n 'url',\n 'proxy_url',\n '_http',\n 'content_type',\n 'description',\n 'ephemeral',\n 'duration',\n 'waveform',\n '_flags',\n )\n\n def __init__(self, *, data: AttachmentPayload, state: ConnectionState):\n self.id: int = int(data['id'])\n self.size: int = data['size']\n self.height: Optional[int] = data.get('height')\n self.width: Optional[int] = data.get('width')\n self.filename: str = data['filename']\n self.url: str = data['url']\n self.proxy_url: str = data['proxy_url']\n self._http = state.http\n self.content_type: Optional[str] = data.get('content_type')\n self.description: Optional[str] = data.get('description')\n self.ephemeral: bool = data.get('ephemeral', False)\n self.duration: Optional[float] = data.get('duration_secs')\n\n waveform = data.get('waveform')\n self.waveform: Optional[bytes] = utils._base64_to_bytes(waveform) if waveform is not None else None\n\n self._flags: int = data.get('flags', 0)\n\n @property\n def flags(self) -> AttachmentFlags:\n \"\"\":class:`AttachmentFlags`: The attachment's flags.\"\"\"\n return AttachmentFlags._from_value(self._flags)\n\n def is_spoiler(self) -> bool:\n \"\"\":class:`bool`: Whether this attachment contains a spoiler.\"\"\"\n return self.filename.startswith('SPOILER_')\n\n def is_voice_message(self) -> bool:\n \"\"\":class:`bool`: Whether this attachment is a voice message.\"\"\"\n return self.duration is not None and 'voice-message' in self.url\n\n def __repr__(self) -> str:\n return f''\n\n def __str__(self) -> str:\n return self.url or ''\n\n async def save(\n self,\n fp: Union[io.BufferedIOBase, PathLike[Any]],\n *,\n seek_begin: bool = True,\n use_cached: bool = False,\n ) -> int:\n \"\"\"|coro|\n\n Saves this attachment into a file-like object.\n\n Parameters\n -----------\n fp: Union[:class:`io.BufferedIOBase`, :class:`os.PathLike`]\n The file-like object to save this attachment to or the filename\n to use. If a filename is passed then a file is created with that\n filename and used instead.\n seek_begin: :class:`bool`\n Whether to seek to the beginning of the file after saving is\n successfully done.\n use_cached: :class:`bool`\n Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading\n the attachment. This will allow attachments to be saved after deletion\n more often, compared to the regular URL which is generally deleted right\n after the message is deleted. Note that this can still fail to download\n deleted attachments if too much time has passed and it does not work\n on some types of attachments.\n\n Raises\n --------\n HTTPException\n Saving the attachment failed.\n NotFound\n The attachment was deleted.\n\n Returns\n --------\n :class:`int`\n The number of bytes written.\n \"\"\"\n data = await self.read(use_cached=use_cached)\n if isinstance(fp, io.BufferedIOBase):\n written = fp.write(data)\n if seek_begin:\n fp.seek(0)\n return written\n else:\n with open(fp, 'wb') as f:\n return f.write(data)\n\n async def read(self, *, use_cached: bool = False) -> bytes:\n \"\"\"|coro|\n\n Retrieves the content of this attachment as a :class:`bytes` object.\n\n .. versionadded:: 1.1\n\n Parameters\n -----------\n use_cached: :class:`bool`\n Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading\n the attachment. This will allow attachments to be saved after deletion\n more often, compared to the regular URL which is generally deleted right\n after the message is deleted. Note that this can still fail to download\n deleted attachments if too much time has passed and it does not work\n on some types of attachments.\n\n Raises\n ------\n HTTPException\n Downloading the attachment failed.\n Forbidden\n You do not have permissions to access this attachment\n NotFound\n The attachment was deleted.\n\n Returns\n -------\n :class:`bytes`\n The contents of the attachment.\n \"\"\"\n url = self.proxy_url if use_cached else self.url\n data = await self._http.get_from_cdn(url)\n return data\n\n async def to_file(\n self,\n *,\n filename: Optional[str] = MISSING,\n description: Optional[str] = MISSING,\n use_cached: bool = False,\n spoiler: bool = False,\n ) -> File:\n \"\"\"|coro|\n\n Converts the attachment into a :class:`File` suitable for sending via\n :meth:`abc.Messageable.send`.\n\n .. versionadded:: 1.3\n\n Parameters\n -----------\n filename: Optional[:class:`str`]\n The filename to use for the file. If not specified then the filename\n of the attachment is used instead.\n\n .. versionadded:: 2.0\n description: Optional[:class:`str`]\n The description to use for the file. If not specified then the\n description of the attachment is used instead.\n\n .. versionadded:: 2.0\n use_cached: :class:`bool`\n Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading\n the attachment. This will allow attachments to be saved after deletion\n more often, compared to the regular URL which is generally deleted right\n after the message is deleted. Note that this can still fail to download\n deleted attachments if too much time has passed and it does not work\n on some types of attachments.\n\n .. versionadded:: 1.4\n spoiler: :class:`bool`\n Whether the file is a spoiler.\n\n .. versionadded:: 1.4\n\n Raises\n ------\n HTTPException\n Downloading the attachment failed.\n Forbidden\n You do not have permissions to access this attachment\n NotFound\n The attachment was deleted.\n\n Returns\n -------\n :class:`File`\n The attachment as a file suitable for sending.\n \"\"\"\n\n data = await self.read(use_cached=use_cached)\n file_filename = filename if filename is not MISSING else self.filename\n file_description = description if description is not MISSING else self.description\n return File(io.BytesIO(data), filename=file_filename, description=file_description, spoiler=spoiler)\n\n def to_dict(self) -> AttachmentPayload:\n result: AttachmentPayload = {\n 'filename': self.filename,\n 'id': self.id,\n 'proxy_url': self.proxy_url,\n 'size': self.size,\n 'url': self.url,\n 'spoiler': self.is_spoiler(),\n }\n if self.height:\n result['height'] = self.height\n if self.width:\n result['width'] = self.width\n if self.content_type:\n result['content_type'] = self.content_type\n if self.description is not None:\n result['description'] = self.description\n return result\n\n\nclass DeletedReferencedMessage:\n \"\"\"A special sentinel type given when the resolved message reference\n points to a deleted message.\n\n The purpose of this class is to separate referenced messages that could not be\n fetched and those that were previously fetched but have since been deleted.\n\n .. versionadded:: 1.6\n \"\"\"\n\n __slots__ = ('_parent',)\n\n def __init__(self, parent: MessageReference):\n self._parent: MessageReference = parent\n\n def __repr__(self) -> str:\n return f\"\"\n\n @property\n def id(self) -> int:\n \"\"\":class:`int`: The message ID of the deleted referenced message.\"\"\"\n # the parent's message id won't be None here\n return self._parent.message_id # type: ignore\n\n @property\n def channel_id(self) -> int:\n \"\"\":class:`int`: The channel ID of the deleted referenced message.\"\"\"\n return self._parent.channel_id\n\n @property\n def guild_id(self) -> Optional[int]:\n \"\"\"Optional[:class:`int`]: The guild ID of the deleted referenced message.\"\"\"\n return self._parent.guild_id\n\n\nclass MessageReference:\n \"\"\"Represents a reference to a :class:`~discord.Message`.\n\n .. versionadded:: 1.5\n\n .. versionchanged:: 1.6\n This class can now be constructed by users.\n\n Attributes\n -----------\n message_id: Optional[:class:`int`]\n The id of the message referenced.\n channel_id: :class:`int`\n The channel id of the message referenced.\n guild_id: Optional[:class:`int`]\n The guild id of the message referenced.\n fail_if_not_exists: :class:`bool`\n Whether replying to the referenced message should raise :class:`HTTPException`\n if the message no longer exists or Discord could not fetch the message.\n\n .. versionadded:: 1.7\n\n resolved: Optional[Union[:class:`Message`, :class:`DeletedReferencedMessage`]]\n The message that this reference resolved to. If this is ``None``\n then the original message was not fetched either due to the Discord API\n not attempting to resolve it or it not being available at the time of creation.\n If the message was resolved at a prior point but has since been deleted then\n this will be of type :class:`DeletedReferencedMessage`.\n\n Currently, this is mainly the replied to message when a user replies to a message.\n\n .. versionadded:: 1.6\n \"\"\"\n\n __slots__ = ('message_id', 'channel_id', 'guild_id', 'fail_if_not_exists', 'resolved', '_state')\n\n def __init__(self, *, message_id: int, channel_id: int, guild_id: Optional[int] = None, fail_if_not_exists: bool = True):\n self._state: Optional[ConnectionState] = None\n self.resolved: Optional[Union[Message, DeletedReferencedMessage]] = None\n self.message_id: Optional[int] = message_id\n self.channel_id: int = channel_id\n self.guild_id: Optional[int] = guild_id\n self.fail_if_not_exists: bool = fail_if_not_exists\n\n @classmethod\n def with_state(cls, state: ConnectionState, data: MessageReferencePayload) -> Self:\n self = cls.__new__(cls)\n self.message_id = utils._get_as_snowflake(data, 'message_id')\n self.channel_id = int(data['channel_id'])\n self.guild_id = utils._get_as_snowflake(data, 'guild_id')\n self.fail_if_not_exists = data.get('fail_if_not_exists', True)\n self._state = state\n self.resolved = None\n return self\n\n @classmethod\n def from_message(cls, message: PartialMessage, *, fail_if_not_exists: bool = True) -> Self:\n \"\"\"Creates a :class:`MessageReference` from an existing :class:`~discord.Message`.\n\n .. versionadded:: 1.6\n\n Parameters\n ----------\n message: :class:`~discord.Message`\n The message to be converted into a reference.\n fail_if_not_exists: :class:`bool`\n Whether replying to the referenced message should raise :class:`HTTPException`\n if the message no longer exists or Discord could not fetch the message.\n\n .. versionadded:: 1.7\n\n Returns\n -------\n :class:`MessageReference`\n A reference to the message.\n \"\"\"\n self = cls(\n message_id=message.id,\n channel_id=message.channel.id,\n guild_id=getattr(message.guild, 'id', None),\n fail_if_not_exists=fail_if_not_exists,\n )\n self._state = message._state\n return self\n\n @property\n def cached_message(self) -> Optional[Message]:\n \"\"\"Optional[:class:`~discord.Message`]: The cached message, if found in the internal message cache.\"\"\"\n return self._state and self._state._get_message(self.message_id)\n\n @property\n def jump_url(self) -> str:\n \"\"\":class:`str`: Returns a URL that allows the client to jump to the referenced message.\n\n .. versionadded:: 1.7\n \"\"\"\n guild_id = self.guild_id if self.guild_id is not None else '@me'\n return f'https://discord.com/channels/{guild_id}/{self.channel_id}/{self.message_id}'\n\n def __repr__(self) -> str:\n return f''\n\n def to_dict(self) -> MessageReferencePayload:\n result: Dict[str, Any] = {'message_id': self.message_id} if self.message_id is not None else {}\n result['channel_id'] = self.channel_id\n if self.guild_id is not None:\n result['guild_id'] = self.guild_id\n if self.fail_if_not_exists is not None:\n result['fail_if_not_exists'] = self.fail_if_not_exists\n return result # type: ignore # Type checker doesn't understand these are the same.\n\n to_message_reference_dict = to_dict\n\n\nclass MessageInteraction(Hashable):\n \"\"\"Represents the interaction that a :class:`Message` is a response to.\n\n .. versionadded:: 2.0\n\n .. container:: operations\n\n .. describe:: x == y\n\n Checks if two message interactions are equal.\n\n .. describe:: x != y\n\n Checks if two message interactions are not equal.\n\n .. describe:: hash(x)\n\n Returns the message interaction's hash.\n\n Attributes\n -----------\n id: :class:`int`\n The interaction ID.\n type: :class:`InteractionType`\n The interaction type.\n name: :class:`str`\n The name of the interaction.\n user: Union[:class:`User`, :class:`Member`]\n The user or member that invoked the interaction.\n \"\"\"\n\n __slots__: Tuple[str, ...] = ('id', 'type', 'name', 'user')\n\n def __init__(self, *, state: ConnectionState, guild: Optional[Guild], data: MessageInteractionPayload) -> None:\n self.id: int = int(data['id'])\n self.type: InteractionType = try_enum(InteractionType, data['type'])\n self.name: str = data['name']\n self.user: Union[User, Member] = MISSING\n\n try:\n payload = data['member']\n except KeyError:\n self.user = state.create_user(data['user'])\n else:\n if guild is None:\n # This is an unfortunate data loss, but it's better than giving bad data\n # This is also an incredibly rare scenario.\n self.user = state.create_user(data['user'])\n else:\n payload['user'] = data['user']\n self.user = Member(data=payload, guild=guild, state=state) # type: ignore\n\n def __repr__(self) -> str:\n return f''\n\n @property\n def created_at(self) -> datetime.datetime:\n \"\"\":class:`datetime.datetime`: The interaction's creation time in UTC.\"\"\"\n return utils.snowflake_time(self.id)\n\n\ndef flatten_handlers(cls: Type[Message]) -> Type[Message]:\n prefix = len('_handle_')\n handlers = [\n (key[prefix:], value)\n for key, value in cls.__dict__.items()\n if key.startswith('_handle_') and key != '_handle_member'\n ]\n\n # store _handle_member last\n handlers.append(('member', cls._handle_member))\n cls._HANDLERS = handlers\n cls._CACHED_SLOTS = [attr for attr in cls.__slots__ if attr.startswith('_cs_')]\n return cls\n\n\nclass MessageApplication:\n \"\"\"Represents a message's application data from a :class:`~discord.Message`.\n\n .. versionadded:: 2.0\n\n Attributes\n -----------\n id: :class:`int`\n The application ID.\n description: :class:`str`\n The application description.\n name: :class:`str`\n The application's name.\n \"\"\"\n\n __slots__ = ('_state', '_icon', '_cover_image', 'id', 'description', 'name')\n\n def __init__(self, *, state: ConnectionState, data: MessageApplicationPayload) -> None:\n self._state: ConnectionState = state\n self.id: int = int(data['id'])\n self.description: str = data['description']\n self.name: str = data['name']\n self._icon: Optional[str] = data['icon']\n self._cover_image: Optional[str] = data.get('cover_image')\n\n def __repr__(self) -> str:\n return f''\n\n @property\n def icon(self) -> Optional[Asset]:\n \"\"\"Optional[:class:`Asset`]: The application's icon, if any.\"\"\"\n if self._icon:\n return Asset._from_app_icon(state=self._state, object_id=self.id, icon_hash=self._icon, asset_type='icon')\n return None\n\n @property\n def cover(self) -> Optional[Asset]:\n \"\"\"Optional[:class:`Asset`]: The application's cover image, if any.\"\"\"\n if self._cover_image:\n return Asset._from_app_icon(\n state=self._state, object_id=self.id, icon_hash=self._cover_image, asset_type='cover_image'\n )\n return None\n\n\nclass RoleSubscriptionInfo:\n \"\"\"Represents a message's role subscription information.\n\n This is currently only attached to messages of type :attr:`MessageType.role_subscription_purchase`.\n\n .. versionadded:: 2.0\n\n Attributes\n -----------\n role_subscription_listing_id: :class:`int`\n The ID of the SKU and listing that the user is subscribed to.\n tier_name: :class:`str`\n The name of the tier that the user is subscribed to.\n total_months_subscribed: :class:`int`\n The cumulative number of months that the user has been subscribed for.\n is_renewal: :class:`bool`\n Whether this notification is for a renewal rather than a new purchase.\n \"\"\"\n\n __slots__ = (\n 'role_subscription_listing_id',\n 'tier_name',\n 'total_months_subscribed',\n 'is_renewal',\n )\n\n def __init__(self, data: RoleSubscriptionDataPayload) -> None:\n self.role_subscription_listing_id: int = int(data['role_subscription_listing_id'])\n self.tier_name: str = data['tier_name']\n self.total_months_subscribed: int = data['total_months_subscribed']\n self.is_renewal: bool = data['is_renewal']\n\n\nclass PartialMessage(Hashable):\n \"\"\"Represents a partial message to aid with working messages when only\n a message and channel ID are present.\n\n There are two ways to construct this class. The first one is through\n the constructor itself, and the second is via the following:\n\n - :meth:`TextChannel.get_partial_message`\n - :meth:`VoiceChannel.get_partial_message`\n - :meth:`StageChannel.get_partial_message`\n - :meth:`Thread.get_partial_message`\n - :meth:`DMChannel.get_partial_message`\n\n Note that this class is trimmed down and has no rich attributes.\n\n .. versionadded:: 1.6\n\n .. container:: operations\n\n .. describe:: x == y\n\n Checks if two partial messages are equal.\n\n .. describe:: x != y\n\n Checks if two partial messages are not equal.\n\n .. describe:: hash(x)\n\n Returns the partial message's hash.\n\n Attributes\n -----------\n channel: Union[:class:`PartialMessageable`, :class:`TextChannel`, :class:`StageChannel`, :class:`VoiceChannel`, :class:`Thread`, :class:`DMChannel`]\n The channel associated with this partial message.\n id: :class:`int`\n The message ID.\n guild: Optional[:class:`Guild`]\n The guild that the partial message belongs to, if applicable.\n \"\"\"\n\n __slots__ = ('channel', 'id', '_cs_guild', '_state', 'guild')\n\n def __init__(self, *, channel: MessageableChannel, id: int) -> None:\n if not isinstance(channel, PartialMessageable) and channel.type not in (\n ChannelType.text,\n ChannelType.voice,\n ChannelType.stage_voice,\n ChannelType.news,\n ChannelType.private,\n ChannelType.news_thread,\n ChannelType.public_thread,\n ChannelType.private_thread,\n ):\n raise TypeError(\n f'expected PartialMessageable, TextChannel, StageChannel, VoiceChannel, DMChannel or Thread not {type(channel)!r}'\n )\n\n self.channel: MessageableChannel = channel\n self._state: ConnectionState = channel._state\n self.id: int = id\n\n self.guild: Optional[Guild] = getattr(channel, 'guild', None)\n\n def _update(self, data: MessageUpdateEvent) -> None:\n # This is used for duck typing purposes.\n # Just do nothing with the data.\n pass\n\n # Also needed for duck typing purposes\n # n.b. not exposed\n pinned: Any = property(None, lambda x, y: None)\n\n def __repr__(self) -> str:\n return f''\n\n @property\n def created_at(self) -> datetime.datetime:\n \"\"\":class:`datetime.datetime`: The partial message's creation time in UTC.\"\"\"\n return utils.snowflake_time(self.id)\n\n @property\n def jump_url(self) -> str:\n \"\"\":class:`str`: Returns a URL that allows the client to jump to this message.\"\"\"\n guild_id = getattr(self.guild, 'id', '@me')\n return f'https://discord.com/channels/{guild_id}/{self.channel.id}/{self.id}'\n\n @property\n def thread(self) -> Optional[Thread]:\n \"\"\"Optional[:class:`Thread`]: The public thread created from this message, if it exists.\n\n .. note::\n\n This does not retrieve archived threads, as they are not retained in the internal\n cache. Use :meth:`fetch_thread` instead.\n\n .. versionadded:: 2.4\n \"\"\"\n if self.guild is not None:\n return self.guild.get_thread(self.id)\n\n async def fetch(self) -> Message:\n \"\"\"|coro|\n\n Fetches the partial message to a full :class:`Message`.\n\n Raises\n --------\n NotFound\n The message was not found.\n Forbidden\n You do not have the permissions required to get a message.\n HTTPException\n Retrieving the message failed.\n\n Returns\n --------\n :class:`Message`\n The full message.\n \"\"\"\n\n data = await self._state.http.get_message(self.channel.id, self.id)\n return self._state.create_message(channel=self.channel, data=data)\n\n async def delete(self, *, delay: Optional[float] = None) -> None:\n \"\"\"|coro|\n\n Deletes the message.\n\n Your own messages could be deleted without any proper permissions. However to\n delete other people's messages, you must have :attr:`~Permissions.manage_messages`.\n\n .. versionchanged:: 1.1\n Added the new ``delay`` keyword-only parameter.\n\n Parameters\n -----------\n delay: Optional[:class:`float`]\n If provided, the number of seconds to wait in the background\n before deleting the message. If the deletion fails then it is silently ignored.\n\n Raises\n ------\n Forbidden\n You do not have proper permissions to delete the message.\n NotFound\n The message was deleted already\n HTTPException\n Deleting the message failed.\n \"\"\"\n if delay is not None:\n\n async def delete(delay: float):\n await asyncio.sleep(delay)\n try:\n await self._state.http.delete_message(self.channel.id, self.id)\n except HTTPException:\n pass\n\n asyncio.create_task(delete(delay))\n else:\n await self._state.http.delete_message(self.channel.id, self.id)\n\n @overload\n async def edit(\n self,\n *,\n content: Optional[str] = ...,\n embed: Optional[Embed] = ...,\n attachments: Sequence[Union[Attachment, File]] = ...,\n delete_after: Optional[float] = ...,\n allowed_mentions: Optional[AllowedMentions] = ...,\n view: Optional[View] = ...,\n ) -> Message:\n ...\n\n @overload\n async def edit(\n self,\n *,\n content: Optional[str] = ...,\n embeds: Sequence[Embed] = ...,\n attachments: Sequence[Union[Attachment, File]] = ...,\n delete_after: Optional[float] = ...,\n allowed_mentions: Optional[AllowedMentions] = ...,\n view: Optional[View] = ...,\n ) -> Message:\n ...\n\n async def edit(\n self,\n *,\n content: Optional[str] = MISSING,\n embed: Optional[Embed] = MISSING,\n embeds: Sequence[Embed] = MISSING,\n attachments: Sequence[Union[Attachment, File]] = MISSING,\n delete_after: Optional[float] = None,\n allowed_mentions: Optional[AllowedMentions] = MISSING,\n view: Optional[View] = MISSING,\n ) -> Message:\n \"\"\"|coro|\n\n Edits the message.\n\n The content must be able to be transformed into a string via ``str(content)``.\n\n .. versionchanged:: 2.0\n Edits are no longer in-place, the newly edited message is returned instead.\n\n .. versionchanged:: 2.0\n This function will now raise :exc:`TypeError` instead of\n ``InvalidArgument``.\n\n Parameters\n -----------\n content: Optional[:class:`str`]\n The new content to replace the message with.\n Could be ``None`` to remove the content.\n embed: Optional[:class:`Embed`]\n The new embed to replace the original with.\n Could be ``None`` to remove the embed.\n embeds: List[:class:`Embed`]\n The new embeds to replace the original with. Must be a maximum of 10.\n To remove all embeds ``[]`` should be passed.\n\n .. versionadded:: 2.0\n attachments: List[Union[:class:`Attachment`, :class:`File`]]\n A list of attachments to keep in the message as well as new files to upload. If ``[]`` is passed\n then all attachments are removed.\n\n .. note::\n\n New files will always appear after current attachments.\n\n .. versionadded:: 2.0\n delete_after: Optional[:class:`float`]\n If provided, the number of seconds to wait in the background\n before deleting the message we just edited. If the deletion fails,\n then it is silently ignored.\n allowed_mentions: Optional[:class:`~discord.AllowedMentions`]\n Controls the mentions being processed in this message. If this is\n passed, then the object is merged with :attr:`~discord.Client.allowed_mentions`.\n The merging behaviour only overrides attributes that have been explicitly passed\n to the object, otherwise it uses the attributes set in :attr:`~discord.Client.allowed_mentions`.\n If no object is passed at all then the defaults given by :attr:`~discord.Client.allowed_mentions`\n are used instead.\n\n .. versionadded:: 1.4\n view: Optional[:class:`~discord.ui.View`]\n The updated view to update this message with. If ``None`` is passed then\n the view is removed.\n\n Raises\n -------\n HTTPException\n Editing the message failed.\n Forbidden\n Tried to suppress a message without permissions or\n edited a message's content or embed that isn't yours.\n TypeError\n You specified both ``embed`` and ``embeds``\n\n Returns\n --------\n :class:`Message`\n The newly edited message.\n \"\"\"\n\n if content is not MISSING:\n previous_allowed_mentions = self._state.allowed_mentions\n else:\n previous_allowed_mentions = None\n\n if view is not MISSING:\n self._state.prevent_view_updates_for(self.id)\n\n with handle_message_parameters(\n content=content,\n embed=embed,\n embeds=embeds,\n attachments=attachments,\n view=view,\n allowed_mentions=allowed_mentions,\n previous_allowed_mentions=previous_allowed_mentions,\n ) as params:\n data = await self._state.http.edit_message(self.channel.id, self.id, params=params)\n message = Message(state=self._state, channel=self.channel, data=data)\n\n if view and not view.is_finished():\n interaction: Optional[MessageInteraction] = getattr(self, 'interaction', None)\n if interaction is not None:\n self._state.store_view(view, self.id, interaction_id=interaction.id)\n else:\n self._state.store_view(view, self.id)\n\n if delete_after is not None:\n await self.delete(delay=delete_after)\n\n return message\n\n async def publish(self) -> None:\n \"\"\"|coro|\n\n Publishes this message to the channel's followers.\n\n The message must have been sent in a news channel.\n You must have :attr:`~Permissions.send_messages` to do this.\n\n If the message is not your own then :attr:`~Permissions.manage_messages`\n is also needed.\n\n Raises\n -------\n Forbidden\n You do not have the proper permissions to publish this message\n or the channel is not a news channel.\n HTTPException\n Publishing the message failed.\n \"\"\"\n\n await self._state.http.publish_message(self.channel.id, self.id)\n\n async def pin(self, *, reason: Optional[str] = None) -> None:\n \"\"\"|coro|\n\n Pins the message.\n\n You must have :attr:`~Permissions.manage_messages` to do\n this in a non-private channel context.\n\n Parameters\n -----------\n reason: Optional[:class:`str`]\n The reason for pinning the message. Shows up on the audit log.\n\n .. versionadded:: 1.4\n\n Raises\n -------\n Forbidden\n You do not have permissions to pin the message.\n NotFound\n The message or channel was not found or deleted.\n HTTPException\n Pinning the message failed, probably due to the channel\n having more than 50 pinned messages.\n \"\"\"\n\n await self._state.http.pin_message(self.channel.id, self.id, reason=reason)\n # pinned exists on PartialMessage for duck typing purposes\n self.pinned = True\n\n async def unpin(self, *, reason: Optional[str] = None) -> None:\n \"\"\"|coro|\n\n Unpins the message.\n\n You must have :attr:`~Permissions.manage_messages` to do\n this in a non-private channel context.\n\n Parameters\n -----------\n reason: Optional[:class:`str`]\n The reason for unpinning the message. Shows up on the audit log.\n\n .. versionadded:: 1.4\n\n Raises\n -------\n Forbidden\n You do not have permissions to unpin the message.\n NotFound\n The message or channel was not found or deleted.\n HTTPException\n Unpinning the message failed.\n \"\"\"\n\n await self._state.http.unpin_message(self.channel.id, self.id, reason=reason)\n # pinned exists on PartialMessage for duck typing purposes\n self.pinned = False\n\n async def add_reaction(self, emoji: Union[EmojiInputType, Reaction], /) -> None:\n \"\"\"|coro|\n\n Adds a reaction to the message.\n\n The emoji may be a unicode emoji or a custom guild :class:`Emoji`.\n\n You must have :attr:`~Permissions.read_message_history`\n to do this. If nobody else has reacted to the message using this\n emoji, :attr:`~Permissions.add_reactions` is required.\n\n .. versionchanged:: 2.0\n\n ``emoji`` parameter is now positional-only.\n\n .. versionchanged:: 2.0\n This function will now raise :exc:`TypeError` instead of\n ``InvalidArgument``.\n\n Parameters\n ------------\n emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]\n The emoji to react with.\n\n Raises\n --------\n HTTPException\n Adding the reaction failed.\n Forbidden\n You do not have the proper permissions to react to the message.\n NotFound\n The emoji you specified was not found.\n TypeError\n The emoji parameter is invalid.\n \"\"\"\n\n emoji = convert_emoji_reaction(emoji)\n await self._state.http.add_reaction(self.channel.id, self.id, emoji)\n\n async def remove_reaction(self, emoji: Union[EmojiInputType, Reaction], member: Snowflake) -> None:\n \"\"\"|coro|\n\n Remove a reaction by the member from the message.\n\n The emoji may be a unicode emoji or a custom guild :class:`Emoji`.\n\n If the reaction is not your own (i.e. ``member`` parameter is not you) then\n :attr:`~Permissions.manage_messages` is needed.\n\n The ``member`` parameter must represent a member and meet\n the :class:`abc.Snowflake` abc.\n\n .. versionchanged:: 2.0\n This function will now raise :exc:`TypeError` instead of\n ``InvalidArgument``.\n\n Parameters\n ------------\n emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]\n The emoji to remove.\n member: :class:`abc.Snowflake`\n The member for which to remove the reaction.\n\n Raises\n --------\n HTTPException\n Removing the reaction failed.\n Forbidden\n You do not have the proper permissions to remove the reaction.\n NotFound\n The member or emoji you specified was not found.\n TypeError\n The emoji parameter is invalid.\n \"\"\"\n\n emoji = convert_emoji_reaction(emoji)\n\n if member.id == self._state.self_id:\n await self._state.http.remove_own_reaction(self.channel.id, self.id, emoji)\n else:\n await self._state.http.remove_reaction(self.channel.id, self.id, emoji, member.id)\n\n async def clear_reaction(self, emoji: Union[EmojiInputType, Reaction]) -> None:\n \"\"\"|coro|\n\n Clears a specific reaction from the message.\n\n The emoji may be a unicode emoji or a custom guild :class:`Emoji`.\n\n You must have :attr:`~Permissions.manage_messages` to do this.\n\n .. versionadded:: 1.3\n\n .. versionchanged:: 2.0\n This function will now raise :exc:`TypeError` instead of\n ``InvalidArgument``.\n\n Parameters\n -----------\n emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]\n The emoji to clear.\n\n Raises\n --------\n HTTPException\n Clearing the reaction failed.\n Forbidden\n You do not have the proper permissions to clear the reaction.\n NotFound\n The emoji you specified was not found.\n TypeError\n The emoji parameter is invalid.\n \"\"\"\n\n emoji = convert_emoji_reaction(emoji)\n await self._state.http.clear_single_reaction(self.channel.id, self.id, emoji)\n\n async def clear_reactions(self) -> None:\n \"\"\"|coro|\n\n Removes all the reactions from the message.\n\n You must have :attr:`~Permissions.manage_messages` to do this.\n\n Raises\n --------\n HTTPException\n Removing the reactions failed.\n Forbidden\n You do not have the proper permissions to remove all the reactions.\n \"\"\"\n await self._state.http.clear_reactions(self.channel.id, self.id)\n\n async def create_thread(\n self,\n *,\n name: str,\n auto_archive_duration: ThreadArchiveDuration = MISSING,\n slowmode_delay: Optional[int] = None,\n reason: Optional[str] = None,\n ) -> Thread:\n \"\"\"|coro|\n\n Creates a public thread from this message.\n\n You must have :attr:`~discord.Permissions.create_public_threads` in order to\n create a public thread from a message.\n\n The channel this message belongs in must be a :class:`TextChannel`.\n\n .. versionadded:: 2.0\n\n Parameters\n -----------\n name: :class:`str`\n The name of the thread.\n auto_archive_duration: :class:`int`\n The duration in minutes before a thread is automatically hidden from the channel list.\n If not provided, the channel's default auto archive duration is used.\n\n Must be one of ``60``, ``1440``, ``4320``, or ``10080``, if provided.\n slowmode_delay: Optional[:class:`int`]\n Specifies the slowmode rate limit for user in this channel, in seconds.\n The maximum value possible is ``21600``. By default no slowmode rate limit\n if this is ``None``.\n reason: Optional[:class:`str`]\n The reason for creating a new thread. Shows up on the audit log.\n\n Raises\n -------\n Forbidden\n You do not have permissions to create a thread.\n HTTPException\n Creating the thread failed.\n ValueError\n This message does not have guild info attached.\n\n Returns\n --------\n :class:`.Thread`\n The created thread.\n \"\"\"\n if self.guild is None:\n raise ValueError('This message does not have guild info attached.')\n\n default_auto_archive_duration: ThreadArchiveDuration = getattr(self.channel, 'default_auto_archive_duration', 1440)\n data = await self._state.http.start_thread_with_message(\n self.channel.id,\n self.id,\n name=name,\n auto_archive_duration=auto_archive_duration or default_auto_archive_duration,\n rate_limit_per_user=slowmode_delay,\n reason=reason,\n )\n return Thread(guild=self.guild, state=self._state, data=data)\n\n async def fetch_thread(self) -> Thread:\n \"\"\"|coro|\n\n Retrieves the public thread attached to this message.\n\n .. note::\n\n This method is an API call. For general usage, consider :attr:`thread` instead.\n\n .. versionadded:: 2.4\n\n Raises\n -------\n InvalidData\n An unknown channel type was received from Discord\n or the guild the thread belongs to is not the same\n as the one in this object points to.\n HTTPException\n Retrieving the thread failed.\n NotFound\n There is no thread attached to this message.\n Forbidden\n You do not have permission to fetch this channel.\n\n Returns\n --------\n :class:`.Thread`\n The public thread attached to this message.\n \"\"\"\n if self.guild is None:\n raise ValueError('This message does not have guild info attached.')\n\n return await self.guild.fetch_channel(self.id) # type: ignore # Can only be Thread in this case\n\n @overload\n async def reply(\n self,\n content: Optional[str] = ...,\n *,\n tts: bool = ...,\n embed: Embed = ...,\n file: File = ...,\n stickers: Sequence[Union[GuildSticker, StickerItem]] = ...,\n delete_after: float = ...,\n nonce: Union[str, int] = ...,\n allowed_mentions: AllowedMentions = ...,\n reference: Union[Message, MessageReference, PartialMessage] = ...,\n mention_author: bool = ...,\n view: View = ...,\n suppress_embeds: bool = ...,\n silent: bool = ...,\n ) -> Message:\n ...\n\n @overload\n async def reply(\n self,\n content: Optional[str] = ...,\n *,\n tts: bool = ...,\n embed: Embed = ...,\n files: Sequence[File] = ...,\n stickers: Sequence[Union[GuildSticker, StickerItem]] = ...,\n delete_after: float = ...,\n nonce: Union[str, int] = ...,\n allowed_mentions: AllowedMentions = ...,\n reference: Union[Message, MessageReference, PartialMessage] = ...,\n mention_author: bool = ...,\n view: View = ...,\n suppress_embeds: bool = ...,\n silent: bool = ...,\n ) -> Message:\n ...\n\n @overload\n async def reply(\n self,\n content: Optional[str] = ...,\n *,\n tts: bool = ...,\n embeds: Sequence[Embed] = ...,\n file: File = ...,\n stickers: Sequence[Union[GuildSticker, StickerItem]] = ...,\n delete_after: float = ...,\n nonce: Union[str, int] = ...,\n allowed_mentions: AllowedMentions = ...,\n reference: Union[Message, MessageReference, PartialMessage] = ...,\n mention_author: bool = ...,\n view: View = ...,\n suppress_embeds: bool = ...,\n silent: bool = ...,\n ) -> Message:\n ...\n\n @overload\n async def reply(\n self,\n content: Optional[str] = ...,\n *,\n tts: bool = ...,\n embeds: Sequence[Embed] = ...,\n files: Sequence[File] = ...,\n stickers: Sequence[Union[GuildSticker, StickerItem]] = ...,\n delete_after: float = ...,\n nonce: Union[str, int] = ...,\n allowed_mentions: AllowedMentions = ...,\n reference: Union[Message, MessageReference, PartialMessage] = ...,\n mention_author: bool = ...,\n view: View = ...,\n suppress_embeds: bool = ...,\n silent: bool = ...,\n ) -> Message:\n ...\n\n async def reply(self, content: Optional[str] = None, **kwargs: Any) -> Message:\n \"\"\"|coro|\n\n A shortcut method to :meth:`.abc.Messageable.send` to reply to the\n :class:`.Message`.\n\n .. versionadded:: 1.6\n\n .. versionchanged:: 2.0\n This function will now raise :exc:`TypeError` or\n :exc:`ValueError` instead of ``InvalidArgument``.\n\n Raises\n --------\n ~discord.HTTPException\n Sending the message failed.\n ~discord.Forbidden\n You do not have the proper permissions to send the message.\n ValueError\n The ``files`` list is not of the appropriate size\n TypeError\n You specified both ``file`` and ``files``.\n\n Returns\n ---------\n :class:`.Message`\n The message that was sent.\n \"\"\"\n\n return await self.channel.send(content, reference=self, **kwargs)\n\n def to_reference(self, *, fail_if_not_exists: bool = True) -> MessageReference:\n \"\"\"Creates a :class:`~discord.MessageReference` from the current message.\n\n .. versionadded:: 1.6\n\n Parameters\n ----------\n fail_if_not_exists: :class:`bool`\n Whether replying using the message reference should raise :class:`HTTPException`\n if the message no longer exists or Discord could not fetch the message.\n\n .. versionadded:: 1.7\n\n Returns\n ---------\n :class:`~discord.MessageReference`\n The reference to this message.\n \"\"\"\n\n return MessageReference.from_message(self, fail_if_not_exists=fail_if_not_exists)\n\n def to_message_reference_dict(self) -> MessageReferencePayload:\n data: MessageReferencePayload = {\n 'message_id': self.id,\n 'channel_id': self.channel.id,\n }\n\n if self.guild is not None:\n data['guild_id'] = self.guild.id\n\n return data\n\n\n@flatten_handlers\nclass Message(PartialMessage, Hashable):\n r\"\"\"Represents a message from Discord.\n\n .. container:: operations\n\n .. describe:: x == y\n\n Checks if two messages are equal.\n\n .. describe:: x != y\n\n Checks if two messages are not equal.\n\n .. describe:: hash(x)\n\n Returns the message's hash.\n\n Attributes\n -----------\n tts: :class:`bool`\n Specifies if the message was done with text-to-speech.\n This can only be accurately received in :func:`on_message` due to\n a discord limitation.\n type: :class:`MessageType`\n The type of message. In most cases this should not be checked, but it is helpful\n in cases where it might be a system message for :attr:`system_content`.\n author: Union[:class:`Member`, :class:`abc.User`]\n A :class:`Member` that sent the message. If :attr:`channel` is a\n private channel or the user has the left the guild, then it is a :class:`User` instead.\n content: :class:`str`\n The actual contents of the message.\n If :attr:`Intents.message_content` is not enabled this will always be an empty string\n unless the bot is mentioned or the message is a direct message.\n nonce: Optional[Union[:class:`str`, :class:`int`]]\n The value used by the discord guild and the client to verify that the message is successfully sent.\n This is not stored long term within Discord's servers and is only used ephemerally.\n embeds: List[:class:`Embed`]\n A list of embeds the message has.\n If :attr:`Intents.message_content` is not enabled this will always be an empty list\n unless the bot is mentioned or the message is a direct message.\n channel: Union[:class:`TextChannel`, :class:`StageChannel`, :class:`VoiceChannel`, :class:`Thread`, :class:`DMChannel`, :class:`GroupChannel`, :class:`PartialMessageable`]\n The :class:`TextChannel` or :class:`Thread` that the message was sent from.\n Could be a :class:`DMChannel` or :class:`GroupChannel` if it's a private message.\n reference: Optional[:class:`~discord.MessageReference`]\n The message that this message references. This is only applicable to messages of\n type :attr:`MessageType.pins_add`, crossposted messages created by a\n followed channel integration, or message replies.\n\n .. versionadded:: 1.5\n\n mention_everyone: :class:`bool`\n Specifies if the message mentions everyone.\n\n .. note::\n\n This does not check if the ``@everyone`` or the ``@here`` text is in the message itself.\n Rather this boolean indicates if either the ``@everyone`` or the ``@here`` text is in the message\n **and** it did end up mentioning.\n mentions: List[:class:`abc.User`]\n A list of :class:`Member` that were mentioned. If the message is in a private message\n then the list will be of :class:`User` instead. For messages that are not of type\n :attr:`MessageType.default`\\, this array can be used to aid in system messages.\n For more information, see :attr:`system_content`.\n\n .. warning::\n\n The order of the mentions list is not in any particular order so you should\n not rely on it. This is a Discord limitation, not one with the library.\n channel_mentions: List[Union[:class:`abc.GuildChannel`, :class:`Thread`]]\n A list of :class:`abc.GuildChannel` or :class:`Thread` that were mentioned. If the message is\n in a private message then the list is always empty.\n role_mentions: List[:class:`Role`]\n A list of :class:`Role` that were mentioned. If the message is in a private message\n then the list is always empty.\n id: :class:`int`\n The message ID.\n webhook_id: Optional[:class:`int`]\n If this message was sent by a webhook, then this is the webhook ID's that sent this\n message.\n attachments: List[:class:`Attachment`]\n A list of attachments given to a message.\n If :attr:`Intents.message_content` is not enabled this will always be an empty list\n unless the bot is mentioned or the message is a direct message.\n pinned: :class:`bool`\n Specifies if the message is currently pinned.\n flags: :class:`MessageFlags`\n Extra features of the message.\n\n .. versionadded:: 1.3\n\n reactions : List[:class:`Reaction`]\n Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.\n activity: Optional[:class:`dict`]\n The activity associated with this message. Sent with Rich-Presence related messages that for\n example, request joining, spectating, or listening to or with another member.\n\n It is a dictionary with the following optional keys:\n\n - ``type``: An integer denoting the type of message activity being requested.\n - ``party_id``: The party ID associated with the party.\n application: Optional[:class:`~discord.MessageApplication`]\n The rich presence enabled application associated with this message.\n\n .. versionchanged:: 2.0\n Type is now :class:`MessageApplication` instead of :class:`dict`.\n\n stickers: List[:class:`StickerItem`]\n A list of sticker items given to the message.\n\n .. versionadded:: 1.6\n components: List[Union[:class:`ActionRow`, :class:`Button`, :class:`SelectMenu`]]\n A list of components in the message.\n If :attr:`Intents.message_content` is not enabled this will always be an empty list\n unless the bot is mentioned or the message is a direct message.\n\n .. versionadded:: 2.0\n interaction: Optional[:class:`MessageInteraction`]\n The interaction that this message is a response to.\n\n .. versionadded:: 2.0\n role_subscription: Optional[:class:`RoleSubscriptionInfo`]\n The data of the role subscription purchase or renewal that prompted this\n :attr:`MessageType.role_subscription_purchase` message.\n\n .. versionadded:: 2.2\n application_id: Optional[:class:`int`]\n The application ID of the application that created this message if this\n message was sent by an application-owned webhook or an interaction.\n\n .. versionadded:: 2.2\n position: Optional[:class:`int`]\n A generally increasing integer with potentially gaps or duplicates that represents\n the approximate position of the message in a thread.\n\n .. versionadded:: 2.2\n guild: Optional[:class:`Guild`]\n The guild that the message belongs to, if applicable.\n \"\"\"\n\n __slots__ = (\n '_edited_timestamp',\n '_cs_channel_mentions',\n '_cs_raw_mentions',\n '_cs_clean_content',\n '_cs_raw_channel_mentions',\n '_cs_raw_role_mentions',\n '_cs_system_content',\n '_thread',\n 'tts',\n 'content',\n 'webhook_id',\n 'mention_everyone',\n 'embeds',\n 'mentions',\n 'author',\n 'attachments',\n 'nonce',\n 'pinned',\n 'role_mentions',\n 'type',\n 'flags',\n 'reactions',\n 'reference',\n 'application',\n 'activity',\n 'stickers',\n 'components',\n 'interaction',\n 'role_subscription',\n 'application_id',\n 'position',\n )\n\n if TYPE_CHECKING:\n _HANDLERS: ClassVar[List[Tuple[str, Callable[..., None]]]]\n _CACHED_SLOTS: ClassVar[List[str]]\n # guild: Optional[Guild]\n reference: Optional[MessageReference]\n mentions: List[Union[User, Member]]\n author: Union[User, Member]\n role_mentions: List[Role]\n components: List[MessageComponentType]\n\n def __init__(\n self,\n *,\n state: ConnectionState,\n channel: MessageableChannel,\n data: MessagePayload,\n ) -> None:\n self.channel: MessageableChannel = channel\n self.id: int = int(data['id'])\n self._state: ConnectionState = state\n self.webhook_id: Optional[int] = utils._get_as_snowflake(data, 'webhook_id')\n self.reactions: List[Reaction] = [Reaction(message=self, data=d) for d in data.get('reactions', [])]\n self.attachments: List[Attachment] = [Attachment(data=a, state=self._state) for a in data['attachments']]\n self.embeds: List[Embed] = [Embed.from_dict(a) for a in data['embeds']]\n self.activity: Optional[MessageActivityPayload] = data.get('activity')\n self._edited_timestamp: Optional[datetime.datetime] = utils.parse_time(data['edited_timestamp'])\n self.type: MessageType = try_enum(MessageType, data['type'])\n self.pinned: bool = data['pinned']\n self.flags: MessageFlags = MessageFlags._from_value(data.get('flags', 0))\n self.mention_everyone: bool = data['mention_everyone']\n self.tts: bool = data['tts']\n self.content: str = data['content']\n self.nonce: Optional[Union[int, str]] = data.get('nonce')\n self.position: Optional[int] = data.get('position')\n self.application_id: Optional[int] = utils._get_as_snowflake(data, 'application_id')\n self.stickers: List[StickerItem] = [StickerItem(data=d, state=state) for d in data.get('sticker_items', [])]\n\n try:\n # if the channel doesn't have a guild attribute, we handle that\n self.guild = channel.guild\n except AttributeError:\n self.guild = state._get_guild(utils._get_as_snowflake(data, 'guild_id'))\n\n self._thread: Optional[Thread] = None\n\n if self.guild is not None:\n try:\n thread = data['thread']\n except KeyError:\n pass\n else:\n self._thread = self.guild.get_thread(int(thread['id']))\n\n if self._thread is not None:\n self._thread._update(thread)\n else:\n self._thread = Thread(guild=self.guild, state=state, data=thread)\n\n self.interaction: Optional[MessageInteraction] = None\n\n try:\n interaction = data['interaction']\n except KeyError:\n pass\n else:\n self.interaction = MessageInteraction(state=state, guild=self.guild, data=interaction)\n\n try:\n ref = data['message_reference']\n except KeyError:\n self.reference = None\n else:\n self.reference = ref = MessageReference.with_state(state, ref)\n try:\n resolved = data['referenced_message']\n except KeyError:\n pass\n else:\n if resolved is None:\n ref.resolved = DeletedReferencedMessage(ref)\n else:\n # Right now the channel IDs match but maybe in the future they won't.\n if ref.channel_id == channel.id:\n chan = channel\n elif isinstance(channel, Thread) and channel.parent_id == ref.channel_id:\n chan = channel\n else:\n chan, _ = state._get_guild_channel(resolved, ref.guild_id)\n\n # the channel will be the correct type here\n ref.resolved = self.__class__(channel=chan, data=resolved, state=state) # type: ignore\n\n self.application: Optional[MessageApplication] = None\n try:\n application = data['application']\n except KeyError:\n pass\n else:\n self.application = MessageApplication(state=self._state, data=application)\n\n self.role_subscription: Optional[RoleSubscriptionInfo] = None\n try:\n role_subscription = data['role_subscription_data']\n except KeyError:\n pass\n else:\n self.role_subscription = RoleSubscriptionInfo(role_subscription)\n\n for handler in ('author', 'member', 'mentions', 'mention_roles', 'components'):\n try:\n getattr(self, f'_handle_{handler}')(data[handler])\n except KeyError:\n continue\n\n def __repr__(self) -> str:\n name = self.__class__.__name__\n return (\n f'<{name} id={self.id} channel={self.channel!r} type={self.type!r} author={self.author!r} flags={self.flags!r}>'\n )\n\n def _try_patch(self, data, key, transform=None) -> None:\n try:\n value = data[key]\n except KeyError:\n pass\n else:\n if transform is None:\n setattr(self, key, value)\n else:\n setattr(self, key, transform(value))\n\n def _add_reaction(self, data, emoji, user_id) -> Reaction:\n reaction = utils.find(lambda r: r.emoji == emoji, self.reactions)\n is_me = data['me'] = user_id == self._state.self_id\n\n if reaction is None:\n reaction = Reaction(message=self, data=data, emoji=emoji)\n self.reactions.append(reaction)\n else:\n reaction.count += 1\n if is_me:\n reaction.me = is_me\n\n return reaction\n\n def _remove_reaction(self, data: MessageReactionRemoveEvent, emoji: EmojiInputType, user_id: int) -> Reaction:\n reaction = utils.find(lambda r: r.emoji == emoji, self.reactions)\n\n if reaction is None:\n # already removed?\n raise ValueError('Emoji already removed?')\n\n # if reaction isn't in the list, we crash. This means discord\n # sent bad data, or we stored improperly\n reaction.count -= 1\n\n if user_id == self._state.self_id:\n reaction.me = False\n if reaction.count == 0:\n # this raises ValueError if something went wrong as well.\n self.reactions.remove(reaction)\n\n return reaction\n\n def _clear_emoji(self, emoji: PartialEmoji) -> Optional[Reaction]:\n to_check = str(emoji)\n for index, reaction in enumerate(self.reactions):\n if str(reaction.emoji) == to_check:\n break\n else:\n # didn't find anything so just return\n return\n\n del self.reactions[index]\n return reaction\n\n def _update(self, data: MessageUpdateEvent) -> None:\n # In an update scheme, 'author' key has to be handled before 'member'\n # otherwise they overwrite each other which is undesirable.\n # Since there's no good way to do this we have to iterate over every\n # handler rather than iterating over the keys which is a little slower\n for key, handler in self._HANDLERS:\n try:\n value = data[key]\n except KeyError:\n continue\n else:\n handler(self, value)\n\n # clear the cached properties\n for attr in self._CACHED_SLOTS:\n try:\n delattr(self, attr)\n except AttributeError:\n pass\n\n def _handle_edited_timestamp(self, value: str) -> None:\n self._edited_timestamp = utils.parse_time(value)\n\n def _handle_pinned(self, value: bool) -> None:\n self.pinned = value\n\n def _handle_flags(self, value: int) -> None:\n self.flags = MessageFlags._from_value(value)\n\n def _handle_application(self, value: MessageApplicationPayload) -> None:\n application = MessageApplication(state=self._state, data=value)\n self.application = application\n\n def _handle_activity(self, value: MessageActivityPayload) -> None:\n self.activity = value\n\n def _handle_mention_everyone(self, value: bool) -> None:\n self.mention_everyone = value\n\n def _handle_tts(self, value: bool) -> None:\n self.tts = value\n\n def _handle_type(self, value: int) -> None:\n self.type = try_enum(MessageType, value)\n\n def _handle_content(self, value: str) -> None:\n self.content = value\n\n def _handle_attachments(self, value: List[AttachmentPayload]) -> None:\n self.attachments = [Attachment(data=a, state=self._state) for a in value]\n\n def _handle_embeds(self, value: List[EmbedPayload]) -> None:\n self.embeds = [Embed.from_dict(data) for data in value]\n\n def _handle_nonce(self, value: Union[str, int]) -> None:\n self.nonce = value\n\n def _handle_author(self, author: UserPayload) -> None:\n self.author = self._state.store_user(author, cache=self.webhook_id is None)\n if isinstance(self.guild, Guild):\n found = self.guild.get_member(self.author.id)\n if found is not None:\n self.author = found\n\n def _handle_member(self, member: MemberPayload) -> None:\n # The gateway now gives us full Member objects sometimes with the following keys\n # deaf, mute, joined_at, roles\n # For the sake of performance I'm going to assume that the only\n # field that needs *updating* would be the joined_at field.\n # If there is no Member object (for some strange reason), then we can upgrade\n # ourselves to a more \"partial\" member object.\n author = self.author\n try:\n # Update member reference\n author._update_from_message(member) # type: ignore\n except AttributeError:\n # It's a user here\n self.author = Member._from_message(message=self, data=member)\n\n def _handle_mentions(self, mentions: List[UserWithMemberPayload]) -> None:\n self.mentions = r = []\n guild = self.guild\n state = self._state\n if not isinstance(guild, Guild):\n self.mentions = [state.store_user(m) for m in mentions]\n return\n\n for mention in filter(None, mentions):\n id_search = int(mention['id'])\n member = guild.get_member(id_search)\n if member is not None:\n r.append(member)\n else:\n r.append(Member._try_upgrade(data=mention, guild=guild, state=state))\n\n def _handle_mention_roles(self, role_mentions: List[int]) -> None:\n self.role_mentions = []\n if isinstance(self.guild, Guild):\n for role_id in map(int, role_mentions):\n role = self.guild.get_role(role_id)\n if role is not None:\n self.role_mentions.append(role)\n\n def _handle_components(self, data: List[ComponentPayload]) -> None:\n self.components = []\n\n for component_data in data:\n component = _component_factory(component_data)\n\n if component is not None:\n self.components.append(component)\n\n def _handle_interaction(self, data: MessageInteractionPayload):\n self.interaction = MessageInteraction(state=self._state, guild=self.guild, data=data)\n\n def _rebind_cached_references(\n self,\n new_guild: Guild,\n new_channel: Union[GuildChannel, Thread, PartialMessageable],\n ) -> None:\n self.guild = new_guild\n self.channel = new_channel # type: ignore # Not all \"GuildChannel\" are messageable at the moment\n\n @utils.cached_slot_property('_cs_raw_mentions')\n def raw_mentions(self) -> List[int]:\n \"\"\"List[:class:`int`]: A property that returns an array of user IDs matched with\n the syntax of ``<@user_id>`` in the message content.\n\n This allows you to receive the user IDs of mentioned users\n even in a private message context.\n \"\"\"\n return [int(x) for x in re.findall(r'<@!?([0-9]{15,20})>', self.content)]\n\n @utils.cached_slot_property('_cs_raw_channel_mentions')\n def raw_channel_mentions(self) -> List[int]:\n \"\"\"List[:class:`int`]: A property that returns an array of channel IDs matched with\n the syntax of ``<#channel_id>`` in the message content.\n \"\"\"\n return [int(x) for x in re.findall(r'<#([0-9]{15,20})>', self.content)]\n\n @utils.cached_slot_property('_cs_raw_role_mentions')\n def raw_role_mentions(self) -> List[int]:\n \"\"\"List[:class:`int`]: A property that returns an array of role IDs matched with\n the syntax of ``<@&role_id>`` in the message content.\n \"\"\"\n return [int(x) for x in re.findall(r'<@&([0-9]{15,20})>', self.content)]\n\n @utils.cached_slot_property('_cs_channel_mentions')\n def channel_mentions(self) -> List[Union[GuildChannel, Thread]]:\n if self.guild is None:\n return []\n it = filter(None, map(self.guild._resolve_channel, self.raw_channel_mentions))\n return utils._unique(it)\n\n @utils.cached_slot_property('_cs_clean_content')\n def clean_content(self) -> str:\n \"\"\":class:`str`: A property that returns the content in a \"cleaned up\"\n manner. This basically means that mentions are transformed\n into the way the client shows it. e.g. ``<#id>`` will transform\n into ``#name``.\n\n This will also transform @everyone and @here mentions into\n non-mentions.\n\n .. note::\n\n This *does not* affect markdown. If you want to escape\n or remove markdown then use :func:`utils.escape_markdown` or :func:`utils.remove_markdown`\n respectively, along with this function.\n \"\"\"\n\n if self.guild:\n\n def resolve_member(id: int) -> str:\n m = self.guild.get_member(id) or utils.get(self.mentions, id=id) # type: ignore\n return f'@{m.display_name}' if m else '@deleted-user'\n\n def resolve_role(id: int) -> str:\n r = self.guild.get_role(id) or utils.get(self.role_mentions, id=id) # type: ignore\n return f'@{r.name}' if r else '@deleted-role'\n\n def resolve_channel(id: int) -> str:\n c = self.guild._resolve_channel(id) # type: ignore\n return f'#{c.name}' if c else '#deleted-channel'\n\n else:\n\n def resolve_member(id: int) -> str:\n m = utils.get(self.mentions, id=id)\n return f'@{m.display_name}' if m else '@deleted-user'\n\n def resolve_role(id: int) -> str:\n return '@deleted-role'\n\n def resolve_channel(id: int) -> str:\n return '#deleted-channel'\n\n transforms = {\n '@': resolve_member,\n '@!': resolve_member,\n '#': resolve_channel,\n '@&': resolve_role,\n }\n\n def repl(match: re.Match) -> str:\n type = match[1]\n id = int(match[2])\n transformed = transforms[type](id)\n return transformed\n\n result = re.sub(r'<(@[!&]?|#)([0-9]{15,20})>', repl, self.content)\n\n return escape_mentions(result)\n\n @property\n def created_at(self) -> datetime.datetime:\n \"\"\":class:`datetime.datetime`: The message's creation time in UTC.\"\"\"\n return utils.snowflake_time(self.id)\n\n @property\n def edited_at(self) -> Optional[datetime.datetime]:\n \"\"\"Optional[:class:`datetime.datetime`]: An aware UTC datetime object containing the edited time of the message.\"\"\"\n return self._edited_timestamp\n\n @property\n def thread(self) -> Optional[Thread]:\n \"\"\"Optional[:class:`Thread`]: The public thread created from this message, if it exists.\n\n .. note::\n\n For messages received via the gateway this does not retrieve archived threads, as they\n are not retained in the internal cache. Use :meth:`fetch_thread` instead.\n\n .. versionadded:: 2.4\n \"\"\"\n if self.guild is not None:\n # Fall back to guild threads in case one was created after the message\n return self._thread or self.guild.get_thread(self.id)\n\n def is_system(self) -> bool:\n \"\"\":class:`bool`: Whether the message is a system message.\n\n A system message is a message that is constructed entirely by the Discord API\n in response to something.\n\n .. versionadded:: 1.3\n \"\"\"\n return self.type not in (\n MessageType.default,\n MessageType.reply,\n MessageType.chat_input_command,\n MessageType.context_menu_command,\n MessageType.thread_starter_message,\n )\n\n @utils.cached_slot_property('_cs_system_content')\n def system_content(self) -> str:\n r\"\"\":class:`str`: A property that returns the content that is rendered\n regardless of the :attr:`Message.type`.\n\n In the case of :attr:`MessageType.default` and :attr:`MessageType.reply`\\,\n this just returns the regular :attr:`Message.content`. Otherwise this\n returns an English message denoting the contents of the system message.\n \"\"\"\n\n if self.type is MessageType.default:\n return self.content\n\n if self.type is MessageType.recipient_add:\n if self.channel.type is ChannelType.group:\n return f'{self.author.name} added {self.mentions[0].name} to the group.'\n else:\n return f'{self.author.name} added {self.mentions[0].name} to the thread.'\n\n if self.type is MessageType.recipient_remove:\n if self.channel.type is ChannelType.group:\n return f'{self.author.name} removed {self.mentions[0].name} from the group.'\n else:\n return f'{self.author.name} removed {self.mentions[0].name} from the thread.'\n\n if self.type is MessageType.channel_name_change:\n if getattr(self.channel, 'parent', self.channel).type is ChannelType.forum:\n return f'{self.author.name} changed the post title: **{self.content}**'\n else:\n return f'{self.author.name} changed the channel name: **{self.content}**'\n\n if self.type is MessageType.channel_icon_change:\n return f'{self.author.name} changed the group icon.'\n\n if self.type is MessageType.pins_add:\n return f'{self.author.name} pinned a message to this channel.'\n\n if self.type is MessageType.new_member:\n formats = [\n \"{0} joined the party.\",\n \"{0} is here.\",\n \"Welcome, {0}. We hope you brought pizza.\",\n \"A wild {0} appeared.\",\n \"{0} just landed.\",\n \"{0} just slid into the server.\",\n \"{0} just showed up!\",\n \"Welcome {0}. Say hi!\",\n \"{0} hopped into the server.\",\n \"Everyone welcome {0}!\",\n \"Glad you're here, {0}.\",\n \"Good to see you, {0}.\",\n \"Yay you made it, {0}!\",\n ]\n\n created_at_ms = int(self.created_at.timestamp() * 1000)\n return formats[created_at_ms % len(formats)].format(self.author.name)\n\n if self.type is MessageType.premium_guild_subscription:\n if not self.content:\n return f'{self.author.name} just boosted the server!'\n else:\n return f'{self.author.name} just boosted the server **{self.content}** times!'\n\n if self.type is MessageType.premium_guild_tier_1:\n if not self.content:\n return f'{self.author.name} just boosted the server! {self.guild} has achieved **Level 1!**'\n else:\n return f'{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 1!**'\n\n if self.type is MessageType.premium_guild_tier_2:\n if not self.content:\n return f'{self.author.name} just boosted the server! {self.guild} has achieved **Level 2!**'\n else:\n return f'{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 2!**'\n\n if self.type is MessageType.premium_guild_tier_3:\n if not self.content:\n return f'{self.author.name} just boosted the server! {self.guild} has achieved **Level 3!**'\n else:\n return f'{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 3!**'\n\n if self.type is MessageType.channel_follow_add:\n return (\n f'{self.author.name} has added {self.content} to this channel. Its most important updates will show up here.'\n )\n\n if self.type is MessageType.guild_stream:\n # the author will be a Member\n return f'{self.author.name} is live! Now streaming {self.author.activity.name}' # type: ignore\n\n if self.type is MessageType.guild_discovery_disqualified:\n return 'This server has been removed from Server Discovery because it no longer passes all the requirements. Check Server Settings for more details.'\n\n if self.type is MessageType.guild_discovery_requalified:\n return 'This server is eligible for Server Discovery again and has been automatically relisted!'\n\n if self.type is MessageType.guild_discovery_grace_period_initial_warning:\n return 'This server has failed Discovery activity requirements for 1 week. If this server fails for 4 weeks in a row, it will be automatically removed from Discovery.'\n\n if self.type is MessageType.guild_discovery_grace_period_final_warning:\n return 'This server has failed Discovery activity requirements for 3 weeks in a row. If this server fails for 1 more week, it will be removed from Discovery.'\n\n if self.type is MessageType.thread_created:\n return f'{self.author.name} started a thread: **{self.content}**. See all **threads**.'\n\n if self.type is MessageType.reply:\n return self.content\n\n if self.type is MessageType.thread_starter_message:\n if self.reference is None or self.reference.resolved is None:\n return 'Sorry, we couldn\\'t load the first message in this thread'\n\n # the resolved message for the reference will be a Message\n return self.reference.resolved.content # type: ignore\n\n if self.type is MessageType.guild_invite_reminder:\n return 'Wondering who to invite?\\nStart by inviting anyone who can help you build the server!'\n\n if self.type is MessageType.role_subscription_purchase and self.role_subscription is not None:\n # TODO: figure out how the message looks like for is_renewal: true\n total_months = self.role_subscription.total_months_subscribed\n months = '1 month' if total_months == 1 else f'{total_months} months'\n return f'{self.author.name} joined {self.role_subscription.tier_name} and has been a subscriber of {self.guild} for {months}!'\n\n if self.type is MessageType.stage_start:\n return f'{self.author.name} started **{self.content}**.'\n\n if self.type is MessageType.stage_end:\n return f'{self.author.name} ended **{self.content}**.'\n\n if self.type is MessageType.stage_speaker:\n return f'{self.author.name} is now a speaker.'\n\n if self.type is MessageType.stage_raise_hand:\n return f'{self.author.name} requested to speak.'\n\n if self.type is MessageType.stage_topic:\n return f'{self.author.name} changed Stage topic: **{self.content}**.'\n\n # Fallback for unknown message types\n return ''\n\n @overload\n async def edit(\n self,\n *,\n content: Optional[str] = ...,\n embed: Optional[Embed] = ...,\n attachments: Sequence[Union[Attachment, File]] = ...,\n suppress: bool = ...,\n delete_after: Optional[float] = ...,\n allowed_mentions: Optional[AllowedMentions] = ...,\n view: Optional[View] = ...,\n ) -> Message:\n ...\n\n @overload\n async def edit(\n self,\n *,\n content: Optional[str] = ...,\n embeds: Sequence[Embed] = ...,\n attachments: Sequence[Union[Attachment, File]] = ...,\n suppress: bool = ...,\n delete_after: Optional[float] = ...,\n allowed_mentions: Optional[AllowedMentions] = ...,\n view: Optional[View] = ...,\n ) -> Message:\n ...\n\n async def edit(\n self,\n *,\n content: Optional[str] = MISSING,\n embed: Optional[Embed] = MISSING,\n embeds: Sequence[Embed] = MISSING,\n attachments: Sequence[Union[Attachment, File]] = MISSING,\n suppress: bool = False,\n delete_after: Optional[float] = None,\n allowed_mentions: Optional[AllowedMentions] = MISSING,\n view: Optional[View] = MISSING,\n ) -> Message:\n \"\"\"|coro|\n\n Edits the message.\n\n The content must be able to be transformed into a string via ``str(content)``.\n\n .. versionchanged:: 1.3\n The ``suppress`` keyword-only parameter was added.\n\n .. versionchanged:: 2.0\n Edits are no longer in-place, the newly edited message is returned instead.\n\n .. versionchanged:: 2.0\n This function will now raise :exc:`TypeError` instead of\n ``InvalidArgument``.\n\n Parameters\n -----------\n content: Optional[:class:`str`]\n The new content to replace the message with.\n Could be ``None`` to remove the content.\n embed: Optional[:class:`Embed`]\n The new embed to replace the original with.\n Could be ``None`` to remove the embed.\n embeds: List[:class:`Embed`]\n The new embeds to replace the original with. Must be a maximum of 10.\n To remove all embeds ``[]`` should be passed.\n\n .. versionadded:: 2.0\n attachments: List[Union[:class:`Attachment`, :class:`File`]]\n A list of attachments to keep in the message as well as new files to upload. If ``[]`` is passed\n then all attachments are removed.\n\n .. note::\n\n New files will always appear after current attachments.\n\n .. versionadded:: 2.0\n suppress: :class:`bool`\n Whether to suppress embeds for the message. This removes\n all the embeds if set to ``True``. If set to ``False``\n this brings the embeds back if they were suppressed.\n Using this parameter requires :attr:`~.Permissions.manage_messages`.\n delete_after: Optional[:class:`float`]\n If provided, the number of seconds to wait in the background\n before deleting the message we just edited. If the deletion fails,\n then it is silently ignored.\n allowed_mentions: Optional[:class:`~discord.AllowedMentions`]\n Controls the mentions being processed in this message. If this is\n passed, then the object is merged with :attr:`~discord.Client.allowed_mentions`.\n The merging behaviour only overrides attributes that have been explicitly passed\n to the object, otherwise it uses the attributes set in :attr:`~discord.Client.allowed_mentions`.\n If no object is passed at all then the defaults given by :attr:`~discord.Client.allowed_mentions`\n are used instead.\n\n .. versionadded:: 1.4\n view: Optional[:class:`~discord.ui.View`]\n The updated view to update this message with. If ``None`` is passed then\n the view is removed.\n\n Raises\n -------\n HTTPException\n Editing the message failed.\n Forbidden\n Tried to suppress a message without permissions or\n edited a message's content or embed that isn't yours.\n TypeError\n You specified both ``embed`` and ``embeds``\n\n Returns\n --------\n :class:`Message`\n The newly edited message.\n \"\"\"\n\n if content is not MISSING:\n previous_allowed_mentions = self._state.allowed_mentions\n else:\n previous_allowed_mentions = None\n\n if suppress is not MISSING:\n flags = MessageFlags._from_value(self.flags.value)\n flags.suppress_embeds = suppress\n else:\n flags = MISSING\n\n if view is not MISSING:\n self._state.prevent_view_updates_for(self.id)\n\n with handle_message_parameters(\n content=content,\n flags=flags,\n embed=embed,\n embeds=embeds,\n attachments=attachments,\n view=view,\n allowed_mentions=allowed_mentions,\n previous_allowed_mentions=previous_allowed_mentions,\n ) as params:\n data = await self._state.http.edit_message(self.channel.id, self.id, params=params)\n message = Message(state=self._state, channel=self.channel, data=data)\n\n if view and not view.is_finished():\n self._state.store_view(view, self.id)\n\n if delete_after is not None:\n await self.delete(delay=delete_after)\n\n return message\n\n async def add_files(self, *files: File) -> Message:\n r\"\"\"|coro|\n\n Adds new files to the end of the message attachments.\n\n .. versionadded:: 2.0\n\n Parameters\n -----------\n \\*files: :class:`File`\n New files to add to the message.\n\n Raises\n -------\n HTTPException\n Editing the message failed.\n Forbidden\n Tried to edit a message that isn't yours.\n\n Returns\n --------\n :class:`Message`\n The newly edited message.\n \"\"\"\n return await self.edit(attachments=[*self.attachments, *files])\n\n async def remove_attachments(self, *attachments: Attachment) -> Message:\n r\"\"\"|coro|\n\n Removes attachments from the message.\n\n .. versionadded:: 2.0\n\n Parameters\n -----------\n \\*attachments: :class:`Attachment`\n Attachments to remove from the message.\n\n Raises\n -------\n HTTPException\n Editing the message failed.\n Forbidden\n Tried to edit a message that isn't yours.\n\n Returns\n --------\n :class:`Message`\n The newly edited message.\n \"\"\"\n return await self.edit(attachments=[a for a in self.attachments if a not in attachments])\n" }, { "path": "discord/types/message.py", "content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import List, Literal, Optional, TypedDict, Union\nfrom typing_extensions import NotRequired, Required\n\nfrom .snowflake import Snowflake, SnowflakeList\nfrom .member import Member, UserWithMember\nfrom .user import User\nfrom .emoji import PartialEmoji\nfrom .embed import Embed\nfrom .channel import ChannelType\nfrom .components import Component\nfrom .interactions import MessageInteraction\nfrom .sticker import StickerItem\nfrom .threads import Thread\n\n\nclass PartialMessage(TypedDict):\n channel_id: Snowflake\n guild_id: NotRequired[Snowflake]\n\n\nclass ChannelMention(TypedDict):\n id: Snowflake\n guild_id: Snowflake\n type: ChannelType\n name: str\n\n\nclass ReactionCountDetails(TypedDict):\n burst: int\n normal: int\n\n\nclass Reaction(TypedDict):\n count: int\n me: bool\n emoji: PartialEmoji\n me_burst: bool\n count_details: ReactionCountDetails\n burst_colors: List[str]\n\n\nclass Attachment(TypedDict):\n id: Snowflake\n filename: str\n size: int\n url: str\n proxy_url: str\n height: NotRequired[Optional[int]]\n width: NotRequired[Optional[int]]\n description: NotRequired[str]\n content_type: NotRequired[str]\n spoiler: NotRequired[bool]\n ephemeral: NotRequired[bool]\n duration_secs: NotRequired[float]\n waveform: NotRequired[str]\n flags: NotRequired[int]\n\n\nMessageActivityType = Literal[1, 2, 3, 5]\n\n\nclass MessageActivity(TypedDict):\n type: MessageActivityType\n party_id: str\n\n\nclass MessageApplication(TypedDict):\n id: Snowflake\n description: str\n icon: Optional[str]\n name: str\n cover_image: NotRequired[str]\n\n\nclass MessageReference(TypedDict, total=False):\n message_id: Snowflake\n channel_id: Required[Snowflake]\n guild_id: Snowflake\n fail_if_not_exists: bool\n\n\nclass RoleSubscriptionData(TypedDict):\n role_subscription_listing_id: Snowflake\n tier_name: str\n total_months_subscribed: int\n is_renewal: bool\n\n\nMessageType = Literal[\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32\n]\n\n\nclass Message(PartialMessage):\n id: Snowflake\n author: User\n content: str\n timestamp: str\n edited_timestamp: Optional[str]\n tts: bool\n mention_everyone: bool\n mentions: List[UserWithMember]\n mention_roles: SnowflakeList\n attachments: List[Attachment]\n embeds: List[Embed]\n pinned: bool\n type: MessageType\n member: NotRequired[Member]\n mention_channels: NotRequired[List[ChannelMention]]\n reactions: NotRequired[List[Reaction]]\n nonce: NotRequired[Union[int, str]]\n webhook_id: NotRequired[Snowflake]\n activity: NotRequired[MessageActivity]\n application: NotRequired[MessageApplication]\n application_id: NotRequired[Snowflake]\n message_reference: NotRequired[MessageReference]\n flags: NotRequired[int]\n sticker_items: NotRequired[List[StickerItem]]\n referenced_message: NotRequired[Optional[Message]]\n interaction: NotRequired[MessageInteraction]\n components: NotRequired[List[Component]]\n position: NotRequired[int]\n role_subscription_data: NotRequired[RoleSubscriptionData]\n thread: NotRequired[Thread]\n\n\nAllowedMentionType = Literal['roles', 'users', 'everyone']\n\n\nclass AllowedMentions(TypedDict):\n parse: List[AllowedMentionType]\n roles: SnowflakeList\n users: SnowflakeList\n replied_user: bool\n" }, { "path": "docs/api.rst", "content": ".. currentmodule:: discord\n\nAPI Reference\n===============\n\nThe following section outlines the API of discord.py.\n\n.. note::\n\n This module uses the Python logging module to log diagnostic and errors\n in an output independent way. If the logging module is not configured,\n these logs will not be output anywhere. See :ref:`logging_setup` for\n more information on how to set up and use the logging module with\n discord.py.\n\nVersion Related Info\n---------------------\n\nThere are two main ways to query version information about the library. For guarantees, check :ref:`version_guarantees`.\n\n.. data:: version_info\n\n A named tuple that is similar to :obj:`py:sys.version_info`.\n\n Just like :obj:`py:sys.version_info` the valid values for ``releaselevel`` are\n 'alpha', 'beta', 'candidate' and 'final'.\n\n.. data:: __version__\n\n A string representation of the version. e.g. ``'1.0.0rc1'``. This is based\n off of :pep:`440`.\n\nClients\n--------\n\nClient\n~~~~~~~\n\n.. attributetable:: Client\n\n.. autoclass:: Client\n :members:\n :exclude-members: event\n\n .. automethod:: Client.event()\n :decorator:\n\nAutoShardedClient\n~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: AutoShardedClient\n\n.. autoclass:: AutoShardedClient\n :members:\n\nApplication Info\n------------------\n\nAppInfo\n~~~~~~~~\n\n.. attributetable:: AppInfo\n\n.. autoclass:: AppInfo()\n :members:\n\nPartialAppInfo\n~~~~~~~~~~~~~~~\n\n.. attributetable:: PartialAppInfo\n\n.. autoclass:: PartialAppInfo()\n :members:\n\nAppInstallParams\n~~~~~~~~~~~~~~~~\n\n.. attributetable:: AppInstallParams\n\n.. autoclass:: AppInstallParams()\n :members:\n\nTeam\n~~~~~\n\n.. attributetable:: Team\n\n.. autoclass:: Team()\n :members:\n\nTeamMember\n~~~~~~~~~~~\n\n.. attributetable:: TeamMember\n\n.. autoclass:: TeamMember()\n :members:\n :inherited-members:\n\nVoice Related\n---------------\n\nVoiceClient\n~~~~~~~~~~~~\n\n.. attributetable:: VoiceClient\n\n.. autoclass:: VoiceClient()\n :members:\n :exclude-members: connect, on_voice_state_update, on_voice_server_update\n\nVoiceProtocol\n~~~~~~~~~~~~~~~\n\n.. attributetable:: VoiceProtocol\n\n.. autoclass:: VoiceProtocol\n :members:\n\nAudioSource\n~~~~~~~~~~~~\n\n.. attributetable:: AudioSource\n\n.. autoclass:: AudioSource\n :members:\n\nPCMAudio\n~~~~~~~~~\n\n.. attributetable:: PCMAudio\n\n.. autoclass:: PCMAudio\n :members:\n\nFFmpegAudio\n~~~~~~~~~~~~\n\n.. attributetable:: FFmpegAudio\n\n.. autoclass:: FFmpegAudio\n :members:\n\nFFmpegPCMAudio\n~~~~~~~~~~~~~~~\n\n.. attributetable:: FFmpegPCMAudio\n\n.. autoclass:: FFmpegPCMAudio\n :members:\n\nFFmpegOpusAudio\n~~~~~~~~~~~~~~~~\n\n.. attributetable:: FFmpegOpusAudio\n\n.. autoclass:: FFmpegOpusAudio\n :members:\n\nPCMVolumeTransformer\n~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: PCMVolumeTransformer\n\n.. autoclass:: PCMVolumeTransformer\n :members:\n\nOpus Library\n~~~~~~~~~~~~~\n\n.. autofunction:: discord.opus.load_opus\n\n.. autofunction:: discord.opus.is_loaded\n\n.. _discord-api-events:\n\nEvent Reference\n---------------\n\nThis section outlines the different types of events listened by :class:`Client`.\n\nThere are two ways to register an event, the first way is through the use of\n:meth:`Client.event`. The second way is through subclassing :class:`Client` and\noverriding the specific events. For example: ::\n\n import discord\n\n class MyClient(discord.Client):\n async def on_message(self, message):\n if message.author == self.user:\n return\n\n if message.content.startswith('$hello'):\n await message.channel.send('Hello World!')\n\n\nIf an event handler raises an exception, :func:`on_error` will be called\nto handle it, which defaults to logging the traceback and ignoring the exception.\n\n.. warning::\n\n All the events must be a |coroutine_link|_. If they aren't, then you might get unexpected\n errors. In order to turn a function into a coroutine they must be ``async def``\n functions.\n\nApp Commands\n~~~~~~~~~~~~~\n\n.. function:: on_raw_app_command_permissions_update(payload)\n\n Called when application command permissions are updated.\n\n .. versionadded:: 2.0\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawAppCommandPermissionsUpdateEvent`\n\n.. function:: on_app_command_completion(interaction, command)\n\n Called when a :class:`app_commands.Command` or :class:`app_commands.ContextMenu` has\n successfully completed without error.\n\n .. versionadded:: 2.0\n\n :param interaction: The interaction of the command.\n :type interaction: :class:`Interaction`\n :param command: The command that completed successfully\n :type command: Union[:class:`app_commands.Command`, :class:`app_commands.ContextMenu`]\n\nAutoMod\n~~~~~~~~\n\n.. function:: on_automod_rule_create(rule)\n\n Called when a :class:`AutoModRule` is created.\n You must have :attr:`~Permissions.manage_guild` to receive this.\n\n This requires :attr:`Intents.auto_moderation_configuration` to be enabled.\n\n .. versionadded:: 2.0\n\n :param rule: The rule that was created.\n :type rule: :class:`AutoModRule`\n\n.. function:: on_automod_rule_update(rule)\n\n Called when a :class:`AutoModRule` is updated.\n You must have :attr:`~Permissions.manage_guild` to receive this.\n\n This requires :attr:`Intents.auto_moderation_configuration` to be enabled.\n\n .. versionadded:: 2.0\n\n :param rule: The rule that was updated.\n :type rule: :class:`AutoModRule`\n\n.. function:: on_automod_rule_delete(rule)\n\n Called when a :class:`AutoModRule` is deleted.\n You must have :attr:`~Permissions.manage_guild` to receive this.\n\n This requires :attr:`Intents.auto_moderation_configuration` to be enabled.\n\n .. versionadded:: 2.0\n\n :param rule: The rule that was deleted.\n :type rule: :class:`AutoModRule`\n\n.. function:: on_automod_action(execution)\n\n Called when a :class:`AutoModAction` is created/performed.\n You must have :attr:`~Permissions.manage_guild` to receive this.\n\n This requires :attr:`Intents.auto_moderation_execution` to be enabled.\n\n .. versionadded:: 2.0\n\n :param execution: The rule execution that was performed.\n :type execution: :class:`AutoModAction`\n\nChannels\n~~~~~~~~~\n\n.. function:: on_guild_channel_delete(channel)\n on_guild_channel_create(channel)\n\n Called whenever a guild channel is deleted or created.\n\n Note that you can get the guild from :attr:`~abc.GuildChannel.guild`.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n :param channel: The guild channel that got created or deleted.\n :type channel: :class:`abc.GuildChannel`\n\n.. function:: on_guild_channel_update(before, after)\n\n Called whenever a guild channel is updated. e.g. changed name, topic, permissions.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n :param before: The updated guild channel's old info.\n :type before: :class:`abc.GuildChannel`\n :param after: The updated guild channel's new info.\n :type after: :class:`abc.GuildChannel`\n\n.. function:: on_guild_channel_pins_update(channel, last_pin)\n\n Called whenever a message is pinned or unpinned from a guild channel.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n :param channel: The guild channel that had its pins updated.\n :type channel: Union[:class:`abc.GuildChannel`, :class:`Thread`]\n :param last_pin: The latest message that was pinned as an aware datetime in UTC. Could be ``None``.\n :type last_pin: Optional[:class:`datetime.datetime`]\n\n.. function:: on_private_channel_update(before, after)\n\n Called whenever a private group DM is updated. e.g. changed name or topic.\n\n This requires :attr:`Intents.messages` to be enabled.\n\n :param before: The updated group channel's old info.\n :type before: :class:`GroupChannel`\n :param after: The updated group channel's new info.\n :type after: :class:`GroupChannel`\n\n.. function:: on_private_channel_pins_update(channel, last_pin)\n\n Called whenever a message is pinned or unpinned from a private channel.\n\n :param channel: The private channel that had its pins updated.\n :type channel: :class:`abc.PrivateChannel`\n :param last_pin: The latest message that was pinned as an aware datetime in UTC. Could be ``None``.\n :type last_pin: Optional[:class:`datetime.datetime`]\n\n.. function:: on_typing(channel, user, when)\n\n Called when someone begins typing a message.\n\n The ``channel`` parameter can be a :class:`abc.Messageable` instance.\n Which could either be :class:`TextChannel`, :class:`GroupChannel`, or\n :class:`DMChannel`.\n\n If the ``channel`` is a :class:`TextChannel` then the ``user`` parameter\n is a :class:`Member`, otherwise it is a :class:`User`.\n\n If the channel or user could not be found in the internal cache this event\n will not be called, you may use :func:`on_raw_typing` instead.\n\n This requires :attr:`Intents.typing` to be enabled.\n\n :param channel: The location where the typing originated from.\n :type channel: :class:`abc.Messageable`\n :param user: The user that started typing.\n :type user: Union[:class:`User`, :class:`Member`]\n :param when: When the typing started as an aware datetime in UTC.\n :type when: :class:`datetime.datetime`\n\n.. function:: on_raw_typing(payload)\n\n Called when someone begins typing a message. Unlike :func:`on_typing` this\n is called regardless of the channel and user being in the internal cache.\n\n This requires :attr:`Intents.typing` to be enabled.\n\n .. versionadded:: 2.0\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawTypingEvent`\n\nConnection\n~~~~~~~~~~~\n\n.. function:: on_connect()\n\n Called when the client has successfully connected to Discord. This is not\n the same as the client being fully prepared, see :func:`on_ready` for that.\n\n The warnings on :func:`on_ready` also apply.\n\n.. function:: on_disconnect()\n\n Called when the client has disconnected from Discord, or a connection attempt to Discord has failed.\n This could happen either through the internet being disconnected, explicit calls to close,\n or Discord terminating the connection one way or the other.\n\n This function can be called many times without a corresponding :func:`on_connect` call.\n\n.. function:: on_shard_connect(shard_id)\n\n Similar to :func:`on_connect` except used by :class:`AutoShardedClient`\n to denote when a particular shard ID has connected to Discord.\n\n .. versionadded:: 1.4\n\n :param shard_id: The shard ID that has connected.\n :type shard_id: :class:`int`\n\n\n.. function:: on_shard_disconnect(shard_id)\n\n Similar to :func:`on_disconnect` except used by :class:`AutoShardedClient`\n to denote when a particular shard ID has disconnected from Discord.\n\n .. versionadded:: 1.4\n\n :param shard_id: The shard ID that has disconnected.\n :type shard_id: :class:`int`\n\nDebug\n~~~~~~\n\n.. function:: on_error(event, *args, **kwargs)\n\n Usually when an event raises an uncaught exception, a traceback is\n logged to stderr and the exception is ignored. If you want to\n change this behaviour and handle the exception for whatever reason\n yourself, this event can be overridden. Which, when done, will\n suppress the default action of printing the traceback.\n\n The information of the exception raised and the exception itself can\n be retrieved with a standard call to :func:`sys.exc_info`.\n\n .. note::\n\n ``on_error`` will only be dispatched to :meth:`Client.event`.\n\n It will not be received by :meth:`Client.wait_for`, or, if used,\n :ref:`ext_commands_api_bot` listeners such as\n :meth:`~ext.commands.Bot.listen` or :meth:`~ext.commands.Cog.listener`.\n\n .. versionchanged:: 2.0\n\n The traceback is now logged rather than printed.\n\n :param event: The name of the event that raised the exception.\n :type event: :class:`str`\n\n :param args: The positional arguments for the event that raised the\n exception.\n :param kwargs: The keyword arguments for the event that raised the\n exception.\n\n.. function:: on_socket_event_type(event_type)\n\n Called whenever a websocket event is received from the WebSocket.\n\n This is mainly useful for logging how many events you are receiving\n from the Discord gateway.\n\n .. versionadded:: 2.0\n\n :param event_type: The event type from Discord that is received, e.g. ``'READY'``.\n :type event_type: :class:`str`\n\n.. function:: on_socket_raw_receive(msg)\n\n Called whenever a message is completely received from the WebSocket, before\n it's processed and parsed. This event is always dispatched when a\n complete message is received and the passed data is not parsed in any way.\n\n This is only really useful for grabbing the WebSocket stream and\n debugging purposes.\n\n This requires setting the ``enable_debug_events`` setting in the :class:`Client`.\n\n .. note::\n\n This is only for the messages received from the client\n WebSocket. The voice WebSocket will not trigger this event.\n\n :param msg: The message passed in from the WebSocket library.\n :type msg: :class:`str`\n\n.. function:: on_socket_raw_send(payload)\n\n Called whenever a send operation is done on the WebSocket before the\n message is sent. The passed parameter is the message that is being\n sent to the WebSocket.\n\n This is only really useful for grabbing the WebSocket stream and\n debugging purposes.\n\n This requires setting the ``enable_debug_events`` setting in the :class:`Client`.\n\n .. note::\n\n This is only for the messages sent from the client\n WebSocket. The voice WebSocket will not trigger this event.\n\n :param payload: The message that is about to be passed on to the\n WebSocket library. It can be :class:`bytes` to denote a binary\n message or :class:`str` to denote a regular text message.\n :type payload: Union[:class:`bytes`, :class:`str`]\n\n\nEntitlements\n~~~~~~~~~~~~\n\n.. function:: on_entitlement_create(entitlement)\n\n Called when a user subscribes to a SKU.\n\n .. versionadded:: 2.4\n\n :param entitlement: The entitlement that was created.\n :type entitlement: :class:`Entitlement`\n\n.. function:: on_entitlement_update(entitlement)\n\n Called when a user updates their subscription to a SKU. This is usually called when\n the user renews or cancels their subscription.\n\n .. versionadded:: 2.4\n\n :param entitlement: The entitlement that was updated.\n :type entitlement: :class:`Entitlement`\n\n.. function:: on_entitlement_delete(entitlement)\n\n Called when a users subscription to a SKU is cancelled. This is typically only called when:\n\n - Discord issues a refund for the subscription.\n - Discord removes an entitlement from a user.\n\n .. warning::\n\n This event won't be called if the user cancels their subscription manually, instead\n :func:`on_entitlement_update` will be called with :attr:`Entitlement.ends_at` set to the end of the\n current billing period.\n\n .. versionadded:: 2.4\n\n :param entitlement: The entitlement that was deleted.\n :type entitlement: :class:`Entitlement`\n\n\nGateway\n~~~~~~~~\n\n.. function:: on_ready()\n\n Called when the client is done preparing the data received from Discord. Usually after login is successful\n and the :attr:`Client.guilds` and co. are filled up.\n\n .. warning::\n\n This function is not guaranteed to be the first event called.\n Likewise, this function is **not** guaranteed to only be called\n once. This library implements reconnection logic and thus will\n end up calling this event whenever a RESUME request fails.\n\n.. function:: on_resumed()\n\n Called when the client has resumed a session.\n\n.. function:: on_shard_ready(shard_id)\n\n Similar to :func:`on_ready` except used by :class:`AutoShardedClient`\n to denote when a particular shard ID has become ready.\n\n :param shard_id: The shard ID that is ready.\n :type shard_id: :class:`int`\n\n\n.. function:: on_shard_resumed(shard_id)\n\n Similar to :func:`on_resumed` except used by :class:`AutoShardedClient`\n to denote when a particular shard ID has resumed a session.\n\n .. versionadded:: 1.4\n\n :param shard_id: The shard ID that has resumed.\n :type shard_id: :class:`int`\n\nGuilds\n~~~~~~~\n\n.. function:: on_guild_available(guild)\n on_guild_unavailable(guild)\n\n Called when a guild becomes available or unavailable. The guild must have\n existed in the :attr:`Client.guilds` cache.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n :param guild: The :class:`Guild` that has changed availability.\n\n.. function:: on_guild_join(guild)\n\n Called when a :class:`Guild` is either created by the :class:`Client` or when the\n :class:`Client` joins a guild.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n :param guild: The guild that was joined.\n :type guild: :class:`Guild`\n\n.. function:: on_guild_remove(guild)\n\n Called when a :class:`Guild` is removed from the :class:`Client`.\n\n This happens through, but not limited to, these circumstances:\n\n - The client got banned.\n - The client got kicked.\n - The client left the guild.\n - The client or the guild owner deleted the guild.\n\n In order for this event to be invoked then the :class:`Client` must have\n been part of the guild to begin with. (i.e. it is part of :attr:`Client.guilds`)\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n :param guild: The guild that got removed.\n :type guild: :class:`Guild`\n\n.. function:: on_guild_update(before, after)\n\n Called when a :class:`Guild` updates, for example:\n\n - Changed name\n - Changed AFK channel\n - Changed AFK timeout\n - etc\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n :param before: The guild prior to being updated.\n :type before: :class:`Guild`\n :param after: The guild after being updated.\n :type after: :class:`Guild`\n\n.. function:: on_guild_emojis_update(guild, before, after)\n\n Called when a :class:`Guild` adds or removes :class:`Emoji`.\n\n This requires :attr:`Intents.emojis_and_stickers` to be enabled.\n\n :param guild: The guild who got their emojis updated.\n :type guild: :class:`Guild`\n :param before: A list of emojis before the update.\n :type before: Sequence[:class:`Emoji`]\n :param after: A list of emojis after the update.\n :type after: Sequence[:class:`Emoji`]\n\n.. function:: on_guild_stickers_update(guild, before, after)\n\n Called when a :class:`Guild` updates its stickers.\n\n This requires :attr:`Intents.emojis_and_stickers` to be enabled.\n\n .. versionadded:: 2.0\n\n :param guild: The guild who got their stickers updated.\n :type guild: :class:`Guild`\n :param before: A list of stickers before the update.\n :type before: Sequence[:class:`GuildSticker`]\n :param after: A list of stickers after the update.\n :type after: Sequence[:class:`GuildSticker`]\n\n.. function:: on_audit_log_entry_create(entry)\n\n Called when a :class:`Guild` gets a new audit log entry.\n You must have :attr:`~Permissions.view_audit_log` to receive this.\n\n This requires :attr:`Intents.moderation` to be enabled.\n\n .. versionadded:: 2.2\n\n .. warning::\n\n Audit log entries received through the gateway are subject to data retrieval\n from cache rather than REST. This means that some data might not be present\n when you expect it to be. For example, the :attr:`AuditLogEntry.target`\n attribute will usually be a :class:`discord.Object` and the\n :attr:`AuditLogEntry.user` attribute will depend on user and member cache.\n\n To get the user ID of entry, :attr:`AuditLogEntry.user_id` can be used instead.\n\n :param entry: The audit log entry that was created.\n :type entry: :class:`AuditLogEntry`\n\n.. function:: on_invite_create(invite)\n\n Called when an :class:`Invite` is created.\n You must have :attr:`~Permissions.manage_channels` to receive this.\n\n .. versionadded:: 1.3\n\n .. note::\n\n There is a rare possibility that the :attr:`Invite.guild` and :attr:`Invite.channel`\n attributes will be of :class:`Object` rather than the respective models.\n\n This requires :attr:`Intents.invites` to be enabled.\n\n :param invite: The invite that was created.\n :type invite: :class:`Invite`\n\n.. function:: on_invite_delete(invite)\n\n Called when an :class:`Invite` is deleted.\n You must have :attr:`~Permissions.manage_channels` to receive this.\n\n .. versionadded:: 1.3\n\n .. note::\n\n There is a rare possibility that the :attr:`Invite.guild` and :attr:`Invite.channel`\n attributes will be of :class:`Object` rather than the respective models.\n\n Outside of those two attributes, the only other attribute guaranteed to be\n filled by the Discord gateway for this event is :attr:`Invite.code`.\n\n This requires :attr:`Intents.invites` to be enabled.\n\n :param invite: The invite that was deleted.\n :type invite: :class:`Invite`\n\n\nIntegrations\n~~~~~~~~~~~~~\n\n.. function:: on_integration_create(integration)\n\n Called when an integration is created.\n\n This requires :attr:`Intents.integrations` to be enabled.\n\n .. versionadded:: 2.0\n\n :param integration: The integration that was created.\n :type integration: :class:`Integration`\n\n.. function:: on_integration_update(integration)\n\n Called when an integration is updated.\n\n This requires :attr:`Intents.integrations` to be enabled.\n\n .. versionadded:: 2.0\n\n :param integration: The integration that was updated.\n :type integration: :class:`Integration`\n\n.. function:: on_guild_integrations_update(guild)\n\n Called whenever an integration is created, modified, or removed from a guild.\n\n This requires :attr:`Intents.integrations` to be enabled.\n\n .. versionadded:: 1.4\n\n :param guild: The guild that had its integrations updated.\n :type guild: :class:`Guild`\n\n.. function:: on_webhooks_update(channel)\n\n Called whenever a webhook is created, modified, or removed from a guild channel.\n\n This requires :attr:`Intents.webhooks` to be enabled.\n\n :param channel: The channel that had its webhooks updated.\n :type channel: :class:`abc.GuildChannel`\n\n.. function:: on_raw_integration_delete(payload)\n\n Called when an integration is deleted.\n\n This requires :attr:`Intents.integrations` to be enabled.\n\n .. versionadded:: 2.0\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawIntegrationDeleteEvent`\n\nInteractions\n~~~~~~~~~~~~~\n\n.. function:: on_interaction(interaction)\n\n Called when an interaction happened.\n\n This currently happens due to slash command invocations or components being used.\n\n .. warning::\n\n This is a low level function that is not generally meant to be used.\n If you are working with components, consider using the callbacks associated\n with the :class:`~discord.ui.View` instead as it provides a nicer user experience.\n\n .. versionadded:: 2.0\n\n :param interaction: The interaction data.\n :type interaction: :class:`Interaction`\n\nMembers\n~~~~~~~~\n\n.. function:: on_member_join(member)\n\n Called when a :class:`Member` joins a :class:`Guild`.\n\n This requires :attr:`Intents.members` to be enabled.\n\n :param member: The member who joined.\n :type member: :class:`Member`\n\n.. function:: on_member_remove(member)\n\n Called when a :class:`Member` leaves a :class:`Guild`.\n\n If the guild or member could not be found in the internal cache this event\n will not be called, you may use :func:`on_raw_member_remove` instead.\n\n This requires :attr:`Intents.members` to be enabled.\n\n :param member: The member who left.\n :type member: :class:`Member`\n\n.. function:: on_raw_member_remove(payload)\n\n Called when a :class:`Member` leaves a :class:`Guild`.\n\n Unlike :func:`on_member_remove`\n this is called regardless of the guild or member being in the internal cache.\n\n This requires :attr:`Intents.members` to be enabled.\n\n .. versionadded:: 2.0\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawMemberRemoveEvent`\n\n.. function:: on_member_update(before, after)\n\n Called when a :class:`Member` updates their profile.\n\n This is called when one or more of the following things change:\n\n - nickname\n - roles\n - pending\n - timeout\n - guild avatar\n - flags\n\n Due to a Discord limitation, this event is not dispatched when a member's timeout expires.\n\n This requires :attr:`Intents.members` to be enabled.\n\n :param before: The updated member's old info.\n :type before: :class:`Member`\n :param after: The updated member's updated info.\n :type after: :class:`Member`\n\n.. function:: on_user_update(before, after)\n\n Called when a :class:`User` updates their profile.\n\n This is called when one or more of the following things change:\n\n - avatar\n - username\n - discriminator\n\n This requires :attr:`Intents.members` to be enabled.\n\n :param before: The updated user's old info.\n :type before: :class:`User`\n :param after: The updated user's updated info.\n :type after: :class:`User`\n\n.. function:: on_member_ban(guild, user)\n\n Called when a user gets banned from a :class:`Guild`.\n\n This requires :attr:`Intents.moderation` to be enabled.\n\n :param guild: The guild the user got banned from.\n :type guild: :class:`Guild`\n :param user: The user that got banned.\n Can be either :class:`User` or :class:`Member` depending if\n the user was in the guild or not at the time of removal.\n :type user: Union[:class:`User`, :class:`Member`]\n\n.. function:: on_member_unban(guild, user)\n\n Called when a :class:`User` gets unbanned from a :class:`Guild`.\n\n This requires :attr:`Intents.moderation` to be enabled.\n\n :param guild: The guild the user got unbanned from.\n :type guild: :class:`Guild`\n :param user: The user that got unbanned.\n :type user: :class:`User`\n\n.. function:: on_presence_update(before, after)\n\n Called when a :class:`Member` updates their presence.\n\n This is called when one or more of the following things change:\n\n - status\n - activity\n\n This requires :attr:`Intents.presences` and :attr:`Intents.members` to be enabled.\n\n .. versionadded:: 2.0\n\n :param before: The updated member's old info.\n :type before: :class:`Member`\n :param after: The updated member's updated info.\n :type after: :class:`Member`\n\nMessages\n~~~~~~~~~\n\n.. function:: on_message(message)\n\n Called when a :class:`Message` is created and sent.\n\n This requires :attr:`Intents.messages` to be enabled.\n\n .. warning::\n\n Your bot's own messages and private messages are sent through this\n event. This can lead cases of 'recursion' depending on how your bot was\n programmed. If you want the bot to not reply to itself, consider\n checking the user IDs. Note that :class:`~ext.commands.Bot` does not\n have this problem.\n\n :param message: The current message.\n :type message: :class:`Message`\n\n.. function:: on_message_edit(before, after)\n\n Called when a :class:`Message` receives an update event. If the message is not found\n in the internal message cache, then these events will not be called.\n Messages might not be in cache if the message is too old\n or the client is participating in high traffic guilds.\n\n If this occurs increase the :class:`max_messages ` parameter\n or use the :func:`on_raw_message_edit` event instead.\n\n The following non-exhaustive cases trigger this event:\n\n - A message has been pinned or unpinned.\n - The message content has been changed.\n - The message has received an embed.\n\n - For performance reasons, the embed server does not do this in a \"consistent\" manner.\n\n - The message's embeds were suppressed or unsuppressed.\n - A call message has received an update to its participants or ending time.\n\n This requires :attr:`Intents.messages` to be enabled.\n\n :param before: The previous version of the message.\n :type before: :class:`Message`\n :param after: The current version of the message.\n :type after: :class:`Message`\n\n.. function:: on_message_delete(message)\n\n Called when a message is deleted. If the message is not found in the\n internal message cache, then this event will not be called.\n Messages might not be in cache if the message is too old\n or the client is participating in high traffic guilds.\n\n If this occurs increase the :class:`max_messages ` parameter\n or use the :func:`on_raw_message_delete` event instead.\n\n This requires :attr:`Intents.messages` to be enabled.\n\n :param message: The deleted message.\n :type message: :class:`Message`\n\n.. function:: on_bulk_message_delete(messages)\n\n Called when messages are bulk deleted. If none of the messages deleted\n are found in the internal message cache, then this event will not be called.\n If individual messages were not found in the internal message cache,\n this event will still be called, but the messages not found will not be included in\n the messages list. Messages might not be in cache if the message is too old\n or the client is participating in high traffic guilds.\n\n If this occurs increase the :class:`max_messages ` parameter\n or use the :func:`on_raw_bulk_message_delete` event instead.\n\n This requires :attr:`Intents.messages` to be enabled.\n\n :param messages: The messages that have been deleted.\n :type messages: List[:class:`Message`]\n\n.. function:: on_raw_message_edit(payload)\n\n Called when a message is edited. Unlike :func:`on_message_edit`, this is called\n regardless of the state of the internal message cache.\n\n If the message is found in the message cache,\n it can be accessed via :attr:`RawMessageUpdateEvent.cached_message`. The cached message represents\n the message before it has been edited. For example, if the content of a message is modified and\n triggers the :func:`on_raw_message_edit` coroutine, the :attr:`RawMessageUpdateEvent.cached_message`\n will return a :class:`Message` object that represents the message before the content was modified.\n\n Due to the inherently raw nature of this event, the data parameter coincides with\n the raw data given by the :ddocs:`gateway `.\n\n Since the data payload can be partial, care must be taken when accessing stuff in the dictionary.\n One example of a common case of partial data is when the ``'content'`` key is inaccessible. This\n denotes an \"embed\" only edit, which is an edit in which only the embeds are updated by the Discord\n embed server.\n\n This requires :attr:`Intents.messages` to be enabled.\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawMessageUpdateEvent`\n\n\n.. function:: on_raw_message_delete(payload)\n\n Called when a message is deleted. Unlike :func:`on_message_delete`, this is\n called regardless of the message being in the internal message cache or not.\n\n If the message is found in the message cache,\n it can be accessed via :attr:`RawMessageDeleteEvent.cached_message`\n\n This requires :attr:`Intents.messages` to be enabled.\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawMessageDeleteEvent`\n\n.. function:: on_raw_bulk_message_delete(payload)\n\n Called when a bulk delete is triggered. Unlike :func:`on_bulk_message_delete`, this is\n called regardless of the messages being in the internal message cache or not.\n\n If the messages are found in the message cache,\n they can be accessed via :attr:`RawBulkMessageDeleteEvent.cached_messages`\n\n This requires :attr:`Intents.messages` to be enabled.\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawBulkMessageDeleteEvent`\n\nReactions\n~~~~~~~~~~\n\n.. function:: on_reaction_add(reaction, user)\n\n Called when a message has a reaction added to it. Similar to :func:`on_message_edit`,\n if the message is not found in the internal message cache, then this\n event will not be called. Consider using :func:`on_raw_reaction_add` instead.\n\n .. note::\n\n To get the :class:`Message` being reacted, access it via :attr:`Reaction.message`.\n\n This requires :attr:`Intents.reactions` to be enabled.\n\n .. note::\n\n This doesn't require :attr:`Intents.members` within a guild context,\n but due to Discord not providing updated user information in a direct message\n it's required for direct messages to receive this event.\n Consider using :func:`on_raw_reaction_add` if you need this and do not otherwise want\n to enable the members intent.\n\n .. warning::\n\n This event does not have a way of differentiating whether a reaction is a\n burst reaction (also known as \"super reaction\") or not. If you need this,\n consider using :func:`on_raw_reaction_add` instead.\n\n :param reaction: The current state of the reaction.\n :type reaction: :class:`Reaction`\n :param user: The user who added the reaction.\n :type user: Union[:class:`Member`, :class:`User`]\n\n.. function:: on_reaction_remove(reaction, user)\n\n Called when a message has a reaction removed from it. Similar to on_message_edit,\n if the message is not found in the internal message cache, then this event\n will not be called.\n\n .. note::\n\n To get the message being reacted, access it via :attr:`Reaction.message`.\n\n This requires both :attr:`Intents.reactions` and :attr:`Intents.members` to be enabled.\n\n .. note::\n\n Consider using :func:`on_raw_reaction_remove` if you need this and do not want\n to enable the members intent.\n\n .. warning::\n\n This event does not have a way of differentiating whether a reaction is a\n burst reaction (also known as \"super reaction\") or not. If you need this,\n consider using :func:`on_raw_reaction_remove` instead.\n\n :param reaction: The current state of the reaction.\n :type reaction: :class:`Reaction`\n :param user: The user whose reaction was removed.\n :type user: Union[:class:`Member`, :class:`User`]\n\n.. function:: on_reaction_clear(message, reactions)\n\n Called when a message has all its reactions removed from it. Similar to :func:`on_message_edit`,\n if the message is not found in the internal message cache, then this event\n will not be called. Consider using :func:`on_raw_reaction_clear` instead.\n\n This requires :attr:`Intents.reactions` to be enabled.\n\n :param message: The message that had its reactions cleared.\n :type message: :class:`Message`\n :param reactions: The reactions that were removed.\n :type reactions: List[:class:`Reaction`]\n\n.. function:: on_reaction_clear_emoji(reaction)\n\n Called when a message has a specific reaction removed from it. Similar to :func:`on_message_edit`,\n if the message is not found in the internal message cache, then this event\n will not be called. Consider using :func:`on_raw_reaction_clear_emoji` instead.\n\n This requires :attr:`Intents.reactions` to be enabled.\n\n .. versionadded:: 1.3\n\n :param reaction: The reaction that got cleared.\n :type reaction: :class:`Reaction`\n\n\n.. function:: on_raw_reaction_add(payload)\n\n Called when a message has a reaction added. Unlike :func:`on_reaction_add`, this is\n called regardless of the state of the internal message cache.\n\n This requires :attr:`Intents.reactions` to be enabled.\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawReactionActionEvent`\n\n.. function:: on_raw_reaction_remove(payload)\n\n Called when a message has a reaction removed. Unlike :func:`on_reaction_remove`, this is\n called regardless of the state of the internal message cache.\n\n This requires :attr:`Intents.reactions` to be enabled.\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawReactionActionEvent`\n\n.. function:: on_raw_reaction_clear(payload)\n\n Called when a message has all its reactions removed. Unlike :func:`on_reaction_clear`,\n this is called regardless of the state of the internal message cache.\n\n This requires :attr:`Intents.reactions` to be enabled.\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawReactionClearEvent`\n\n.. function:: on_raw_reaction_clear_emoji(payload)\n\n Called when a message has a specific reaction removed from it. Unlike :func:`on_reaction_clear_emoji` this is called\n regardless of the state of the internal message cache.\n\n This requires :attr:`Intents.reactions` to be enabled.\n\n .. versionadded:: 1.3\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawReactionClearEmojiEvent`\n\n\nRoles\n~~~~~~\n\n.. function:: on_guild_role_create(role)\n on_guild_role_delete(role)\n\n Called when a :class:`Guild` creates or deletes a new :class:`Role`.\n\n To get the guild it belongs to, use :attr:`Role.guild`.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n :param role: The role that was created or deleted.\n :type role: :class:`Role`\n\n.. function:: on_guild_role_update(before, after)\n\n Called when a :class:`Role` is changed guild-wide.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n :param before: The updated role's old info.\n :type before: :class:`Role`\n :param after: The updated role's updated info.\n :type after: :class:`Role`\n\n\nScheduled Events\n~~~~~~~~~~~~~~~~~\n\n.. function:: on_scheduled_event_create(event)\n on_scheduled_event_delete(event)\n\n Called when a :class:`ScheduledEvent` is created or deleted.\n\n This requires :attr:`Intents.guild_scheduled_events` to be enabled.\n\n .. versionadded:: 2.0\n\n :param event: The scheduled event that was created or deleted.\n :type event: :class:`ScheduledEvent`\n\n.. function:: on_scheduled_event_update(before, after)\n\n Called when a :class:`ScheduledEvent` is updated.\n\n This requires :attr:`Intents.guild_scheduled_events` to be enabled.\n\n The following, but not limited to, examples illustrate when this event is called:\n\n - The scheduled start/end times are changed.\n - The channel is changed.\n - The description is changed.\n - The status is changed.\n - The image is changed.\n\n .. versionadded:: 2.0\n\n :param before: The scheduled event before the update.\n :type before: :class:`ScheduledEvent`\n :param after: The scheduled event after the update.\n :type after: :class:`ScheduledEvent`\n\n.. function:: on_scheduled_event_user_add(event, user)\n on_scheduled_event_user_remove(event, user)\n\n Called when a user is added or removed from a :class:`ScheduledEvent`.\n\n This requires :attr:`Intents.guild_scheduled_events` to be enabled.\n\n .. versionadded:: 2.0\n\n :param event: The scheduled event that the user was added or removed from.\n :type event: :class:`ScheduledEvent`\n :param user: The user that was added or removed.\n :type user: :class:`User`\n\n\nStages\n~~~~~~~\n\n.. function:: on_stage_instance_create(stage_instance)\n on_stage_instance_delete(stage_instance)\n\n Called when a :class:`StageInstance` is created or deleted for a :class:`StageChannel`.\n\n .. versionadded:: 2.0\n\n :param stage_instance: The stage instance that was created or deleted.\n :type stage_instance: :class:`StageInstance`\n\n.. function:: on_stage_instance_update(before, after)\n\n Called when a :class:`StageInstance` is updated.\n\n The following, but not limited to, examples illustrate when this event is called:\n\n - The topic is changed.\n - The privacy level is changed.\n\n .. versionadded:: 2.0\n\n :param before: The stage instance before the update.\n :type before: :class:`StageInstance`\n :param after: The stage instance after the update.\n :type after: :class:`StageInstance`\n\nThreads\n~~~~~~~~\n\n.. function:: on_thread_create(thread)\n\n Called whenever a thread is created.\n\n Note that you can get the guild from :attr:`Thread.guild`.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n .. versionadded:: 2.0\n\n :param thread: The thread that was created.\n :type thread: :class:`Thread`\n\n.. function:: on_thread_join(thread)\n\n Called whenever a thread is joined.\n\n Note that you can get the guild from :attr:`Thread.guild`.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n .. versionadded:: 2.0\n\n :param thread: The thread that got joined.\n :type thread: :class:`Thread`\n\n.. function:: on_thread_update(before, after)\n\n Called whenever a thread is updated. If the thread could\n not be found in the internal cache this event will not be called.\n Threads will not be in the cache if they are archived.\n\n If you need this information use :func:`on_raw_thread_update` instead.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n .. versionadded:: 2.0\n\n :param before: The updated thread's old info.\n :type before: :class:`Thread`\n :param after: The updated thread's new info.\n :type after: :class:`Thread`\n\n.. function:: on_thread_remove(thread)\n\n Called whenever a thread is removed. This is different from a thread being deleted.\n\n Note that you can get the guild from :attr:`Thread.guild`.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n .. warning::\n\n Due to technical limitations, this event might not be called\n as soon as one expects. Since the library tracks thread membership\n locally, the API only sends updated thread membership status upon being\n synced by joining a thread.\n\n .. versionadded:: 2.0\n\n :param thread: The thread that got removed.\n :type thread: :class:`Thread`\n\n.. function:: on_thread_delete(thread)\n\n Called whenever a thread is deleted. If the thread could\n not be found in the internal cache this event will not be called.\n Threads will not be in the cache if they are archived.\n\n If you need this information use :func:`on_raw_thread_delete` instead.\n\n Note that you can get the guild from :attr:`Thread.guild`.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n .. versionadded:: 2.0\n\n :param thread: The thread that got deleted.\n :type thread: :class:`Thread`\n\n.. function:: on_raw_thread_update(payload)\n\n Called whenever a thread is updated. Unlike :func:`on_thread_update` this\n is called regardless of the thread being in the internal thread cache or not.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n .. versionadded:: 2.0\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawThreadUpdateEvent`\n\n.. function:: on_raw_thread_delete(payload)\n\n Called whenever a thread is deleted. Unlike :func:`on_thread_delete` this\n is called regardless of the thread being in the internal thread cache or not.\n\n This requires :attr:`Intents.guilds` to be enabled.\n\n .. versionadded:: 2.0\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawThreadDeleteEvent`\n\n.. function:: on_thread_member_join(member)\n on_thread_member_remove(member)\n\n Called when a :class:`ThreadMember` leaves or joins a :class:`Thread`.\n\n You can get the thread a member belongs in by accessing :attr:`ThreadMember.thread`.\n\n This requires :attr:`Intents.members` to be enabled.\n\n .. versionadded:: 2.0\n\n :param member: The member who joined or left.\n :type member: :class:`ThreadMember`\n\n.. function:: on_raw_thread_member_remove(payload)\n\n Called when a :class:`ThreadMember` leaves a :class:`Thread`. Unlike :func:`on_thread_member_remove` this\n is called regardless of the member being in the internal thread's members cache or not.\n\n This requires :attr:`Intents.members` to be enabled.\n\n .. versionadded:: 2.0\n\n :param payload: The raw event payload data.\n :type payload: :class:`RawThreadMembersUpdate`\n\nVoice\n~~~~~~\n\n.. function:: on_voice_state_update(member, before, after)\n\n Called when a :class:`Member` changes their :class:`VoiceState`.\n\n The following, but not limited to, examples illustrate when this event is called:\n\n - A member joins a voice or stage channel.\n - A member leaves a voice or stage channel.\n - A member is muted or deafened by their own accord.\n - A member is muted or deafened by a guild administrator.\n\n This requires :attr:`Intents.voice_states` to be enabled.\n\n :param member: The member whose voice states changed.\n :type member: :class:`Member`\n :param before: The voice state prior to the changes.\n :type before: :class:`VoiceState`\n :param after: The voice state after the changes.\n :type after: :class:`VoiceState`\n\n.. _discord-api-utils:\n\nUtility Functions\n-----------------\n\n.. autofunction:: discord.utils.find\n\n.. autofunction:: discord.utils.get\n\n.. autofunction:: discord.utils.setup_logging\n\n.. autofunction:: discord.utils.maybe_coroutine\n\n.. autofunction:: discord.utils.snowflake_time\n\n.. autofunction:: discord.utils.time_snowflake\n\n.. autofunction:: discord.utils.oauth_url\n\n.. autofunction:: discord.utils.remove_markdown\n\n.. autofunction:: discord.utils.escape_markdown\n\n.. autofunction:: discord.utils.escape_mentions\n\n.. class:: ResolvedInvite\n\n A data class which represents a resolved invite returned from :func:`discord.utils.resolve_invite`.\n\n .. attribute:: code\n\n The invite code.\n\n :type: :class:`str`\n\n .. attribute:: event\n\n The id of the scheduled event that the invite refers to.\n\n :type: Optional[:class:`int`]\n\n.. autofunction:: discord.utils.resolve_invite\n\n.. autofunction:: discord.utils.resolve_template\n\n.. autofunction:: discord.utils.sleep_until\n\n.. autofunction:: discord.utils.utcnow\n\n.. autofunction:: discord.utils.format_dt\n\n.. autofunction:: discord.utils.as_chunks\n\n.. data:: MISSING\n :module: discord.utils\n\n A type safe sentinel used in the library to represent something as missing. Used to distinguish from ``None`` values.\n\n .. versionadded:: 2.0\n\n.. _discord-api-enums:\n\nEnumerations\n-------------\n\nThe API provides some enumerations for certain types of strings to avoid the API\nfrom being stringly typed in case the strings change in the future.\n\nAll enumerations are subclasses of an internal class which mimics the behaviour\nof :class:`enum.Enum`.\n\n.. class:: ChannelType\n\n Specifies the type of channel.\n\n .. attribute:: text\n\n A text channel.\n .. attribute:: voice\n\n A voice channel.\n .. attribute:: private\n\n A private text channel. Also called a direct message.\n .. attribute:: group\n\n A private group text channel.\n .. attribute:: category\n\n A category channel.\n .. attribute:: news\n\n A guild news channel.\n\n .. attribute:: stage_voice\n\n A guild stage voice channel.\n\n .. versionadded:: 1.7\n\n .. attribute:: news_thread\n\n A news thread\n\n .. versionadded:: 2.0\n\n .. attribute:: public_thread\n\n A public thread\n\n .. versionadded:: 2.0\n\n .. attribute:: private_thread\n\n A private thread\n\n .. versionadded:: 2.0\n\n .. attribute:: forum\n\n A forum channel.\n\n .. versionadded:: 2.0\n\n .. attribute:: media\n\n A media channel.\n\n .. versionadded:: 2.4\n\n.. class:: MessageType\n\n Specifies the type of :class:`Message`. This is used to denote if a message\n is to be interpreted as a system message or a regular message.\n\n .. container:: operations\n\n .. describe:: x == y\n\n Checks if two messages are equal.\n .. describe:: x != y\n\n Checks if two messages are not equal.\n\n .. attribute:: default\n\n The default message type. This is the same as regular messages.\n .. attribute:: recipient_add\n\n The system message when a user is added to a group private\n message or a thread.\n .. attribute:: recipient_remove\n\n The system message when a user is removed from a group private\n message or a thread.\n .. attribute:: call\n\n The system message denoting call state, e.g. missed call, started call,\n etc.\n .. attribute:: channel_name_change\n\n The system message denoting that a channel's name has been changed.\n .. attribute:: channel_icon_change\n\n The system message denoting that a channel's icon has been changed.\n .. attribute:: pins_add\n\n The system message denoting that a pinned message has been added to a channel.\n .. attribute:: new_member\n\n The system message denoting that a new member has joined a Guild.\n\n .. attribute:: premium_guild_subscription\n\n The system message denoting that a member has \"nitro boosted\" a guild.\n .. attribute:: premium_guild_tier_1\n\n The system message denoting that a member has \"nitro boosted\" a guild\n and it achieved level 1.\n .. attribute:: premium_guild_tier_2\n\n The system message denoting that a member has \"nitro boosted\" a guild\n and it achieved level 2.\n .. attribute:: premium_guild_tier_3\n\n The system message denoting that a member has \"nitro boosted\" a guild\n and it achieved level 3.\n .. attribute:: channel_follow_add\n\n The system message denoting that an announcement channel has been followed.\n\n .. versionadded:: 1.3\n .. attribute:: guild_stream\n\n The system message denoting that a member is streaming in the guild.\n\n .. versionadded:: 1.7\n .. attribute:: guild_discovery_disqualified\n\n The system message denoting that the guild is no longer eligible for Server\n Discovery.\n\n .. versionadded:: 1.7\n .. attribute:: guild_discovery_requalified\n\n The system message denoting that the guild has become eligible again for Server\n Discovery.\n\n .. versionadded:: 1.7\n .. attribute:: guild_discovery_grace_period_initial_warning\n\n The system message denoting that the guild has failed to meet the Server\n Discovery requirements for one week.\n\n .. versionadded:: 1.7\n .. attribute:: guild_discovery_grace_period_final_warning\n\n The system message denoting that the guild has failed to meet the Server\n Discovery requirements for 3 weeks in a row.\n\n .. versionadded:: 1.7\n .. attribute:: thread_created\n\n The system message denoting that a thread has been created. This is only\n sent if the thread has been created from an older message. The period of time\n required for a message to be considered old cannot be relied upon and is up to\n Discord.\n\n .. versionadded:: 2.0\n .. attribute:: reply\n\n The system message denoting that the author is replying to a message.\n\n .. versionadded:: 2.0\n .. attribute:: chat_input_command\n\n The system message denoting that a slash command was executed.\n\n .. versionadded:: 2.0\n .. attribute:: guild_invite_reminder\n\n The system message sent as a reminder to invite people to the guild.\n\n .. versionadded:: 2.0\n .. attribute:: thread_starter_message\n\n The system message denoting the message in the thread that is the one that started the\n thread's conversation topic.\n\n .. versionadded:: 2.0\n .. attribute:: context_menu_command\n\n The system message denoting that a context menu command was executed.\n\n .. versionadded:: 2.0\n .. attribute:: auto_moderation_action\n\n The system message sent when an AutoMod rule is triggered. This is only\n sent if the rule is configured to sent an alert when triggered.\n\n .. versionadded:: 2.0\n .. attribute:: role_subscription_purchase\n\n The system message sent when a user purchases or renews a role subscription.\n\n .. versionadded:: 2.2\n .. attribute:: interaction_premium_upsell\n\n The system message sent when a user is given an advertisement to purchase a premium tier for\n an application during an interaction.\n\n .. versionadded:: 2.2\n .. attribute:: stage_start\n\n The system message sent when the stage starts.\n\n .. versionadded:: 2.2\n .. attribute:: stage_end\n\n The system message sent when the stage ends.\n\n .. versionadded:: 2.2\n .. attribute:: stage_speaker\n\n The system message sent when the stage speaker changes.\n\n .. versionadded:: 2.2\n .. attribute:: stage_raise_hand\n\n The system message sent when a user is requesting to speak by raising their hands.\n\n .. versionadded:: 2.2\n .. attribute:: stage_topic\n\n The system message sent when the stage topic changes.\n\n .. versionadded:: 2.2\n .. attribute:: guild_application_premium_subscription\n\n The system message sent when an application's premium subscription is purchased for the guild.\n\n .. versionadded:: 2.2\n\n.. class:: UserFlags\n\n Represents Discord User flags.\n\n .. attribute:: staff\n\n The user is a Discord Employee.\n .. attribute:: partner\n\n The user is a Discord Partner.\n .. attribute:: hypesquad\n\n The user is a HypeSquad Events member.\n .. attribute:: bug_hunter\n\n The user is a Bug Hunter.\n .. attribute:: mfa_sms\n\n The user has SMS recovery for Multi Factor Authentication enabled.\n .. attribute:: premium_promo_dismissed\n\n The user has dismissed the Discord Nitro promotion.\n .. attribute:: hypesquad_bravery\n\n The user is a HypeSquad Bravery member.\n .. attribute:: hypesquad_brilliance\n\n The user is a HypeSquad Brilliance member.\n .. attribute:: hypesquad_balance\n\n The user is a HypeSquad Balance member.\n .. attribute:: early_supporter\n\n The user is an Early Supporter.\n .. attribute:: team_user\n\n The user is a Team User.\n .. attribute:: system\n\n The user is a system user (i.e. represents Discord officially).\n .. attribute:: has_unread_urgent_messages\n\n The user has an unread system message.\n .. attribute:: bug_hunter_level_2\n\n The user is a Bug Hunter Level 2.\n .. attribute:: verified_bot\n\n The user is a Verified Bot.\n .. attribute:: verified_bot_developer\n\n The user is an Early Verified Bot Developer.\n .. attribute:: discord_certified_moderator\n\n The user is a Moderator Programs Alumni.\n .. attribute:: bot_http_interactions\n\n The user is a bot that only uses HTTP interactions and is shown in the online member list.\n\n .. versionadded:: 2.0\n .. attribute:: spammer\n\n The user is flagged as a spammer by Discord.\n\n .. versionadded:: 2.0\n\n .. attribute:: active_developer\n\n The user is an active developer.\n\n .. versionadded:: 2.1\n\n.. class:: ActivityType\n\n Specifies the type of :class:`Activity`. This is used to check how to\n interpret the activity itself.\n\n .. attribute:: unknown\n\n An unknown activity type. This should generally not happen.\n .. attribute:: playing\n\n A \"Playing\" activity type.\n .. attribute:: streaming\n\n A \"Streaming\" activity type.\n .. attribute:: listening\n\n A \"Listening\" activity type.\n .. attribute:: watching\n\n A \"Watching\" activity type.\n .. attribute:: custom\n\n A custom activity type.\n .. attribute:: competing\n\n A competing activity type.\n\n .. versionadded:: 1.5\n\n.. class:: VerificationLevel\n\n Specifies a :class:`Guild`\\'s verification level, which is the criteria in\n which a member must meet before being able to send messages to the guild.\n\n .. container:: operations\n\n .. versionadded:: 2.0\n\n .. describe:: x == y\n\n Checks if two verification levels are equal.\n .. describe:: x != y\n\n Checks if two verification levels are not equal.\n .. describe:: x > y\n\n Checks if a verification level is higher than another.\n .. describe:: x < y\n\n Checks if a verification level is lower than another.\n .. describe:: x >= y\n\n Checks if a verification level is higher or equal to another.\n .. describe:: x <= y\n\n Checks if a verification level is lower or equal to another.\n\n .. attribute:: none\n\n No criteria set.\n .. attribute:: low\n\n Member must have a verified email on their Discord account.\n .. attribute:: medium\n\n Member must have a verified email and be registered on Discord for more\n than five minutes.\n .. attribute:: high\n\n Member must have a verified email, be registered on Discord for more\n than five minutes, and be a member of the guild itself for more than\n ten minutes.\n .. attribute:: highest\n\n Member must have a verified phone on their Discord account.\n\n.. class:: NotificationLevel\n\n Specifies whether a :class:`Guild` has notifications on for all messages or mentions only by default.\n\n .. container:: operations\n\n .. versionadded:: 2.0\n\n .. describe:: x == y\n\n Checks if two notification levels are equal.\n .. describe:: x != y\n\n Checks if two notification levels are not equal.\n .. describe:: x > y\n\n Checks if a notification level is higher than another.\n .. describe:: x < y\n\n Checks if a notification level is lower than another.\n .. describe:: x >= y\n\n Checks if a notification level is higher or equal to another.\n .. describe:: x <= y\n\n Checks if a notification level is lower or equal to another.\n\n .. attribute:: all_messages\n\n Members receive notifications for every message regardless of them being mentioned.\n .. attribute:: only_mentions\n\n Members receive notifications for messages they are mentioned in.\n\n.. class:: ContentFilter\n\n Specifies a :class:`Guild`\\'s explicit content filter, which is the machine\n learning algorithms that Discord uses to detect if an image contains\n pornography or otherwise explicit content.\n\n .. container:: operations\n\n .. versionadded:: 2.0\n\n .. describe:: x == y\n\n Checks if two content filter levels are equal.\n .. describe:: x != y\n\n Checks if two content filter levels are not equal.\n .. describe:: x > y\n\n Checks if a content filter level is higher than another.\n .. describe:: x < y\n\n Checks if a content filter level is lower than another.\n .. describe:: x >= y\n\n Checks if a content filter level is higher or equal to another.\n .. describe:: x <= y\n\n Checks if a content filter level is lower or equal to another.\n\n .. attribute:: disabled\n\n The guild does not have the content filter enabled.\n .. attribute:: no_role\n\n The guild has the content filter enabled for members without a role.\n .. attribute:: all_members\n\n The guild has the content filter enabled for every member.\n\n.. class:: Status\n\n Specifies a :class:`Member` 's status.\n\n .. attribute:: online\n\n The member is online.\n .. attribute:: offline\n\n The member is offline.\n .. attribute:: idle\n\n The member is idle.\n .. attribute:: dnd\n\n The member is \"Do Not Disturb\".\n .. attribute:: do_not_disturb\n\n An alias for :attr:`dnd`.\n .. attribute:: invisible\n\n The member is \"invisible\". In reality, this is only used when sending\n a presence a la :meth:`Client.change_presence`. When you receive a\n user's presence this will be :attr:`offline` instead.\n\n\n.. class:: AuditLogAction\n\n Represents the type of action being done for a :class:`AuditLogEntry`\\,\n which is retrievable via :meth:`Guild.audit_logs`.\n\n .. attribute:: guild_update\n\n The guild has updated. Things that trigger this include:\n\n - Changing the guild vanity URL\n - Changing the guild invite splash\n - Changing the guild AFK channel or timeout\n - Changing the guild voice server region\n - Changing the guild icon, banner, or discovery splash\n - Changing the guild moderation settings\n - Changing things related to the guild widget\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Guild`.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.afk_channel`\n - :attr:`~AuditLogDiff.system_channel`\n - :attr:`~AuditLogDiff.afk_timeout`\n - :attr:`~AuditLogDiff.default_notifications`\n - :attr:`~AuditLogDiff.explicit_content_filter`\n - :attr:`~AuditLogDiff.mfa_level`\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.owner`\n - :attr:`~AuditLogDiff.splash`\n - :attr:`~AuditLogDiff.discovery_splash`\n - :attr:`~AuditLogDiff.icon`\n - :attr:`~AuditLogDiff.banner`\n - :attr:`~AuditLogDiff.vanity_url_code`\n - :attr:`~AuditLogDiff.description`\n - :attr:`~AuditLogDiff.preferred_locale`\n - :attr:`~AuditLogDiff.prune_delete_days`\n - :attr:`~AuditLogDiff.public_updates_channel`\n - :attr:`~AuditLogDiff.rules_channel`\n - :attr:`~AuditLogDiff.verification_level`\n - :attr:`~AuditLogDiff.widget_channel`\n - :attr:`~AuditLogDiff.widget_enabled`\n - :attr:`~AuditLogDiff.premium_progress_bar_enabled`\n - :attr:`~AuditLogDiff.system_channel_flags`\n\n .. attribute:: channel_create\n\n A new channel was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n either a :class:`abc.GuildChannel` or :class:`Object` with an ID.\n\n A more filled out object in the :class:`Object` case can be found\n by using :attr:`~AuditLogEntry.after`.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.type`\n - :attr:`~AuditLogDiff.overwrites`\n\n .. attribute:: channel_update\n\n A channel was updated. Things that trigger this include:\n\n - The channel name or topic was changed\n - The channel bitrate was changed\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`abc.GuildChannel` or :class:`Object` with an ID.\n\n A more filled out object in the :class:`Object` case can be found\n by using :attr:`~AuditLogEntry.after` or :attr:`~AuditLogEntry.before`.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.type`\n - :attr:`~AuditLogDiff.position`\n - :attr:`~AuditLogDiff.overwrites`\n - :attr:`~AuditLogDiff.topic`\n - :attr:`~AuditLogDiff.bitrate`\n - :attr:`~AuditLogDiff.rtc_region`\n - :attr:`~AuditLogDiff.video_quality_mode`\n - :attr:`~AuditLogDiff.default_auto_archive_duration`\n - :attr:`~AuditLogDiff.nsfw`\n - :attr:`~AuditLogDiff.slowmode_delay`\n - :attr:`~AuditLogDiff.user_limit`\n\n .. attribute:: channel_delete\n\n A channel was deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n an :class:`Object` with an ID.\n\n A more filled out object can be found by using the\n :attr:`~AuditLogEntry.before` object.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.type`\n - :attr:`~AuditLogDiff.overwrites`\n - :attr:`~AuditLogDiff.flags`\n - :attr:`~AuditLogDiff.nsfw`\n - :attr:`~AuditLogDiff.slowmode_delay`\n\n .. attribute:: overwrite_create\n\n A channel permission overwrite was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`abc.GuildChannel` or :class:`Object` with an ID.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n either a :class:`Role` or :class:`Member`. If the object is not found\n then it is a :class:`Object` with an ID being filled, a name, and a\n ``type`` attribute set to either ``'role'`` or ``'member'`` to help\n dictate what type of ID it is.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.deny`\n - :attr:`~AuditLogDiff.allow`\n - :attr:`~AuditLogDiff.id`\n - :attr:`~AuditLogDiff.type`\n\n .. attribute:: overwrite_update\n\n A channel permission overwrite was changed, this is typically\n when the permission values change.\n\n See :attr:`overwrite_create` for more information on how the\n :attr:`~AuditLogEntry.target` and :attr:`~AuditLogEntry.extra` fields\n are set.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.deny`\n - :attr:`~AuditLogDiff.allow`\n - :attr:`~AuditLogDiff.id`\n - :attr:`~AuditLogDiff.type`\n\n .. attribute:: overwrite_delete\n\n A channel permission overwrite was deleted.\n\n See :attr:`overwrite_create` for more information on how the\n :attr:`~AuditLogEntry.target` and :attr:`~AuditLogEntry.extra` fields\n are set.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.deny`\n - :attr:`~AuditLogDiff.allow`\n - :attr:`~AuditLogDiff.id`\n - :attr:`~AuditLogDiff.type`\n\n .. attribute:: kick\n\n A member was kicked.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`User` or :class:`Object` who got kicked.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with one attribute:\n\n - ``integration_type``: An optional string that denotes the type of integration that did the action.\n\n When this is the action, :attr:`~AuditLogEntry.changes` is empty.\n\n .. attribute:: member_prune\n\n A member prune was triggered.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n set to ``None``.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with two attributes:\n\n - ``delete_member_days``: An integer specifying how far the prune was.\n - ``members_removed``: An integer specifying how many members were removed.\n\n When this is the action, :attr:`~AuditLogEntry.changes` is empty.\n\n .. attribute:: ban\n\n A member was banned.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`User` or :class:`Object` who got banned.\n\n When this is the action, :attr:`~AuditLogEntry.changes` is empty.\n\n .. attribute:: unban\n\n A member was unbanned.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`User` or :class:`Object` who got unbanned.\n\n When this is the action, :attr:`~AuditLogEntry.changes` is empty.\n\n .. attribute:: member_update\n\n A member has updated. This triggers in the following situations:\n\n - A nickname was changed\n - They were server muted or deafened (or it was undo'd)\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Member`, :class:`User`, or :class:`Object` who got updated.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.nick`\n - :attr:`~AuditLogDiff.mute`\n - :attr:`~AuditLogDiff.deaf`\n - :attr:`~AuditLogDiff.timed_out_until`\n\n .. attribute:: member_role_update\n\n A member's role has been updated. This triggers when a member\n either gains a role or loses a role.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Member`, :class:`User`, or :class:`Object` who got the role.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with one attribute:\n\n - ``integration_type``: An optional string that denotes the type of integration that did the action.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.roles`\n\n .. attribute:: member_move\n\n A member's voice channel has been updated. This triggers when a\n member is moved to a different voice channel.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with two attributes:\n\n - ``channel``: A :class:`TextChannel` or :class:`Object` with the channel ID where the members were moved.\n - ``count``: An integer specifying how many members were moved.\n\n .. versionadded:: 1.3\n\n .. attribute:: member_disconnect\n\n A member's voice state has changed. This triggers when a\n member is force disconnected from voice.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with one attribute:\n\n - ``count``: An integer specifying how many members were disconnected.\n\n .. versionadded:: 1.3\n\n .. attribute:: bot_add\n\n A bot was added to the guild.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Member`, :class:`User`, or :class:`Object` which was added to the guild.\n\n .. versionadded:: 1.3\n\n .. attribute:: role_create\n\n A new role was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Role` or a :class:`Object` with the ID.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.colour`\n - :attr:`~AuditLogDiff.mentionable`\n - :attr:`~AuditLogDiff.hoist`\n - :attr:`~AuditLogDiff.icon`\n - :attr:`~AuditLogDiff.unicode_emoji`\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.permissions`\n\n .. attribute:: role_update\n\n A role was updated. This triggers in the following situations:\n\n - The name has changed\n - The permissions have changed\n - The colour has changed\n - The role icon (or unicode emoji) has changed\n - Its hoist/mentionable state has changed\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Role` or a :class:`Object` with the ID.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.colour`\n - :attr:`~AuditLogDiff.mentionable`\n - :attr:`~AuditLogDiff.hoist`\n - :attr:`~AuditLogDiff.icon`\n - :attr:`~AuditLogDiff.unicode_emoji`\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.permissions`\n\n .. attribute:: role_delete\n\n A role was deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Role` or a :class:`Object` with the ID.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.colour`\n - :attr:`~AuditLogDiff.mentionable`\n - :attr:`~AuditLogDiff.hoist`\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.permissions`\n\n .. attribute:: invite_create\n\n An invite was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Invite` that was created.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.max_age`\n - :attr:`~AuditLogDiff.code`\n - :attr:`~AuditLogDiff.temporary`\n - :attr:`~AuditLogDiff.inviter`\n - :attr:`~AuditLogDiff.channel`\n - :attr:`~AuditLogDiff.uses`\n - :attr:`~AuditLogDiff.max_uses`\n\n .. attribute:: invite_update\n\n An invite was updated.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Invite` that was updated.\n\n .. attribute:: invite_delete\n\n An invite was deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Invite` that was deleted.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.max_age`\n - :attr:`~AuditLogDiff.code`\n - :attr:`~AuditLogDiff.temporary`\n - :attr:`~AuditLogDiff.inviter`\n - :attr:`~AuditLogDiff.channel`\n - :attr:`~AuditLogDiff.uses`\n - :attr:`~AuditLogDiff.max_uses`\n\n .. attribute:: webhook_create\n\n A webhook was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Object` with the webhook ID.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.channel`\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.type` (always set to ``1`` if so)\n\n .. attribute:: webhook_update\n\n A webhook was updated. This trigger in the following situations:\n\n - The webhook name changed\n - The webhook channel changed\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Object` with the webhook ID.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.channel`\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.avatar`\n\n .. attribute:: webhook_delete\n\n A webhook was deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Object` with the webhook ID.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.channel`\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.type` (always set to ``1`` if so)\n\n .. attribute:: emoji_create\n\n An emoji was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Emoji` or :class:`Object` with the emoji ID.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n\n .. attribute:: emoji_update\n\n An emoji was updated. This triggers when the name has changed.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Emoji` or :class:`Object` with the emoji ID.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n\n .. attribute:: emoji_delete\n\n An emoji was deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Object` with the emoji ID.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n\n .. attribute:: message_delete\n\n A message was deleted by a moderator. Note that this\n only triggers if the message was deleted by someone other than the author.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Member`, :class:`User`, or :class:`Object` who had their message deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with two attributes:\n\n - ``count``: An integer specifying how many messages were deleted.\n - ``channel``: A :class:`TextChannel` or :class:`Object` with the channel ID where the message got deleted.\n\n .. attribute:: message_bulk_delete\n\n Messages were bulk deleted by a moderator.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`TextChannel` or :class:`Object` with the ID of the channel that was purged.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with one attribute:\n\n - ``count``: An integer specifying how many messages were deleted.\n\n .. versionadded:: 1.3\n\n .. attribute:: message_pin\n\n A message was pinned in a channel.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Member`, :class:`User`, or :class:`Object` who had their message pinned.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with two attributes:\n\n - ``channel``: A :class:`TextChannel` or :class:`Object` with the channel ID where the message was pinned.\n - ``message_id``: the ID of the message which was pinned.\n\n .. versionadded:: 1.3\n\n .. attribute:: message_unpin\n\n A message was unpinned in a channel.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Member`, :class:`User`, or :class:`Object` who had their message unpinned.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with two attributes:\n\n - ``channel``: A :class:`TextChannel` or :class:`Object` with the channel ID where the message was unpinned.\n - ``message_id``: the ID of the message which was unpinned.\n\n .. versionadded:: 1.3\n\n .. attribute:: integration_create\n\n A guild integration was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`PartialIntegration` or :class:`Object` with the\n integration ID of the integration which was created.\n\n .. versionadded:: 1.3\n\n .. attribute:: integration_update\n\n A guild integration was updated.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`PartialIntegration` or :class:`Object` with the\n integration ID of the integration which was updated.\n\n .. versionadded:: 1.3\n\n .. attribute:: integration_delete\n\n A guild integration was deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`PartialIntegration` or :class:`Object` with the\n integration ID of the integration which was deleted.\n\n .. versionadded:: 1.3\n\n .. attribute:: stage_instance_create\n\n A stage instance was started.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`StageInstance` or :class:`Object` with the ID of the stage\n instance which was created.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.topic`\n - :attr:`~AuditLogDiff.privacy_level`\n\n .. versionadded:: 2.0\n\n .. attribute:: stage_instance_update\n\n A stage instance was updated.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`StageInstance` or :class:`Object` with the ID of the stage\n instance which was updated.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.topic`\n - :attr:`~AuditLogDiff.privacy_level`\n\n .. versionadded:: 2.0\n\n .. attribute:: stage_instance_delete\n\n A stage instance was ended.\n\n .. versionadded:: 2.0\n\n .. attribute:: sticker_create\n\n A sticker was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`GuildSticker` or :class:`Object` with the ID of the sticker\n which was created.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.emoji`\n - :attr:`~AuditLogDiff.type`\n - :attr:`~AuditLogDiff.format_type`\n - :attr:`~AuditLogDiff.description`\n - :attr:`~AuditLogDiff.available`\n\n .. versionadded:: 2.0\n\n .. attribute:: sticker_update\n\n A sticker was updated.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`GuildSticker` or :class:`Object` with the ID of the sticker\n which was updated.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.emoji`\n - :attr:`~AuditLogDiff.type`\n - :attr:`~AuditLogDiff.format_type`\n - :attr:`~AuditLogDiff.description`\n - :attr:`~AuditLogDiff.available`\n\n .. versionadded:: 2.0\n\n .. attribute:: sticker_delete\n\n A sticker was deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`GuildSticker` or :class:`Object` with the ID of the sticker\n which was updated.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.emoji`\n - :attr:`~AuditLogDiff.type`\n - :attr:`~AuditLogDiff.format_type`\n - :attr:`~AuditLogDiff.description`\n - :attr:`~AuditLogDiff.available`\n\n .. versionadded:: 2.0\n\n .. attribute:: scheduled_event_create\n\n A scheduled event was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`ScheduledEvent` or :class:`Object` with the ID of the event\n which was created.\n\n Possible attributes for :class:`AuditLogDiff`:\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.channel`\n - :attr:`~AuditLogDiff.description`\n - :attr:`~AuditLogDiff.privacy_level`\n - :attr:`~AuditLogDiff.status`\n - :attr:`~AuditLogDiff.entity_type`\n - :attr:`~AuditLogDiff.cover_image`\n\n .. versionadded:: 2.0\n\n .. attribute:: scheduled_event_update\n\n A scheduled event was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`ScheduledEvent` or :class:`Object` with the ID of the event\n which was updated.\n\n Possible attributes for :class:`AuditLogDiff`:\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.channel`\n - :attr:`~AuditLogDiff.description`\n - :attr:`~AuditLogDiff.privacy_level`\n - :attr:`~AuditLogDiff.status`\n - :attr:`~AuditLogDiff.entity_type`\n - :attr:`~AuditLogDiff.cover_image`\n\n .. versionadded:: 2.0\n\n .. attribute:: scheduled_event_delete\n\n A scheduled event was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`ScheduledEvent` or :class:`Object` with the ID of the event\n which was deleted.\n\n Possible attributes for :class:`AuditLogDiff`:\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.channel`\n - :attr:`~AuditLogDiff.description`\n - :attr:`~AuditLogDiff.privacy_level`\n - :attr:`~AuditLogDiff.status`\n - :attr:`~AuditLogDiff.entity_type`\n - :attr:`~AuditLogDiff.cover_image`\n\n .. versionadded:: 2.0\n\n .. attribute:: thread_create\n\n A thread was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Thread` or :class:`Object` with the ID of the thread which\n was created.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.archived`\n - :attr:`~AuditLogDiff.locked`\n - :attr:`~AuditLogDiff.auto_archive_duration`\n - :attr:`~AuditLogDiff.invitable`\n\n .. versionadded:: 2.0\n\n .. attribute:: thread_update\n\n A thread was updated.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Thread` or :class:`Object` with the ID of the thread which\n was updated.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.archived`\n - :attr:`~AuditLogDiff.locked`\n - :attr:`~AuditLogDiff.auto_archive_duration`\n - :attr:`~AuditLogDiff.invitable`\n\n .. versionadded:: 2.0\n\n .. attribute:: thread_delete\n\n A thread was deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n the :class:`Thread` or :class:`Object` with the ID of the thread which\n was deleted.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.archived`\n - :attr:`~AuditLogDiff.locked`\n - :attr:`~AuditLogDiff.auto_archive_duration`\n - :attr:`~AuditLogDiff.invitable`\n\n .. versionadded:: 2.0\n\n .. attribute:: app_command_permission_update\n\n An application command or integrations application command permissions\n were updated.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`PartialIntegration` for an integrations general permissions,\n :class:`~discord.app_commands.AppCommand` for a specific commands permissions,\n or :class:`Object` with the ID of the command or integration which\n was updated.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an :class:`PartialIntegration` or :class:`Object` with the ID of\n application that command or integration belongs to.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.app_command_permissions`\n\n .. versionadded:: 2.0\n\n .. attribute:: automod_rule_create\n\n An automod rule was created.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`AutoModRule` or :class:`Object` with the ID of the automod\n rule that was created.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.enabled`\n - :attr:`~AuditLogDiff.event_type`\n - :attr:`~AuditLogDiff.trigger_type`\n - :attr:`~AuditLogDiff.trigger`\n - :attr:`~AuditLogDiff.actions`\n - :attr:`~AuditLogDiff.exempt_roles`\n - :attr:`~AuditLogDiff.exempt_channels`\n\n .. versionadded:: 2.0\n\n .. attribute:: automod_rule_update\n\n An automod rule was updated.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`AutoModRule` or :class:`Object` with the ID of the automod\n rule that was created.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.enabled`\n - :attr:`~AuditLogDiff.event_type`\n - :attr:`~AuditLogDiff.trigger_type`\n - :attr:`~AuditLogDiff.trigger`\n - :attr:`~AuditLogDiff.actions`\n - :attr:`~AuditLogDiff.exempt_roles`\n - :attr:`~AuditLogDiff.exempt_channels`\n\n .. versionadded:: 2.0\n\n .. attribute:: automod_rule_delete\n\n An automod rule was deleted.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`AutoModRule` or :class:`Object` with the ID of the automod\n rule that was created.\n\n Possible attributes for :class:`AuditLogDiff`:\n\n - :attr:`~AuditLogDiff.name`\n - :attr:`~AuditLogDiff.enabled`\n - :attr:`~AuditLogDiff.event_type`\n - :attr:`~AuditLogDiff.trigger_type`\n - :attr:`~AuditLogDiff.trigger`\n - :attr:`~AuditLogDiff.actions`\n - :attr:`~AuditLogDiff.exempt_roles`\n - :attr:`~AuditLogDiff.exempt_channels`\n\n .. versionadded:: 2.0\n\n .. attribute:: automod_block_message\n\n An automod rule blocked a message from being sent.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`Member` with the ID of the person who triggered the automod rule.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with 3 attributes:\n\n - ``automod_rule_name``: The name of the automod rule that was triggered.\n - ``automod_rule_trigger_type``: A :class:`AutoModRuleTriggerType` representation of the rule type that was triggered.\n - ``channel``: The channel in which the automod rule was triggered.\n\n When this is the action, :attr:`AuditLogEntry.changes` is empty.\n\n .. versionadded:: 2.0\n\n .. attribute:: automod_flag_message\n\n An automod rule flagged a message.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`Member` with the ID of the person who triggered the automod rule.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with 3 attributes:\n\n - ``automod_rule_name``: The name of the automod rule that was triggered.\n - ``automod_rule_trigger_type``: A :class:`AutoModRuleTriggerType` representation of the rule type that was triggered.\n - ``channel``: The channel in which the automod rule was triggered.\n\n When this is the action, :attr:`AuditLogEntry.changes` is empty.\n\n .. versionadded:: 2.1\n\n .. attribute:: automod_timeout_member\n\n An automod rule timed-out a member.\n\n When this is the action, the type of :attr:`~AuditLogEntry.target` is\n a :class:`Member` with the ID of the person who triggered the automod rule.\n\n When this is the action, the type of :attr:`~AuditLogEntry.extra` is\n set to an unspecified proxy object with 3 attributes:\n\n - ``automod_rule_name``: The name of the automod rule that was triggered.\n - ``automod_rule_trigger_type``: A :class:`AutoModRuleTriggerType` representation of the rule type that was triggered.\n - ``channel``: The channel in which the automod rule was triggered.\n\n When this is the action, :attr:`AuditLogEntry.changes` is empty.\n\n .. versionadded:: 2.1\n\n .. attribute:: creator_monetization_request_created\n\n A request to monetize the server was created.\n\n .. versionadded:: 2.4\n\n .. attribute:: creator_monetization_terms_accepted\n\n The terms and conditions for creator monetization were accepted.\n\n .. versionadded:: 2.4\n\n.. class:: AuditLogActionCategory\n\n Represents the category that the :class:`AuditLogAction` belongs to.\n\n This can be retrieved via :attr:`AuditLogEntry.category`.\n\n .. attribute:: create\n\n The action is the creation of something.\n\n .. attribute:: delete\n\n The action is the deletion of something.\n\n .. attribute:: update\n\n The action is the update of something.\n\n.. class:: TeamMembershipState\n\n Represents the membership state of a team member retrieved through :func:`Client.application_info`.\n\n .. versionadded:: 1.3\n\n .. attribute:: invited\n\n Represents an invited member.\n\n .. attribute:: accepted\n\n Represents a member currently in the team.\n\n.. class:: TeamMemberRole\n\n Represents the type of role of a team member retrieved through :func:`Client.application_info`.\n\n .. versionadded:: 2.4\n\n .. attribute:: admin\n\n The team member is an admin. This allows them to invite members to the team, access credentials, edit the application,\n and do most things the owner can do. However they cannot do destructive actions.\n\n .. attribute:: developer\n\n The team member is a developer. This allows them to access information, like the client secret or public key.\n They can also configure interaction endpoints or reset the bot token. Developers cannot invite anyone to the team\n nor can they do destructive actions.\n\n .. attribute:: read_only\n\n The team member is a read-only member. This allows them to access information, but not edit anything.\n\n.. class:: WebhookType\n\n Represents the type of webhook that can be received.\n\n .. versionadded:: 1.3\n\n .. attribute:: incoming\n\n Represents a webhook that can post messages to channels with a token.\n\n .. attribute:: channel_follower\n\n Represents a webhook that is internally managed by Discord, used for following channels.\n\n .. attribute:: application\n\n Represents a webhook that is used for interactions or applications.\n\n .. versionadded:: 2.0\n\n.. class:: ExpireBehaviour\n\n Represents the behaviour the :class:`Integration` should perform\n when a user's subscription has finished.\n\n There is an alias for this called ``ExpireBehavior``.\n\n .. versionadded:: 1.4\n\n .. attribute:: remove_role\n\n This will remove the :attr:`StreamIntegration.role` from the user\n when their subscription is finished.\n\n .. attribute:: kick\n\n This will kick the user when their subscription is finished.\n\n.. class:: DefaultAvatar\n\n Represents the default avatar of a Discord :class:`User`\n\n .. attribute:: blurple\n\n Represents the default avatar with the colour blurple.\n See also :attr:`Colour.blurple`\n .. attribute:: grey\n\n Represents the default avatar with the colour grey.\n See also :attr:`Colour.greyple`\n .. attribute:: gray\n\n An alias for :attr:`grey`.\n .. attribute:: green\n\n Represents the default avatar with the colour green.\n See also :attr:`Colour.green`\n .. attribute:: orange\n\n Represents the default avatar with the colour orange.\n See also :attr:`Colour.orange`\n .. attribute:: red\n\n Represents the default avatar with the colour red.\n See also :attr:`Colour.red`\n .. attribute:: pink\n\n Represents the default avatar with the colour pink.\n See also :attr:`Colour.pink`\n\n .. versionadded:: 2.3\n\n.. class:: StickerType\n\n Represents the type of sticker.\n\n .. versionadded:: 2.0\n\n .. attribute:: standard\n\n Represents a standard sticker that all Nitro users can use.\n\n .. attribute:: guild\n\n Represents a custom sticker created in a guild.\n\n.. class:: StickerFormatType\n\n Represents the type of sticker images.\n\n .. versionadded:: 1.6\n\n .. attribute:: png\n\n Represents a sticker with a png image.\n\n .. attribute:: apng\n\n Represents a sticker with an apng image.\n\n .. attribute:: lottie\n\n Represents a sticker with a lottie image.\n\n .. attribute:: gif\n\n Represents a sticker with a gif image.\n\n .. versionadded:: 2.2\n\n.. class:: InviteTarget\n\n Represents the invite type for voice channel invites.\n\n .. versionadded:: 2.0\n\n .. attribute:: unknown\n\n The invite doesn't target anyone or anything.\n\n .. attribute:: stream\n\n A stream invite that targets a user.\n\n .. attribute:: embedded_application\n\n A stream invite that targets an embedded application.\n\n.. class:: VideoQualityMode\n\n Represents the camera video quality mode for voice channel participants.\n\n .. versionadded:: 2.0\n\n .. attribute:: auto\n\n Represents auto camera video quality.\n\n .. attribute:: full\n\n Represents full camera video quality.\n\n.. class:: PrivacyLevel\n\n Represents the privacy level of a stage instance or scheduled event.\n\n .. versionadded:: 2.0\n\n .. attribute:: guild_only\n\n The stage instance or scheduled event is only accessible within the guild.\n\n.. class:: NSFWLevel\n\n Represents the NSFW level of a guild.\n\n .. versionadded:: 2.0\n\n .. container:: operations\n\n .. describe:: x == y\n\n Checks if two NSFW levels are equal.\n .. describe:: x != y\n\n Checks if two NSFW levels are not equal.\n .. describe:: x > y\n\n Checks if a NSFW level is higher than another.\n .. describe:: x < y\n\n Checks if a NSFW level is lower than another.\n .. describe:: x >= y\n\n Checks if a NSFW level is higher or equal to another.\n .. describe:: x <= y\n\n Checks if a NSFW level is lower or equal to another.\n\n .. attribute:: default\n\n The guild has not been categorised yet.\n\n .. attribute:: explicit\n\n The guild contains NSFW content.\n\n .. attribute:: safe\n\n The guild does not contain any NSFW content.\n\n .. attribute:: age_restricted\n\n The guild may contain NSFW content.\n\n.. class:: Locale\n\n Supported locales by Discord. Mainly used for application command localisation.\n\n .. versionadded:: 2.0\n\n .. attribute:: american_english\n\n The ``en-US`` locale.\n\n .. attribute:: british_english\n\n The ``en-GB`` locale.\n\n .. attribute:: bulgarian\n\n The ``bg`` locale.\n\n .. attribute:: chinese\n\n The ``zh-CN`` locale.\n\n .. attribute:: taiwan_chinese\n\n The ``zh-TW`` locale.\n\n .. attribute:: croatian\n\n The ``hr`` locale.\n\n .. attribute:: czech\n\n The ``cs`` locale.\n\n .. attribute:: indonesian\n\n The ``id`` locale.\n\n .. versionadded:: 2.2\n\n .. attribute:: danish\n\n The ``da`` locale.\n\n .. attribute:: dutch\n\n The ``nl`` locale.\n\n .. attribute:: finnish\n\n The ``fi`` locale.\n\n .. attribute:: french\n\n The ``fr`` locale.\n\n .. attribute:: german\n\n The ``de`` locale.\n\n .. attribute:: greek\n\n The ``el`` locale.\n\n .. attribute:: hindi\n\n The ``hi`` locale.\n\n .. attribute:: hungarian\n\n The ``hu`` locale.\n\n .. attribute:: italian\n\n The ``it`` locale.\n\n .. attribute:: japanese\n\n The ``ja`` locale.\n\n .. attribute:: korean\n\n The ``ko`` locale.\n\n .. attribute:: lithuanian\n\n The ``lt`` locale.\n\n .. attribute:: norwegian\n\n The ``no`` locale.\n\n .. attribute:: polish\n\n The ``pl`` locale.\n\n .. attribute:: brazil_portuguese\n\n The ``pt-BR`` locale.\n\n .. attribute:: romanian\n\n The ``ro`` locale.\n\n .. attribute:: russian\n\n The ``ru`` locale.\n\n .. attribute:: spain_spanish\n\n The ``es-ES`` locale.\n\n .. attribute:: swedish\n\n The ``sv-SE`` locale.\n\n .. attribute:: thai\n\n The ``th`` locale.\n\n .. attribute:: turkish\n\n The ``tr`` locale.\n\n .. attribute:: ukrainian\n\n The ``uk`` locale.\n\n .. attribute:: vietnamese\n\n The ``vi`` locale.\n\n\n.. class:: MFALevel\n\n Represents the Multi-Factor Authentication requirement level of a guild.\n\n .. versionadded:: 2.0\n\n .. container:: operations\n\n .. describe:: x == y\n\n Checks if two MFA levels are equal.\n .. describe:: x != y\n\n Checks if two MFA levels are not equal.\n .. describe:: x > y\n\n Checks if a MFA level is higher than another.\n .. describe:: x < y\n\n Checks if a MFA level is lower than another.\n .. describe:: x >= y\n\n Checks if a MFA level is higher or equal to another.\n .. describe:: x <= y\n\n Checks if a MFA level is lower or equal to another.\n\n .. attribute:: disabled\n\n The guild has no MFA requirement.\n\n .. attribute:: require_2fa\n\n The guild requires 2 factor authentication.\n\n.. class:: EntityType\n\n Represents the type of entity that a scheduled event is for.\n\n .. versionadded:: 2.0\n\n .. attribute:: stage_instance\n\n The scheduled event will occur in a stage instance.\n\n .. attribute:: voice\n\n The scheduled event will occur in a voice channel.\n\n .. attribute:: external\n\n The scheduled event will occur externally.\n\n.. class:: EventStatus\n\n Represents the status of an event.\n\n .. versionadded:: 2.0\n\n .. attribute:: scheduled\n\n The event is scheduled.\n\n .. attribute:: active\n\n The event is active.\n\n .. attribute:: completed\n\n The event has ended.\n\n .. attribute:: cancelled\n\n The event has been cancelled.\n\n .. attribute:: canceled\n\n An alias for :attr:`cancelled`.\n\n .. attribute:: ended\n\n An alias for :attr:`completed`.\n\n.. class:: AutoModRuleTriggerType\n\n Represents the trigger type of an automod rule.\n\n .. versionadded:: 2.0\n\n .. attribute:: keyword\n\n The rule will trigger when a keyword is mentioned.\n\n .. attribute:: harmful_link\n\n The rule will trigger when a harmful link is posted.\n\n .. attribute:: spam\n\n The rule will trigger when a spam message is posted.\n\n .. attribute:: keyword_preset\n\n The rule will trigger when something triggers based on the set keyword preset types.\n\n .. attribute:: mention_spam\n\n The rule will trigger when combined number of role and user mentions\n is greater than the set limit.\n\n .. attribute:: member_profile\n\n The rule will trigger when a user's profile contains a keyword.\n\n .. versionadded:: 2.4\n\n.. class:: AutoModRuleEventType\n\n Represents the event type of an automod rule.\n\n .. versionadded:: 2.0\n\n .. attribute:: message_send\n\n The rule will trigger when a message is sent.\n\n .. attribute:: member_update\n\n The rule will trigger when a member's profile is updated.\n\n .. versionadded:: 2.4\n\n.. class:: AutoModRuleActionType\n\n Represents the action type of an automod rule.\n\n .. versionadded:: 2.0\n\n .. attribute:: block_message\n\n The rule will block a message from being sent.\n\n .. attribute:: send_alert_message\n\n The rule will send an alert message to a predefined channel.\n\n .. attribute:: timeout\n\n The rule will timeout a user.\n\n .. attribute:: block_member_interactions\n\n Similar to :attr:`timeout`, except the user will be timed out indefinitely.\n This will request the user to edit it's profile.\n\n .. versionadded:: 2.4\n\n.. class:: ForumLayoutType\n\n Represents how a forum's posts are layed out in the client.\n\n .. versionadded:: 2.2\n\n .. attribute:: not_set\n\n No default has been set, so it is up to the client to know how to lay it out.\n\n .. attribute:: list_view\n\n Displays posts as a list.\n\n .. attribute:: gallery_view\n\n Displays posts as a collection of tiles.\n\n\n.. class:: ForumOrderType\n\n Represents how a forum's posts are sorted in the client.\n\n .. versionadded:: 2.3\n\n .. attribute:: latest_activity\n\n Sort forum posts by activity.\n\n .. attribute:: creation_date\n\n Sort forum posts by creation time (from most recent to oldest).\n\n.. class:: SelectDefaultValueType\n\n Represents the default value of a select menu.\n\n .. versionadded:: 2.4\n\n .. attribute:: user\n\n The underlying type of the ID is a user.\n\n .. attribute:: role\n\n The underlying type of the ID is a role.\n\n .. attribute:: channel\n\n The underlying type of the ID is a channel or thread.\n\n\n.. class:: SKUType\n\n Represents the type of a SKU.\n\n .. versionadded:: 2.4\n\n .. attribute:: subscription\n\n The SKU is a recurring subscription.\n\n .. attribute:: subscription_group\n\n The SKU is a system-generated group which is created for each :attr:`SKUType.subscription`.\n\n\n.. class:: EntitlementType\n\n Represents the type of an entitlement.\n\n .. versionadded:: 2.4\n\n .. attribute:: application_subscription\n\n The entitlement was purchased as an app subscription.\n\n\n.. class:: EntitlementOwnerType\n\n Represents the type of an entitlement owner.\n\n .. versionadded:: 2.4\n\n .. attribute:: guild\n\n The entitlement owner is a guild.\n\n .. attribute:: user\n\n The entitlement owner is a user.\n\n\n.. _discord-api-audit-logs:\n\nAudit Log Data\n----------------\n\nWorking with :meth:`Guild.audit_logs` is a complicated process with a lot of machinery\ninvolved. The library attempts to make it easy to use and friendly. In order to accomplish\nthis goal, it must make use of a couple of data classes that aid in this goal.\n\nAuditLogEntry\n~~~~~~~~~~~~~~~\n\n.. attributetable:: AuditLogEntry\n\n.. autoclass:: AuditLogEntry\n :members:\n\nAuditLogChanges\n~~~~~~~~~~~~~~~~~\n\n.. attributetable:: AuditLogChanges\n\n.. class:: AuditLogChanges\n\n An audit log change set.\n\n .. attribute:: before\n\n The old value. The attribute has the type of :class:`AuditLogDiff`.\n\n Depending on the :class:`AuditLogActionCategory` retrieved by\n :attr:`~AuditLogEntry.category`\\, the data retrieved by this\n attribute differs:\n\n +----------------------------------------+---------------------------------------------------+\n | Category | Description |\n +----------------------------------------+---------------------------------------------------+\n | :attr:`~AuditLogActionCategory.create` | All attributes are set to ``None``. |\n +----------------------------------------+---------------------------------------------------+\n | :attr:`~AuditLogActionCategory.delete` | All attributes are set the value before deletion. |\n +----------------------------------------+---------------------------------------------------+\n | :attr:`~AuditLogActionCategory.update` | All attributes are set the value before updating. |\n +----------------------------------------+---------------------------------------------------+\n | ``None`` | No attributes are set. |\n +----------------------------------------+---------------------------------------------------+\n\n .. attribute:: after\n\n The new value. The attribute has the type of :class:`AuditLogDiff`.\n\n Depending on the :class:`AuditLogActionCategory` retrieved by\n :attr:`~AuditLogEntry.category`\\, the data retrieved by this\n attribute differs:\n\n +----------------------------------------+--------------------------------------------------+\n | Category | Description |\n +----------------------------------------+--------------------------------------------------+\n | :attr:`~AuditLogActionCategory.create` | All attributes are set to the created value |\n +----------------------------------------+--------------------------------------------------+\n | :attr:`~AuditLogActionCategory.delete` | All attributes are set to ``None`` |\n +----------------------------------------+--------------------------------------------------+\n | :attr:`~AuditLogActionCategory.update` | All attributes are set the value after updating. |\n +----------------------------------------+--------------------------------------------------+\n | ``None`` | No attributes are set. |\n +----------------------------------------+--------------------------------------------------+\n\nAuditLogDiff\n~~~~~~~~~~~~~\n\n.. attributetable:: AuditLogDiff\n\n.. class:: AuditLogDiff\n\n Represents an audit log \"change\" object. A change object has dynamic\n attributes that depend on the type of action being done. Certain actions\n map to certain attributes being set.\n\n Note that accessing an attribute that does not match the specified action\n will lead to an attribute error.\n\n To get a list of attributes that have been set, you can iterate over\n them. To see a list of all possible attributes that could be set based\n on the action being done, check the documentation for :class:`AuditLogAction`,\n otherwise check the documentation below for all attributes that are possible.\n\n .. container:: operations\n\n .. describe:: iter(diff)\n\n Returns an iterator over (attribute, value) tuple of this diff.\n\n .. attribute:: name\n\n A name of something.\n\n :type: :class:`str`\n\n .. attribute:: guild\n\n The guild of something.\n\n :type: :class:`Guild`\n\n .. attribute:: icon\n\n A guild's or role's icon. See also :attr:`Guild.icon` or :attr:`Role.icon`.\n\n :type: :class:`Asset`\n\n .. attribute:: splash\n\n The guild's invite splash. See also :attr:`Guild.splash`.\n\n :type: :class:`Asset`\n\n .. attribute:: discovery_splash\n\n The guild's discovery splash. See also :attr:`Guild.discovery_splash`.\n\n :type: :class:`Asset`\n\n .. attribute:: banner\n\n The guild's banner. See also :attr:`Guild.banner`.\n\n :type: :class:`Asset`\n\n .. attribute:: owner\n\n The guild's owner. See also :attr:`Guild.owner`\n\n :type: Union[:class:`Member`, :class:`User`]\n\n .. attribute:: afk_channel\n\n The guild's AFK channel.\n\n If this could not be found, then it falls back to a :class:`Object`\n with the ID being set.\n\n See :attr:`Guild.afk_channel`.\n\n :type: Union[:class:`VoiceChannel`, :class:`Object`]\n\n .. attribute:: system_channel\n\n The guild's system channel.\n\n If this could not be found, then it falls back to a :class:`Object`\n with the ID being set.\n\n See :attr:`Guild.system_channel`.\n\n :type: Union[:class:`TextChannel`, :class:`Object`]\n\n\n .. attribute:: rules_channel\n\n The guild's rules channel.\n\n If this could not be found then it falls back to a :class:`Object`\n with the ID being set.\n\n See :attr:`Guild.rules_channel`.\n\n :type: Union[:class:`TextChannel`, :class:`Object`]\n\n\n .. attribute:: public_updates_channel\n\n The guild's public updates channel.\n\n If this could not be found then it falls back to a :class:`Object`\n with the ID being set.\n\n See :attr:`Guild.public_updates_channel`.\n\n :type: Union[:class:`TextChannel`, :class:`Object`]\n\n .. attribute:: afk_timeout\n\n The guild's AFK timeout. See :attr:`Guild.afk_timeout`.\n\n :type: :class:`int`\n\n .. attribute:: mfa_level\n\n The guild's MFA level. See :attr:`Guild.mfa_level`.\n\n :type: :class:`MFALevel`\n\n .. attribute:: widget_enabled\n\n The guild's widget has been enabled or disabled.\n\n :type: :class:`bool`\n\n .. attribute:: widget_channel\n\n The widget's channel.\n\n If this could not be found then it falls back to a :class:`Object`\n with the ID being set.\n\n :type: Union[:class:`TextChannel`, :class:`Object`]\n\n .. attribute:: verification_level\n\n The guild's verification level.\n\n See also :attr:`Guild.verification_level`.\n\n :type: :class:`VerificationLevel`\n\n .. attribute:: default_notifications\n\n The guild's default notification level.\n\n See also :attr:`Guild.default_notifications`.\n\n :type: :class:`NotificationLevel`\n\n .. attribute:: explicit_content_filter\n\n The guild's content filter.\n\n See also :attr:`Guild.explicit_content_filter`.\n\n :type: :class:`ContentFilter`\n\n .. attribute:: vanity_url_code\n\n The guild's vanity URL.\n\n See also :meth:`Guild.vanity_invite` and :meth:`Guild.edit`.\n\n :type: :class:`str`\n\n .. attribute:: position\n\n The position of a :class:`Role` or :class:`abc.GuildChannel`.\n\n :type: :class:`int`\n\n .. attribute:: type\n\n The type of channel, sticker, webhook or integration.\n\n :type: Union[:class:`ChannelType`, :class:`StickerType`, :class:`WebhookType`, :class:`str`]\n\n .. attribute:: topic\n\n The topic of a :class:`TextChannel` or :class:`StageChannel`.\n\n See also :attr:`TextChannel.topic` or :attr:`StageChannel.topic`.\n\n :type: :class:`str`\n\n .. attribute:: bitrate\n\n The bitrate of a :class:`VoiceChannel`.\n\n See also :attr:`VoiceChannel.bitrate`.\n\n :type: :class:`int`\n\n .. attribute:: overwrites\n\n A list of permission overwrite tuples that represents a target and a\n :class:`PermissionOverwrite` for said target.\n\n The first element is the object being targeted, which can either\n be a :class:`Member` or :class:`User` or :class:`Role`. If this object\n is not found then it is a :class:`Object` with an ID being filled and\n a ``type`` attribute set to either ``'role'`` or ``'member'`` to help\n decide what type of ID it is.\n\n :type: List[Tuple[target, :class:`PermissionOverwrite`]]\n\n .. attribute:: privacy_level\n\n The privacy level of the stage instance or scheduled event\n\n :type: :class:`PrivacyLevel`\n\n .. attribute:: roles\n\n A list of roles being added or removed from a member.\n\n If a role is not found then it is a :class:`Object` with the ID and name being\n filled in.\n\n :type: List[Union[:class:`Role`, :class:`Object`]]\n\n .. attribute:: nick\n\n The nickname of a member.\n\n See also :attr:`Member.nick`\n\n :type: Optional[:class:`str`]\n\n .. attribute:: deaf\n\n Whether the member is being server deafened.\n\n See also :attr:`VoiceState.deaf`.\n\n :type: :class:`bool`\n\n .. attribute:: mute\n\n Whether the member is being server muted.\n\n See also :attr:`VoiceState.mute`.\n\n :type: :class:`bool`\n\n .. attribute:: permissions\n\n The permissions of a role.\n\n See also :attr:`Role.permissions`.\n\n :type: :class:`Permissions`\n\n .. attribute:: colour\n color\n\n The colour of a role.\n\n See also :attr:`Role.colour`\n\n :type: :class:`Colour`\n\n .. attribute:: hoist\n\n Whether the role is being hoisted or not.\n\n See also :attr:`Role.hoist`\n\n :type: :class:`bool`\n\n .. attribute:: mentionable\n\n Whether the role is mentionable or not.\n\n See also :attr:`Role.mentionable`\n\n :type: :class:`bool`\n\n .. attribute:: code\n\n The invite's code.\n\n See also :attr:`Invite.code`\n\n :type: :class:`str`\n\n .. attribute:: channel\n\n A guild channel.\n\n If the channel is not found then it is a :class:`Object` with the ID\n being set. In some cases the channel name is also set.\n\n :type: Union[:class:`abc.GuildChannel`, :class:`Object`]\n\n .. attribute:: inviter\n\n The user who created the invite.\n\n See also :attr:`Invite.inviter`.\n\n :type: Optional[:class:`User`]\n\n .. attribute:: max_uses\n\n The invite's max uses.\n\n See also :attr:`Invite.max_uses`.\n\n :type: :class:`int`\n\n .. attribute:: uses\n\n The invite's current uses.\n\n See also :attr:`Invite.uses`.\n\n :type: :class:`int`\n\n .. attribute:: max_age\n\n The invite's max age in seconds.\n\n See also :attr:`Invite.max_age`.\n\n :type: :class:`int`\n\n .. attribute:: temporary\n\n If the invite is a temporary invite.\n\n See also :attr:`Invite.temporary`.\n\n :type: :class:`bool`\n\n .. attribute:: allow\n deny\n\n The permissions being allowed or denied.\n\n :type: :class:`Permissions`\n\n .. attribute:: id\n\n The ID of the object being changed.\n\n :type: :class:`int`\n\n .. attribute:: avatar\n\n The avatar of a member.\n\n See also :attr:`User.avatar`.\n\n :type: :class:`Asset`\n\n .. attribute:: slowmode_delay\n\n The number of seconds members have to wait before\n sending another message in the channel.\n\n See also :attr:`TextChannel.slowmode_delay`.\n\n :type: :class:`int`\n\n .. attribute:: rtc_region\n\n The region for the voice channel\u2019s voice communication.\n A value of ``None`` indicates automatic voice region detection.\n\n See also :attr:`VoiceChannel.rtc_region`.\n\n :type: :class:`str`\n\n .. attribute:: video_quality_mode\n\n The camera video quality for the voice channel's participants.\n\n See also :attr:`VoiceChannel.video_quality_mode`.\n\n :type: :class:`VideoQualityMode`\n\n .. attribute:: format_type\n\n The format type of a sticker being changed.\n\n See also :attr:`GuildSticker.format`\n\n :type: :class:`StickerFormatType`\n\n .. attribute:: emoji\n\n The name of the emoji that represents a sticker being changed.\n\n See also :attr:`GuildSticker.emoji`.\n\n :type: :class:`str`\n\n .. attribute:: unicode_emoji\n\n The unicode emoji that is used as an icon for the role being changed.\n\n See also :attr:`Role.unicode_emoji`.\n\n :type: :class:`str`\n\n .. attribute:: description\n\n The description of a guild, a sticker, or a scheduled event.\n\n See also :attr:`Guild.description`, :attr:`GuildSticker.description`, or\n :attr:`ScheduledEvent.description`.\n\n :type: :class:`str`\n\n .. attribute:: available\n\n The availability of a sticker being changed.\n\n See also :attr:`GuildSticker.available`\n\n :type: :class:`bool`\n\n .. attribute:: archived\n\n The thread is now archived.\n\n :type: :class:`bool`\n\n .. attribute:: locked\n\n The thread is being locked or unlocked.\n\n :type: :class:`bool`\n\n .. attribute:: auto_archive_duration\n\n The thread's auto archive duration being changed.\n\n See also :attr:`Thread.auto_archive_duration`\n\n :type: :class:`int`\n\n .. attribute:: default_auto_archive_duration\n\n The default auto archive duration for newly created threads being changed.\n\n :type: :class:`int`\n\n .. attribute:: invitable\n\n Whether non-moderators can add users to this private thread.\n\n :type: :class:`bool`\n\n .. attribute:: timed_out_until\n\n Whether the user is timed out, and if so until when.\n\n :type: Optional[:class:`datetime.datetime`]\n\n .. attribute:: enable_emoticons\n\n Integration emoticons were enabled or disabled.\n\n See also :attr:`StreamIntegration.enable_emoticons`\n\n :type: :class:`bool`\n\n .. attribute:: expire_behaviour\n expire_behavior\n\n The behaviour of expiring subscribers changed.\n\n See also :attr:`StreamIntegration.expire_behaviour`\n\n :type: :class:`ExpireBehaviour`\n\n .. attribute:: expire_grace_period\n\n The grace period before expiring subscribers changed.\n\n See also :attr:`StreamIntegration.expire_grace_period`\n\n :type: :class:`int`\n\n .. attribute:: preferred_locale\n\n The preferred locale for the guild changed.\n\n See also :attr:`Guild.preferred_locale`\n\n :type: :class:`Locale`\n\n .. attribute:: prune_delete_days\n\n The number of days after which inactive and role-unassigned members are kicked has been changed.\n\n :type: :class:`int`\n\n .. attribute:: status\n\n The status of the scheduled event.\n\n :type: :class:`EventStatus`\n\n .. attribute:: entity_type\n\n The type of entity this scheduled event is for.\n\n :type: :class:`EntityType`\n\n .. attribute:: cover_image\n\n The scheduled event's cover image.\n\n See also :attr:`ScheduledEvent.cover_image`.\n\n :type: :class:`Asset`\n\n .. attribute:: app_command_permissions\n\n List of permissions for the app command.\n\n :type: List[:class:`~discord.app_commands.AppCommandPermissions`]\n\n .. attribute:: enabled\n\n Whether the automod rule is active or not.\n\n :type: :class:`bool`\n\n .. attribute:: event_type\n\n The event type for triggering the automod rule.\n\n :type: :class:`AutoModRuleEventType`\n\n .. attribute:: trigger_type\n\n The trigger type for the automod rule.\n\n :type: :class:`AutoModRuleTriggerType`\n\n .. attribute:: trigger\n\n The trigger for the automod rule.\n\n .. note ::\n\n The :attr:`~AutoModTrigger.type` of the trigger may be incorrect.\n Some attributes such as :attr:`~AutoModTrigger.keyword_filter`, :attr:`~AutoModTrigger.regex_patterns`,\n and :attr:`~AutoModTrigger.allow_list` will only have the added or removed values.\n\n :type: :class:`AutoModTrigger`\n\n .. attribute:: actions\n\n The actions to take when an automod rule is triggered.\n\n :type: List[AutoModRuleAction]\n\n .. attribute:: exempt_roles\n\n The list of roles that are exempt from the automod rule.\n\n :type: List[Union[:class:`Role`, :class:`Object`]]\n\n .. attribute:: exempt_channels\n\n The list of channels or threads that are exempt from the automod rule.\n\n :type: List[:class:`abc.GuildChannel`, :class:`Thread`, :class:`Object`]\n\n .. attribute:: premium_progress_bar_enabled\n\n The guild\u2019s display setting to show boost progress bar.\n\n :type: :class:`bool`\n\n .. attribute:: system_channel_flags\n\n The guild\u2019s system channel settings.\n\n See also :attr:`Guild.system_channel_flags`\n\n :type: :class:`SystemChannelFlags`\n\n .. attribute:: nsfw\n\n Whether the channel is marked as \u201cnot safe for work\u201d or \u201cage restricted\u201d.\n\n :type: :class:`bool`\n\n .. attribute:: user_limit\n\n The channel\u2019s limit for number of members that can be in a voice or stage channel.\n\n See also :attr:`VoiceChannel.user_limit` and :attr:`StageChannel.user_limit`\n\n :type: :class:`int`\n\n .. attribute:: flags\n\n The channel flags associated with this thread or forum post.\n\n See also :attr:`ForumChannel.flags` and :attr:`Thread.flags`\n\n :type: :class:`ChannelFlags`\n\n .. attribute:: default_thread_slowmode_delay\n\n The default slowmode delay for threads created in this text channel or forum.\n\n See also :attr:`TextChannel.default_thread_slowmode_delay` and :attr:`ForumChannel.default_thread_slowmode_delay`\n\n :type: :class:`int`\n\n .. attribute:: applied_tags\n\n The applied tags of a forum post.\n\n See also :attr:`Thread.applied_tags`\n\n :type: List[Union[:class:`ForumTag`, :class:`Object`]]\n\n .. attribute:: available_tags\n\n The available tags of a forum.\n\n See also :attr:`ForumChannel.available_tags`\n\n :type: Sequence[:class:`ForumTag`]\n\n .. attribute:: default_reaction_emoji\n\n The default_reaction_emoji for forum posts.\n\n See also :attr:`ForumChannel.default_reaction_emoji`\n\n :type: Optional[:class:`PartialEmoji`]\n\n.. this is currently missing the following keys: reason and application_id\n I'm not sure how to port these\n\nWebhook Support\n------------------\n\ndiscord.py offers support for creating, editing, and executing webhooks through the :class:`Webhook` class.\n\nWebhook\n~~~~~~~~~\n\n.. attributetable:: Webhook\n\n.. autoclass:: Webhook()\n :members:\n :inherited-members:\n\nWebhookMessage\n~~~~~~~~~~~~~~~~\n\n.. attributetable:: WebhookMessage\n\n.. autoclass:: WebhookMessage()\n :members:\n :inherited-members:\n\nSyncWebhook\n~~~~~~~~~~~~\n\n.. attributetable:: SyncWebhook\n\n.. autoclass:: SyncWebhook()\n :members:\n :inherited-members:\n\nSyncWebhookMessage\n~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: SyncWebhookMessage\n\n.. autoclass:: SyncWebhookMessage()\n :members:\n\n.. _discord_api_abcs:\n\nAbstract Base Classes\n-----------------------\n\nAn :term:`abstract base class` (also known as an ``abc``) is a class that models can inherit\nto get their behaviour. **Abstract base classes should not be instantiated**.\nThey are mainly there for usage with :func:`isinstance` and :func:`issubclass`\\.\n\nThis library has a module related to abstract base classes, in which all the ABCs are subclasses of\n:class:`typing.Protocol`.\n\nSnowflake\n~~~~~~~~~~\n\n.. attributetable:: discord.abc.Snowflake\n\n.. autoclass:: discord.abc.Snowflake()\n :members:\n\nUser\n~~~~~\n\n.. attributetable:: discord.abc.User\n\n.. autoclass:: discord.abc.User()\n :members:\n\nPrivateChannel\n~~~~~~~~~~~~~~~\n\n.. attributetable:: discord.abc.PrivateChannel\n\n.. autoclass:: discord.abc.PrivateChannel()\n :members:\n\nGuildChannel\n~~~~~~~~~~~~~\n\n.. attributetable:: discord.abc.GuildChannel\n\n.. autoclass:: discord.abc.GuildChannel()\n :members:\n\nMessageable\n~~~~~~~~~~~~\n\n.. attributetable:: discord.abc.Messageable\n\n.. autoclass:: discord.abc.Messageable()\n :members:\n :exclude-members: typing\n\n .. automethod:: discord.abc.Messageable.typing\n :async-with:\n\nConnectable\n~~~~~~~~~~~~\n\n.. attributetable:: discord.abc.Connectable\n\n.. autoclass:: discord.abc.Connectable()\n :members:\n\n.. _discord_api_models:\n\nDiscord Models\n---------------\n\nModels are classes that are received from Discord and are not meant to be created by\nthe user of the library.\n\n.. danger::\n\n The classes listed below are **not intended to be created by users** and are also\n **read-only**.\n\n For example, this means that you should not make your own :class:`User` instances\n nor should you modify the :class:`User` instance yourself.\n\n If you want to get one of these model classes instances they'd have to be through\n the cache, and a common way of doing so is through the :func:`utils.find` function\n or attributes of model classes that you receive from the events specified in the\n :ref:`discord-api-events`.\n\n.. note::\n\n Nearly all classes here have :ref:`py:slots` defined which means that it is\n impossible to have dynamic attributes to the data classes.\n\n\nClientUser\n~~~~~~~~~~~~\n\n.. attributetable:: ClientUser\n\n.. autoclass:: ClientUser()\n :members:\n :inherited-members:\n\nUser\n~~~~~\n\n.. attributetable:: User\n\n.. autoclass:: User()\n :members:\n :inherited-members:\n :exclude-members: typing\n\n .. automethod:: typing\n :async-with:\n\nAutoMod\n~~~~~~~\n\n.. attributetable:: AutoModRule\n\n.. autoclass:: AutoModRule()\n :members:\n\n.. attributetable:: AutoModAction\n\n.. autoclass:: AutoModAction()\n :members:\n\nAttachment\n~~~~~~~~~~~\n\n.. attributetable:: Attachment\n\n.. autoclass:: Attachment()\n :members:\n\nAsset\n~~~~~\n\n.. attributetable:: Asset\n\n.. autoclass:: Asset()\n :members:\n :inherited-members:\n\nMessage\n~~~~~~~\n\n.. attributetable:: Message\n\n.. autoclass:: Message()\n :members:\n :inherited-members:\n\nDeletedReferencedMessage\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: DeletedReferencedMessage\n\n.. autoclass:: DeletedReferencedMessage()\n :members:\n\n\nReaction\n~~~~~~~~~\n\n.. attributetable:: Reaction\n\n.. autoclass:: Reaction()\n :members:\n\nGuild\n~~~~~~\n\n.. attributetable:: Guild\n\n.. autoclass:: Guild()\n :members:\n\n.. class:: BanEntry\n\n A namedtuple which represents a ban returned from :meth:`~Guild.bans`.\n\n .. attribute:: reason\n\n The reason this user was banned.\n\n :type: Optional[:class:`str`]\n .. attribute:: user\n\n The :class:`User` that was banned.\n\n :type: :class:`User`\n\n\nScheduledEvent\n~~~~~~~~~~~~~~\n\n.. attributetable:: ScheduledEvent\n\n.. autoclass:: ScheduledEvent()\n :members:\n\n\nIntegration\n~~~~~~~~~~~~\n\n.. attributetable:: Integration\n\n.. autoclass:: Integration()\n :members:\n\n.. attributetable:: IntegrationAccount\n\n.. autoclass:: IntegrationAccount()\n :members:\n\n.. attributetable:: BotIntegration\n\n.. autoclass:: BotIntegration()\n :members:\n\n.. attributetable:: IntegrationApplication\n\n.. autoclass:: IntegrationApplication()\n :members:\n\n.. attributetable:: StreamIntegration\n\n.. autoclass:: StreamIntegration()\n :members:\n\n.. attributetable:: PartialIntegration\n\n.. autoclass:: PartialIntegration()\n :members:\n\nMember\n~~~~~~\n\n.. attributetable:: Member\n\n.. autoclass:: Member()\n :members:\n :inherited-members:\n :exclude-members: typing\n\n .. automethod:: typing\n :async-with:\n\nSpotify\n~~~~~~~~\n\n.. attributetable:: Spotify\n\n.. autoclass:: Spotify()\n :members:\n\nVoiceState\n~~~~~~~~~~~\n\n.. attributetable:: VoiceState\n\n.. autoclass:: VoiceState()\n :members:\n\nEmoji\n~~~~~\n\n.. attributetable:: Emoji\n\n.. autoclass:: Emoji()\n :members:\n :inherited-members:\n\nPartialEmoji\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: PartialEmoji\n\n.. autoclass:: PartialEmoji()\n :members:\n :inherited-members:\n\nRole\n~~~~~\n\n.. attributetable:: Role\n\n.. autoclass:: Role()\n :members:\n\nRoleTags\n~~~~~~~~~~\n\n.. attributetable:: RoleTags\n\n.. autoclass:: RoleTags()\n :members:\n\nPartialMessageable\n~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: PartialMessageable\n\n.. autoclass:: PartialMessageable()\n :members:\n :inherited-members:\n\nTextChannel\n~~~~~~~~~~~~\n\n.. attributetable:: TextChannel\n\n.. autoclass:: TextChannel()\n :members:\n :inherited-members:\n :exclude-members: typing\n\n .. automethod:: typing\n :async-with:\n\nForumChannel\n~~~~~~~~~~~~~\n\n.. attributetable:: ForumChannel\n\n.. autoclass:: ForumChannel()\n :members:\n :inherited-members:\n\nThread\n~~~~~~~~\n\n.. attributetable:: Thread\n\n.. autoclass:: Thread()\n :members:\n :inherited-members:\n :exclude-members: typing\n\n .. automethod:: typing\n :async-with:\n\nThreadMember\n~~~~~~~~~~~~~\n\n.. attributetable:: ThreadMember\n\n.. autoclass:: ThreadMember()\n :members:\n\nVoiceChannel\n~~~~~~~~~~~~~\n\n.. attributetable:: VoiceChannel\n\n.. autoclass:: VoiceChannel()\n :members:\n :inherited-members:\n\nStageChannel\n~~~~~~~~~~~~~\n\n.. attributetable:: StageChannel\n\n.. autoclass:: StageChannel()\n :members:\n :inherited-members:\n\n\nStageInstance\n~~~~~~~~~~~~~~\n\n.. attributetable:: StageInstance\n\n.. autoclass:: StageInstance()\n :members:\n\nCategoryChannel\n~~~~~~~~~~~~~~~~~\n\n.. attributetable:: CategoryChannel\n\n.. autoclass:: CategoryChannel()\n :members:\n :inherited-members:\n\nDMChannel\n~~~~~~~~~\n\n.. attributetable:: DMChannel\n\n.. autoclass:: DMChannel()\n :members:\n :inherited-members:\n :exclude-members: typing\n\n .. automethod:: typing\n :async-with:\n\nGroupChannel\n~~~~~~~~~~~~\n\n.. attributetable:: GroupChannel\n\n.. autoclass:: GroupChannel()\n :members:\n :inherited-members:\n :exclude-members: typing\n\n .. automethod:: typing\n :async-with:\n\nPartialInviteGuild\n~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: PartialInviteGuild\n\n.. autoclass:: PartialInviteGuild()\n :members:\n\nPartialInviteChannel\n~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: PartialInviteChannel\n\n.. autoclass:: PartialInviteChannel()\n :members:\n\nInvite\n~~~~~~~\n\n.. attributetable:: Invite\n\n.. autoclass:: Invite()\n :members:\n\nTemplate\n~~~~~~~~~\n\n.. attributetable:: Template\n\n.. autoclass:: Template()\n :members:\n\nWelcomeScreen\n~~~~~~~~~~~~~~~\n\n.. attributetable:: WelcomeScreen\n\n.. autoclass:: WelcomeScreen()\n :members:\n\nWelcomeChannel\n~~~~~~~~~~~~~~~\n\n.. attributetable:: WelcomeChannel\n\n.. autoclass:: WelcomeChannel()\n :members:\n\nWidgetChannel\n~~~~~~~~~~~~~~~\n\n.. attributetable:: WidgetChannel\n\n.. autoclass:: WidgetChannel()\n :members:\n\nWidgetMember\n~~~~~~~~~~~~~\n\n.. attributetable:: WidgetMember\n\n.. autoclass:: WidgetMember()\n :members:\n :inherited-members:\n\nWidget\n~~~~~~~\n\n.. attributetable:: Widget\n\n.. autoclass:: Widget()\n :members:\n\nStickerPack\n~~~~~~~~~~~~~\n\n.. attributetable:: StickerPack\n\n.. autoclass:: StickerPack()\n :members:\n\nStickerItem\n~~~~~~~~~~~~~\n\n.. attributetable:: StickerItem\n\n.. autoclass:: StickerItem()\n :members:\n\nSticker\n~~~~~~~~~~~~~~~\n\n.. attributetable:: Sticker\n\n.. autoclass:: Sticker()\n :members:\n\nStandardSticker\n~~~~~~~~~~~~~~~~\n\n.. attributetable:: StandardSticker\n\n.. autoclass:: StandardSticker()\n :members:\n\nGuildSticker\n~~~~~~~~~~~~~\n\n.. attributetable:: GuildSticker\n\n.. autoclass:: GuildSticker()\n :members:\n\nShardInfo\n~~~~~~~~~~~\n\n.. attributetable:: ShardInfo\n\n.. autoclass:: ShardInfo()\n :members:\n\nSKU\n~~~~~~~~~~~\n\n.. attributetable:: SKU\n\n.. autoclass:: SKU()\n :members:\n\nEntitlement\n~~~~~~~~~~~\n\n.. attributetable:: Entitlement\n\n.. autoclass:: Entitlement()\n :members:\n\nRawMessageDeleteEvent\n~~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawMessageDeleteEvent\n\n.. autoclass:: RawMessageDeleteEvent()\n :members:\n\nRawBulkMessageDeleteEvent\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawBulkMessageDeleteEvent\n\n.. autoclass:: RawBulkMessageDeleteEvent()\n :members:\n\nRawMessageUpdateEvent\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawMessageUpdateEvent\n\n.. autoclass:: RawMessageUpdateEvent()\n :members:\n\nRawReactionActionEvent\n~~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawReactionActionEvent\n\n.. autoclass:: RawReactionActionEvent()\n :members:\n\nRawReactionClearEvent\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawReactionClearEvent\n\n.. autoclass:: RawReactionClearEvent()\n :members:\n\nRawReactionClearEmojiEvent\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawReactionClearEmojiEvent\n\n.. autoclass:: RawReactionClearEmojiEvent()\n :members:\n\nRawIntegrationDeleteEvent\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawIntegrationDeleteEvent\n\n.. autoclass:: RawIntegrationDeleteEvent()\n :members:\n\nRawThreadUpdateEvent\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawThreadUpdateEvent\n\n.. autoclass:: RawThreadUpdateEvent()\n :members:\n\nRawThreadMembersUpdate\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawThreadMembersUpdate\n\n.. autoclass:: RawThreadMembersUpdate()\n :members:\n\nRawThreadDeleteEvent\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawThreadDeleteEvent\n\n.. autoclass:: RawThreadDeleteEvent()\n :members:\n\nRawTypingEvent\n~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawTypingEvent\n\n.. autoclass:: RawTypingEvent()\n :members:\n\nRawMemberRemoveEvent\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawMemberRemoveEvent\n\n.. autoclass:: RawMemberRemoveEvent()\n :members:\n\nRawAppCommandPermissionsUpdateEvent\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RawAppCommandPermissionsUpdateEvent\n\n.. autoclass:: RawAppCommandPermissionsUpdateEvent()\n :members:\n\nPartialWebhookGuild\n~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: PartialWebhookGuild\n\n.. autoclass:: PartialWebhookGuild()\n :members:\n\nPartialWebhookChannel\n~~~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: PartialWebhookChannel\n\n.. autoclass:: PartialWebhookChannel()\n :members:\n\n.. _discord_api_data:\n\nData Classes\n--------------\n\nSome classes are just there to be data containers, this lists them.\n\nUnlike :ref:`models ` you are allowed to create\nmost of these yourself, even if they can also be used to hold attributes.\n\nNearly all classes here have :ref:`py:slots` defined which means that it is\nimpossible to have dynamic attributes to the data classes.\n\nThe only exception to this rule is :class:`Object`, which is made with\ndynamic attributes in mind.\n\n\nObject\n~~~~~~~\n\n.. attributetable:: Object\n\n.. autoclass:: Object\n :members:\n\nEmbed\n~~~~~~\n\n.. attributetable:: Embed\n\n.. autoclass:: Embed\n :members:\n\nAllowedMentions\n~~~~~~~~~~~~~~~~~\n\n.. attributetable:: AllowedMentions\n\n.. autoclass:: AllowedMentions\n :members:\n\nMessageReference\n~~~~~~~~~~~~~~~~~\n\n.. attributetable:: MessageReference\n\n.. autoclass:: MessageReference\n :members:\n\nPartialMessage\n~~~~~~~~~~~~~~~~~\n\n.. attributetable:: PartialMessage\n\n.. autoclass:: PartialMessage\n :members:\n\nMessageApplication\n~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: MessageApplication\n\n.. autoclass:: MessageApplication\n :members:\n\nRoleSubscriptionInfo\n~~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: RoleSubscriptionInfo\n\n.. autoclass:: RoleSubscriptionInfo\n :members:\n\nIntents\n~~~~~~~~~~\n\n.. attributetable:: Intents\n\n.. autoclass:: Intents\n :members:\n\nMemberCacheFlags\n~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: MemberCacheFlags\n\n.. autoclass:: MemberCacheFlags\n :members:\n\nApplicationFlags\n~~~~~~~~~~~~~~~~~\n\n.. attributetable:: ApplicationFlags\n\n.. autoclass:: ApplicationFlags\n :members:\n\nChannelFlags\n~~~~~~~~~~~~~~\n\n.. attributetable:: ChannelFlags\n\n.. autoclass:: ChannelFlags\n :members:\n\nAutoModPresets\n~~~~~~~~~~~~~~\n\n.. attributetable:: AutoModPresets\n\n.. autoclass:: AutoModPresets\n :members:\n\nAutoModRuleAction\n~~~~~~~~~~~~~~~~~\n\n.. attributetable:: AutoModRuleAction\n\n.. autoclass:: AutoModRuleAction\n :members:\n\nAutoModTrigger\n~~~~~~~~~~~~~~\n\n.. attributetable:: AutoModTrigger\n\n.. autoclass:: AutoModTrigger\n :members:\n\nFile\n~~~~~\n\n.. attributetable:: File\n\n.. autoclass:: File\n :members:\n\nColour\n~~~~~~\n\n.. attributetable:: Colour\n\n.. autoclass:: Colour\n :members:\n\nBaseActivity\n~~~~~~~~~~~~~~\n\n.. attributetable:: BaseActivity\n\n.. autoclass:: BaseActivity\n :members:\n\nActivity\n~~~~~~~~~\n\n.. attributetable:: Activity\n\n.. autoclass:: Activity\n :members:\n\nGame\n~~~~~\n\n.. attributetable:: Game\n\n.. autoclass:: Game\n :members:\n\nStreaming\n~~~~~~~~~~~\n\n.. attributetable:: Streaming\n\n.. autoclass:: Streaming\n :members:\n\nCustomActivity\n~~~~~~~~~~~~~~~\n\n.. attributetable:: CustomActivity\n\n.. autoclass:: CustomActivity\n :members:\n\nPermissions\n~~~~~~~~~~~~\n\n.. attributetable:: Permissions\n\n.. autoclass:: Permissions\n :members:\n\nPermissionOverwrite\n~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: PermissionOverwrite\n\n.. autoclass:: PermissionOverwrite\n :members:\n\nSystemChannelFlags\n~~~~~~~~~~~~~~~~~~~~\n\n.. attributetable:: SystemChannelFlags\n\n.. autoclass:: SystemChannelFlags\n :members:\n\nMessageFlags\n~~~~~~~~~~~~\n\n.. attributetable:: MessageFlags\n\n.. autoclass:: MessageFlags\n :members:\n\nPublicUserFlags\n~~~~~~~~~~~~~~~\n\n.. attributetable:: PublicUserFlags\n\n.. autoclass:: PublicUserFlags\n :members:\n\nMemberFlags\n~~~~~~~~~~~~\n\n.. attributetable:: MemberFlags\n\n.. autoclass:: MemberFlags\n :members:\n\nAttachmentFlags\n~~~~~~~~~~~~~~~~\n\n.. attributetable:: AttachmentFlags\n\n.. autoclass:: AttachmentFlags\n :members:\n\nRoleFlags\n~~~~~~~~~~\n\n.. attributetable:: RoleFlags\n\n.. autoclass:: RoleFlags\n :members:\n\nSKUFlags\n~~~~~~~~~~~\n\n.. attributetable:: SKUFlags\n\n.. autoclass:: SKUFlags()\n :members:\n\nForumTag\n~~~~~~~~~\n\n.. attributetable:: ForumTag\n\n.. autoclass:: ForumTag\n :members:\n\n\nExceptions\n------------\n\nThe following exceptions are thrown by the library.\n\n.. autoexception:: DiscordException\n\n.. autoexception:: ClientException\n\n.. autoexception:: LoginFailure\n\n.. autoexception:: HTTPException\n :members:\n\n.. autoexception:: RateLimited\n :members:\n\n.. autoexception:: Forbidden\n\n.. autoexception:: NotFound\n\n.. autoexception:: DiscordServerError\n\n.. autoexception:: InvalidData\n\n.. autoexception:: GatewayNotFound\n\n.. autoexception:: ConnectionClosed\n\n.. autoexception:: PrivilegedIntentsRequired\n\n.. autoexception:: InteractionResponded\n\n.. autoexception:: discord.opus.OpusError\n\n.. autoexception:: discord.opus.OpusNotLoaded\n\nException Hierarchy\n~~~~~~~~~~~~~~~~~~~~~\n\n.. exception_hierarchy::\n\n - :exc:`Exception`\n - :exc:`DiscordException`\n - :exc:`ClientException`\n - :exc:`InvalidData`\n - :exc:`LoginFailure`\n - :exc:`ConnectionClosed`\n - :exc:`PrivilegedIntentsRequired`\n - :exc:`InteractionResponded`\n - :exc:`GatewayNotFound`\n - :exc:`HTTPException`\n - :exc:`Forbidden`\n - :exc:`NotFound`\n - :exc:`DiscordServerError`\n - :exc:`app_commands.CommandSyncFailure`\n - :exc:`RateLimited`\n" } ], "language": "python" }, { "id": "10_10", "repo_url": "https://github.com/teamqurrent/discord.py", "instruction": "in the `discord/state.py` file, locate the `parse_entitlement_delete` method within the `ConnectionState` class. Change the event name in the dispatch call from 'entitlement_update' to 'entitlement_delete'. This modification ensures that the correct event is dispatched when the `parse_entitlement_delete` method is invoked.", "base_commit": "99618c8", "test_script": "import unittest\nimport sys\nimport inspect\n\n\n\nclass TestEntitlementDeleteEventDispatch(unittest.TestCase): \n def test_entitlement_delete_event_dispatch(self):\n from discord.state import ConnectionState\n\n # Inspect the ConnectionState class for the parse_entitlement_delete method\n method = getattr(ConnectionState, 'parse_entitlement_delete', None)\n self.assertIsNotNone(method, \"Method parse_entitlement_delete not found in ConnectionState\")\n\n # Inspect the source code of the method\n source_lines = inspect.getsource(method).splitlines()\n\n # Check if the correct dispatch call is present in the method\n correct_dispatch = any(\"dispatch('entitlement_delete'\" in line for line in source_lines)\n self.assertTrue(correct_dispatch, \"The dispatch call for 'entitlement_delete' is not correct in parse_entitlement_delete\")\n\ndef main():\n\n suite = unittest.TestSuite()\n suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestEntitlementDeleteEventDispatch))\n runner = unittest.TextTestRunner()\n\n if runner.run(suite).wasSuccessful():\n sys.exit(0)\n else:\n sys.exit(1)\n\nif __name__ == '__main__':\n\n main()\n", "testbed_environment": "python3.9", "requirements_txt": "discord", "solution_commit": "7d159920", "solution_patch": "diff --git a/discord/state.py b/discord/state.py\n--- a/discord/state.py\n+++ b/discord/state.py\n@@ -1595,7 +1595,7 @@ class ConnectionState(Generic[ClientT]):\n \n def parse_entitlement_delete(self, data: gw.EntitlementDeleteEvent) -> None:\n entitlement = Entitlement(data=data, state=self)\n- self.dispatch('entitlement_update', entitlement)\n+ self.dispatch('entitlement_delete', entitlement)\n \n def _get_reaction_user(self, channel: MessageableChannel, user_id: int) -> Optional[Union[User, Member]]:\n if isinstance(channel, (TextChannel, Thread, VoiceChannel)):\n", "modified_files": [ { "path": "discord/state.py", "content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\nfrom collections import deque, OrderedDict\nimport copy\nimport logging\nfrom typing import (\n Dict,\n Optional,\n TYPE_CHECKING,\n Type,\n Union,\n Callable,\n Any,\n List,\n TypeVar,\n Coroutine,\n Sequence,\n Generic,\n Tuple,\n Deque,\n Literal,\n overload,\n)\nimport weakref\nimport inspect\n\nimport os\n\nfrom .guild import Guild\nfrom .activity import BaseActivity\nfrom .sku import Entitlement\nfrom .user import User, ClientUser\nfrom .emoji import Emoji\nfrom .mentions import AllowedMentions\nfrom .partial_emoji import PartialEmoji\nfrom .message import Message\nfrom .channel import *\nfrom .channel import _channel_factory\nfrom .raw_models import *\nfrom .member import Member\nfrom .role import Role\nfrom .enums import ChannelType, try_enum, Status\nfrom . import utils\nfrom .flags import ApplicationFlags, Intents, MemberCacheFlags\nfrom .invite import Invite\nfrom .integrations import _integration_factory\nfrom .interactions import Interaction\nfrom .ui.view import ViewStore, View\nfrom .scheduled_event import ScheduledEvent\nfrom .stage_instance import StageInstance\nfrom .threads import Thread, ThreadMember\nfrom .sticker import GuildSticker\nfrom .automod import AutoModRule, AutoModAction\nfrom .audit_logs import AuditLogEntry\nfrom ._types import ClientT\n\nif TYPE_CHECKING:\n from .abc import PrivateChannel\n from .message import MessageableChannel\n from .guild import GuildChannel\n from .http import HTTPClient\n from .voice_client import VoiceProtocol\n from .gateway import DiscordWebSocket\n from .ui.item import Item\n from .ui.dynamic import DynamicItem\n from .app_commands import CommandTree, Translator\n\n from .types.automod import AutoModerationRule, AutoModerationActionExecution\n from .types.snowflake import Snowflake\n from .types.activity import Activity as ActivityPayload\n from .types.channel import DMChannel as DMChannelPayload\n from .types.user import User as UserPayload, PartialUser as PartialUserPayload\n from .types.emoji import Emoji as EmojiPayload, PartialEmoji as PartialEmojiPayload\n from .types.sticker import GuildSticker as GuildStickerPayload\n from .types.guild import Guild as GuildPayload\n from .types.message import Message as MessagePayload, PartialMessage as PartialMessagePayload\n from .types import gateway as gw\n from .types.command import GuildApplicationCommandPermissions as GuildApplicationCommandPermissionsPayload\n\n T = TypeVar('T')\n Channel = Union[GuildChannel, PrivateChannel, PartialMessageable]\n\n\nclass ChunkRequest:\n def __init__(\n self,\n guild_id: int,\n loop: asyncio.AbstractEventLoop,\n resolver: Callable[[int], Any],\n *,\n cache: bool = True,\n ) -> None:\n self.guild_id: int = guild_id\n self.resolver: Callable[[int], Any] = resolver\n self.loop: asyncio.AbstractEventLoop = loop\n self.cache: bool = cache\n self.nonce: str = os.urandom(16).hex()\n self.buffer: List[Member] = []\n self.waiters: List[asyncio.Future[List[Member]]] = []\n\n def add_members(self, members: List[Member]) -> None:\n self.buffer.extend(members)\n if self.cache:\n guild = self.resolver(self.guild_id)\n if guild is None:\n return\n\n for member in members:\n existing = guild.get_member(member.id)\n if existing is None or existing.joined_at is None:\n guild._add_member(member)\n\n async def wait(self) -> List[Member]:\n future = self.loop.create_future()\n self.waiters.append(future)\n try:\n return await future\n finally:\n self.waiters.remove(future)\n\n def get_future(self) -> asyncio.Future[List[Member]]:\n future = self.loop.create_future()\n self.waiters.append(future)\n return future\n\n def done(self) -> None:\n for future in self.waiters:\n if not future.done():\n future.set_result(self.buffer)\n\n\n_log = logging.getLogger(__name__)\n\n\nasync def logging_coroutine(coroutine: Coroutine[Any, Any, T], *, info: str) -> Optional[T]:\n try:\n await coroutine\n except Exception:\n _log.exception('Exception occurred during %s', info)\n\n\nclass ConnectionState(Generic[ClientT]):\n if TYPE_CHECKING:\n _get_websocket: Callable[..., DiscordWebSocket]\n _get_client: Callable[..., ClientT]\n _parsers: Dict[str, Callable[[Dict[str, Any]], None]]\n\n def __init__(\n self,\n *,\n dispatch: Callable[..., Any],\n handlers: Dict[str, Callable[..., Any]],\n hooks: Dict[str, Callable[..., Coroutine[Any, Any, Any]]],\n http: HTTPClient,\n **options: Any,\n ) -> None:\n # Set later, after Client.login\n self.loop: asyncio.AbstractEventLoop = utils.MISSING\n self.http: HTTPClient = http\n self.max_messages: Optional[int] = options.get('max_messages', 1000)\n if self.max_messages is not None and self.max_messages <= 0:\n self.max_messages = 1000\n\n self.dispatch: Callable[..., Any] = dispatch\n self.handlers: Dict[str, Callable[..., Any]] = handlers\n self.hooks: Dict[str, Callable[..., Coroutine[Any, Any, Any]]] = hooks\n self.shard_count: Optional[int] = None\n self._ready_task: Optional[asyncio.Task] = None\n self.application_id: Optional[int] = utils._get_as_snowflake(options, 'application_id')\n self.application_flags: ApplicationFlags = utils.MISSING\n self.heartbeat_timeout: float = options.get('heartbeat_timeout', 60.0)\n self.guild_ready_timeout: float = options.get('guild_ready_timeout', 2.0)\n if self.guild_ready_timeout < 0:\n raise ValueError('guild_ready_timeout cannot be negative')\n\n allowed_mentions = options.get('allowed_mentions')\n\n if allowed_mentions is not None and not isinstance(allowed_mentions, AllowedMentions):\n raise TypeError('allowed_mentions parameter must be AllowedMentions')\n\n self.allowed_mentions: Optional[AllowedMentions] = allowed_mentions\n self._chunk_requests: Dict[Union[int, str], ChunkRequest] = {}\n\n activity = options.get('activity', None)\n if activity:\n if not isinstance(activity, BaseActivity):\n raise TypeError('activity parameter must derive from BaseActivity.')\n\n activity = activity.to_dict()\n\n status = options.get('status', None)\n if status:\n if status is Status.offline:\n status = 'invisible'\n else:\n status = str(status)\n\n intents = options.get('intents', None)\n if intents is not None:\n if not isinstance(intents, Intents):\n raise TypeError(f'intents parameter must be Intent not {type(intents)!r}')\n else:\n intents = Intents.default()\n\n if not intents.guilds:\n _log.warning('Guilds intent seems to be disabled. This may cause state related issues.')\n\n self._chunk_guilds: bool = options.get('chunk_guilds_at_startup', intents.members)\n\n # Ensure these two are set properly\n if not intents.members and self._chunk_guilds:\n raise ValueError('Intents.members must be enabled to chunk guilds at startup.')\n\n cache_flags = options.get('member_cache_flags', None)\n if cache_flags is None:\n cache_flags = MemberCacheFlags.from_intents(intents)\n else:\n if not isinstance(cache_flags, MemberCacheFlags):\n raise TypeError(f'member_cache_flags parameter must be MemberCacheFlags not {type(cache_flags)!r}')\n\n cache_flags._verify_intents(intents)\n\n self.member_cache_flags: MemberCacheFlags = cache_flags\n self._activity: Optional[ActivityPayload] = activity\n self._status: Optional[str] = status\n self._intents: Intents = intents\n self._command_tree: Optional[CommandTree] = None\n self._translator: Optional[Translator] = None\n\n if not intents.members or cache_flags._empty:\n self.store_user = self.store_user_no_intents\n\n self.parsers: Dict[str, Callable[[Any], None]]\n self.parsers = parsers = {}\n for attr, func in inspect.getmembers(self):\n if attr.startswith('parse_'):\n parsers[attr[6:].upper()] = func\n\n self.clear()\n\n # For some reason Discord still sends emoji/sticker data in payloads\n # This makes it hard to actually swap out the appropriate store methods\n # So this is checked instead, it's a small penalty to pay\n @property\n def cache_guild_expressions(self) -> bool:\n return self._intents.emojis_and_stickers\n\n async def close(self) -> None:\n for voice in self.voice_clients:\n try:\n await voice.disconnect(force=True)\n except Exception:\n # if an error happens during disconnects, disregard it.\n pass\n\n if self._translator:\n await self._translator.unload()\n\n # Purposefully don't call `clear` because users rely on cache being available post-close\n\n def clear(self, *, views: bool = True) -> None:\n self.user: Optional[ClientUser] = None\n self._users: weakref.WeakValueDictionary[int, User] = weakref.WeakValueDictionary()\n self._emojis: Dict[int, Emoji] = {}\n self._stickers: Dict[int, GuildSticker] = {}\n self._guilds: Dict[int, Guild] = {}\n if views:\n self._view_store: ViewStore = ViewStore(self)\n\n self._voice_clients: Dict[int, VoiceProtocol] = {}\n\n # LRU of max size 128\n self._private_channels: OrderedDict[int, PrivateChannel] = OrderedDict()\n # extra dict to look up private channels by user id\n self._private_channels_by_user: Dict[int, DMChannel] = {}\n if self.max_messages is not None:\n self._messages: Optional[Deque[Message]] = deque(maxlen=self.max_messages)\n else:\n self._messages: Optional[Deque[Message]] = None\n\n def process_chunk_requests(self, guild_id: int, nonce: Optional[str], members: List[Member], complete: bool) -> None:\n removed = []\n for key, request in self._chunk_requests.items():\n if request.guild_id == guild_id and request.nonce == nonce:\n request.add_members(members)\n if complete:\n request.done()\n removed.append(key)\n\n for key in removed:\n del self._chunk_requests[key]\n\n def call_handlers(self, key: str, *args: Any, **kwargs: Any) -> None:\n try:\n func = self.handlers[key]\n except KeyError:\n pass\n else:\n func(*args, **kwargs)\n\n async def call_hooks(self, key: str, *args: Any, **kwargs: Any) -> None:\n try:\n coro = self.hooks[key]\n except KeyError:\n pass\n else:\n await coro(*args, **kwargs)\n\n @property\n def self_id(self) -> Optional[int]:\n u = self.user\n return u.id if u else None\n\n @property\n def intents(self) -> Intents:\n ret = Intents.none()\n ret.value = self._intents.value\n return ret\n\n @property\n def voice_clients(self) -> List[VoiceProtocol]:\n return list(self._voice_clients.values())\n\n def _get_voice_client(self, guild_id: Optional[int]) -> Optional[VoiceProtocol]:\n # the keys of self._voice_clients are ints\n return self._voice_clients.get(guild_id) # type: ignore\n\n def _add_voice_client(self, guild_id: int, voice: VoiceProtocol) -> None:\n self._voice_clients[guild_id] = voice\n\n def _remove_voice_client(self, guild_id: int) -> None:\n self._voice_clients.pop(guild_id, None)\n\n def _update_references(self, ws: DiscordWebSocket) -> None:\n for vc in self.voice_clients:\n vc.main_ws = ws # type: ignore # Silencing the unknown attribute (ok at runtime).\n\n def store_user(self, data: Union[UserPayload, PartialUserPayload], *, cache: bool = True) -> User:\n # this way is 300% faster than `dict.setdefault`.\n user_id = int(data['id'])\n try:\n return self._users[user_id]\n except KeyError:\n user = User(state=self, data=data)\n if cache:\n self._users[user_id] = user\n return user\n\n def store_user_no_intents(self, data: Union[UserPayload, PartialUserPayload], *, cache: bool = True) -> User:\n return User(state=self, data=data)\n\n def create_user(self, data: Union[UserPayload, PartialUserPayload]) -> User:\n return User(state=self, data=data)\n\n def get_user(self, id: int) -> Optional[User]:\n return self._users.get(id)\n\n def store_emoji(self, guild: Guild, data: EmojiPayload) -> Emoji:\n # the id will be present here\n emoji_id = int(data['id']) # type: ignore\n self._emojis[emoji_id] = emoji = Emoji(guild=guild, state=self, data=data)\n return emoji\n\n def store_sticker(self, guild: Guild, data: GuildStickerPayload) -> GuildSticker:\n sticker_id = int(data['id'])\n self._stickers[sticker_id] = sticker = GuildSticker(state=self, data=data)\n return sticker\n\n def store_view(self, view: View, message_id: Optional[int] = None, interaction_id: Optional[int] = None) -> None:\n if interaction_id is not None:\n self._view_store.remove_interaction_mapping(interaction_id)\n self._view_store.add_view(view, message_id)\n\n def prevent_view_updates_for(self, message_id: int) -> Optional[View]:\n return self._view_store.remove_message_tracking(message_id)\n\n def store_dynamic_items(self, *items: Type[DynamicItem[Item[Any]]]) -> None:\n self._view_store.add_dynamic_items(*items)\n\n def remove_dynamic_items(self, *items: Type[DynamicItem[Item[Any]]]) -> None:\n self._view_store.remove_dynamic_items(*items)\n\n @property\n def persistent_views(self) -> Sequence[View]:\n return self._view_store.persistent_views\n\n @property\n def guilds(self) -> Sequence[Guild]:\n return utils.SequenceProxy(self._guilds.values())\n\n def _get_guild(self, guild_id: Optional[int]) -> Optional[Guild]:\n # the keys of self._guilds are ints\n return self._guilds.get(guild_id) # type: ignore\n\n def _get_or_create_unavailable_guild(self, guild_id: int) -> Guild:\n return self._guilds.get(guild_id) or Guild._create_unavailable(state=self, guild_id=guild_id)\n\n def _add_guild(self, guild: Guild) -> None:\n self._guilds[guild.id] = guild\n\n def _remove_guild(self, guild: Guild) -> None:\n self._guilds.pop(guild.id, None)\n\n for emoji in guild.emojis:\n self._emojis.pop(emoji.id, None)\n\n for sticker in guild.stickers:\n self._stickers.pop(sticker.id, None)\n\n del guild\n\n @property\n def emojis(self) -> Sequence[Emoji]:\n return utils.SequenceProxy(self._emojis.values())\n\n @property\n def stickers(self) -> Sequence[GuildSticker]:\n return utils.SequenceProxy(self._stickers.values())\n\n def get_emoji(self, emoji_id: Optional[int]) -> Optional[Emoji]:\n # the keys of self._emojis are ints\n return self._emojis.get(emoji_id) # type: ignore\n\n def get_sticker(self, sticker_id: Optional[int]) -> Optional[GuildSticker]:\n # the keys of self._stickers are ints\n return self._stickers.get(sticker_id) # type: ignore\n\n @property\n def private_channels(self) -> Sequence[PrivateChannel]:\n return utils.SequenceProxy(self._private_channels.values())\n\n def _get_private_channel(self, channel_id: Optional[int]) -> Optional[PrivateChannel]:\n try:\n # the keys of self._private_channels are ints\n value = self._private_channels[channel_id] # type: ignore\n except KeyError:\n return None\n else:\n # Type narrowing can't figure out that channel_id isn't None here\n self._private_channels.move_to_end(channel_id) # type: ignore\n return value\n\n def _get_private_channel_by_user(self, user_id: Optional[int]) -> Optional[DMChannel]:\n # the keys of self._private_channels are ints\n return self._private_channels_by_user.get(user_id) # type: ignore\n\n def _add_private_channel(self, channel: PrivateChannel) -> None:\n channel_id = channel.id\n self._private_channels[channel_id] = channel\n\n if len(self._private_channels) > 128:\n _, to_remove = self._private_channels.popitem(last=False)\n if isinstance(to_remove, DMChannel) and to_remove.recipient:\n self._private_channels_by_user.pop(to_remove.recipient.id, None)\n\n if isinstance(channel, DMChannel) and channel.recipient:\n self._private_channels_by_user[channel.recipient.id] = channel\n\n def add_dm_channel(self, data: DMChannelPayload) -> DMChannel:\n # self.user is *always* cached when this is called\n channel = DMChannel(me=self.user, state=self, data=data) # type: ignore\n self._add_private_channel(channel)\n return channel\n\n def _remove_private_channel(self, channel: PrivateChannel) -> None:\n self._private_channels.pop(channel.id, None)\n if isinstance(channel, DMChannel):\n recipient = channel.recipient\n if recipient is not None:\n self._private_channels_by_user.pop(recipient.id, None)\n\n def _get_message(self, msg_id: Optional[int]) -> Optional[Message]:\n return utils.find(lambda m: m.id == msg_id, reversed(self._messages)) if self._messages else None\n\n def _add_guild_from_data(self, data: GuildPayload) -> Guild:\n guild = Guild(data=data, state=self)\n self._add_guild(guild)\n return guild\n\n def _guild_needs_chunking(self, guild: Guild) -> bool:\n # If presences are enabled then we get back the old guild.large behaviour\n return self._chunk_guilds and not guild.chunked and not (self._intents.presences and not guild.large)\n\n def _get_guild_channel(\n self, data: PartialMessagePayload, guild_id: Optional[int] = None\n ) -> Tuple[Union[Channel, Thread], Optional[Guild]]:\n channel_id = int(data['channel_id'])\n try:\n guild_id = guild_id or int(data['guild_id'])\n guild = self._get_guild(guild_id)\n except KeyError:\n channel = DMChannel._from_message(self, channel_id)\n guild = None\n else:\n channel = guild and guild._resolve_channel(channel_id)\n\n return channel or PartialMessageable(state=self, guild_id=guild_id, id=channel_id), guild\n\n async def chunker(\n self, guild_id: int, query: str = '', limit: int = 0, presences: bool = False, *, nonce: Optional[str] = None\n ) -> None:\n ws = self._get_websocket(guild_id) # This is ignored upstream\n await ws.request_chunks(guild_id, query=query, limit=limit, presences=presences, nonce=nonce)\n\n async def query_members(\n self, guild: Guild, query: Optional[str], limit: int, user_ids: Optional[List[int]], cache: bool, presences: bool\n ) -> List[Member]:\n guild_id = guild.id\n ws = self._get_websocket(guild_id)\n if ws is None:\n raise RuntimeError('Somehow do not have a websocket for this guild_id')\n\n request = ChunkRequest(guild.id, self.loop, self._get_guild, cache=cache)\n self._chunk_requests[request.nonce] = request\n\n try:\n # start the query operation\n await ws.request_chunks(\n guild_id, query=query, limit=limit, user_ids=user_ids, presences=presences, nonce=request.nonce\n )\n return await asyncio.wait_for(request.wait(), timeout=30.0)\n except asyncio.TimeoutError:\n _log.warning('Timed out waiting for chunks with query %r and limit %d for guild_id %d', query, limit, guild_id)\n raise\n\n async def _delay_ready(self) -> None:\n try:\n states = []\n while True:\n # this snippet of code is basically waiting N seconds\n # until the last GUILD_CREATE was sent\n try:\n guild = await asyncio.wait_for(self._ready_state.get(), timeout=self.guild_ready_timeout)\n except asyncio.TimeoutError:\n break\n else:\n if self._guild_needs_chunking(guild):\n future = await self.chunk_guild(guild, wait=False)\n states.append((guild, future))\n else:\n if guild.unavailable is False:\n self.dispatch('guild_available', guild)\n else:\n self.dispatch('guild_join', guild)\n\n for guild, future in states:\n timeout = self._chunk_timeout(guild)\n\n try:\n await asyncio.wait_for(future, timeout=timeout)\n except asyncio.TimeoutError:\n _log.warning('Shard ID %s timed out waiting for chunks for guild_id %s.', guild.shard_id, guild.id)\n\n if guild.unavailable is False:\n self.dispatch('guild_available', guild)\n else:\n self.dispatch('guild_join', guild)\n\n # remove the state\n try:\n del self._ready_state\n except AttributeError:\n pass # already been deleted somehow\n\n except asyncio.CancelledError:\n pass\n else:\n # dispatch the event\n self.call_handlers('ready')\n self.dispatch('ready')\n finally:\n self._ready_task = None\n\n def parse_ready(self, data: gw.ReadyEvent) -> None:\n if self._ready_task is not None:\n self._ready_task.cancel()\n\n self._ready_state: asyncio.Queue[Guild] = asyncio.Queue()\n self.clear(views=False)\n self.user = user = ClientUser(state=self, data=data['user'])\n self._users[user.id] = user # type: ignore\n\n if self.application_id is None:\n try:\n application = data['application']\n except KeyError:\n pass\n else:\n self.application_id = utils._get_as_snowflake(application, 'id')\n self.application_flags: ApplicationFlags = ApplicationFlags._from_value(application['flags'])\n\n for guild_data in data['guilds']:\n self._add_guild_from_data(guild_data) # type: ignore\n\n self.dispatch('connect')\n self._ready_task = asyncio.create_task(self._delay_ready())\n\n def parse_resumed(self, data: gw.ResumedEvent) -> None:\n self.dispatch('resumed')\n\n def parse_message_create(self, data: gw.MessageCreateEvent) -> None:\n channel, _ = self._get_guild_channel(data)\n # channel would be the correct type here\n message = Message(channel=channel, data=data, state=self) # type: ignore\n self.dispatch('message', message)\n if self._messages is not None:\n self._messages.append(message)\n # we ensure that the channel is either a TextChannel, VoiceChannel, or Thread\n if channel and channel.__class__ in (TextChannel, VoiceChannel, Thread, StageChannel):\n channel.last_message_id = message.id # type: ignore\n\n def parse_message_delete(self, data: gw.MessageDeleteEvent) -> None:\n raw = RawMessageDeleteEvent(data)\n found = self._get_message(raw.message_id)\n raw.cached_message = found\n self.dispatch('raw_message_delete', raw)\n if self._messages is not None and found is not None:\n self.dispatch('message_delete', found)\n self._messages.remove(found)\n\n def parse_message_delete_bulk(self, data: gw.MessageDeleteBulkEvent) -> None:\n raw = RawBulkMessageDeleteEvent(data)\n if self._messages:\n found_messages = [message for message in self._messages if message.id in raw.message_ids]\n else:\n found_messages = []\n raw.cached_messages = found_messages\n self.dispatch('raw_bulk_message_delete', raw)\n if found_messages:\n self.dispatch('bulk_message_delete', found_messages)\n for msg in found_messages:\n # self._messages won't be None here\n self._messages.remove(msg) # type: ignore\n\n def parse_message_update(self, data: gw.MessageUpdateEvent) -> None:\n raw = RawMessageUpdateEvent(data)\n message = self._get_message(raw.message_id)\n if message is not None:\n older_message = copy.copy(message)\n raw.cached_message = older_message\n self.dispatch('raw_message_edit', raw)\n message._update(data)\n # Coerce the `after` parameter to take the new updated Member\n # ref: #5999\n older_message.author = message.author\n self.dispatch('message_edit', older_message, message)\n else:\n self.dispatch('raw_message_edit', raw)\n\n if 'components' in data:\n try:\n entity_id = int(data['interaction']['id'])\n except (KeyError, ValueError):\n entity_id = raw.message_id\n\n if self._view_store.is_message_tracked(entity_id):\n self._view_store.update_from_message(entity_id, data['components'])\n\n def parse_message_reaction_add(self, data: gw.MessageReactionAddEvent) -> None:\n emoji = PartialEmoji.from_dict(data['emoji'])\n emoji._state = self\n raw = RawReactionActionEvent(data, emoji, 'REACTION_ADD')\n\n member_data = data.get('member')\n if member_data:\n guild = self._get_guild(raw.guild_id)\n if guild is not None:\n raw.member = Member(data=member_data, guild=guild, state=self)\n else:\n raw.member = None\n else:\n raw.member = None\n self.dispatch('raw_reaction_add', raw)\n\n # rich interface here\n message = self._get_message(raw.message_id)\n if message is not None:\n emoji = self._upgrade_partial_emoji(emoji)\n reaction = message._add_reaction(data, emoji, raw.user_id)\n user = raw.member or self._get_reaction_user(message.channel, raw.user_id)\n\n if user:\n self.dispatch('reaction_add', reaction, user)\n\n def parse_message_reaction_remove_all(self, data: gw.MessageReactionRemoveAllEvent) -> None:\n raw = RawReactionClearEvent(data)\n self.dispatch('raw_reaction_clear', raw)\n\n message = self._get_message(raw.message_id)\n if message is not None:\n old_reactions = message.reactions.copy()\n message.reactions.clear()\n self.dispatch('reaction_clear', message, old_reactions)\n\n def parse_message_reaction_remove(self, data: gw.MessageReactionRemoveEvent) -> None:\n emoji = PartialEmoji.from_dict(data['emoji'])\n emoji._state = self\n raw = RawReactionActionEvent(data, emoji, 'REACTION_REMOVE')\n self.dispatch('raw_reaction_remove', raw)\n\n message = self._get_message(raw.message_id)\n if message is not None:\n emoji = self._upgrade_partial_emoji(emoji)\n try:\n reaction = message._remove_reaction(data, emoji, raw.user_id)\n except (AttributeError, ValueError): # eventual consistency lol\n pass\n else:\n user = self._get_reaction_user(message.channel, raw.user_id)\n if user:\n self.dispatch('reaction_remove', reaction, user)\n\n def parse_message_reaction_remove_emoji(self, data: gw.MessageReactionRemoveEmojiEvent) -> None:\n emoji = PartialEmoji.from_dict(data['emoji'])\n emoji._state = self\n raw = RawReactionClearEmojiEvent(data, emoji)\n self.dispatch('raw_reaction_clear_emoji', raw)\n\n message = self._get_message(raw.message_id)\n if message is not None:\n try:\n reaction = message._clear_emoji(emoji)\n except (AttributeError, ValueError): # eventual consistency lol\n pass\n else:\n if reaction:\n self.dispatch('reaction_clear_emoji', reaction)\n\n def parse_interaction_create(self, data: gw.InteractionCreateEvent) -> None:\n interaction = Interaction(data=data, state=self)\n if data['type'] in (2, 4) and self._command_tree: # application command and auto complete\n self._command_tree._from_interaction(interaction)\n elif data['type'] == 3: # interaction component\n # These keys are always there for this interaction type\n inner_data = data['data']\n custom_id = inner_data['custom_id']\n component_type = inner_data['component_type']\n self._view_store.dispatch_view(component_type, custom_id, interaction)\n elif data['type'] == 5: # modal submit\n # These keys are always there for this interaction type\n inner_data = data['data']\n custom_id = inner_data['custom_id']\n components = inner_data['components']\n self._view_store.dispatch_modal(custom_id, interaction, components)\n self.dispatch('interaction', interaction)\n\n def parse_presence_update(self, data: gw.PresenceUpdateEvent) -> None:\n guild_id = utils._get_as_snowflake(data, 'guild_id')\n # guild_id won't be None here\n guild = self._get_guild(guild_id)\n if guild is None:\n _log.debug('PRESENCE_UPDATE referencing an unknown guild ID: %s. Discarding.', guild_id)\n return\n\n user = data['user']\n member_id = int(user['id'])\n member = guild.get_member(member_id)\n if member is None:\n _log.debug('PRESENCE_UPDATE referencing an unknown member ID: %s. Discarding', member_id)\n return\n\n old_member = Member._copy(member)\n user_update = member._presence_update(data=data, user=user)\n if user_update:\n self.dispatch('user_update', user_update[0], user_update[1])\n\n self.dispatch('presence_update', old_member, member)\n\n def parse_user_update(self, data: gw.UserUpdateEvent) -> None:\n if self.user:\n self.user._update(data)\n\n def parse_invite_create(self, data: gw.InviteCreateEvent) -> None:\n invite = Invite.from_gateway(state=self, data=data)\n self.dispatch('invite_create', invite)\n\n def parse_invite_delete(self, data: gw.InviteDeleteEvent) -> None:\n invite = Invite.from_gateway(state=self, data=data)\n self.dispatch('invite_delete', invite)\n\n def parse_channel_delete(self, data: gw.ChannelDeleteEvent) -> None:\n guild = self._get_guild(utils._get_as_snowflake(data, 'guild_id'))\n channel_id = int(data['id'])\n if guild is not None:\n channel = guild.get_channel(channel_id)\n if channel is not None:\n guild._remove_channel(channel)\n self.dispatch('guild_channel_delete', channel)\n\n if channel.type in (ChannelType.voice, ChannelType.stage_voice):\n for s in guild.scheduled_events:\n if s.channel_id == channel.id:\n guild._scheduled_events.pop(s.id)\n self.dispatch('scheduled_event_delete', s)\n\n def parse_channel_update(self, data: gw.ChannelUpdateEvent) -> None:\n channel_type = try_enum(ChannelType, data.get('type'))\n channel_id = int(data['id'])\n if channel_type is ChannelType.group:\n channel = self._get_private_channel(channel_id)\n if channel is not None:\n old_channel = copy.copy(channel)\n # the channel is a GroupChannel rather than PrivateChannel\n channel._update_group(data) # type: ignore\n self.dispatch('private_channel_update', old_channel, channel)\n return\n else:\n _log.debug('CHANNEL_UPDATE referencing an unknown channel ID: %s. Discarding.', channel_id)\n\n guild_id = utils._get_as_snowflake(data, 'guild_id')\n guild = self._get_guild(guild_id)\n if guild is not None:\n channel = guild.get_channel(channel_id)\n if channel is not None:\n old_channel = copy.copy(channel)\n channel._update(guild, data) # type: ignore # the data payload varies based on the channel type.\n self.dispatch('guild_channel_update', old_channel, channel)\n else:\n _log.debug('CHANNEL_UPDATE referencing an unknown channel ID: %s. Discarding.', channel_id)\n else:\n _log.debug('CHANNEL_UPDATE referencing an unknown guild ID: %s. Discarding.', guild_id)\n\n def parse_channel_create(self, data: gw.ChannelCreateEvent) -> None:\n factory, ch_type = _channel_factory(data['type'])\n if factory is None:\n _log.debug('CHANNEL_CREATE referencing an unknown channel type %s. Discarding.', data['type'])\n return\n\n guild_id = utils._get_as_snowflake(data, 'guild_id')\n guild = self._get_guild(guild_id)\n if guild is not None:\n # the factory can't be a DMChannel or GroupChannel here\n channel = factory(guild=guild, state=self, data=data) # type: ignore\n guild._add_channel(channel) # type: ignore\n self.dispatch('guild_channel_create', channel)\n else:\n _log.debug('CHANNEL_CREATE referencing an unknown guild ID: %s. Discarding.', guild_id)\n return\n\n def parse_channel_pins_update(self, data: gw.ChannelPinsUpdateEvent) -> None:\n channel_id = int(data['channel_id'])\n try:\n guild = self._get_guild(int(data['guild_id']))\n except KeyError:\n guild = None\n channel = self._get_private_channel(channel_id)\n else:\n channel = guild and guild._resolve_channel(channel_id)\n\n if channel is None:\n _log.debug('CHANNEL_PINS_UPDATE referencing an unknown channel ID: %s. Discarding.', channel_id)\n return\n\n last_pin = utils.parse_time(data.get('last_pin_timestamp'))\n\n if guild is None:\n self.dispatch('private_channel_pins_update', channel, last_pin)\n else:\n self.dispatch('guild_channel_pins_update', channel, last_pin)\n\n def parse_thread_create(self, data: gw.ThreadCreateEvent) -> None:\n guild_id = int(data['guild_id'])\n guild: Optional[Guild] = self._get_guild(guild_id)\n if guild is None:\n _log.debug('THREAD_CREATE referencing an unknown guild ID: %s. Discarding', guild_id)\n return\n\n thread = Thread(guild=guild, state=guild._state, data=data)\n has_thread = guild.get_thread(thread.id)\n guild._add_thread(thread)\n if not has_thread:\n if data.get('newly_created'):\n if thread.parent.__class__ is ForumChannel:\n thread.parent.last_message_id = thread.id # type: ignore\n\n self.dispatch('thread_create', thread)\n else:\n self.dispatch('thread_join', thread)\n\n def parse_thread_update(self, data: gw.ThreadUpdateEvent) -> None:\n guild_id = int(data['guild_id'])\n guild = self._get_guild(guild_id)\n if guild is None:\n _log.debug('THREAD_UPDATE referencing an unknown guild ID: %s. Discarding', guild_id)\n return\n\n raw = RawThreadUpdateEvent(data)\n raw.thread = thread = guild.get_thread(raw.thread_id)\n self.dispatch('raw_thread_update', raw)\n if thread is not None:\n old = copy.copy(thread)\n thread._update(data)\n if thread.archived:\n guild._remove_thread(thread)\n self.dispatch('thread_update', old, thread)\n else:\n thread = Thread(guild=guild, state=guild._state, data=data)\n if not thread.archived:\n guild._add_thread(thread)\n self.dispatch('thread_join', thread)\n\n def parse_thread_delete(self, data: gw.ThreadDeleteEvent) -> None:\n guild_id = int(data['guild_id'])\n guild = self._get_guild(guild_id)\n if guild is None:\n _log.debug('THREAD_DELETE referencing an unknown guild ID: %s. Discarding', guild_id)\n return\n\n raw = RawThreadDeleteEvent(data)\n raw.thread = thread = guild.get_thread(raw.thread_id)\n self.dispatch('raw_thread_delete', raw)\n\n if thread is not None:\n guild._remove_thread(thread)\n self.dispatch('thread_delete', thread)\n\n def parse_thread_list_sync(self, data: gw.ThreadListSyncEvent) -> None:\n guild_id = int(data['guild_id'])\n guild: Optional[Guild] = self._get_guild(guild_id)\n if guild is None:\n _log.debug('THREAD_LIST_SYNC referencing an unknown guild ID: %s. Discarding', guild_id)\n return\n\n try:\n channel_ids = {int(i) for i in data['channel_ids']}\n except KeyError:\n # If not provided, then the entire guild is being synced\n # So all previous thread data should be overwritten\n previous_threads = guild._threads.copy()\n guild._clear_threads()\n else:\n previous_threads = guild._filter_threads(channel_ids)\n\n threads = {d['id']: guild._store_thread(d) for d in data.get('threads', [])}\n\n for member in data.get('members', []):\n try:\n # note: member['id'] is the thread_id\n thread = threads[member['id']]\n except KeyError:\n continue\n else:\n thread._add_member(ThreadMember(thread, member))\n\n for thread in threads.values():\n old = previous_threads.pop(thread.id, None)\n if old is None:\n self.dispatch('thread_join', thread)\n\n for thread in previous_threads.values():\n self.dispatch('thread_remove', thread)\n\n def parse_thread_member_update(self, data: gw.ThreadMemberUpdate) -> None:\n guild_id = int(data['guild_id'])\n guild: Optional[Guild] = self._get_guild(guild_id)\n if guild is None:\n _log.debug('THREAD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding', guild_id)\n return\n\n thread_id = int(data['id'])\n thread: Optional[Thread] = guild.get_thread(thread_id)\n if thread is None:\n _log.debug('THREAD_MEMBER_UPDATE referencing an unknown thread ID: %s. Discarding', thread_id)\n return\n\n member = ThreadMember(thread, data)\n thread.me = member\n\n def parse_thread_members_update(self, data: gw.ThreadMembersUpdate) -> None:\n guild_id = int(data['guild_id'])\n guild: Optional[Guild] = self._get_guild(guild_id)\n if guild is None:\n _log.debug('THREAD_MEMBERS_UPDATE referencing an unknown guild ID: %s. Discarding', guild_id)\n return\n\n thread_id = int(data['id'])\n thread: Optional[Thread] = guild.get_thread(thread_id)\n raw = RawThreadMembersUpdate(data)\n if thread is None:\n _log.debug('THREAD_MEMBERS_UPDATE referencing an unknown thread ID: %s. Discarding', thread_id)\n return\n\n added_members = [ThreadMember(thread, d) for d in data.get('added_members', [])]\n removed_member_ids = [int(x) for x in data.get('removed_member_ids', [])]\n self_id = self.self_id\n for member in added_members:\n if member.id != self_id:\n thread._add_member(member)\n self.dispatch('thread_member_join', member)\n else:\n thread.me = member\n self.dispatch('thread_join', thread)\n\n for member_id in removed_member_ids:\n if member_id != self_id:\n member = thread._pop_member(member_id)\n self.dispatch('raw_thread_member_remove', raw)\n if member is not None:\n self.dispatch('thread_member_remove', member)\n else:\n self.dispatch('thread_remove', thread)\n\n def parse_guild_member_add(self, data: gw.GuildMemberAddEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('GUILD_MEMBER_ADD referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n member = Member(guild=guild, data=data, state=self)\n if self.member_cache_flags.joined:\n guild._add_member(member)\n\n if guild._member_count is not None:\n guild._member_count += 1\n\n self.dispatch('member_join', member)\n\n def parse_guild_member_remove(self, data: gw.GuildMemberRemoveEvent) -> None:\n user = self.store_user(data['user'])\n raw = RawMemberRemoveEvent(data, user)\n\n guild = self._get_guild(raw.guild_id)\n if guild is not None:\n if guild._member_count is not None:\n guild._member_count -= 1\n\n member = guild.get_member(user.id)\n if member is not None:\n raw.user = member\n guild._remove_member(member)\n self.dispatch('member_remove', member)\n else:\n _log.debug('GUILD_MEMBER_REMOVE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n\n self.dispatch('raw_member_remove', raw)\n\n def parse_guild_member_update(self, data: gw.GuildMemberUpdateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n user = data['user']\n user_id = int(user['id'])\n if guild is None:\n _log.debug('GUILD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n member = guild.get_member(user_id)\n if member is not None:\n old_member = Member._copy(member)\n member._update(data)\n user_update = member._update_inner_user(user)\n if user_update:\n self.dispatch('user_update', user_update[0], user_update[1])\n\n self.dispatch('member_update', old_member, member)\n else:\n if self.member_cache_flags.joined:\n member = Member(data=data, guild=guild, state=self) # type: ignore # the data is not complete, contains a delta of values\n\n # Force an update on the inner user if necessary\n user_update = member._update_inner_user(user)\n if user_update:\n self.dispatch('user_update', user_update[0], user_update[1])\n\n guild._add_member(member)\n _log.debug('GUILD_MEMBER_UPDATE referencing an unknown member ID: %s. Discarding.', user_id)\n\n def parse_guild_emojis_update(self, data: gw.GuildEmojisUpdateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('GUILD_EMOJIS_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n before_emojis = guild.emojis\n for emoji in before_emojis:\n self._emojis.pop(emoji.id, None)\n # guild won't be None here\n guild.emojis = tuple(map(lambda d: self.store_emoji(guild, d), data['emojis']))\n self.dispatch('guild_emojis_update', guild, before_emojis, guild.emojis)\n\n def parse_guild_stickers_update(self, data: gw.GuildStickersUpdateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('GUILD_STICKERS_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n before_stickers = guild.stickers\n for emoji in before_stickers:\n self._stickers.pop(emoji.id, None)\n\n guild.stickers = tuple(map(lambda d: self.store_sticker(guild, d), data['stickers']))\n self.dispatch('guild_stickers_update', guild, before_stickers, guild.stickers)\n\n def parse_guild_audit_log_entry_create(self, data: gw.GuildAuditLogEntryCreate) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('GUILD_AUDIT_LOG_ENTRY_CREATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n entry = AuditLogEntry(\n users=self._users,\n integrations={},\n app_commands={},\n automod_rules={},\n webhooks={},\n data=data,\n guild=guild,\n )\n\n self.dispatch('audit_log_entry_create', entry)\n\n def parse_auto_moderation_rule_create(self, data: AutoModerationRule) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('AUTO_MODERATION_RULE_CREATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n rule = AutoModRule(data=data, guild=guild, state=self)\n\n self.dispatch('automod_rule_create', rule)\n\n def parse_auto_moderation_rule_update(self, data: AutoModerationRule) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('AUTO_MODERATION_RULE_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n rule = AutoModRule(data=data, guild=guild, state=self)\n\n self.dispatch('automod_rule_update', rule)\n\n def parse_auto_moderation_rule_delete(self, data: AutoModerationRule) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('AUTO_MODERATION_RULE_DELETE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n rule = AutoModRule(data=data, guild=guild, state=self)\n\n self.dispatch('automod_rule_delete', rule)\n\n def parse_auto_moderation_action_execution(self, data: AutoModerationActionExecution) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('AUTO_MODERATION_ACTION_EXECUTION referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n execution = AutoModAction(data=data, state=self)\n\n self.dispatch('automod_action', execution)\n\n def _get_create_guild(self, data: gw.GuildCreateEvent) -> Guild:\n if data.get('unavailable') is False:\n # GUILD_CREATE with unavailable in the response\n # usually means that the guild has become available\n # and is therefore in the cache\n guild = self._get_guild(int(data['id']))\n if guild is not None:\n guild.unavailable = False\n guild._from_data(data)\n return guild\n\n return self._add_guild_from_data(data)\n\n def is_guild_evicted(self, guild: Guild) -> bool:\n return guild.id not in self._guilds\n\n @overload\n async def chunk_guild(self, guild: Guild, *, wait: Literal[True] = ..., cache: Optional[bool] = ...) -> List[Member]:\n ...\n\n @overload\n async def chunk_guild(\n self, guild: Guild, *, wait: Literal[False] = ..., cache: Optional[bool] = ...\n ) -> asyncio.Future[List[Member]]:\n ...\n\n async def chunk_guild(\n self, guild: Guild, *, wait: bool = True, cache: Optional[bool] = None\n ) -> Union[List[Member], asyncio.Future[List[Member]]]:\n cache = cache or self.member_cache_flags.joined\n request = self._chunk_requests.get(guild.id)\n if request is None:\n self._chunk_requests[guild.id] = request = ChunkRequest(guild.id, self.loop, self._get_guild, cache=cache)\n await self.chunker(guild.id, nonce=request.nonce)\n\n if wait:\n return await request.wait()\n return request.get_future()\n\n def _chunk_timeout(self, guild: Guild) -> float:\n return max(5.0, (guild.member_count or 0) / 10000)\n\n async def _chunk_and_dispatch(self, guild, unavailable):\n timeout = self._chunk_timeout(guild)\n\n try:\n await asyncio.wait_for(self.chunk_guild(guild), timeout=timeout)\n except asyncio.TimeoutError:\n _log.warning('Somehow timed out waiting for chunks for guild ID %s.', guild.id)\n\n if unavailable is False:\n self.dispatch('guild_available', guild)\n else:\n self.dispatch('guild_join', guild)\n\n def _add_ready_state(self, guild: Guild) -> bool:\n try:\n # Notify the on_ready state, if any, that this guild is complete.\n self._ready_state.put_nowait(guild)\n except AttributeError:\n return False\n else:\n return True\n\n def parse_guild_create(self, data: gw.GuildCreateEvent) -> None:\n unavailable = data.get('unavailable')\n if unavailable is True:\n # joined a guild with unavailable == True so..\n return\n\n guild = self._get_create_guild(data)\n\n if self._add_ready_state(guild):\n return # We're waiting for the ready event, put the rest on hold\n\n # check if it requires chunking\n if self._guild_needs_chunking(guild):\n asyncio.create_task(self._chunk_and_dispatch(guild, unavailable))\n return\n\n # Dispatch available if newly available\n if unavailable is False:\n self.dispatch('guild_available', guild)\n else:\n self.dispatch('guild_join', guild)\n\n def parse_guild_update(self, data: gw.GuildUpdateEvent) -> None:\n guild = self._get_guild(int(data['id']))\n if guild is not None:\n old_guild = copy.copy(guild)\n guild._from_data(data)\n self.dispatch('guild_update', old_guild, guild)\n else:\n _log.debug('GUILD_UPDATE referencing an unknown guild ID: %s. Discarding.', data['id'])\n\n def parse_guild_delete(self, data: gw.GuildDeleteEvent) -> None:\n guild = self._get_guild(int(data['id']))\n if guild is None:\n _log.debug('GUILD_DELETE referencing an unknown guild ID: %s. Discarding.', data['id'])\n return\n\n if data.get('unavailable', False):\n # GUILD_DELETE with unavailable being True means that the\n # guild that was available is now currently unavailable\n guild.unavailable = True\n self.dispatch('guild_unavailable', guild)\n return\n\n # do a cleanup of the messages cache\n if self._messages is not None:\n self._messages: Optional[Deque[Message]] = deque(\n (msg for msg in self._messages if msg.guild != guild), maxlen=self.max_messages\n )\n\n self._remove_guild(guild)\n self.dispatch('guild_remove', guild)\n\n def parse_guild_ban_add(self, data: gw.GuildBanAddEvent) -> None:\n # we make the assumption that GUILD_BAN_ADD is done\n # before GUILD_MEMBER_REMOVE is called\n # hence we don't remove it from cache or do anything\n # strange with it, the main purpose of this event\n # is mainly to dispatch to another event worth listening to for logging\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n try:\n user = User(data=data['user'], state=self)\n except KeyError:\n pass\n else:\n member = guild.get_member(user.id) or user\n self.dispatch('member_ban', guild, member)\n\n def parse_guild_ban_remove(self, data: gw.GuildBanRemoveEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None and 'user' in data:\n user = self.store_user(data['user'])\n self.dispatch('member_unban', guild, user)\n\n def parse_guild_role_create(self, data: gw.GuildRoleCreateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('GUILD_ROLE_CREATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n role_data = data['role']\n role = Role(guild=guild, data=role_data, state=self)\n guild._add_role(role)\n self.dispatch('guild_role_create', role)\n\n def parse_guild_role_delete(self, data: gw.GuildRoleDeleteEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n role_id = int(data['role_id'])\n try:\n role = guild._remove_role(role_id)\n except KeyError:\n return\n else:\n self.dispatch('guild_role_delete', role)\n else:\n _log.debug('GUILD_ROLE_DELETE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_guild_role_update(self, data: gw.GuildRoleUpdateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n role_data = data['role']\n role_id = int(role_data['id'])\n role = guild.get_role(role_id)\n if role is not None:\n old_role = copy.copy(role)\n role._update(role_data)\n self.dispatch('guild_role_update', old_role, role)\n else:\n _log.debug('GUILD_ROLE_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_guild_members_chunk(self, data: gw.GuildMembersChunkEvent) -> None:\n guild_id = int(data['guild_id'])\n guild = self._get_guild(guild_id)\n presences = data.get('presences', [])\n\n if guild is None:\n return\n\n members = [Member(guild=guild, data=member, state=self) for member in data.get('members', [])]\n _log.debug('Processed a chunk for %s members in guild ID %s.', len(members), guild_id)\n\n if presences:\n member_dict: Dict[Snowflake, Member] = {str(member.id): member for member in members}\n for presence in presences:\n user = presence['user']\n member_id = user['id']\n member = member_dict.get(member_id)\n if member is not None:\n member._presence_update(presence, user)\n\n complete = data.get('chunk_index', 0) + 1 == data.get('chunk_count')\n self.process_chunk_requests(guild_id, data.get('nonce'), members, complete)\n\n def parse_guild_integrations_update(self, data: gw.GuildIntegrationsUpdateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n self.dispatch('guild_integrations_update', guild)\n else:\n _log.debug('GUILD_INTEGRATIONS_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_integration_create(self, data: gw.IntegrationCreateEvent) -> None:\n guild_id = int(data['guild_id'])\n guild = self._get_guild(guild_id)\n if guild is not None:\n cls, _ = _integration_factory(data['type'])\n integration = cls(data=data, guild=guild)\n self.dispatch('integration_create', integration)\n else:\n _log.debug('INTEGRATION_CREATE referencing an unknown guild ID: %s. Discarding.', guild_id)\n\n def parse_integration_update(self, data: gw.IntegrationUpdateEvent) -> None:\n guild_id = int(data['guild_id'])\n guild = self._get_guild(guild_id)\n if guild is not None:\n cls, _ = _integration_factory(data['type'])\n integration = cls(data=data, guild=guild)\n self.dispatch('integration_update', integration)\n else:\n _log.debug('INTEGRATION_UPDATE referencing an unknown guild ID: %s. Discarding.', guild_id)\n\n def parse_integration_delete(self, data: gw.IntegrationDeleteEvent) -> None:\n guild_id = int(data['guild_id'])\n guild = self._get_guild(guild_id)\n if guild is not None:\n raw = RawIntegrationDeleteEvent(data)\n self.dispatch('raw_integration_delete', raw)\n else:\n _log.debug('INTEGRATION_DELETE referencing an unknown guild ID: %s. Discarding.', guild_id)\n\n def parse_webhooks_update(self, data: gw.WebhooksUpdateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('WEBHOOKS_UPDATE referencing an unknown guild ID: %s. Discarding', data['guild_id'])\n return\n\n channel_id = utils._get_as_snowflake(data, 'channel_id')\n channel = guild.get_channel(channel_id) # type: ignore # None is okay here\n if channel is not None:\n self.dispatch('webhooks_update', channel)\n else:\n _log.debug('WEBHOOKS_UPDATE referencing an unknown channel ID: %s. Discarding.', data['channel_id'])\n\n def parse_stage_instance_create(self, data: gw.StageInstanceCreateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n stage_instance = StageInstance(guild=guild, state=self, data=data)\n guild._stage_instances[stage_instance.id] = stage_instance\n self.dispatch('stage_instance_create', stage_instance)\n else:\n _log.debug('STAGE_INSTANCE_CREATE referencing unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_stage_instance_update(self, data: gw.StageInstanceUpdateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n stage_instance = guild._stage_instances.get(int(data['id']))\n if stage_instance is not None:\n old_stage_instance = copy.copy(stage_instance)\n stage_instance._update(data)\n self.dispatch('stage_instance_update', old_stage_instance, stage_instance)\n else:\n _log.debug('STAGE_INSTANCE_UPDATE referencing unknown stage instance ID: %s. Discarding.', data['id'])\n else:\n _log.debug('STAGE_INSTANCE_UPDATE referencing unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_stage_instance_delete(self, data: gw.StageInstanceDeleteEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n try:\n stage_instance = guild._stage_instances.pop(int(data['id']))\n except KeyError:\n pass\n else:\n self.dispatch('stage_instance_delete', stage_instance)\n else:\n _log.debug('STAGE_INSTANCE_DELETE referencing unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_guild_scheduled_event_create(self, data: gw.GuildScheduledEventCreateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n scheduled_event = ScheduledEvent(state=self, data=data)\n guild._scheduled_events[scheduled_event.id] = scheduled_event\n self.dispatch('scheduled_event_create', scheduled_event)\n else:\n _log.debug('SCHEDULED_EVENT_CREATE referencing unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_guild_scheduled_event_update(self, data: gw.GuildScheduledEventUpdateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n scheduled_event = guild._scheduled_events.get(int(data['id']))\n if scheduled_event is not None:\n old_scheduled_event = copy.copy(scheduled_event)\n scheduled_event._update(data)\n self.dispatch('scheduled_event_update', old_scheduled_event, scheduled_event)\n else:\n _log.debug('SCHEDULED_EVENT_UPDATE referencing unknown scheduled event ID: %s. Discarding.', data['id'])\n else:\n _log.debug('SCHEDULED_EVENT_UPDATE referencing unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_guild_scheduled_event_delete(self, data: gw.GuildScheduledEventDeleteEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n try:\n scheduled_event = guild._scheduled_events.pop(int(data['id']))\n except KeyError:\n pass\n else:\n self.dispatch('scheduled_event_delete', scheduled_event)\n else:\n _log.debug('SCHEDULED_EVENT_DELETE referencing unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_guild_scheduled_event_user_add(self, data: gw.GuildScheduledEventUserAdd) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n scheduled_event = guild._scheduled_events.get(int(data['guild_scheduled_event_id']))\n if scheduled_event is not None:\n user = self.get_user(int(data['user_id']))\n if user is not None:\n scheduled_event._add_user(user)\n self.dispatch('scheduled_event_user_add', scheduled_event, user)\n else:\n _log.debug('SCHEDULED_EVENT_USER_ADD referencing unknown user ID: %s. Discarding.', data['user_id'])\n else:\n _log.debug(\n 'SCHEDULED_EVENT_USER_ADD referencing unknown scheduled event ID: %s. Discarding.',\n data['guild_scheduled_event_id'],\n )\n else:\n _log.debug('SCHEDULED_EVENT_USER_ADD referencing unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_guild_scheduled_event_user_remove(self, data: gw.GuildScheduledEventUserRemove) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n scheduled_event = guild._scheduled_events.get(int(data['guild_scheduled_event_id']))\n if scheduled_event is not None:\n user = self.get_user(int(data['user_id']))\n if user is not None:\n scheduled_event._pop_user(user.id)\n self.dispatch('scheduled_event_user_remove', scheduled_event, user)\n else:\n _log.debug('SCHEDULED_EVENT_USER_REMOVE referencing unknown user ID: %s. Discarding.', data['user_id'])\n else:\n _log.debug(\n 'SCHEDULED_EVENT_USER_REMOVE referencing unknown scheduled event ID: %s. Discarding.',\n data['guild_scheduled_event_id'],\n )\n else:\n _log.debug('SCHEDULED_EVENT_USER_REMOVE referencing unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_application_command_permissions_update(self, data: GuildApplicationCommandPermissionsPayload):\n raw = RawAppCommandPermissionsUpdateEvent(data=data, state=self)\n self.dispatch('raw_app_command_permissions_update', raw)\n\n def parse_voice_state_update(self, data: gw.VoiceStateUpdateEvent) -> None:\n guild = self._get_guild(utils._get_as_snowflake(data, 'guild_id'))\n channel_id = utils._get_as_snowflake(data, 'channel_id')\n flags = self.member_cache_flags\n # self.user is *always* cached when this is called\n self_id = self.user.id # type: ignore\n if guild is not None:\n if int(data['user_id']) == self_id:\n voice = self._get_voice_client(guild.id)\n if voice is not None:\n coro = voice.on_voice_state_update(data)\n asyncio.create_task(logging_coroutine(coro, info='Voice Protocol voice state update handler'))\n\n member, before, after = guild._update_voice_state(data, channel_id) # type: ignore\n if member is not None:\n if flags.voice:\n if channel_id is None and flags._voice_only and member.id != self_id:\n # Only remove from cache if we only have the voice flag enabled\n guild._remove_member(member)\n elif channel_id is not None:\n guild._add_member(member)\n\n self.dispatch('voice_state_update', member, before, after)\n else:\n _log.debug('VOICE_STATE_UPDATE referencing an unknown member ID: %s. Discarding.', data['user_id'])\n\n def parse_voice_server_update(self, data: gw.VoiceServerUpdateEvent) -> None:\n key_id = int(data['guild_id'])\n\n vc = self._get_voice_client(key_id)\n if vc is not None:\n coro = vc.on_voice_server_update(data)\n asyncio.create_task(logging_coroutine(coro, info='Voice Protocol voice server update handler'))\n\n def parse_typing_start(self, data: gw.TypingStartEvent) -> None:\n raw = RawTypingEvent(data)\n raw.user = self.get_user(raw.user_id)\n channel, guild = self._get_guild_channel(data)\n\n if channel is not None:\n if isinstance(channel, DMChannel):\n channel.recipient = raw.user\n elif guild is not None:\n raw.user = guild.get_member(raw.user_id)\n\n if raw.user is None:\n member_data = data.get('member')\n if member_data:\n raw.user = Member(data=member_data, state=self, guild=guild)\n\n if raw.user is not None:\n self.dispatch('typing', channel, raw.user, raw.timestamp)\n\n self.dispatch('raw_typing', raw)\n\n def parse_entitlement_create(self, data: gw.EntitlementCreateEvent) -> None:\n entitlement = Entitlement(data=data, state=self)\n self.dispatch('entitlement_create', entitlement)\n\n def parse_entitlement_update(self, data: gw.EntitlementUpdateEvent) -> None:\n entitlement = Entitlement(data=data, state=self)\n self.dispatch('entitlement_update', entitlement)\n\n def parse_entitlement_delete(self, data: gw.EntitlementDeleteEvent) -> None:\n entitlement = Entitlement(data=data, state=self)\n self.dispatch('entitlement_update', entitlement)\n\n def _get_reaction_user(self, channel: MessageableChannel, user_id: int) -> Optional[Union[User, Member]]:\n if isinstance(channel, (TextChannel, Thread, VoiceChannel)):\n return channel.guild.get_member(user_id)\n return self.get_user(user_id)\n\n def get_reaction_emoji(self, data: PartialEmojiPayload) -> Union[Emoji, PartialEmoji, str]:\n emoji_id = utils._get_as_snowflake(data, 'id')\n\n if not emoji_id:\n # the name key will be a str\n return data['name'] # type: ignore\n\n try:\n return self._emojis[emoji_id]\n except KeyError:\n return PartialEmoji.with_state(\n self, animated=data.get('animated', False), id=emoji_id, name=data['name'] # type: ignore\n )\n\n def _upgrade_partial_emoji(self, emoji: PartialEmoji) -> Union[Emoji, PartialEmoji, str]:\n emoji_id = emoji.id\n if not emoji_id:\n return emoji.name\n try:\n return self._emojis[emoji_id]\n except KeyError:\n return emoji\n\n def get_channel(self, id: Optional[int]) -> Optional[Union[Channel, Thread]]:\n if id is None:\n return None\n\n pm = self._get_private_channel(id)\n if pm is not None:\n return pm\n\n for guild in self.guilds:\n channel = guild._resolve_channel(id)\n if channel is not None:\n return channel\n\n def create_message(self, *, channel: MessageableChannel, data: MessagePayload) -> Message:\n return Message(state=self, channel=channel, data=data)\n\n\nclass AutoShardedConnectionState(ConnectionState[ClientT]):\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n super().__init__(*args, **kwargs)\n\n self.shard_ids: Union[List[int], range] = []\n\n self._ready_tasks: Dict[int, asyncio.Task[None]] = {}\n self._ready_states: Dict[int, asyncio.Queue[Guild]] = {}\n\n def _update_message_references(self) -> None:\n # self._messages won't be None when this is called\n for msg in self._messages: # type: ignore\n if not msg.guild:\n continue\n\n new_guild = self._get_guild(msg.guild.id)\n if new_guild is not None and new_guild is not msg.guild:\n channel_id = msg.channel.id\n channel = new_guild._resolve_channel(channel_id) or PartialMessageable(\n state=self, id=channel_id, guild_id=new_guild.id\n )\n msg._rebind_cached_references(new_guild, channel)\n\n async def chunker(\n self,\n guild_id: int,\n query: str = '',\n limit: int = 0,\n presences: bool = False,\n *,\n shard_id: Optional[int] = None,\n nonce: Optional[str] = None,\n ) -> None:\n ws = self._get_websocket(guild_id, shard_id=shard_id)\n await ws.request_chunks(guild_id, query=query, limit=limit, presences=presences, nonce=nonce)\n\n def _add_ready_state(self, guild: Guild) -> bool:\n try:\n # Notify the on_ready state, if any, that this guild is complete.\n self._ready_states[guild.shard_id].put_nowait(guild)\n except KeyError:\n return False\n else:\n return True\n\n async def _delay_ready(self) -> None:\n await asyncio.gather(*self._ready_tasks.values())\n\n # clear the current tasks\n self._ready_task = None\n self._ready_tasks = {}\n\n # dispatch the event\n self.call_handlers('ready')\n self.dispatch('ready')\n\n async def _delay_shard_ready(self, shard_id: int) -> None:\n try:\n states = []\n while True:\n # this snippet of code is basically waiting N seconds\n # until the last GUILD_CREATE was sent\n try:\n guild = await asyncio.wait_for(self._ready_states[shard_id].get(), timeout=self.guild_ready_timeout)\n except asyncio.TimeoutError:\n break\n else:\n if self._guild_needs_chunking(guild):\n future = await self.chunk_guild(guild, wait=False)\n states.append((guild, future))\n else:\n if guild.unavailable is False:\n self.dispatch('guild_available', guild)\n else:\n self.dispatch('guild_join', guild)\n\n for guild, future in states:\n timeout = self._chunk_timeout(guild)\n\n try:\n await asyncio.wait_for(future, timeout=timeout)\n except asyncio.TimeoutError:\n _log.warning('Shard ID %s timed out waiting for chunks for guild_id %s.', guild.shard_id, guild.id)\n\n if guild.unavailable is False:\n self.dispatch('guild_available', guild)\n else:\n self.dispatch('guild_join', guild)\n\n # remove the state\n try:\n del self._ready_states[shard_id]\n except KeyError:\n pass # already been deleted somehow\n\n except asyncio.CancelledError:\n pass\n else:\n # dispatch the event\n self.dispatch('shard_ready', shard_id)\n\n def parse_ready(self, data: gw.ReadyEvent) -> None:\n if self._ready_task is not None:\n self._ready_task.cancel()\n\n shard_id = data['shard'][0] # shard_id, num_shards\n\n if shard_id in self._ready_tasks:\n self._ready_tasks[shard_id].cancel()\n\n if shard_id not in self._ready_states:\n self._ready_states[shard_id] = asyncio.Queue()\n\n self.user: Optional[ClientUser]\n self.user = user = ClientUser(state=self, data=data['user'])\n # self._users is a list of Users, we're setting a ClientUser\n self._users[user.id] = user # type: ignore\n\n if self.application_id is None:\n try:\n application = data['application']\n except KeyError:\n pass\n else:\n self.application_id: Optional[int] = utils._get_as_snowflake(application, 'id')\n self.application_flags: ApplicationFlags = ApplicationFlags._from_value(application['flags'])\n\n for guild_data in data['guilds']:\n self._add_guild_from_data(guild_data) # type: ignore # _add_guild_from_data requires a complete Guild payload\n\n if self._messages:\n self._update_message_references()\n\n self.dispatch('connect')\n self.dispatch('shard_connect', shard_id)\n\n self._ready_tasks[shard_id] = asyncio.create_task(self._delay_shard_ready(shard_id))\n\n # The delay task for every shard has been started\n if len(self._ready_tasks) == len(self.shard_ids):\n self._ready_task = asyncio.create_task(self._delay_ready())\n\n def parse_resumed(self, data: gw.ResumedEvent) -> None:\n self.dispatch('resumed')\n self.dispatch('shard_resumed', data['__shard_id__']) # type: ignore # This is an internal discord.py key\n" } ], "language": "python" }, { "id": "10_3", "repo_url": "https://github.com/teamqurrent/discord.py", "instruction": "Enhance the `HTTPClient` class in `http.py` to allow editing various application details via Discord's API. Implement the `edit_application_info` method to send a PATCH request to the /applications/@me endpoint. This method should accept reason and payload, filter the payload for specific valid keys like 'custom_install_url', 'description', etc., and use self.request to send the PATCH request with the filtered payload and reason. Ensure the method returns the response from the API call.", "base_commit": "9810cb9", "test_script": "import unittest\nimport asyncio\nimport sys\n\n\n\nclass TestEditApplicationInfo(unittest.TestCase):\n def setUp(self):\n from discord.http import HTTPClient\n from unittest.mock import MagicMock\n self.loop = asyncio.new_event_loop()\n asyncio.set_event_loop(self.loop)\n self.http_client = HTTPClient(loop=self.loop)\n self.http_client.request = MagicMock()\n\n def test_edit_application_info(self):\n from unittest.mock import ANY\n payload = {\n 'custom_install_url': 'https://example.com',\n 'description': 'Test Description',\n }\n self.http_client.edit_application_info(reason='Test Reason', payload=payload)\n\n # Use ANY to match any Route object\n self.http_client.request.assert_called_with(\n ANY, json=payload, reason='Test Reason'\n )\n\n def tearDown(self):\n self.loop.close()\n\ndef main():\n\n\n suite = unittest.TestSuite()\n suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestEditApplicationInfo))\n runner = unittest.TextTestRunner()\n\n if runner.run(suite).wasSuccessful():\n sys.exit(0)\n else:\n sys.exit(1)\n\nif __name__ == '__main__':\n\n main()\n", "testbed_environment": "python3.9", "requirements_txt": "discord", "solution_commit": "56c67d39", "solution_patch": "diff --git a/discord/appinfo.py b/discord/appinfo.py\n--- a/discord/appinfo.py\n+++ b/discord/appinfo.py\n@@ -30,8 +30,11 @@ from . import utils\n from .asset import Asset\n from .flags import ApplicationFlags\n from .permissions import Permissions\n+from .utils import MISSING\n \n if TYPE_CHECKING:\n+ from typing import Dict, Any\n+\n from .guild import Guild\n from .types.appinfo import (\n AppInfo as AppInfoPayload,\n@@ -131,6 +134,15 @@ class AppInfo:\n a verification method in the guild's role verification configuration.\n \n .. versionadded:: 2.2\n+ interactions_endpoint_url: Optional[:class:`str`]\n+ The interactions endpoint url of the application to receive interactions over this endpoint rather than\n+ over the gateway, if configured.\n+\n+ .. versionadded:: 2.4\n+ redirect_uris: List[:class:`str`]\n+ A list of authentication redirect URIs.\n+\n+ .. versionadded:: 2.4\n \"\"\"\n \n __slots__ = (\n@@ -156,6 +168,8 @@ class AppInfo:\n 'custom_install_url',\n 'install_params',\n 'role_connections_verification_url',\n+ 'interactions_endpoint_url',\n+ 'redirect_uris',\n )\n \n def __init__(self, state: ConnectionState, data: AppInfoPayload):\n@@ -190,6 +204,8 @@ class AppInfo:\n \n params = data.get('install_params')\n self.install_params: Optional[AppInstallParams] = AppInstallParams(params) if params else None\n+ self.interactions_endpoint_url: Optional[str] = data.get('interactions_endpoint_url')\n+ self.redirect_uris: List[str] = data.get('redirect_uris', [])\n \n def __repr__(self) -> str:\n return (\n@@ -232,6 +248,138 @@ class AppInfo:\n \"\"\"\n return ApplicationFlags._from_value(self._flags)\n \n+ async def edit(\n+ self,\n+ *,\n+ reason: Optional[str] = MISSING,\n+ custom_install_url: Optional[str] = MISSING,\n+ description: Optional[str] = MISSING,\n+ role_connections_verification_url: Optional[str] = MISSING,\n+ install_params_scopes: Optional[List[str]] = MISSING,\n+ install_params_permissions: Optional[Permissions] = MISSING,\n+ flags: Optional[ApplicationFlags] = MISSING,\n+ icon: Optional[bytes] = MISSING,\n+ cover_image: Optional[bytes] = MISSING,\n+ interactions_endpoint_url: Optional[str] = MISSING,\n+ tags: Optional[List[str]] = MISSING,\n+ ) -> AppInfo:\n+ r\"\"\"|coro|\n+\n+ Edits the application info.\n+\n+ .. versionadded:: 2.4\n+\n+ Parameters\n+ ----------\n+ custom_install_url: Optional[:class:`str`]\n+ The new custom authorization URL for the application. Can be ``None`` to remove the URL.\n+ description: Optional[:class:`str`]\n+ The new application description. Can be ``None`` to remove the description.\n+ role_connections_verification_url: Optional[:class:`str`]\n+ The new application\u2019s connection verification URL which will render the application\n+ as a verification method in the guild\u2019s role verification configuration. Can be ``None`` to remove the URL.\n+ install_params_scopes: Optional[List[:class:`str`]]\n+ The new list of :ddocs:`OAuth2 scopes ` of\n+ the :attr:`~install_params`. Can be ``None`` to remove the scopes.\n+ install_params_permissions: Optional[:class:`Permissions`]\n+ The new permissions of the :attr:`~install_params`. Can be ``None`` to remove the permissions.\n+ flags: Optional[:class:`ApplicationFlags`]\n+ The new application\u2019s flags. Only limited intent flags (:attr:`~ApplicationFlags.gateway_presence_limited`,\n+ :attr:`~ApplicationFlags.gateway_guild_members_limited`, :attr:`~ApplicationFlags.gateway_message_content_limited`)\n+ can be edited. Can be ``None`` to remove the flags.\n+\n+ .. warning::\n+\n+ Editing the limited intent flags leads to the termination of the bot.\n+\n+ icon: Optional[:class:`bytes`]\n+ The new application\u2019s icon as a :term:`py:bytes-like object`. Can be ``None`` to remove the icon.\n+ cover_image: Optional[:class:`bytes`]\n+ The new application\u2019s cover image as a :term:`py:bytes-like object` on a store embed.\n+ The cover image is only available if the application is a game sold on Discord.\n+ Can be ``None`` to remove the image.\n+ interactions_endpoint_url: Optional[:class:`str`]\n+ The new interactions endpoint url of the application to receive interactions over this endpoint rather than\n+ over the gateway. Can be ``None`` to remove the URL.\n+ tags: Optional[List[:class:`str`]]\n+ The new list of tags describing the functionality of the application. Can be ``None`` to remove the tags.\n+ reason: Optional[:class:`str`]\n+ The reason for editing the application. Shows up on the audit log.\n+\n+ Raises\n+ -------\n+ HTTPException\n+ Editing the application failed\n+ ValueError\n+ The image format passed in to ``icon`` or ``cover_image`` is invalid. This is also raised\n+ when ``install_params_scopes`` and ``install_params_permissions`` are incompatible with each other.\n+\n+ Returns\n+ -------\n+ :class:`AppInfo`\n+ The newly updated application info.\n+ \"\"\"\n+ payload: Dict[str, Any] = {}\n+\n+ if custom_install_url is not MISSING:\n+ payload['custom_install_url'] = custom_install_url\n+\n+ if description is not MISSING:\n+ payload['description'] = description\n+\n+ if role_connections_verification_url is not MISSING:\n+ payload['role_connections_verification_url'] = role_connections_verification_url\n+\n+ if install_params_scopes is not MISSING:\n+ install_params: Optional[Dict[str, Any]] = {}\n+ if install_params_scopes is None:\n+ install_params = None\n+ else:\n+ if \"bot\" not in install_params_scopes and install_params_permissions is not MISSING:\n+ raise ValueError(\"'bot' must be in install_params_scopes if install_params_permissions is set\")\n+\n+ install_params['scopes'] = install_params_scopes\n+\n+ if install_params_permissions is MISSING:\n+ install_params['permissions'] = 0\n+ else:\n+ if install_params_permissions is None:\n+ install_params['permissions'] = 0\n+ else:\n+ install_params['permissions'] = install_params_permissions.value\n+\n+ payload['install_params'] = install_params\n+\n+ else:\n+ if install_params_permissions is not MISSING:\n+ raise ValueError(\"install_params_scopes must be set if install_params_permissions is set\")\n+\n+ if flags is not MISSING:\n+ if flags is None:\n+ payload['flags'] = flags\n+ else:\n+ payload['flags'] = flags.value\n+\n+ if icon is not MISSING:\n+ if icon is None:\n+ payload['icon'] = icon\n+ else:\n+ payload['icon'] = utils._bytes_to_base64_data(icon)\n+\n+ if cover_image is not MISSING:\n+ if cover_image is None:\n+ payload['cover_image'] = cover_image\n+ else:\n+ payload['cover_image'] = utils._bytes_to_base64_data(cover_image)\n+\n+ if interactions_endpoint_url is not MISSING:\n+ payload['interactions_endpoint_url'] = interactions_endpoint_url\n+\n+ if tags is not MISSING:\n+ payload['tags'] = tags\n+ data = await self._state.http.edit_application_info(reason=reason, payload=payload)\n+ return AppInfo(data=data, state=self._state)\n+\n \n class PartialAppInfo:\n \"\"\"Represents a partial AppInfo given by :func:`~discord.abc.GuildChannel.create_invite`\ndiff --git a/discord/http.py b/discord/http.py\n--- a/discord/http.py\n+++ b/discord/http.py\n@@ -2456,6 +2456,22 @@ class HTTPClient:\n def application_info(self) -> Response[appinfo.AppInfo]:\n return self.request(Route('GET', '/oauth2/applications/@me'))\n \n+ def edit_application_info(self, *, reason: Optional[str], payload: Any) -> Response[appinfo.AppInfo]:\n+ valid_keys = (\n+ 'custom_install_url',\n+ 'description',\n+ 'role_connections_verification_url',\n+ 'install_params',\n+ 'flags',\n+ 'icon',\n+ 'cover_image',\n+ 'interactions_endpoint_url ',\n+ 'tags',\n+ )\n+\n+ payload = {k: v for k, v in payload.items() if k in valid_keys}\n+ return self.request(Route('PATCH', '/applications/@me'), json=payload, reason=reason)\n+\n async def get_gateway(self, *, encoding: str = 'json', zlib: bool = True) -> str:\n try:\n data = await self.request(Route('GET', '/gateway'))\ndiff --git a/discord/types/appinfo.py b/discord/types/appinfo.py\n--- a/discord/types/appinfo.py\n+++ b/discord/types/appinfo.py\n@@ -49,6 +49,9 @@ class BaseAppInfo(TypedDict):\n terms_of_service_url: NotRequired[str]\n privacy_policy_url: NotRequired[str]\n rpc_origins: NotRequired[List[str]]\n+ interactions_endpoint_url: NotRequired[Optional[str]]\n+ redirect_uris: NotRequired[List[str]]\n+ role_connections_verification_url: NotRequired[Optional[str]]\n \n \n class AppInfo(BaseAppInfo):\n@@ -64,16 +67,12 @@ class AppInfo(BaseAppInfo):\n tags: NotRequired[List[str]]\n install_params: NotRequired[InstallParams]\n custom_install_url: NotRequired[str]\n- role_connections_verification_url: NotRequired[str]\n \n \n class PartialAppInfo(BaseAppInfo, total=False):\n hook: bool\n max_participants: int\n approximate_guild_count: int\n- redirect_uris: List[str]\n- interactions_endpoint_url: Optional[str]\n- role_connections_verification_url: Optional[str]\n \n \n class GatewayAppInfo(TypedDict):\n", "modified_files": [ { "path": "discord/appinfo.py", "content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import List, TYPE_CHECKING, Optional\n\nfrom . import utils\nfrom .asset import Asset\nfrom .flags import ApplicationFlags\nfrom .permissions import Permissions\n\nif TYPE_CHECKING:\n from .guild import Guild\n from .types.appinfo import (\n AppInfo as AppInfoPayload,\n PartialAppInfo as PartialAppInfoPayload,\n Team as TeamPayload,\n InstallParams as InstallParamsPayload,\n )\n from .user import User\n from .state import ConnectionState\n\n__all__ = (\n 'AppInfo',\n 'PartialAppInfo',\n 'AppInstallParams',\n)\n\n\nclass AppInfo:\n \"\"\"Represents the application info for the bot provided by Discord.\n\n\n Attributes\n -------------\n id: :class:`int`\n The application ID.\n name: :class:`str`\n The application name.\n owner: :class:`User`\n The application owner.\n team: Optional[:class:`Team`]\n The application's team.\n\n .. versionadded:: 1.3\n\n description: :class:`str`\n The application description.\n bot_public: :class:`bool`\n Whether the bot can be invited by anyone or if it is locked\n to the application owner.\n bot_require_code_grant: :class:`bool`\n Whether the bot requires the completion of the full oauth2 code\n grant flow to join.\n rpc_origins: Optional[List[:class:`str`]]\n A list of RPC origin URLs, if RPC is enabled.\n\n verify_key: :class:`str`\n The hex encoded key for verification in interactions and the\n GameSDK's :ddocs:`GetTicket `.\n\n .. versionadded:: 1.3\n\n guild_id: Optional[:class:`int`]\n If this application is a game sold on Discord,\n this field will be the guild to which it has been linked to.\n\n .. versionadded:: 1.3\n\n primary_sku_id: Optional[:class:`int`]\n If this application is a game sold on Discord,\n this field will be the id of the \"Game SKU\" that is created,\n if it exists.\n\n .. versionadded:: 1.3\n\n slug: Optional[:class:`str`]\n If this application is a game sold on Discord,\n this field will be the URL slug that links to the store page.\n\n .. versionadded:: 1.3\n\n terms_of_service_url: Optional[:class:`str`]\n The application's terms of service URL, if set.\n\n .. versionadded:: 2.0\n\n privacy_policy_url: Optional[:class:`str`]\n The application's privacy policy URL, if set.\n\n .. versionadded:: 2.0\n\n tags: List[:class:`str`]\n The list of tags describing the functionality of the application.\n\n .. versionadded:: 2.0\n\n custom_install_url: List[:class:`str`]\n The custom authorization URL for the application, if enabled.\n\n .. versionadded:: 2.0\n\n install_params: Optional[:class:`AppInstallParams`]\n The settings for custom authorization URL of application, if enabled.\n\n .. versionadded:: 2.0\n role_connections_verification_url: Optional[:class:`str`]\n The application's connection verification URL which will render the application as\n a verification method in the guild's role verification configuration.\n\n .. versionadded:: 2.2\n \"\"\"\n\n __slots__ = (\n '_state',\n 'description',\n 'id',\n 'name',\n 'rpc_origins',\n 'bot_public',\n 'bot_require_code_grant',\n 'owner',\n '_icon',\n 'verify_key',\n 'team',\n 'guild_id',\n 'primary_sku_id',\n 'slug',\n '_cover_image',\n '_flags',\n 'terms_of_service_url',\n 'privacy_policy_url',\n 'tags',\n 'custom_install_url',\n 'install_params',\n 'role_connections_verification_url',\n )\n\n def __init__(self, state: ConnectionState, data: AppInfoPayload):\n from .team import Team\n\n self._state: ConnectionState = state\n self.id: int = int(data['id'])\n self.name: str = data['name']\n self.description: str = data['description']\n self._icon: Optional[str] = data['icon']\n self.rpc_origins: Optional[List[str]] = data.get('rpc_origins')\n self.bot_public: bool = data['bot_public']\n self.bot_require_code_grant: bool = data['bot_require_code_grant']\n self.owner: User = state.create_user(data['owner'])\n\n team: Optional[TeamPayload] = data.get('team')\n self.team: Optional[Team] = Team(state, team) if team else None\n\n self.verify_key: str = data['verify_key']\n\n self.guild_id: Optional[int] = utils._get_as_snowflake(data, 'guild_id')\n\n self.primary_sku_id: Optional[int] = utils._get_as_snowflake(data, 'primary_sku_id')\n self.slug: Optional[str] = data.get('slug')\n self._flags: int = data.get('flags', 0)\n self._cover_image: Optional[str] = data.get('cover_image')\n self.terms_of_service_url: Optional[str] = data.get('terms_of_service_url')\n self.privacy_policy_url: Optional[str] = data.get('privacy_policy_url')\n self.tags: List[str] = data.get('tags', [])\n self.custom_install_url: Optional[str] = data.get('custom_install_url')\n self.role_connections_verification_url: Optional[str] = data.get('role_connections_verification_url')\n\n params = data.get('install_params')\n self.install_params: Optional[AppInstallParams] = AppInstallParams(params) if params else None\n\n def __repr__(self) -> str:\n return (\n f'<{self.__class__.__name__} id={self.id} name={self.name!r} '\n f'description={self.description!r} public={self.bot_public} '\n f'owner={self.owner!r}>'\n )\n\n @property\n def icon(self) -> Optional[Asset]:\n \"\"\"Optional[:class:`.Asset`]: Retrieves the application's icon asset, if any.\"\"\"\n if self._icon is None:\n return None\n return Asset._from_icon(self._state, self.id, self._icon, path='app')\n\n @property\n def cover_image(self) -> Optional[Asset]:\n \"\"\"Optional[:class:`.Asset`]: Retrieves the cover image on a store embed, if any.\n\n This is only available if the application is a game sold on Discord.\n \"\"\"\n if self._cover_image is None:\n return None\n return Asset._from_cover_image(self._state, self.id, self._cover_image)\n\n @property\n def guild(self) -> Optional[Guild]:\n \"\"\"Optional[:class:`Guild`]: If this application is a game sold on Discord,\n this field will be the guild to which it has been linked\n\n .. versionadded:: 1.3\n \"\"\"\n return self._state._get_guild(self.guild_id)\n\n @property\n def flags(self) -> ApplicationFlags:\n \"\"\":class:`ApplicationFlags`: The application's flags.\n\n .. versionadded:: 2.0\n \"\"\"\n return ApplicationFlags._from_value(self._flags)\n\n\nclass PartialAppInfo:\n \"\"\"Represents a partial AppInfo given by :func:`~discord.abc.GuildChannel.create_invite`\n\n .. versionadded:: 2.0\n\n Attributes\n -------------\n id: :class:`int`\n The application ID.\n name: :class:`str`\n The application name.\n description: :class:`str`\n The application description.\n rpc_origins: Optional[List[:class:`str`]]\n A list of RPC origin URLs, if RPC is enabled.\n verify_key: :class:`str`\n The hex encoded key for verification in interactions and the\n GameSDK's :ddocs:`GetTicket `.\n terms_of_service_url: Optional[:class:`str`]\n The application's terms of service URL, if set.\n privacy_policy_url: Optional[:class:`str`]\n The application's privacy policy URL, if set.\n approximate_guild_count: :class:`int`\n The approximate count of the guilds the bot was added to.\n\n .. versionadded:: 2.3\n redirect_uris: List[:class:`str`]\n A list of authentication redirect URIs.\n\n .. versionadded:: 2.3\n interactions_endpoint_url: Optional[:class:`str`]\n The interactions endpoint url of the application to receive interactions over this endpoint rather than\n over the gateway, if configured.\n\n .. versionadded:: 2.3\n role_connections_verification_url: Optional[:class:`str`]\n The application's connection verification URL which will render the application as\n a verification method in the guild's role verification configuration.\n\n .. versionadded:: 2.3\n \"\"\"\n\n __slots__ = (\n '_state',\n 'id',\n 'name',\n 'description',\n 'rpc_origins',\n 'verify_key',\n 'terms_of_service_url',\n 'privacy_policy_url',\n '_icon',\n '_flags',\n '_cover_image',\n 'approximate_guild_count',\n 'redirect_uris',\n 'interactions_endpoint_url',\n 'role_connections_verification_url',\n )\n\n def __init__(self, *, state: ConnectionState, data: PartialAppInfoPayload):\n self._state: ConnectionState = state\n self.id: int = int(data['id'])\n self.name: str = data['name']\n self._icon: Optional[str] = data.get('icon')\n self._flags: int = data.get('flags', 0)\n self._cover_image: Optional[str] = data.get('cover_image')\n self.description: str = data['description']\n self.rpc_origins: Optional[List[str]] = data.get('rpc_origins')\n self.verify_key: str = data['verify_key']\n self.terms_of_service_url: Optional[str] = data.get('terms_of_service_url')\n self.privacy_policy_url: Optional[str] = data.get('privacy_policy_url')\n self.approximate_guild_count: int = data.get('approximate_guild_count', 0)\n self.redirect_uris: List[str] = data.get('redirect_uris', [])\n self.interactions_endpoint_url: Optional[str] = data.get('interactions_endpoint_url')\n self.role_connections_verification_url: Optional[str] = data.get('role_connections_verification_url')\n\n def __repr__(self) -> str:\n return f'<{self.__class__.__name__} id={self.id} name={self.name!r} description={self.description!r}>'\n\n @property\n def icon(self) -> Optional[Asset]:\n \"\"\"Optional[:class:`.Asset`]: Retrieves the application's icon asset, if any.\"\"\"\n if self._icon is None:\n return None\n return Asset._from_icon(self._state, self.id, self._icon, path='app')\n\n @property\n def cover_image(self) -> Optional[Asset]:\n \"\"\"Optional[:class:`.Asset`]: Retrieves the cover image of the application's default rich presence.\n\n This is only available if the application is a game sold on Discord.\n\n .. versionadded:: 2.3\n \"\"\"\n if self._cover_image is None:\n return None\n return Asset._from_cover_image(self._state, self.id, self._cover_image)\n\n @property\n def flags(self) -> ApplicationFlags:\n \"\"\":class:`ApplicationFlags`: The application's flags.\n\n .. versionadded:: 2.0\n \"\"\"\n return ApplicationFlags._from_value(self._flags)\n\n\nclass AppInstallParams:\n \"\"\"Represents the settings for custom authorization URL of an application.\n\n .. versionadded:: 2.0\n\n Attributes\n ----------\n scopes: List[:class:`str`]\n The list of :ddocs:`OAuth2 scopes `\n to add the application to a guild with.\n permissions: :class:`Permissions`\n The permissions to give to application in the guild.\n \"\"\"\n\n __slots__ = ('scopes', 'permissions')\n\n def __init__(self, data: InstallParamsPayload) -> None:\n self.scopes: List[str] = data.get('scopes', [])\n self.permissions: Permissions = Permissions(int(data['permissions']))\n" }, { "path": "discord/http.py", "content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\nimport logging\nimport sys\nfrom typing import (\n Any,\n ClassVar,\n Coroutine,\n Dict,\n Iterable,\n List,\n Literal,\n NamedTuple,\n Optional,\n overload,\n Sequence,\n Tuple,\n TYPE_CHECKING,\n Type,\n TypeVar,\n Union,\n)\nfrom urllib.parse import quote as _uriquote\nfrom collections import deque\nimport datetime\nimport socket\n\nimport aiohttp\n\nfrom .errors import HTTPException, RateLimited, Forbidden, NotFound, LoginFailure, DiscordServerError, GatewayNotFound\nfrom .gateway import DiscordClientWebSocketResponse\nfrom .file import File\nfrom .mentions import AllowedMentions\nfrom . import __version__, utils\nfrom .utils import MISSING\n\n_log = logging.getLogger(__name__)\n\nif TYPE_CHECKING:\n from typing_extensions import Self\n\n from .ui.view import View\n from .embeds import Embed\n from .message import Attachment\n from .flags import MessageFlags\n\n from .types import (\n appinfo,\n audit_log,\n automod,\n channel,\n command,\n emoji,\n guild,\n integration,\n invite,\n member,\n message,\n template,\n role,\n user,\n webhook,\n widget,\n threads,\n scheduled_event,\n sticker,\n welcome_screen,\n sku,\n )\n from .types.snowflake import Snowflake, SnowflakeList\n\n from types import TracebackType\n\n T = TypeVar('T')\n BE = TypeVar('BE', bound=BaseException)\n Response = Coroutine[Any, Any, T]\n\n\nasync def json_or_text(response: aiohttp.ClientResponse) -> Union[Dict[str, Any], str]:\n text = await response.text(encoding='utf-8')\n try:\n if response.headers['content-type'] == 'application/json':\n return utils._from_json(text)\n except KeyError:\n # Thanks Cloudflare\n pass\n\n return text\n\n\nclass MultipartParameters(NamedTuple):\n payload: Optional[Dict[str, Any]]\n multipart: Optional[List[Dict[str, Any]]]\n files: Optional[Sequence[File]]\n\n def __enter__(self) -> Self:\n return self\n\n def __exit__(\n self,\n exc_type: Optional[Type[BE]],\n exc: Optional[BE],\n traceback: Optional[TracebackType],\n ) -> None:\n if self.files:\n for file in self.files:\n file.close()\n\n\ndef handle_message_parameters(\n content: Optional[str] = MISSING,\n *,\n username: str = MISSING,\n avatar_url: Any = MISSING,\n tts: bool = False,\n nonce: Optional[Union[int, str]] = None,\n flags: MessageFlags = MISSING,\n file: File = MISSING,\n files: Sequence[File] = MISSING,\n embed: Optional[Embed] = MISSING,\n embeds: Sequence[Embed] = MISSING,\n attachments: Sequence[Union[Attachment, File]] = MISSING,\n view: Optional[View] = MISSING,\n allowed_mentions: Optional[AllowedMentions] = MISSING,\n message_reference: Optional[message.MessageReference] = MISSING,\n stickers: Optional[SnowflakeList] = MISSING,\n previous_allowed_mentions: Optional[AllowedMentions] = None,\n mention_author: Optional[bool] = None,\n thread_name: str = MISSING,\n channel_payload: Dict[str, Any] = MISSING,\n) -> MultipartParameters:\n if files is not MISSING and file is not MISSING:\n raise TypeError('Cannot mix file and files keyword arguments.')\n if embeds is not MISSING and embed is not MISSING:\n raise TypeError('Cannot mix embed and embeds keyword arguments.')\n\n if file is not MISSING:\n files = [file]\n\n if attachments is not MISSING and files is not MISSING:\n raise TypeError('Cannot mix attachments and files keyword arguments.')\n\n payload = {}\n if embeds is not MISSING:\n if len(embeds) > 10:\n raise ValueError('embeds has a maximum of 10 elements.')\n payload['embeds'] = [e.to_dict() for e in embeds]\n\n if embed is not MISSING:\n if embed is None:\n payload['embeds'] = []\n else:\n payload['embeds'] = [embed.to_dict()]\n\n if content is not MISSING:\n if content is not None:\n payload['content'] = str(content)\n else:\n payload['content'] = None\n\n if view is not MISSING:\n if view is not None:\n payload['components'] = view.to_components()\n else:\n payload['components'] = []\n\n if nonce is not None:\n payload['nonce'] = str(nonce)\n\n if message_reference is not MISSING:\n payload['message_reference'] = message_reference\n\n if stickers is not MISSING:\n if stickers is not None:\n payload['sticker_ids'] = stickers\n else:\n payload['sticker_ids'] = []\n\n payload['tts'] = tts\n if avatar_url:\n payload['avatar_url'] = str(avatar_url)\n if username:\n payload['username'] = username\n\n if flags is not MISSING:\n payload['flags'] = flags.value\n\n if thread_name is not MISSING:\n payload['thread_name'] = thread_name\n\n if allowed_mentions:\n if previous_allowed_mentions is not None:\n payload['allowed_mentions'] = previous_allowed_mentions.merge(allowed_mentions).to_dict()\n else:\n payload['allowed_mentions'] = allowed_mentions.to_dict()\n elif previous_allowed_mentions is not None:\n payload['allowed_mentions'] = previous_allowed_mentions.to_dict()\n\n if mention_author is not None:\n if 'allowed_mentions' not in payload:\n payload['allowed_mentions'] = AllowedMentions().to_dict()\n payload['allowed_mentions']['replied_user'] = mention_author\n\n if attachments is MISSING:\n attachments = files\n else:\n files = [a for a in attachments if isinstance(a, File)]\n\n if attachments is not MISSING:\n file_index = 0\n attachments_payload = []\n for attachment in attachments:\n if isinstance(attachment, File):\n attachments_payload.append(attachment.to_dict(file_index))\n file_index += 1\n else:\n attachments_payload.append(attachment.to_dict())\n\n payload['attachments'] = attachments_payload\n\n if channel_payload is not MISSING:\n payload = {\n 'message': payload,\n }\n payload.update(channel_payload)\n\n multipart = []\n if files:\n multipart.append({'name': 'payload_json', 'value': utils._to_json(payload)})\n payload = None\n for index, file in enumerate(files):\n multipart.append(\n {\n 'name': f'files[{index}]',\n 'value': file.fp,\n 'filename': file.filename,\n 'content_type': 'application/octet-stream',\n }\n )\n\n return MultipartParameters(payload=payload, multipart=multipart, files=files)\n\n\nINTERNAL_API_VERSION: int = 10\n\n\ndef _set_api_version(value: int):\n global INTERNAL_API_VERSION\n\n if not isinstance(value, int):\n raise TypeError(f'expected int not {value.__class__.__name__}')\n\n if value not in (9, 10):\n raise ValueError(f'expected either 9 or 10 not {value}')\n\n INTERNAL_API_VERSION = value\n Route.BASE = f'https://discord.com/api/v{value}'\n\n\nclass Route:\n BASE: ClassVar[str] = 'https://discord.com/api/v10'\n\n def __init__(self, method: str, path: str, *, metadata: Optional[str] = None, **parameters: Any) -> None:\n self.path: str = path\n self.method: str = method\n # Metadata is a special string used to differentiate between known sub rate limits\n # Since these can't be handled generically, this is the next best way to do so.\n self.metadata: Optional[str] = metadata\n url = self.BASE + self.path\n if parameters:\n url = url.format_map({k: _uriquote(v) if isinstance(v, str) else v for k, v in parameters.items()})\n self.url: str = url\n\n # major parameters:\n self.channel_id: Optional[Snowflake] = parameters.get('channel_id')\n self.guild_id: Optional[Snowflake] = parameters.get('guild_id')\n self.webhook_id: Optional[Snowflake] = parameters.get('webhook_id')\n self.webhook_token: Optional[str] = parameters.get('webhook_token')\n\n @property\n def key(self) -> str:\n \"\"\"The bucket key is used to represent the route in various mappings.\"\"\"\n if self.metadata:\n return f'{self.method} {self.path}:{self.metadata}'\n return f'{self.method} {self.path}'\n\n @property\n def major_parameters(self) -> str:\n \"\"\"Returns the major parameters formatted a string.\n\n This needs to be appended to a bucket hash to constitute as a full rate limit key.\n \"\"\"\n return '+'.join(\n str(k) for k in (self.channel_id, self.guild_id, self.webhook_id, self.webhook_token) if k is not None\n )\n\n\nclass Ratelimit:\n \"\"\"Represents a Discord rate limit.\n\n This is similar to a semaphore except tailored to Discord's rate limits. This is aware of\n the expiry of a token window, along with the number of tokens available. The goal of this\n design is to increase throughput of requests being sent concurrently rather than forcing\n everything into a single lock queue per route.\n \"\"\"\n\n __slots__ = (\n 'limit',\n 'remaining',\n 'outgoing',\n 'reset_after',\n 'expires',\n 'dirty',\n '_last_request',\n '_max_ratelimit_timeout',\n '_loop',\n '_pending_requests',\n '_sleeping',\n )\n\n def __init__(self, max_ratelimit_timeout: Optional[float]) -> None:\n self.limit: int = 1\n self.remaining: int = self.limit\n self.outgoing: int = 0\n self.reset_after: float = 0.0\n self.expires: Optional[float] = None\n self.dirty: bool = False\n self._max_ratelimit_timeout: Optional[float] = max_ratelimit_timeout\n self._loop: asyncio.AbstractEventLoop = asyncio.get_running_loop()\n self._pending_requests: deque[asyncio.Future[Any]] = deque()\n # Only a single rate limit object should be sleeping at a time.\n # The object that is sleeping is ultimately responsible for freeing the semaphore\n # for the requests currently pending.\n self._sleeping: asyncio.Lock = asyncio.Lock()\n self._last_request: float = self._loop.time()\n\n def __repr__(self) -> str:\n return (\n f''\n )\n\n def reset(self):\n self.remaining = self.limit - self.outgoing\n self.expires = None\n self.reset_after = 0.0\n self.dirty = False\n\n def update(self, response: aiohttp.ClientResponse, *, use_clock: bool = False) -> None:\n headers = response.headers\n self.limit = int(headers.get('X-Ratelimit-Limit', 1))\n\n if self.dirty:\n self.remaining = min(int(headers.get('X-Ratelimit-Remaining', 0)), self.limit - self.outgoing)\n else:\n self.remaining = int(headers.get('X-Ratelimit-Remaining', 0))\n self.dirty = True\n\n reset_after = headers.get('X-Ratelimit-Reset-After')\n if use_clock or not reset_after:\n utc = datetime.timezone.utc\n now = datetime.datetime.now(utc)\n reset = datetime.datetime.fromtimestamp(float(headers['X-Ratelimit-Reset']), utc)\n self.reset_after = (reset - now).total_seconds()\n else:\n self.reset_after = float(reset_after)\n\n self.expires = self._loop.time() + self.reset_after\n\n def _wake_next(self) -> None:\n while self._pending_requests:\n future = self._pending_requests.popleft()\n if not future.done():\n future.set_result(None)\n break\n\n def _wake(self, count: int = 1, *, exception: Optional[RateLimited] = None) -> None:\n awaken = 0\n while self._pending_requests:\n future = self._pending_requests.popleft()\n if not future.done():\n if exception:\n future.set_exception(exception)\n else:\n future.set_result(None)\n awaken += 1\n\n if awaken >= count:\n break\n\n async def _refresh(self) -> None:\n error = self._max_ratelimit_timeout and self.reset_after > self._max_ratelimit_timeout\n exception = RateLimited(self.reset_after) if error else None\n async with self._sleeping:\n if not error:\n await asyncio.sleep(self.reset_after)\n\n self.reset()\n self._wake(self.remaining, exception=exception)\n\n def is_expired(self) -> bool:\n return self.expires is not None and self._loop.time() > self.expires\n\n def is_inactive(self) -> bool:\n delta = self._loop.time() - self._last_request\n return delta >= 300 and self.outgoing == 0 and len(self._pending_requests) == 0\n\n async def acquire(self) -> None:\n self._last_request = self._loop.time()\n if self.is_expired():\n self.reset()\n\n if self._max_ratelimit_timeout is not None and self.expires is not None:\n # Check if we can pre-emptively block this request for having too large of a timeout\n current_reset_after = self.expires - self._loop.time()\n if current_reset_after > self._max_ratelimit_timeout:\n raise RateLimited(current_reset_after)\n\n while self.remaining <= 0:\n future = self._loop.create_future()\n self._pending_requests.append(future)\n try:\n await future\n except:\n future.cancel()\n if self.remaining > 0 and not future.cancelled():\n self._wake_next()\n raise\n\n self.remaining -= 1\n self.outgoing += 1\n\n async def __aenter__(self) -> Self:\n await self.acquire()\n return self\n\n async def __aexit__(self, type: Type[BE], value: BE, traceback: TracebackType) -> None:\n self.outgoing -= 1\n tokens = self.remaining - self.outgoing\n # Check whether the rate limit needs to be pre-emptively slept on\n # Note that this is a Lock to prevent multiple rate limit objects from sleeping at once\n if not self._sleeping.locked():\n if tokens <= 0:\n await self._refresh()\n elif self._pending_requests:\n exception = (\n RateLimited(self.reset_after)\n if self._max_ratelimit_timeout and self.reset_after > self._max_ratelimit_timeout\n else None\n )\n self._wake(tokens, exception=exception)\n\n\n# For some reason, the Discord voice websocket expects this header to be\n# completely lowercase while aiohttp respects spec and does it as case-insensitive\naiohttp.hdrs.WEBSOCKET = 'websocket' # type: ignore\n\n\nclass HTTPClient:\n \"\"\"Represents an HTTP client sending HTTP requests to the Discord API.\"\"\"\n\n def __init__(\n self,\n loop: asyncio.AbstractEventLoop,\n connector: Optional[aiohttp.BaseConnector] = None,\n *,\n proxy: Optional[str] = None,\n proxy_auth: Optional[aiohttp.BasicAuth] = None,\n unsync_clock: bool = True,\n http_trace: Optional[aiohttp.TraceConfig] = None,\n max_ratelimit_timeout: Optional[float] = None,\n ) -> None:\n self.loop: asyncio.AbstractEventLoop = loop\n self.connector: aiohttp.BaseConnector = connector or MISSING\n self.__session: aiohttp.ClientSession = MISSING # filled in static_login\n # Route key -> Bucket hash\n self._bucket_hashes: Dict[str, str] = {}\n # Bucket Hash + Major Parameters -> Rate limit\n # or\n # Route key + Major Parameters -> Rate limit\n # When the key is the latter, it is used for temporary\n # one shot requests that don't have a bucket hash\n # When this reaches 256 elements, it will try to evict based off of expiry\n self._buckets: Dict[str, Ratelimit] = {}\n self._global_over: asyncio.Event = MISSING\n self.token: Optional[str] = None\n self.proxy: Optional[str] = proxy\n self.proxy_auth: Optional[aiohttp.BasicAuth] = proxy_auth\n self.http_trace: Optional[aiohttp.TraceConfig] = http_trace\n self.use_clock: bool = not unsync_clock\n self.max_ratelimit_timeout: Optional[float] = max(30.0, max_ratelimit_timeout) if max_ratelimit_timeout else None\n\n user_agent = 'DiscordBot (https://github.com/Rapptz/discord.py {0}) Python/{1[0]}.{1[1]} aiohttp/{2}'\n self.user_agent: str = user_agent.format(__version__, sys.version_info, aiohttp.__version__)\n\n def clear(self) -> None:\n if self.__session and self.__session.closed:\n self.__session = MISSING\n\n async def ws_connect(self, url: str, *, compress: int = 0) -> aiohttp.ClientWebSocketResponse:\n kwargs = {\n 'proxy_auth': self.proxy_auth,\n 'proxy': self.proxy,\n 'max_msg_size': 0,\n 'timeout': 30.0,\n 'autoclose': False,\n 'headers': {\n 'User-Agent': self.user_agent,\n },\n 'compress': compress,\n }\n\n return await self.__session.ws_connect(url, **kwargs)\n\n def _try_clear_expired_ratelimits(self) -> None:\n if len(self._buckets) < 256:\n return\n\n keys = [key for key, bucket in self._buckets.items() if bucket.is_inactive()]\n for key in keys:\n del self._buckets[key]\n\n def get_ratelimit(self, key: str) -> Ratelimit:\n try:\n value = self._buckets[key]\n except KeyError:\n self._buckets[key] = value = Ratelimit(self.max_ratelimit_timeout)\n self._try_clear_expired_ratelimits()\n return value\n\n async def request(\n self,\n route: Route,\n *,\n files: Optional[Sequence[File]] = None,\n form: Optional[Iterable[Dict[str, Any]]] = None,\n **kwargs: Any,\n ) -> Any:\n method = route.method\n url = route.url\n route_key = route.key\n\n bucket_hash = None\n try:\n bucket_hash = self._bucket_hashes[route_key]\n except KeyError:\n key = f'{route_key}:{route.major_parameters}'\n else:\n key = f'{bucket_hash}:{route.major_parameters}'\n\n ratelimit = self.get_ratelimit(key)\n\n # header creation\n headers: Dict[str, str] = {\n 'User-Agent': self.user_agent,\n }\n\n if self.token is not None:\n headers['Authorization'] = 'Bot ' + self.token\n # some checking if it's a JSON request\n if 'json' in kwargs:\n headers['Content-Type'] = 'application/json'\n kwargs['data'] = utils._to_json(kwargs.pop('json'))\n\n try:\n reason = kwargs.pop('reason')\n except KeyError:\n pass\n else:\n if reason:\n headers['X-Audit-Log-Reason'] = _uriquote(reason, safe='/ ')\n\n kwargs['headers'] = headers\n\n # Proxy support\n if self.proxy is not None:\n kwargs['proxy'] = self.proxy\n if self.proxy_auth is not None:\n kwargs['proxy_auth'] = self.proxy_auth\n\n if not self._global_over.is_set():\n # wait until the global lock is complete\n await self._global_over.wait()\n\n response: Optional[aiohttp.ClientResponse] = None\n data: Optional[Union[Dict[str, Any], str]] = None\n async with ratelimit:\n for tries in range(5):\n if files:\n for f in files:\n f.reset(seek=tries)\n\n if form:\n # with quote_fields=True '[' and ']' in file field names are escaped, which discord does not support\n form_data = aiohttp.FormData(quote_fields=False)\n for params in form:\n form_data.add_field(**params)\n kwargs['data'] = form_data\n\n try:\n async with self.__session.request(method, url, **kwargs) as response:\n _log.debug('%s %s with %s has returned %s', method, url, kwargs.get('data'), response.status)\n\n # even errors have text involved in them so this is safe to call\n data = await json_or_text(response)\n\n # Update and use rate limit information if the bucket header is present\n discord_hash = response.headers.get('X-Ratelimit-Bucket')\n # I am unsure if X-Ratelimit-Bucket is always available\n # However, X-Ratelimit-Remaining has been a consistent cornerstone that worked\n has_ratelimit_headers = 'X-Ratelimit-Remaining' in response.headers\n if discord_hash is not None:\n # If the hash Discord has provided is somehow different from our current hash something changed\n if bucket_hash != discord_hash:\n if bucket_hash is not None:\n # If the previous hash was an actual Discord hash then this means the\n # hash has changed sporadically.\n # This can be due to two reasons\n # 1. It's a sub-ratelimit which is hard to handle\n # 2. The rate limit information genuinely changed\n # There is no good way to discern these, Discord doesn't provide a way to do so.\n # At best, there will be some form of logging to help catch it.\n # Alternating sub-ratelimits means that the requests oscillate between\n # different underlying rate limits -- this can lead to unexpected 429s\n # It is unavoidable.\n fmt = 'A route (%s) has changed hashes: %s -> %s.'\n _log.debug(fmt, route_key, bucket_hash, discord_hash)\n\n self._bucket_hashes[route_key] = discord_hash\n recalculated_key = discord_hash + route.major_parameters\n self._buckets[recalculated_key] = ratelimit\n self._buckets.pop(key, None)\n elif route_key not in self._bucket_hashes:\n fmt = '%s has found its initial rate limit bucket hash (%s).'\n _log.debug(fmt, route_key, discord_hash)\n self._bucket_hashes[route_key] = discord_hash\n self._buckets[discord_hash + route.major_parameters] = ratelimit\n\n if has_ratelimit_headers:\n if response.status != 429:\n ratelimit.update(response, use_clock=self.use_clock)\n if ratelimit.remaining == 0:\n _log.debug(\n 'A rate limit bucket (%s) has been exhausted. Pre-emptively rate limiting...',\n discord_hash or route_key,\n )\n\n # the request was successful so just return the text/json\n if 300 > response.status >= 200:\n _log.debug('%s %s has received %s', method, url, data)\n return data\n\n # we are being rate limited\n if response.status == 429:\n if not response.headers.get('Via') or isinstance(data, str):\n # Banned by Cloudflare more than likely.\n raise HTTPException(response, data)\n\n if ratelimit.remaining > 0:\n # According to night\n # https://github.com/discord/discord-api-docs/issues/2190#issuecomment-816363129\n # Remaining > 0 and 429 means that a sub ratelimit was hit.\n # It is unclear what should happen in these cases other than just using the retry_after\n # value in the body.\n _log.debug(\n '%s %s received a 429 despite having %s remaining requests. This is a sub-ratelimit.',\n method,\n url,\n ratelimit.remaining,\n )\n\n retry_after: float = data['retry_after']\n if self.max_ratelimit_timeout and retry_after > self.max_ratelimit_timeout:\n _log.warning(\n 'We are being rate limited. %s %s responded with 429. Timeout of %.2f was too long, erroring instead.',\n method,\n url,\n retry_after,\n )\n raise RateLimited(retry_after)\n\n fmt = 'We are being rate limited. %s %s responded with 429. Retrying in %.2f seconds.'\n _log.warning(fmt, method, url, retry_after)\n\n _log.debug(\n 'Rate limit is being handled by bucket hash %s with %r major parameters',\n bucket_hash,\n route.major_parameters,\n )\n\n # check if it's a global rate limit\n is_global = data.get('global', False)\n if is_global:\n _log.warning('Global rate limit has been hit. Retrying in %.2f seconds.', retry_after)\n self._global_over.clear()\n\n await asyncio.sleep(retry_after)\n _log.debug('Done sleeping for the rate limit. Retrying...')\n\n # release the global lock now that the\n # global rate limit has passed\n if is_global:\n self._global_over.set()\n _log.debug('Global rate limit is now over.')\n\n continue\n\n # we've received a 500, 502, 504, or 524, unconditional retry\n if response.status in {500, 502, 504, 524}:\n await asyncio.sleep(1 + tries * 2)\n continue\n\n # the usual error cases\n if response.status == 403:\n raise Forbidden(response, data)\n elif response.status == 404:\n raise NotFound(response, data)\n elif response.status >= 500:\n raise DiscordServerError(response, data)\n else:\n raise HTTPException(response, data)\n\n # This is handling exceptions from the request\n except OSError as e:\n # Connection reset by peer\n if tries < 4 and e.errno in (54, 10054):\n await asyncio.sleep(1 + tries * 2)\n continue\n raise\n\n if response is not None:\n # We've run out of retries, raise.\n if response.status >= 500:\n raise DiscordServerError(response, data)\n\n raise HTTPException(response, data)\n\n raise RuntimeError('Unreachable code in HTTP handling')\n\n async def get_from_cdn(self, url: str) -> bytes:\n async with self.__session.get(url) as resp:\n if resp.status == 200:\n return await resp.read()\n elif resp.status == 404:\n raise NotFound(resp, 'asset not found')\n elif resp.status == 403:\n raise Forbidden(resp, 'cannot retrieve asset')\n else:\n raise HTTPException(resp, 'failed to get asset')\n\n raise RuntimeError('Unreachable')\n\n # state management\n\n async def close(self) -> None:\n if self.__session:\n await self.__session.close()\n\n # login management\n\n async def static_login(self, token: str) -> user.User:\n # Necessary to get aiohttp to stop complaining about session creation\n if self.connector is MISSING:\n # discord does not support ipv6\n self.connector = aiohttp.TCPConnector(limit=0, family=socket.AF_INET)\n\n self.__session = aiohttp.ClientSession(\n connector=self.connector,\n ws_response_class=DiscordClientWebSocketResponse,\n trace_configs=None if self.http_trace is None else [self.http_trace],\n )\n self._global_over = asyncio.Event()\n self._global_over.set()\n\n old_token = self.token\n self.token = token\n\n try:\n data = await self.request(Route('GET', '/users/@me'))\n except HTTPException as exc:\n self.token = old_token\n if exc.status == 401:\n raise LoginFailure('Improper token has been passed.') from exc\n raise\n\n return data\n\n def logout(self) -> Response[None]:\n return self.request(Route('POST', '/auth/logout'))\n\n # Group functionality\n\n def start_group(self, user_id: Snowflake, recipients: List[int]) -> Response[channel.GroupDMChannel]:\n payload = {\n 'recipients': recipients,\n }\n\n return self.request(Route('POST', '/users/{user_id}/channels', user_id=user_id), json=payload)\n\n def leave_group(self, channel_id: Snowflake) -> Response[None]:\n return self.request(Route('DELETE', '/channels/{channel_id}', channel_id=channel_id))\n\n # Message management\n\n def start_private_message(self, user_id: Snowflake) -> Response[channel.DMChannel]:\n payload = {\n 'recipient_id': user_id,\n }\n\n return self.request(Route('POST', '/users/@me/channels'), json=payload)\n\n def send_message(\n self,\n channel_id: Snowflake,\n *,\n params: MultipartParameters,\n ) -> Response[message.Message]:\n r = Route('POST', '/channels/{channel_id}/messages', channel_id=channel_id)\n if params.files:\n return self.request(r, files=params.files, form=params.multipart)\n else:\n return self.request(r, json=params.payload)\n\n def send_typing(self, channel_id: Snowflake) -> Response[None]:\n return self.request(Route('POST', '/channels/{channel_id}/typing', channel_id=channel_id))\n\n def delete_message(\n self, channel_id: Snowflake, message_id: Snowflake, *, reason: Optional[str] = None\n ) -> Response[None]:\n # Special case certain sub-rate limits\n # https://github.com/discord/discord-api-docs/issues/1092\n # https://github.com/discord/discord-api-docs/issues/1295\n difference = utils.utcnow() - utils.snowflake_time(int(message_id))\n metadata: Optional[str] = None\n if difference <= datetime.timedelta(seconds=10):\n metadata = 'sub-10-seconds'\n elif difference >= datetime.timedelta(days=14):\n metadata = 'older-than-two-weeks'\n r = Route(\n 'DELETE',\n '/channels/{channel_id}/messages/{message_id}',\n channel_id=channel_id,\n message_id=message_id,\n metadata=metadata,\n )\n return self.request(r, reason=reason)\n\n def delete_messages(\n self, channel_id: Snowflake, message_ids: SnowflakeList, *, reason: Optional[str] = None\n ) -> Response[None]:\n r = Route('POST', '/channels/{channel_id}/messages/bulk-delete', channel_id=channel_id)\n payload = {\n 'messages': message_ids,\n }\n\n return self.request(r, json=payload, reason=reason)\n\n def edit_message(\n self, channel_id: Snowflake, message_id: Snowflake, *, params: MultipartParameters\n ) -> Response[message.Message]:\n r = Route('PATCH', '/channels/{channel_id}/messages/{message_id}', channel_id=channel_id, message_id=message_id)\n if params.files:\n return self.request(r, files=params.files, form=params.multipart)\n else:\n return self.request(r, json=params.payload)\n\n def add_reaction(self, channel_id: Snowflake, message_id: Snowflake, emoji: str) -> Response[None]:\n r = Route(\n 'PUT',\n '/channels/{channel_id}/messages/{message_id}/reactions/{emoji}/@me',\n channel_id=channel_id,\n message_id=message_id,\n emoji=emoji,\n )\n return self.request(r)\n\n def remove_reaction(\n self, channel_id: Snowflake, message_id: Snowflake, emoji: str, member_id: Snowflake\n ) -> Response[None]:\n r = Route(\n 'DELETE',\n '/channels/{channel_id}/messages/{message_id}/reactions/{emoji}/{member_id}',\n channel_id=channel_id,\n message_id=message_id,\n member_id=member_id,\n emoji=emoji,\n )\n return self.request(r)\n\n def remove_own_reaction(self, channel_id: Snowflake, message_id: Snowflake, emoji: str) -> Response[None]:\n r = Route(\n 'DELETE',\n '/channels/{channel_id}/messages/{message_id}/reactions/{emoji}/@me',\n channel_id=channel_id,\n message_id=message_id,\n emoji=emoji,\n )\n return self.request(r)\n\n def get_reaction_users(\n self,\n channel_id: Snowflake,\n message_id: Snowflake,\n emoji: str,\n limit: int,\n after: Optional[Snowflake] = None,\n ) -> Response[List[user.User]]:\n r = Route(\n 'GET',\n '/channels/{channel_id}/messages/{message_id}/reactions/{emoji}',\n channel_id=channel_id,\n message_id=message_id,\n emoji=emoji,\n )\n\n params: Dict[str, Any] = {\n 'limit': limit,\n }\n if after:\n params['after'] = after\n return self.request(r, params=params)\n\n def clear_reactions(self, channel_id: Snowflake, message_id: Snowflake) -> Response[None]:\n r = Route(\n 'DELETE',\n '/channels/{channel_id}/messages/{message_id}/reactions',\n channel_id=channel_id,\n message_id=message_id,\n )\n\n return self.request(r)\n\n def clear_single_reaction(self, channel_id: Snowflake, message_id: Snowflake, emoji: str) -> Response[None]:\n r = Route(\n 'DELETE',\n '/channels/{channel_id}/messages/{message_id}/reactions/{emoji}',\n channel_id=channel_id,\n message_id=message_id,\n emoji=emoji,\n )\n return self.request(r)\n\n def get_message(self, channel_id: Snowflake, message_id: Snowflake) -> Response[message.Message]:\n r = Route('GET', '/channels/{channel_id}/messages/{message_id}', channel_id=channel_id, message_id=message_id)\n return self.request(r)\n\n def get_channel(self, channel_id: Snowflake) -> Response[channel.Channel]:\n r = Route('GET', '/channels/{channel_id}', channel_id=channel_id)\n return self.request(r)\n\n def logs_from(\n self,\n channel_id: Snowflake,\n limit: int,\n before: Optional[Snowflake] = None,\n after: Optional[Snowflake] = None,\n around: Optional[Snowflake] = None,\n ) -> Response[List[message.Message]]:\n params: Dict[str, Any] = {\n 'limit': limit,\n }\n\n if before is not None:\n params['before'] = before\n if after is not None:\n params['after'] = after\n if around is not None:\n params['around'] = around\n\n return self.request(Route('GET', '/channels/{channel_id}/messages', channel_id=channel_id), params=params)\n\n def publish_message(self, channel_id: Snowflake, message_id: Snowflake) -> Response[message.Message]:\n return self.request(\n Route(\n 'POST',\n '/channels/{channel_id}/messages/{message_id}/crosspost',\n channel_id=channel_id,\n message_id=message_id,\n )\n )\n\n def pin_message(self, channel_id: Snowflake, message_id: Snowflake, reason: Optional[str] = None) -> Response[None]:\n r = Route(\n 'PUT',\n '/channels/{channel_id}/pins/{message_id}',\n channel_id=channel_id,\n message_id=message_id,\n )\n return self.request(r, reason=reason)\n\n def unpin_message(self, channel_id: Snowflake, message_id: Snowflake, reason: Optional[str] = None) -> Response[None]:\n r = Route(\n 'DELETE',\n '/channels/{channel_id}/pins/{message_id}',\n channel_id=channel_id,\n message_id=message_id,\n )\n return self.request(r, reason=reason)\n\n def pins_from(self, channel_id: Snowflake) -> Response[List[message.Message]]:\n return self.request(Route('GET', '/channels/{channel_id}/pins', channel_id=channel_id))\n\n # Member management\n\n def kick(self, user_id: Snowflake, guild_id: Snowflake, reason: Optional[str] = None) -> Response[None]:\n r = Route('DELETE', '/guilds/{guild_id}/members/{user_id}', guild_id=guild_id, user_id=user_id)\n return self.request(r, reason=reason)\n\n def ban(\n self,\n user_id: Snowflake,\n guild_id: Snowflake,\n delete_message_seconds: int = 86400, # one day\n reason: Optional[str] = None,\n ) -> Response[None]:\n r = Route('PUT', '/guilds/{guild_id}/bans/{user_id}', guild_id=guild_id, user_id=user_id)\n params = {\n 'delete_message_seconds': delete_message_seconds,\n }\n\n return self.request(r, params=params, reason=reason)\n\n def unban(self, user_id: Snowflake, guild_id: Snowflake, *, reason: Optional[str] = None) -> Response[None]:\n r = Route('DELETE', '/guilds/{guild_id}/bans/{user_id}', guild_id=guild_id, user_id=user_id)\n return self.request(r, reason=reason)\n\n def guild_voice_state(\n self,\n user_id: Snowflake,\n guild_id: Snowflake,\n *,\n mute: Optional[bool] = None,\n deafen: Optional[bool] = None,\n reason: Optional[str] = None,\n ) -> Response[member.Member]:\n r = Route('PATCH', '/guilds/{guild_id}/members/{user_id}', guild_id=guild_id, user_id=user_id)\n payload = {}\n if mute is not None:\n payload['mute'] = mute\n\n if deafen is not None:\n payload['deaf'] = deafen\n\n return self.request(r, json=payload, reason=reason)\n\n def edit_profile(self, payload: Dict[str, Any]) -> Response[user.User]:\n return self.request(Route('PATCH', '/users/@me'), json=payload)\n\n def change_my_nickname(\n self,\n guild_id: Snowflake,\n nickname: str,\n *,\n reason: Optional[str] = None,\n ) -> Response[member.Nickname]:\n r = Route('PATCH', '/guilds/{guild_id}/members/@me/nick', guild_id=guild_id)\n payload = {\n 'nick': nickname,\n }\n return self.request(r, json=payload, reason=reason)\n\n def change_nickname(\n self,\n guild_id: Snowflake,\n user_id: Snowflake,\n nickname: str,\n *,\n reason: Optional[str] = None,\n ) -> Response[member.Member]:\n r = Route('PATCH', '/guilds/{guild_id}/members/{user_id}', guild_id=guild_id, user_id=user_id)\n payload = {\n 'nick': nickname,\n }\n return self.request(r, json=payload, reason=reason)\n\n def edit_my_voice_state(self, guild_id: Snowflake, payload: Dict[str, Any]) -> Response[None]:\n r = Route('PATCH', '/guilds/{guild_id}/voice-states/@me', guild_id=guild_id)\n return self.request(r, json=payload)\n\n def edit_voice_state(self, guild_id: Snowflake, user_id: Snowflake, payload: Dict[str, Any]) -> Response[None]:\n r = Route('PATCH', '/guilds/{guild_id}/voice-states/{user_id}', guild_id=guild_id, user_id=user_id)\n return self.request(r, json=payload)\n\n def edit_member(\n self,\n guild_id: Snowflake,\n user_id: Snowflake,\n *,\n reason: Optional[str] = None,\n **fields: Any,\n ) -> Response[member.MemberWithUser]:\n r = Route('PATCH', '/guilds/{guild_id}/members/{user_id}', guild_id=guild_id, user_id=user_id)\n return self.request(r, json=fields, reason=reason)\n\n # Channel management\n\n def edit_channel(\n self,\n channel_id: Snowflake,\n *,\n reason: Optional[str] = None,\n **options: Any,\n ) -> Response[channel.Channel]:\n r = Route('PATCH', '/channels/{channel_id}', channel_id=channel_id)\n valid_keys = (\n 'name',\n 'parent_id',\n 'topic',\n 'bitrate',\n 'nsfw',\n 'user_limit',\n 'position',\n 'permission_overwrites',\n 'rate_limit_per_user',\n 'type',\n 'rtc_region',\n 'video_quality_mode',\n 'archived',\n 'auto_archive_duration',\n 'locked',\n 'invitable',\n 'default_auto_archive_duration',\n 'flags',\n 'default_thread_rate_limit_per_user',\n 'default_reaction_emoji',\n 'available_tags',\n 'applied_tags',\n 'default_forum_layout',\n 'default_sort_order',\n )\n\n payload = {k: v for k, v in options.items() if k in valid_keys}\n return self.request(r, reason=reason, json=payload)\n\n def bulk_channel_update(\n self,\n guild_id: Snowflake,\n data: List[guild.ChannelPositionUpdate],\n *,\n reason: Optional[str] = None,\n ) -> Response[None]:\n r = Route('PATCH', '/guilds/{guild_id}/channels', guild_id=guild_id)\n return self.request(r, json=data, reason=reason)\n\n def create_channel(\n self,\n guild_id: Snowflake,\n channel_type: channel.ChannelType,\n *,\n reason: Optional[str] = None,\n **options: Any,\n ) -> Response[channel.GuildChannel]:\n payload = {\n 'type': channel_type,\n }\n\n valid_keys = (\n 'name',\n 'parent_id',\n 'topic',\n 'bitrate',\n 'nsfw',\n 'user_limit',\n 'position',\n 'permission_overwrites',\n 'rate_limit_per_user',\n 'rtc_region',\n 'video_quality_mode',\n 'default_auto_archive_duration',\n 'default_thread_rate_limit_per_user',\n 'default_sort_order',\n 'default_reaction_emoji',\n 'default_forum_layout',\n 'available_tags',\n )\n payload.update({k: v for k, v in options.items() if k in valid_keys and v is not None})\n\n return self.request(Route('POST', '/guilds/{guild_id}/channels', guild_id=guild_id), json=payload, reason=reason)\n\n def delete_channel(\n self,\n channel_id: Snowflake,\n *,\n reason: Optional[str] = None,\n ) -> Response[None]:\n return self.request(Route('DELETE', '/channels/{channel_id}', channel_id=channel_id), reason=reason)\n\n # Thread management\n\n def start_thread_with_message(\n self,\n channel_id: Snowflake,\n message_id: Snowflake,\n *,\n name: str,\n auto_archive_duration: threads.ThreadArchiveDuration,\n rate_limit_per_user: Optional[int] = None,\n reason: Optional[str] = None,\n ) -> Response[threads.Thread]:\n payload = {\n 'name': name,\n 'auto_archive_duration': auto_archive_duration,\n 'rate_limit_per_user': rate_limit_per_user,\n }\n\n route = Route(\n 'POST', '/channels/{channel_id}/messages/{message_id}/threads', channel_id=channel_id, message_id=message_id\n )\n return self.request(route, json=payload, reason=reason)\n\n def start_thread_without_message(\n self,\n channel_id: Snowflake,\n *,\n name: str,\n auto_archive_duration: threads.ThreadArchiveDuration,\n type: threads.ThreadType,\n invitable: bool = True,\n rate_limit_per_user: Optional[int] = None,\n reason: Optional[str] = None,\n ) -> Response[threads.Thread]:\n payload = {\n 'name': name,\n 'auto_archive_duration': auto_archive_duration,\n 'type': type,\n 'invitable': invitable,\n 'rate_limit_per_user': rate_limit_per_user,\n }\n\n route = Route('POST', '/channels/{channel_id}/threads', channel_id=channel_id)\n return self.request(route, json=payload, reason=reason)\n\n def start_thread_in_forum(\n self,\n channel_id: Snowflake,\n *,\n params: MultipartParameters,\n reason: Optional[str] = None,\n ) -> Response[threads.ForumThread]:\n query = {'use_nested_fields': 1}\n r = Route('POST', '/channels/{channel_id}/threads', channel_id=channel_id)\n if params.files:\n return self.request(r, files=params.files, form=params.multipart, params=query, reason=reason)\n else:\n return self.request(r, json=params.payload, params=query, reason=reason)\n\n def join_thread(self, channel_id: Snowflake) -> Response[None]:\n return self.request(Route('POST', '/channels/{channel_id}/thread-members/@me', channel_id=channel_id))\n\n def add_user_to_thread(self, channel_id: Snowflake, user_id: Snowflake) -> Response[None]:\n return self.request(\n Route('PUT', '/channels/{channel_id}/thread-members/{user_id}', channel_id=channel_id, user_id=user_id)\n )\n\n def leave_thread(self, channel_id: Snowflake) -> Response[None]:\n return self.request(Route('DELETE', '/channels/{channel_id}/thread-members/@me', channel_id=channel_id))\n\n def remove_user_from_thread(self, channel_id: Snowflake, user_id: Snowflake) -> Response[None]:\n route = Route('DELETE', '/channels/{channel_id}/thread-members/{user_id}', channel_id=channel_id, user_id=user_id)\n return self.request(route)\n\n def get_public_archived_threads(\n self, channel_id: Snowflake, before: Optional[Snowflake] = None, limit: int = 50\n ) -> Response[threads.ThreadPaginationPayload]:\n route = Route('GET', '/channels/{channel_id}/threads/archived/public', channel_id=channel_id)\n\n params = {}\n if before:\n params['before'] = before\n params['limit'] = limit\n return self.request(route, params=params)\n\n def get_private_archived_threads(\n self, channel_id: Snowflake, before: Optional[Snowflake] = None, limit: int = 50\n ) -> Response[threads.ThreadPaginationPayload]:\n route = Route('GET', '/channels/{channel_id}/threads/archived/private', channel_id=channel_id)\n\n params = {}\n if before:\n params['before'] = before\n params['limit'] = limit\n return self.request(route, params=params)\n\n def get_joined_private_archived_threads(\n self, channel_id: Snowflake, before: Optional[Snowflake] = None, limit: int = 50\n ) -> Response[threads.ThreadPaginationPayload]:\n route = Route('GET', '/channels/{channel_id}/users/@me/threads/archived/private', channel_id=channel_id)\n params = {}\n if before:\n params['before'] = before\n params['limit'] = limit\n return self.request(route, params=params)\n\n def get_active_threads(self, guild_id: Snowflake) -> Response[threads.ThreadPaginationPayload]:\n route = Route('GET', '/guilds/{guild_id}/threads/active', guild_id=guild_id)\n return self.request(route)\n\n def get_thread_member(self, channel_id: Snowflake, user_id: Snowflake) -> Response[threads.ThreadMember]:\n route = Route('GET', '/channels/{channel_id}/thread-members/{user_id}', channel_id=channel_id, user_id=user_id)\n return self.request(route)\n\n def get_thread_members(self, channel_id: Snowflake) -> Response[List[threads.ThreadMember]]:\n route = Route('GET', '/channels/{channel_id}/thread-members', channel_id=channel_id)\n return self.request(route)\n\n # Webhook management\n\n def create_webhook(\n self,\n channel_id: Snowflake,\n *,\n name: str,\n avatar: Optional[bytes] = None,\n reason: Optional[str] = None,\n ) -> Response[webhook.Webhook]:\n payload: Dict[str, Any] = {\n 'name': name,\n }\n if avatar is not None:\n payload['avatar'] = avatar\n\n r = Route('POST', '/channels/{channel_id}/webhooks', channel_id=channel_id)\n return self.request(r, json=payload, reason=reason)\n\n def channel_webhooks(self, channel_id: Snowflake) -> Response[List[webhook.Webhook]]:\n return self.request(Route('GET', '/channels/{channel_id}/webhooks', channel_id=channel_id))\n\n def guild_webhooks(self, guild_id: Snowflake) -> Response[List[webhook.Webhook]]:\n return self.request(Route('GET', '/guilds/{guild_id}/webhooks', guild_id=guild_id))\n\n def get_webhook(self, webhook_id: Snowflake) -> Response[webhook.Webhook]:\n return self.request(Route('GET', '/webhooks/{webhook_id}', webhook_id=webhook_id))\n\n def follow_webhook(\n self,\n channel_id: Snowflake,\n webhook_channel_id: Snowflake,\n reason: Optional[str] = None,\n ) -> Response[None]:\n payload = {\n 'webhook_channel_id': str(webhook_channel_id),\n }\n return self.request(\n Route('POST', '/channels/{channel_id}/followers', channel_id=channel_id), json=payload, reason=reason\n )\n\n # Guild management\n\n def get_guilds(\n self,\n limit: int,\n before: Optional[Snowflake] = None,\n after: Optional[Snowflake] = None,\n with_counts: bool = True,\n ) -> Response[List[guild.Guild]]:\n params: Dict[str, Any] = {\n 'limit': limit,\n 'with_counts': int(with_counts),\n }\n\n if before:\n params['before'] = before\n if after:\n params['after'] = after\n\n return self.request(Route('GET', '/users/@me/guilds'), params=params)\n\n def leave_guild(self, guild_id: Snowflake) -> Response[None]:\n return self.request(Route('DELETE', '/users/@me/guilds/{guild_id}', guild_id=guild_id))\n\n def get_guild(self, guild_id: Snowflake, *, with_counts: bool = True) -> Response[guild.Guild]:\n params = {'with_counts': int(with_counts)}\n return self.request(Route('GET', '/guilds/{guild_id}', guild_id=guild_id), params=params)\n\n def delete_guild(self, guild_id: Snowflake) -> Response[None]:\n return self.request(Route('DELETE', '/guilds/{guild_id}', guild_id=guild_id))\n\n def create_guild(self, name: str, icon: Optional[str]) -> Response[guild.Guild]:\n payload = {\n 'name': name,\n }\n if icon:\n payload['icon'] = icon\n\n return self.request(Route('POST', '/guilds'), json=payload)\n\n def edit_guild(self, guild_id: Snowflake, *, reason: Optional[str] = None, **fields: Any) -> Response[guild.Guild]:\n valid_keys = (\n 'name',\n 'region',\n 'icon',\n 'afk_timeout',\n 'owner_id',\n 'afk_channel_id',\n 'splash',\n 'discovery_splash',\n 'features',\n 'verification_level',\n 'system_channel_id',\n 'default_message_notifications',\n 'description',\n 'explicit_content_filter',\n 'banner',\n 'system_channel_flags',\n 'rules_channel_id',\n 'public_updates_channel_id',\n 'preferred_locale',\n 'premium_progress_bar_enabled',\n 'safety_alerts_channel_id',\n )\n\n payload = {k: v for k, v in fields.items() if k in valid_keys}\n\n return self.request(Route('PATCH', '/guilds/{guild_id}', guild_id=guild_id), json=payload, reason=reason)\n\n def edit_guild_mfa_level(\n self, guild_id: Snowflake, *, mfa_level: int, reason: Optional[str] = None\n ) -> Response[guild.GuildMFALevel]:\n payload = {'level': mfa_level}\n return self.request(Route('POST', '/guilds/{guild_id}/mfa', guild_id=guild_id), json=payload, reason=reason)\n\n def get_template(self, code: str) -> Response[template.Template]:\n return self.request(Route('GET', '/guilds/templates/{code}', code=code))\n\n def guild_templates(self, guild_id: Snowflake) -> Response[List[template.Template]]:\n return self.request(Route('GET', '/guilds/{guild_id}/templates', guild_id=guild_id))\n\n def create_template(self, guild_id: Snowflake, payload: Dict[str, Any]) -> Response[template.Template]:\n return self.request(Route('POST', '/guilds/{guild_id}/templates', guild_id=guild_id), json=payload)\n\n def sync_template(self, guild_id: Snowflake, code: str) -> Response[template.Template]:\n return self.request(Route('PUT', '/guilds/{guild_id}/templates/{code}', guild_id=guild_id, code=code))\n\n def edit_template(self, guild_id: Snowflake, code: str, payload: Dict[str, Any]) -> Response[template.Template]:\n valid_keys = (\n 'name',\n 'description',\n )\n payload = {k: v for k, v in payload.items() if k in valid_keys}\n return self.request(\n Route('PATCH', '/guilds/{guild_id}/templates/{code}', guild_id=guild_id, code=code), json=payload\n )\n\n def delete_template(self, guild_id: Snowflake, code: str) -> Response[None]:\n return self.request(Route('DELETE', '/guilds/{guild_id}/templates/{code}', guild_id=guild_id, code=code))\n\n def create_from_template(self, code: str, name: str, icon: Optional[str]) -> Response[guild.Guild]:\n payload = {\n 'name': name,\n }\n if icon:\n payload['icon'] = icon\n return self.request(Route('POST', '/guilds/templates/{code}', code=code), json=payload)\n\n def get_bans(\n self,\n guild_id: Snowflake,\n limit: int,\n before: Optional[Snowflake] = None,\n after: Optional[Snowflake] = None,\n ) -> Response[List[guild.Ban]]:\n params: Dict[str, Any] = {\n 'limit': limit,\n }\n if before is not None:\n params['before'] = before\n if after is not None:\n params['after'] = after\n\n return self.request(Route('GET', '/guilds/{guild_id}/bans', guild_id=guild_id), params=params)\n\n def get_welcome_screen(self, guild_id: Snowflake) -> Response[welcome_screen.WelcomeScreen]:\n return self.request(Route('GET', '/guilds/{guild_id}/welcome-screen', guild_id=guild_id))\n\n def edit_welcome_screen(\n self, guild_id: Snowflake, *, reason: Optional[str] = None, **fields: Any\n ) -> Response[welcome_screen.WelcomeScreen]:\n valid_keys = (\n 'description',\n 'welcome_channels',\n 'enabled',\n )\n payload = {k: v for k, v in fields.items() if k in valid_keys}\n return self.request(\n Route('PATCH', '/guilds/{guild_id}/welcome-screen', guild_id=guild_id), json=payload, reason=reason\n )\n\n def get_ban(self, user_id: Snowflake, guild_id: Snowflake) -> Response[guild.Ban]:\n return self.request(Route('GET', '/guilds/{guild_id}/bans/{user_id}', guild_id=guild_id, user_id=user_id))\n\n def get_vanity_code(self, guild_id: Snowflake) -> Response[invite.VanityInvite]:\n return self.request(Route('GET', '/guilds/{guild_id}/vanity-url', guild_id=guild_id))\n\n def change_vanity_code(self, guild_id: Snowflake, code: str, *, reason: Optional[str] = None) -> Response[None]:\n payload: Dict[str, Any] = {'code': code}\n return self.request(Route('PATCH', '/guilds/{guild_id}/vanity-url', guild_id=guild_id), json=payload, reason=reason)\n\n def get_all_guild_channels(self, guild_id: Snowflake) -> Response[List[guild.GuildChannel]]:\n return self.request(Route('GET', '/guilds/{guild_id}/channels', guild_id=guild_id))\n\n def get_members(\n self, guild_id: Snowflake, limit: int, after: Optional[Snowflake]\n ) -> Response[List[member.MemberWithUser]]:\n params: Dict[str, Any] = {\n 'limit': limit,\n }\n if after:\n params['after'] = after\n\n r = Route('GET', '/guilds/{guild_id}/members', guild_id=guild_id)\n return self.request(r, params=params)\n\n def get_member(self, guild_id: Snowflake, member_id: Snowflake) -> Response[member.MemberWithUser]:\n return self.request(Route('GET', '/guilds/{guild_id}/members/{member_id}', guild_id=guild_id, member_id=member_id))\n\n def prune_members(\n self,\n guild_id: Snowflake,\n days: int,\n compute_prune_count: bool,\n roles: Iterable[str],\n *,\n reason: Optional[str] = None,\n ) -> Response[guild.GuildPrune]:\n payload: Dict[str, Any] = {\n 'days': days,\n 'compute_prune_count': 'true' if compute_prune_count else 'false',\n }\n if roles:\n payload['include_roles'] = ', '.join(roles)\n\n return self.request(Route('POST', '/guilds/{guild_id}/prune', guild_id=guild_id), json=payload, reason=reason)\n\n def estimate_pruned_members(\n self,\n guild_id: Snowflake,\n days: int,\n roles: Iterable[str],\n ) -> Response[guild.GuildPrune]:\n params: Dict[str, Any] = {\n 'days': days,\n }\n if roles:\n params['include_roles'] = ', '.join(roles)\n\n return self.request(Route('GET', '/guilds/{guild_id}/prune', guild_id=guild_id), params=params)\n\n def get_sticker(self, sticker_id: Snowflake) -> Response[sticker.Sticker]:\n return self.request(Route('GET', '/stickers/{sticker_id}', sticker_id=sticker_id))\n\n def list_premium_sticker_packs(self) -> Response[sticker.ListPremiumStickerPacks]:\n return self.request(Route('GET', '/sticker-packs'))\n\n def get_all_guild_stickers(self, guild_id: Snowflake) -> Response[List[sticker.GuildSticker]]:\n return self.request(Route('GET', '/guilds/{guild_id}/stickers', guild_id=guild_id))\n\n def get_guild_sticker(self, guild_id: Snowflake, sticker_id: Snowflake) -> Response[sticker.GuildSticker]:\n return self.request(\n Route('GET', '/guilds/{guild_id}/stickers/{sticker_id}', guild_id=guild_id, sticker_id=sticker_id)\n )\n\n def create_guild_sticker(\n self, guild_id: Snowflake, payload: Dict[str, Any], file: File, reason: Optional[str]\n ) -> Response[sticker.GuildSticker]:\n initial_bytes = file.fp.read(16)\n\n try:\n mime_type = utils._get_mime_type_for_image(initial_bytes)\n except ValueError:\n if initial_bytes.startswith(b'{'):\n mime_type = 'application/json'\n else:\n mime_type = 'application/octet-stream'\n finally:\n file.reset()\n\n form: List[Dict[str, Any]] = [\n {\n 'name': 'file',\n 'value': file.fp,\n 'filename': file.filename,\n 'content_type': mime_type,\n }\n ]\n\n for k, v in payload.items():\n form.append(\n {\n 'name': k,\n 'value': v,\n }\n )\n\n return self.request(\n Route('POST', '/guilds/{guild_id}/stickers', guild_id=guild_id), form=form, files=[file], reason=reason\n )\n\n def modify_guild_sticker(\n self,\n guild_id: Snowflake,\n sticker_id: Snowflake,\n payload: Dict[str, Any],\n reason: Optional[str],\n ) -> Response[sticker.GuildSticker]:\n return self.request(\n Route('PATCH', '/guilds/{guild_id}/stickers/{sticker_id}', guild_id=guild_id, sticker_id=sticker_id),\n json=payload,\n reason=reason,\n )\n\n def delete_guild_sticker(self, guild_id: Snowflake, sticker_id: Snowflake, reason: Optional[str]) -> Response[None]:\n return self.request(\n Route('DELETE', '/guilds/{guild_id}/stickers/{sticker_id}', guild_id=guild_id, sticker_id=sticker_id),\n reason=reason,\n )\n\n def get_all_custom_emojis(self, guild_id: Snowflake) -> Response[List[emoji.Emoji]]:\n return self.request(Route('GET', '/guilds/{guild_id}/emojis', guild_id=guild_id))\n\n def get_custom_emoji(self, guild_id: Snowflake, emoji_id: Snowflake) -> Response[emoji.Emoji]:\n return self.request(Route('GET', '/guilds/{guild_id}/emojis/{emoji_id}', guild_id=guild_id, emoji_id=emoji_id))\n\n def create_custom_emoji(\n self,\n guild_id: Snowflake,\n name: str,\n image: str,\n *,\n roles: Optional[SnowflakeList] = None,\n reason: Optional[str] = None,\n ) -> Response[emoji.Emoji]:\n payload = {\n 'name': name,\n 'image': image,\n 'roles': roles or [],\n }\n\n r = Route('POST', '/guilds/{guild_id}/emojis', guild_id=guild_id)\n return self.request(r, json=payload, reason=reason)\n\n def delete_custom_emoji(\n self,\n guild_id: Snowflake,\n emoji_id: Snowflake,\n *,\n reason: Optional[str] = None,\n ) -> Response[None]:\n r = Route('DELETE', '/guilds/{guild_id}/emojis/{emoji_id}', guild_id=guild_id, emoji_id=emoji_id)\n return self.request(r, reason=reason)\n\n def edit_custom_emoji(\n self,\n guild_id: Snowflake,\n emoji_id: Snowflake,\n *,\n payload: Dict[str, Any],\n reason: Optional[str] = None,\n ) -> Response[emoji.Emoji]:\n r = Route('PATCH', '/guilds/{guild_id}/emojis/{emoji_id}', guild_id=guild_id, emoji_id=emoji_id)\n return self.request(r, json=payload, reason=reason)\n\n def get_all_integrations(self, guild_id: Snowflake) -> Response[List[integration.Integration]]:\n r = Route('GET', '/guilds/{guild_id}/integrations', guild_id=guild_id)\n\n return self.request(r)\n\n def create_integration(self, guild_id: Snowflake, type: integration.IntegrationType, id: int) -> Response[None]:\n payload = {\n 'type': type,\n 'id': id,\n }\n\n r = Route('POST', '/guilds/{guild_id}/integrations', guild_id=guild_id)\n return self.request(r, json=payload)\n\n def edit_integration(self, guild_id: Snowflake, integration_id: Snowflake, **payload: Any) -> Response[None]:\n r = Route(\n 'PATCH', '/guilds/{guild_id}/integrations/{integration_id}', guild_id=guild_id, integration_id=integration_id\n )\n\n return self.request(r, json=payload)\n\n def sync_integration(self, guild_id: Snowflake, integration_id: Snowflake) -> Response[None]:\n r = Route(\n 'POST', '/guilds/{guild_id}/integrations/{integration_id}/sync', guild_id=guild_id, integration_id=integration_id\n )\n\n return self.request(r)\n\n def delete_integration(\n self, guild_id: Snowflake, integration_id: Snowflake, *, reason: Optional[str] = None\n ) -> Response[None]:\n r = Route(\n 'DELETE', '/guilds/{guild_id}/integrations/{integration_id}', guild_id=guild_id, integration_id=integration_id\n )\n\n return self.request(r, reason=reason)\n\n def get_audit_logs(\n self,\n guild_id: Snowflake,\n limit: int = 100,\n before: Optional[Snowflake] = None,\n after: Optional[Snowflake] = None,\n user_id: Optional[Snowflake] = None,\n action_type: Optional[audit_log.AuditLogEvent] = None,\n ) -> Response[audit_log.AuditLog]:\n params: Dict[str, Any] = {'limit': limit}\n if before:\n params['before'] = before\n if after is not None:\n params['after'] = after\n if user_id:\n params['user_id'] = user_id\n if action_type:\n params['action_type'] = action_type\n\n r = Route('GET', '/guilds/{guild_id}/audit-logs', guild_id=guild_id)\n return self.request(r, params=params)\n\n def get_widget(self, guild_id: Snowflake) -> Response[widget.Widget]:\n return self.request(Route('GET', '/guilds/{guild_id}/widget.json', guild_id=guild_id))\n\n def edit_widget(\n self, guild_id: Snowflake, payload: widget.EditWidgetSettings, reason: Optional[str] = None\n ) -> Response[widget.WidgetSettings]:\n return self.request(Route('PATCH', '/guilds/{guild_id}/widget', guild_id=guild_id), json=payload, reason=reason)\n\n # Invite management\n\n def create_invite(\n self,\n channel_id: Snowflake,\n *,\n reason: Optional[str] = None,\n max_age: int = 0,\n max_uses: int = 0,\n temporary: bool = False,\n unique: bool = True,\n target_type: Optional[invite.InviteTargetType] = None,\n target_user_id: Optional[Snowflake] = None,\n target_application_id: Optional[Snowflake] = None,\n ) -> Response[invite.Invite]:\n r = Route('POST', '/channels/{channel_id}/invites', channel_id=channel_id)\n payload = {\n 'max_age': max_age,\n 'max_uses': max_uses,\n 'temporary': temporary,\n 'unique': unique,\n }\n\n if target_type:\n payload['target_type'] = target_type\n\n if target_user_id:\n payload['target_user_id'] = target_user_id\n\n if target_application_id:\n payload['target_application_id'] = str(target_application_id)\n\n return self.request(r, reason=reason, json=payload)\n\n def get_invite(\n self,\n invite_id: str,\n *,\n with_counts: bool = True,\n with_expiration: bool = True,\n guild_scheduled_event_id: Optional[Snowflake] = None,\n ) -> Response[invite.Invite]:\n params: Dict[str, Any] = {\n 'with_counts': int(with_counts),\n 'with_expiration': int(with_expiration),\n }\n\n if guild_scheduled_event_id:\n params['guild_scheduled_event_id'] = guild_scheduled_event_id\n\n return self.request(Route('GET', '/invites/{invite_id}', invite_id=invite_id), params=params)\n\n def invites_from(self, guild_id: Snowflake) -> Response[List[invite.Invite]]:\n return self.request(Route('GET', '/guilds/{guild_id}/invites', guild_id=guild_id))\n\n def invites_from_channel(self, channel_id: Snowflake) -> Response[List[invite.Invite]]:\n return self.request(Route('GET', '/channels/{channel_id}/invites', channel_id=channel_id))\n\n def delete_invite(self, invite_id: str, *, reason: Optional[str] = None) -> Response[None]:\n return self.request(Route('DELETE', '/invites/{invite_id}', invite_id=invite_id), reason=reason)\n\n # Role management\n\n def get_roles(self, guild_id: Snowflake) -> Response[List[role.Role]]:\n return self.request(Route('GET', '/guilds/{guild_id}/roles', guild_id=guild_id))\n\n def edit_role(\n self, guild_id: Snowflake, role_id: Snowflake, *, reason: Optional[str] = None, **fields: Any\n ) -> Response[role.Role]:\n r = Route('PATCH', '/guilds/{guild_id}/roles/{role_id}', guild_id=guild_id, role_id=role_id)\n valid_keys = ('name', 'permissions', 'color', 'hoist', 'icon', 'unicode_emoji', 'mentionable')\n payload = {k: v for k, v in fields.items() if k in valid_keys}\n return self.request(r, json=payload, reason=reason)\n\n def delete_role(self, guild_id: Snowflake, role_id: Snowflake, *, reason: Optional[str] = None) -> Response[None]:\n r = Route('DELETE', '/guilds/{guild_id}/roles/{role_id}', guild_id=guild_id, role_id=role_id)\n return self.request(r, reason=reason)\n\n def replace_roles(\n self,\n user_id: Snowflake,\n guild_id: Snowflake,\n role_ids: List[int],\n *,\n reason: Optional[str] = None,\n ) -> Response[member.MemberWithUser]:\n return self.edit_member(guild_id=guild_id, user_id=user_id, roles=role_ids, reason=reason)\n\n def create_role(self, guild_id: Snowflake, *, reason: Optional[str] = None, **fields: Any) -> Response[role.Role]:\n r = Route('POST', '/guilds/{guild_id}/roles', guild_id=guild_id)\n return self.request(r, json=fields, reason=reason)\n\n def move_role_position(\n self,\n guild_id: Snowflake,\n positions: List[guild.RolePositionUpdate],\n *,\n reason: Optional[str] = None,\n ) -> Response[List[role.Role]]:\n r = Route('PATCH', '/guilds/{guild_id}/roles', guild_id=guild_id)\n return self.request(r, json=positions, reason=reason)\n\n def add_role(\n self, guild_id: Snowflake, user_id: Snowflake, role_id: Snowflake, *, reason: Optional[str] = None\n ) -> Response[None]:\n r = Route(\n 'PUT',\n '/guilds/{guild_id}/members/{user_id}/roles/{role_id}',\n guild_id=guild_id,\n user_id=user_id,\n role_id=role_id,\n )\n return self.request(r, reason=reason)\n\n def remove_role(\n self, guild_id: Snowflake, user_id: Snowflake, role_id: Snowflake, *, reason: Optional[str] = None\n ) -> Response[None]:\n r = Route(\n 'DELETE',\n '/guilds/{guild_id}/members/{user_id}/roles/{role_id}',\n guild_id=guild_id,\n user_id=user_id,\n role_id=role_id,\n )\n return self.request(r, reason=reason)\n\n def edit_channel_permissions(\n self,\n channel_id: Snowflake,\n target: Snowflake,\n allow: str,\n deny: str,\n type: channel.OverwriteType,\n *,\n reason: Optional[str] = None,\n ) -> Response[None]:\n payload = {'id': target, 'allow': allow, 'deny': deny, 'type': type}\n r = Route('PUT', '/channels/{channel_id}/permissions/{target}', channel_id=channel_id, target=target)\n return self.request(r, json=payload, reason=reason)\n\n def delete_channel_permissions(\n self, channel_id: Snowflake, target: Snowflake, *, reason: Optional[str] = None\n ) -> Response[None]:\n r = Route('DELETE', '/channels/{channel_id}/permissions/{target}', channel_id=channel_id, target=target)\n return self.request(r, reason=reason)\n\n # Voice management\n\n def move_member(\n self,\n user_id: Snowflake,\n guild_id: Snowflake,\n channel_id: Snowflake,\n *,\n reason: Optional[str] = None,\n ) -> Response[member.MemberWithUser]:\n return self.edit_member(guild_id=guild_id, user_id=user_id, channel_id=channel_id, reason=reason)\n\n # Stage instance management\n\n def get_stage_instance(self, channel_id: Snowflake) -> Response[channel.StageInstance]:\n return self.request(Route('GET', '/stage-instances/{channel_id}', channel_id=channel_id))\n\n def create_stage_instance(self, *, reason: Optional[str], **payload: Any) -> Response[channel.StageInstance]:\n valid_keys = (\n 'channel_id',\n 'topic',\n 'privacy_level',\n 'send_start_notification',\n 'guild_scheduled_event_id',\n )\n payload = {k: v for k, v in payload.items() if k in valid_keys}\n\n return self.request(Route('POST', '/stage-instances'), json=payload, reason=reason)\n\n def edit_stage_instance(self, channel_id: Snowflake, *, reason: Optional[str] = None, **payload: Any) -> Response[None]:\n valid_keys = (\n 'topic',\n 'privacy_level',\n )\n payload = {k: v for k, v in payload.items() if k in valid_keys}\n\n return self.request(\n Route('PATCH', '/stage-instances/{channel_id}', channel_id=channel_id), json=payload, reason=reason\n )\n\n def delete_stage_instance(self, channel_id: Snowflake, *, reason: Optional[str] = None) -> Response[None]:\n return self.request(Route('DELETE', '/stage-instances/{channel_id}', channel_id=channel_id), reason=reason)\n\n # Guild scheduled event management\n\n @overload\n def get_scheduled_events(\n self, guild_id: Snowflake, with_user_count: Literal[True]\n ) -> Response[List[scheduled_event.GuildScheduledEventWithUserCount]]:\n ...\n\n @overload\n def get_scheduled_events(\n self, guild_id: Snowflake, with_user_count: Literal[False]\n ) -> Response[List[scheduled_event.GuildScheduledEvent]]:\n ...\n\n @overload\n def get_scheduled_events(\n self, guild_id: Snowflake, with_user_count: bool\n ) -> Union[\n Response[List[scheduled_event.GuildScheduledEventWithUserCount]], Response[List[scheduled_event.GuildScheduledEvent]]\n ]:\n ...\n\n def get_scheduled_events(self, guild_id: Snowflake, with_user_count: bool) -> Response[Any]:\n params = {'with_user_count': int(with_user_count)}\n return self.request(Route('GET', '/guilds/{guild_id}/scheduled-events', guild_id=guild_id), params=params)\n\n def create_guild_scheduled_event(\n self, guild_id: Snowflake, *, reason: Optional[str] = None, **payload: Any\n ) -> Response[scheduled_event.GuildScheduledEvent]:\n valid_keys = (\n 'channel_id',\n 'entity_metadata',\n 'name',\n 'privacy_level',\n 'scheduled_start_time',\n 'scheduled_end_time',\n 'description',\n 'entity_type',\n 'image',\n )\n payload = {k: v for k, v in payload.items() if k in valid_keys}\n\n return self.request(\n Route('POST', '/guilds/{guild_id}/scheduled-events', guild_id=guild_id), json=payload, reason=reason\n )\n\n @overload\n def get_scheduled_event(\n self, guild_id: Snowflake, guild_scheduled_event_id: Snowflake, with_user_count: Literal[True]\n ) -> Response[scheduled_event.GuildScheduledEventWithUserCount]:\n ...\n\n @overload\n def get_scheduled_event(\n self, guild_id: Snowflake, guild_scheduled_event_id: Snowflake, with_user_count: Literal[False]\n ) -> Response[scheduled_event.GuildScheduledEvent]:\n ...\n\n @overload\n def get_scheduled_event(\n self, guild_id: Snowflake, guild_scheduled_event_id: Snowflake, with_user_count: bool\n ) -> Union[Response[scheduled_event.GuildScheduledEventWithUserCount], Response[scheduled_event.GuildScheduledEvent]]:\n ...\n\n def get_scheduled_event(\n self, guild_id: Snowflake, guild_scheduled_event_id: Snowflake, with_user_count: bool\n ) -> Response[Any]:\n params = {'with_user_count': int(with_user_count)}\n return self.request(\n Route(\n 'GET',\n '/guilds/{guild_id}/scheduled-events/{guild_scheduled_event_id}',\n guild_id=guild_id,\n guild_scheduled_event_id=guild_scheduled_event_id,\n ),\n params=params,\n )\n\n def edit_scheduled_event(\n self, guild_id: Snowflake, guild_scheduled_event_id: Snowflake, *, reason: Optional[str] = None, **payload: Any\n ) -> Response[scheduled_event.GuildScheduledEvent]:\n valid_keys = (\n 'channel_id',\n 'entity_metadata',\n 'name',\n 'privacy_level',\n 'scheduled_start_time',\n 'scheduled_end_time',\n 'status',\n 'description',\n 'entity_type',\n 'image',\n )\n payload = {k: v for k, v in payload.items() if k in valid_keys}\n\n return self.request(\n Route(\n 'PATCH',\n '/guilds/{guild_id}/scheduled-events/{guild_scheduled_event_id}',\n guild_id=guild_id,\n guild_scheduled_event_id=guild_scheduled_event_id,\n ),\n json=payload,\n reason=reason,\n )\n\n def delete_scheduled_event(\n self,\n guild_id: Snowflake,\n guild_scheduled_event_id: Snowflake,\n *,\n reason: Optional[str] = None,\n ) -> Response[None]:\n return self.request(\n Route(\n 'DELETE',\n '/guilds/{guild_id}/scheduled-events/{guild_scheduled_event_id}',\n guild_id=guild_id,\n guild_scheduled_event_id=guild_scheduled_event_id,\n ),\n reason=reason,\n )\n\n @overload\n def get_scheduled_event_users(\n self,\n guild_id: Snowflake,\n guild_scheduled_event_id: Snowflake,\n limit: int,\n with_member: Literal[True],\n before: Optional[Snowflake] = ...,\n after: Optional[Snowflake] = ...,\n ) -> Response[scheduled_event.ScheduledEventUsersWithMember]:\n ...\n\n @overload\n def get_scheduled_event_users(\n self,\n guild_id: Snowflake,\n guild_scheduled_event_id: Snowflake,\n limit: int,\n with_member: Literal[False],\n before: Optional[Snowflake] = ...,\n after: Optional[Snowflake] = ...,\n ) -> Response[scheduled_event.ScheduledEventUsers]:\n ...\n\n @overload\n def get_scheduled_event_users(\n self,\n guild_id: Snowflake,\n guild_scheduled_event_id: Snowflake,\n limit: int,\n with_member: bool,\n before: Optional[Snowflake] = ...,\n after: Optional[Snowflake] = ...,\n ) -> Union[Response[scheduled_event.ScheduledEventUsersWithMember], Response[scheduled_event.ScheduledEventUsers]]:\n ...\n\n def get_scheduled_event_users(\n self,\n guild_id: Snowflake,\n guild_scheduled_event_id: Snowflake,\n limit: int,\n with_member: bool,\n before: Optional[Snowflake] = None,\n after: Optional[Snowflake] = None,\n ) -> Response[Any]:\n params: Dict[str, Any] = {\n 'limit': limit,\n 'with_member': int(with_member),\n }\n\n if before is not None:\n params['before'] = before\n if after is not None:\n params['after'] = after\n\n return self.request(\n Route(\n 'GET',\n '/guilds/{guild_id}/scheduled-events/{guild_scheduled_event_id}/users',\n guild_id=guild_id,\n guild_scheduled_event_id=guild_scheduled_event_id,\n ),\n params=params,\n )\n\n # Application commands (global)\n\n def get_global_commands(self, application_id: Snowflake) -> Response[List[command.ApplicationCommand]]:\n return self.request(Route('GET', '/applications/{application_id}/commands', application_id=application_id))\n\n def get_global_command(self, application_id: Snowflake, command_id: Snowflake) -> Response[command.ApplicationCommand]:\n r = Route(\n 'GET',\n '/applications/{application_id}/commands/{command_id}',\n application_id=application_id,\n command_id=command_id,\n )\n return self.request(r)\n\n def upsert_global_command(\n self, application_id: Snowflake, payload: command.ApplicationCommand\n ) -> Response[command.ApplicationCommand]:\n r = Route('POST', '/applications/{application_id}/commands', application_id=application_id)\n return self.request(r, json=payload)\n\n def edit_global_command(\n self,\n application_id: Snowflake,\n command_id: Snowflake,\n payload: Dict[str, Any],\n ) -> Response[command.ApplicationCommand]:\n valid_keys = (\n 'name',\n 'description',\n 'options',\n )\n payload = {k: v for k, v in payload.items() if k in valid_keys}\n r = Route(\n 'PATCH',\n '/applications/{application_id}/commands/{command_id}',\n application_id=application_id,\n command_id=command_id,\n )\n return self.request(r, json=payload)\n\n def delete_global_command(self, application_id: Snowflake, command_id: Snowflake) -> Response[None]:\n r = Route(\n 'DELETE',\n '/applications/{application_id}/commands/{command_id}',\n application_id=application_id,\n command_id=command_id,\n )\n return self.request(r)\n\n def bulk_upsert_global_commands(\n self, application_id: Snowflake, payload: List[Dict[str, Any]]\n ) -> Response[List[command.ApplicationCommand]]:\n r = Route('PUT', '/applications/{application_id}/commands', application_id=application_id)\n return self.request(r, json=payload)\n\n # Application commands (guild)\n\n def get_guild_commands(\n self, application_id: Snowflake, guild_id: Snowflake\n ) -> Response[List[command.ApplicationCommand]]:\n r = Route(\n 'GET',\n '/applications/{application_id}/guilds/{guild_id}/commands',\n application_id=application_id,\n guild_id=guild_id,\n )\n return self.request(r)\n\n def get_guild_command(\n self,\n application_id: Snowflake,\n guild_id: Snowflake,\n command_id: Snowflake,\n ) -> Response[command.ApplicationCommand]:\n r = Route(\n 'GET',\n '/applications/{application_id}/guilds/{guild_id}/commands/{command_id}',\n application_id=application_id,\n guild_id=guild_id,\n command_id=command_id,\n )\n return self.request(r)\n\n def upsert_guild_command(\n self,\n application_id: Snowflake,\n guild_id: Snowflake,\n payload: Dict[str, Any],\n ) -> Response[command.ApplicationCommand]:\n r = Route(\n 'POST',\n '/applications/{application_id}/guilds/{guild_id}/commands',\n application_id=application_id,\n guild_id=guild_id,\n )\n return self.request(r, json=payload)\n\n def edit_guild_command(\n self,\n application_id: Snowflake,\n guild_id: Snowflake,\n command_id: Snowflake,\n payload: Dict[str, Any],\n ) -> Response[command.ApplicationCommand]:\n valid_keys = (\n 'name',\n 'description',\n 'options',\n )\n payload = {k: v for k, v in payload.items() if k in valid_keys}\n r = Route(\n 'PATCH',\n '/applications/{application_id}/guilds/{guild_id}/commands/{command_id}',\n application_id=application_id,\n guild_id=guild_id,\n command_id=command_id,\n )\n return self.request(r, json=payload)\n\n def delete_guild_command(\n self,\n application_id: Snowflake,\n guild_id: Snowflake,\n command_id: Snowflake,\n ) -> Response[None]:\n r = Route(\n 'DELETE',\n '/applications/{application_id}/guilds/{guild_id}/commands/{command_id}',\n application_id=application_id,\n guild_id=guild_id,\n command_id=command_id,\n )\n return self.request(r)\n\n def bulk_upsert_guild_commands(\n self,\n application_id: Snowflake,\n guild_id: Snowflake,\n payload: List[Dict[str, Any]],\n ) -> Response[List[command.ApplicationCommand]]:\n r = Route(\n 'PUT',\n '/applications/{application_id}/guilds/{guild_id}/commands',\n application_id=application_id,\n guild_id=guild_id,\n )\n return self.request(r, json=payload)\n\n def get_guild_application_command_permissions(\n self,\n application_id: Snowflake,\n guild_id: Snowflake,\n ) -> Response[List[command.GuildApplicationCommandPermissions]]:\n r = Route(\n 'GET',\n '/applications/{application_id}/guilds/{guild_id}/commands/permissions',\n application_id=application_id,\n guild_id=guild_id,\n )\n return self.request(r)\n\n def get_application_command_permissions(\n self,\n application_id: Snowflake,\n guild_id: Snowflake,\n command_id: Snowflake,\n ) -> Response[command.GuildApplicationCommandPermissions]:\n r = Route(\n 'GET',\n '/applications/{application_id}/guilds/{guild_id}/commands/{command_id}/permissions',\n application_id=application_id,\n guild_id=guild_id,\n command_id=command_id,\n )\n return self.request(r)\n\n def edit_application_command_permissions(\n self,\n application_id: Snowflake,\n guild_id: Snowflake,\n command_id: Snowflake,\n payload: Dict[str, Any],\n ) -> Response[None]:\n r = Route(\n 'PUT',\n '/applications/{application_id}/guilds/{guild_id}/commands/{command_id}/permissions',\n application_id=application_id,\n guild_id=guild_id,\n command_id=command_id,\n )\n return self.request(r, json=payload)\n\n def get_auto_moderation_rules(self, guild_id: Snowflake) -> Response[List[automod.AutoModerationRule]]:\n return self.request(Route('GET', '/guilds/{guild_id}/auto-moderation/rules', guild_id=guild_id))\n\n def get_auto_moderation_rule(self, guild_id: Snowflake, rule_id: Snowflake) -> Response[automod.AutoModerationRule]:\n return self.request(\n Route('GET', '/guilds/{guild_id}/auto-moderation/rules/{rule_id}', guild_id=guild_id, rule_id=rule_id)\n )\n\n def create_auto_moderation_rule(\n self, guild_id: Snowflake, *, reason: Optional[str], **payload: Any\n ) -> Response[automod.AutoModerationRule]:\n valid_keys = (\n 'name',\n 'event_type',\n 'trigger_type',\n 'trigger_metadata',\n 'actions',\n 'enabled',\n 'exempt_roles',\n 'exempt_channels',\n )\n\n payload = {k: v for k, v in payload.items() if k in valid_keys and v is not None}\n\n return self.request(\n Route('POST', '/guilds/{guild_id}/auto-moderation/rules', guild_id=guild_id), json=payload, reason=reason\n )\n\n def edit_auto_moderation_rule(\n self, guild_id: Snowflake, rule_id: Snowflake, *, reason: Optional[str], **payload: Any\n ) -> Response[automod.AutoModerationRule]:\n valid_keys = (\n 'name',\n 'event_type',\n 'trigger_metadata',\n 'actions',\n 'enabled',\n 'exempt_roles',\n 'exempt_channels',\n )\n\n payload = {k: v for k, v in payload.items() if k in valid_keys and v is not None}\n\n return self.request(\n Route('PATCH', '/guilds/{guild_id}/auto-moderation/rules/{rule_id}', guild_id=guild_id, rule_id=rule_id),\n json=payload,\n reason=reason,\n )\n\n def delete_auto_moderation_rule(\n self, guild_id: Snowflake, rule_id: Snowflake, *, reason: Optional[str]\n ) -> Response[None]:\n return self.request(\n Route('DELETE', '/guilds/{guild_id}/auto-moderation/rules/{rule_id}', guild_id=guild_id, rule_id=rule_id),\n reason=reason,\n )\n\n # SKU\n\n def get_skus(self, application_id: Snowflake) -> Response[List[sku.SKU]]:\n return self.request(Route('GET', '/applications/{application_id}/skus', application_id=application_id))\n\n def get_entitlements(\n self,\n application_id: Snowflake,\n user_id: Optional[Snowflake] = None,\n sku_ids: Optional[SnowflakeList] = None,\n before: Optional[Snowflake] = None,\n after: Optional[Snowflake] = None,\n limit: Optional[int] = None,\n guild_id: Optional[Snowflake] = None,\n exclude_ended: Optional[bool] = None,\n ) -> Response[List[sku.Entitlement]]:\n params: Dict[str, Any] = {}\n\n if user_id is not None:\n params['user_id'] = user_id\n if sku_ids is not None:\n params['sku_ids'] = ','.join(map(str, sku_ids))\n if before is not None:\n params['before'] = before\n if after is not None:\n params['after'] = after\n if limit is not None:\n params['limit'] = limit\n if guild_id is not None:\n params['guild_id'] = guild_id\n if exclude_ended is not None:\n params['exclude_ended'] = int(exclude_ended)\n\n return self.request(\n Route('GET', '/applications/{application_id}/entitlements', application_id=application_id), params=params\n )\n\n def get_entitlement(self, application_id: Snowflake, entitlement_id: Snowflake) -> Response[sku.Entitlement]:\n return self.request(\n Route(\n 'GET',\n '/applications/{application_id}/entitlements/{entitlement_id}',\n application_id=application_id,\n entitlement_id=entitlement_id,\n ),\n )\n\n def create_entitlement(\n self, application_id: Snowflake, sku_id: Snowflake, owner_id: Snowflake, owner_type: sku.EntitlementOwnerType\n ) -> Response[sku.Entitlement]:\n payload = {\n 'sku_id': sku_id,\n 'owner_id': owner_id,\n 'owner_type': owner_type,\n }\n\n return self.request(\n Route(\n 'POST',\n '/applications/{application_id}/entitlements',\n application_id=application_id,\n ),\n json=payload,\n )\n\n def delete_entitlement(self, application_id: Snowflake, entitlement_id: Snowflake) -> Response[None]:\n return self.request(\n Route(\n 'DELETE',\n '/applications/{application_id}/entitlements/{entitlement_id}',\n application_id=application_id,\n entitlement_id=entitlement_id,\n ),\n )\n\n # Misc\n\n def application_info(self) -> Response[appinfo.AppInfo]:\n return self.request(Route('GET', '/oauth2/applications/@me'))\n\n async def get_gateway(self, *, encoding: str = 'json', zlib: bool = True) -> str:\n try:\n data = await self.request(Route('GET', '/gateway'))\n except HTTPException as exc:\n raise GatewayNotFound() from exc\n if zlib:\n value = '{0}?encoding={1}&v={2}&compress=zlib-stream'\n else:\n value = '{0}?encoding={1}&v={2}'\n return value.format(data['url'], encoding, INTERNAL_API_VERSION)\n\n async def get_bot_gateway(self, *, encoding: str = 'json', zlib: bool = True) -> Tuple[int, str]:\n try:\n data = await self.request(Route('GET', '/gateway/bot'))\n except HTTPException as exc:\n raise GatewayNotFound() from exc\n\n if zlib:\n value = '{0}?encoding={1}&v={2}&compress=zlib-stream'\n else:\n value = '{0}?encoding={1}&v={2}'\n return data['shards'], value.format(data['url'], encoding, INTERNAL_API_VERSION)\n\n def get_user(self, user_id: Snowflake) -> Response[user.User]:\n return self.request(Route('GET', '/users/{user_id}', user_id=user_id))\n" }, { "path": "discord/types/appinfo.py", "content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import TypedDict, List, Optional\nfrom typing_extensions import NotRequired\n\nfrom .user import User\nfrom .team import Team\nfrom .snowflake import Snowflake\n\n\nclass InstallParams(TypedDict):\n scopes: List[str]\n permissions: str\n\n\nclass BaseAppInfo(TypedDict):\n id: Snowflake\n name: str\n verify_key: str\n icon: Optional[str]\n summary: str\n description: str\n flags: int\n cover_image: NotRequired[str]\n terms_of_service_url: NotRequired[str]\n privacy_policy_url: NotRequired[str]\n rpc_origins: NotRequired[List[str]]\n\n\nclass AppInfo(BaseAppInfo):\n owner: User\n bot_public: bool\n bot_require_code_grant: bool\n team: NotRequired[Team]\n guild_id: NotRequired[Snowflake]\n primary_sku_id: NotRequired[Snowflake]\n slug: NotRequired[str]\n hook: NotRequired[bool]\n max_participants: NotRequired[int]\n tags: NotRequired[List[str]]\n install_params: NotRequired[InstallParams]\n custom_install_url: NotRequired[str]\n role_connections_verification_url: NotRequired[str]\n\n\nclass PartialAppInfo(BaseAppInfo, total=False):\n hook: bool\n max_participants: int\n approximate_guild_count: int\n redirect_uris: List[str]\n interactions_endpoint_url: Optional[str]\n role_connections_verification_url: Optional[str]\n\n\nclass GatewayAppInfo(TypedDict):\n id: Snowflake\n flags: int\n" } ], "language": "python" }, { "id": "10_4", "repo_url": "https://github.com/teamqurrent/discord.py", "instruction": "Enhance the `AutoModRuleAction` class in `automod.py` by modifying its `__init__` method to handle different action types more effectively. Specifically, implement conditional logic to set and validate attributes based on the action type: ensure channel_id is assigned for send_alert_message actions, duration for timeout actions, and custom_message for block_message actions. Include checks to raise errors if necessary attributes for each specific action type are missing, thereby ensuring the integrity and correctness of each `AutoModRuleAction` instance.", "base_commit": "933460c", "test_script": "import unittest\nimport datetime\nimport sys\n\n\n\nclass TestAutoModRuleAction(unittest.TestCase):\n def test_send_alert_message_initialization(self):\n from discord.automod import AutoModRuleAction, AutoModRuleActionType\n action = AutoModRuleAction(type=AutoModRuleActionType.send_alert_message, channel_id=12345)\n self.assertEqual(action.channel_id, 12345)\n self.assertIsNone(action.duration)\n self.assertIsNone(action.custom_message)\n\n def test_timeout_initialization(self):\n from discord.automod import AutoModRuleAction, AutoModRuleActionType\n duration = datetime.timedelta(minutes=10)\n action = AutoModRuleAction(type=AutoModRuleActionType.timeout, duration=duration)\n self.assertEqual(action.duration, duration)\n self.assertIsNone(action.channel_id)\n self.assertIsNone(action.custom_message)\n\n def test_block_message_initialization(self):\n from discord.automod import AutoModRuleAction, AutoModRuleActionType\n action = AutoModRuleAction(type=AutoModRuleActionType.block_message, custom_message=\"Blocked\")\n self.assertEqual(action.custom_message, \"Blocked\")\n self.assertIsNone(action.channel_id)\n self.assertIsNone(action.duration)\n\ndef main():\n\n\n suite = unittest.TestSuite()\n suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestAutoModRuleAction))\n runner = unittest.TextTestRunner()\n\n if runner.run(suite).wasSuccessful():\n sys.exit(0)\n else:\n sys.exit(1)\n\nif __name__ == '__main__':\n\n main()\n", "testbed_environment": "python3.9", "requirements_txt": "discord", "solution_commit": "e1c1a72a", "solution_patch": "diff --git a/discord/automod.py b/discord/automod.py\n--- a/discord/automod.py\n+++ b/discord/automod.py\n@@ -135,6 +135,10 @@ class AutoModRuleAction:\n raise ValueError('Only one of channel_id, duration, or custom_message can be passed.')\n \n self.type: AutoModRuleActionType\n+ self.channel_id: Optional[int] = None\n+ self.duration: Optional[datetime.timedelta] = None\n+ self.custom_message: Optional[str] = None\n+\n if type is not None:\n self.type = type\n elif channel_id is not None:\n@@ -147,14 +151,15 @@ class AutoModRuleAction:\n if self.type is AutoModRuleActionType.send_alert_message:\n if channel_id is None:\n raise ValueError('channel_id cannot be None if type is send_alert_message')\n- self.channel_id: Optional[int] = channel_id\n+ self.channel_id = channel_id\n \n if self.type is AutoModRuleActionType.timeout:\n if duration is None:\n raise ValueError('duration cannot be None set if type is timeout')\n- self.duration: Optional[datetime.timedelta] = duration\n+ self.duration = duration\n \n- self.custom_message: Optional[str] = custom_message\n+ if self.type is AutoModRuleActionType.block_message:\n+ self.custom_message = custom_message\n \n def __repr__(self) -> str:\n return f''\n", "modified_files": [ { "path": "discord/automod.py", "content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\n\nfrom __future__ import annotations\nimport datetime\n\nfrom typing import TYPE_CHECKING, Any, Dict, Optional, List, Set, Union, Sequence, overload, Literal\n\nfrom .enums import AutoModRuleTriggerType, AutoModRuleActionType, AutoModRuleEventType, try_enum\nfrom .flags import AutoModPresets\nfrom . import utils\nfrom .utils import MISSING, cached_slot_property\n\nif TYPE_CHECKING:\n from typing_extensions import Self\n from .abc import Snowflake, GuildChannel\n from .threads import Thread\n from .guild import Guild\n from .member import Member\n from .state import ConnectionState\n from .types.automod import (\n AutoModerationRule as AutoModerationRulePayload,\n AutoModerationTriggerMetadata as AutoModerationTriggerMetadataPayload,\n AutoModerationAction as AutoModerationActionPayload,\n AutoModerationActionExecution as AutoModerationActionExecutionPayload,\n )\n from .role import Role\n\n__all__ = (\n 'AutoModRuleAction',\n 'AutoModTrigger',\n 'AutoModRule',\n 'AutoModAction',\n)\n\n\nclass AutoModRuleAction:\n \"\"\"Represents an auto moderation's rule action.\n\n .. note::\n Only one of ``channel_id``, ``duration``, or ``custom_message`` can be used.\n\n .. versionadded:: 2.0\n\n Attributes\n -----------\n type: :class:`AutoModRuleActionType`\n The type of action to take.\n Defaults to :attr:`~AutoModRuleActionType.block_message`.\n channel_id: Optional[:class:`int`]\n The ID of the channel or thread to send the alert message to, if any.\n Passing this sets :attr:`type` to :attr:`~AutoModRuleActionType.send_alert_message`.\n duration: Optional[:class:`datetime.timedelta`]\n The duration of the timeout to apply, if any.\n Has a maximum of 28 days.\n Passing this sets :attr:`type` to :attr:`~AutoModRuleActionType.timeout`.\n custom_message: Optional[:class:`str`]\n A custom message which will be shown to a user when their message is blocked.\n Passing this sets :attr:`type` to :attr:`~AutoModRuleActionType.block_message`.\n\n .. versionadded:: 2.2\n \"\"\"\n\n __slots__ = ('type', 'channel_id', 'duration', 'custom_message')\n\n @overload\n def __init__(self, *, channel_id: int = ...) -> None:\n ...\n\n @overload\n def __init__(self, *, type: Literal[AutoModRuleActionType.send_alert_message], channel_id: int = ...) -> None:\n ...\n\n @overload\n def __init__(self, *, duration: datetime.timedelta = ...) -> None:\n ...\n\n @overload\n def __init__(self, *, type: Literal[AutoModRuleActionType.timeout], duration: datetime.timedelta = ...) -> None:\n ...\n\n @overload\n def __init__(self, *, custom_message: str = ...) -> None:\n ...\n\n @overload\n def __init__(self, *, type: Literal[AutoModRuleActionType.block_message]) -> None:\n ...\n\n @overload\n def __init__(self, *, type: Literal[AutoModRuleActionType.block_message], custom_message: Optional[str] = ...) -> None:\n ...\n\n @overload\n def __init__(\n self,\n *,\n type: Optional[AutoModRuleActionType] = ...,\n channel_id: Optional[int] = ...,\n duration: Optional[datetime.timedelta] = ...,\n custom_message: Optional[str] = ...,\n ) -> None:\n ...\n\n def __init__(\n self,\n *,\n type: Optional[AutoModRuleActionType] = None,\n channel_id: Optional[int] = None,\n duration: Optional[datetime.timedelta] = None,\n custom_message: Optional[str] = None,\n ) -> None:\n if sum(v is None for v in (channel_id, duration, custom_message)) < 2:\n raise ValueError('Only one of channel_id, duration, or custom_message can be passed.')\n\n self.type: AutoModRuleActionType\n if type is not None:\n self.type = type\n elif channel_id is not None:\n self.type = AutoModRuleActionType.send_alert_message\n elif duration is not None:\n self.type = AutoModRuleActionType.timeout\n else:\n self.type = AutoModRuleActionType.block_message\n\n if self.type is AutoModRuleActionType.send_alert_message:\n if channel_id is None:\n raise ValueError('channel_id cannot be None if type is send_alert_message')\n self.channel_id: Optional[int] = channel_id\n\n if self.type is AutoModRuleActionType.timeout:\n if duration is None:\n raise ValueError('duration cannot be None set if type is timeout')\n self.duration: Optional[datetime.timedelta] = duration\n\n self.custom_message: Optional[str] = custom_message\n\n def __repr__(self) -> str:\n return f''\n\n @classmethod\n def from_data(cls, data: AutoModerationActionPayload) -> Self:\n if data['type'] == AutoModRuleActionType.timeout.value:\n duration_seconds = data['metadata']['duration_seconds']\n return cls(duration=datetime.timedelta(seconds=duration_seconds))\n elif data['type'] == AutoModRuleActionType.send_alert_message.value:\n channel_id = int(data['metadata']['channel_id'])\n return cls(channel_id=channel_id)\n elif data['type'] == AutoModRuleActionType.block_message.value:\n custom_message = data.get('metadata', {}).get('custom_message')\n return cls(type=AutoModRuleActionType.block_message, custom_message=custom_message)\n\n return cls(type=AutoModRuleActionType.block_member_interactions)\n\n def to_dict(self) -> Dict[str, Any]:\n ret = {'type': self.type.value, 'metadata': {}}\n if self.type is AutoModRuleActionType.block_message and self.custom_message is not None:\n ret['metadata'] = {'custom_message': self.custom_message}\n elif self.type is AutoModRuleActionType.timeout:\n ret['metadata'] = {'duration_seconds': int(self.duration.total_seconds())} # type: ignore # duration cannot be None here\n elif self.type is AutoModRuleActionType.send_alert_message:\n ret['metadata'] = {'channel_id': str(self.channel_id)}\n return ret\n\n\nclass AutoModTrigger:\n r\"\"\"Represents a trigger for an auto moderation rule.\n\n The following table illustrates relevant attributes for each :class:`AutoModRuleTriggerType`:\n\n +-----------------------------------------------+------------------------------------------------+\n | Type | Attributes |\n +===============================================+================================================+\n | :attr:`AutoModRuleTriggerType.keyword` | :attr:`keyword_filter`, :attr:`regex_patterns`,|\n | | :attr:`allow_list` |\n +-----------------------------------------------+------------------------------------------------+\n | :attr:`AutoModRuleTriggerType.spam` | |\n +-----------------------------------------------+------------------------------------------------+\n | :attr:`AutoModRuleTriggerType.keyword_preset` | :attr:`presets`\\, :attr:`allow_list` |\n +-----------------------------------------------+------------------------------------------------+\n | :attr:`AutoModRuleTriggerType.mention_spam` | :attr:`mention_limit`, |\n | | :attr:`mention_raid_protection` |\n +-----------------------------------------------+------------------------------------------------+\n | :attr:`AutoModRuleTriggerType.member_profile` | :attr:`keyword_filter`, :attr:`regex_patterns`,|\n | | :attr:`allow_list` |\n +-----------------------------------------------+------------------------------------------------+\n\n .. versionadded:: 2.0\n\n Attributes\n -----------\n type: :class:`AutoModRuleTriggerType`\n The type of trigger.\n keyword_filter: List[:class:`str`]\n The list of strings that will trigger the filter.\n Maximum of 1000. Keywords can only be up to 60 characters in length.\n\n This could be combined with :attr:`regex_patterns`.\n regex_patterns: List[:class:`str`]\n The regex pattern that will trigger the filter. The syntax is based off of\n `Rust's regex syntax `_.\n Maximum of 10. Regex strings can only be up to 260 characters in length.\n\n This could be combined with :attr:`keyword_filter` and/or :attr:`allow_list`\n\n .. versionadded:: 2.1\n presets: :class:`AutoModPresets`\n The presets used with the preset keyword filter.\n allow_list: List[:class:`str`]\n The list of words that are exempt from the commonly flagged words. Maximum of 100.\n Keywords can only be up to 60 characters in length.\n mention_limit: :class:`int`\n The total number of user and role mentions a message can contain.\n Has a maximum of 50.\n mention_raid_protection: :class:`bool`\n Whether mention raid protection is enabled or not.\n\n .. versionadded:: 2.4\n \"\"\"\n\n __slots__ = (\n 'type',\n 'keyword_filter',\n 'presets',\n 'allow_list',\n 'mention_limit',\n 'regex_patterns',\n 'mention_raid_protection',\n )\n\n def __init__(\n self,\n *,\n type: Optional[AutoModRuleTriggerType] = None,\n keyword_filter: Optional[List[str]] = None,\n presets: Optional[AutoModPresets] = None,\n allow_list: Optional[List[str]] = None,\n mention_limit: Optional[int] = None,\n regex_patterns: Optional[List[str]] = None,\n mention_raid_protection: Optional[bool] = None,\n ) -> None:\n unique_args = (keyword_filter or regex_patterns, presets, mention_limit or mention_raid_protection)\n if type is None and sum(arg is not None for arg in unique_args) > 1:\n raise ValueError(\n 'Please pass only one of keyword_filter/regex_patterns, presets, or mention_limit/mention_raid_protection.'\n )\n\n if type is not None:\n self.type = type\n elif keyword_filter is not None or regex_patterns is not None:\n self.type = AutoModRuleTriggerType.keyword\n elif presets is not None:\n self.type = AutoModRuleTriggerType.keyword_preset\n elif mention_limit is not None or mention_raid_protection is not None:\n self.type = AutoModRuleTriggerType.mention_spam\n else:\n raise ValueError(\n 'Please pass the trigger type explicitly if not using keyword_filter, regex_patterns, presets, mention_limit, or mention_raid_protection.'\n )\n\n self.keyword_filter: List[str] = keyword_filter if keyword_filter is not None else []\n self.presets: AutoModPresets = presets if presets is not None else AutoModPresets()\n self.allow_list: List[str] = allow_list if allow_list is not None else []\n self.mention_limit: int = mention_limit if mention_limit is not None else 0\n self.mention_raid_protection: bool = mention_raid_protection if mention_raid_protection is not None else False\n self.regex_patterns: List[str] = regex_patterns if regex_patterns is not None else []\n\n def __repr__(self) -> str:\n data = self.to_metadata_dict()\n if data:\n joined = ' '.join(f'{k}={v!r}' for k, v in data.items())\n return f''\n\n return f''\n\n @classmethod\n def from_data(cls, type: int, data: Optional[AutoModerationTriggerMetadataPayload]) -> Self:\n type_ = try_enum(AutoModRuleTriggerType, type)\n if data is None:\n return cls(type=type_)\n elif type_ in (AutoModRuleTriggerType.keyword, AutoModRuleTriggerType.member_profile):\n return cls(\n type=type_,\n keyword_filter=data.get('keyword_filter'),\n regex_patterns=data.get('regex_patterns'),\n allow_list=data.get('allow_list'),\n )\n elif type_ is AutoModRuleTriggerType.keyword_preset:\n return cls(\n type=type_, presets=AutoModPresets._from_value(data.get('presets', [])), allow_list=data.get('allow_list')\n )\n elif type_ is AutoModRuleTriggerType.mention_spam:\n return cls(\n type=type_,\n mention_limit=data.get('mention_total_limit'),\n mention_raid_protection=data.get('mention_raid_protection_enabled'),\n )\n else:\n return cls(type=type_)\n\n def to_metadata_dict(self) -> Optional[Dict[str, Any]]:\n if self.type in (AutoModRuleTriggerType.keyword, AutoModRuleTriggerType.member_profile):\n return {\n 'keyword_filter': self.keyword_filter,\n 'regex_patterns': self.regex_patterns,\n 'allow_list': self.allow_list,\n }\n elif self.type is AutoModRuleTriggerType.keyword_preset:\n return {'presets': self.presets.to_array(), 'allow_list': self.allow_list}\n elif self.type is AutoModRuleTriggerType.mention_spam:\n return {\n 'mention_total_limit': self.mention_limit,\n 'mention_raid_protection_enabled': self.mention_raid_protection,\n }\n\n\nclass AutoModRule:\n \"\"\"Represents an auto moderation rule.\n\n .. versionadded:: 2.0\n\n Attributes\n -----------\n id: :class:`int`\n The ID of the rule.\n guild: :class:`Guild`\n The guild the rule is for.\n name: :class:`str`\n The name of the rule.\n creator_id: :class:`int`\n The ID of the user that created the rule.\n trigger: :class:`AutoModTrigger`\n The rule's trigger.\n enabled: :class:`bool`\n Whether the rule is enabled.\n exempt_role_ids: Set[:class:`int`]\n The IDs of the roles that are exempt from the rule.\n exempt_channel_ids: Set[:class:`int`]\n The IDs of the channels that are exempt from the rule.\n event_type: :class:`AutoModRuleEventType`\n The type of event that will trigger the the rule.\n \"\"\"\n\n __slots__ = (\n '_state',\n '_cs_exempt_roles',\n '_cs_exempt_channels',\n '_cs_actions',\n 'id',\n 'guild',\n 'name',\n 'creator_id',\n 'event_type',\n 'trigger',\n 'enabled',\n 'exempt_role_ids',\n 'exempt_channel_ids',\n '_actions',\n )\n\n def __init__(self, *, data: AutoModerationRulePayload, guild: Guild, state: ConnectionState) -> None:\n self._state: ConnectionState = state\n self.guild: Guild = guild\n self.id: int = int(data['id'])\n self.name: str = data['name']\n self.creator_id = int(data['creator_id'])\n self.event_type: AutoModRuleEventType = try_enum(AutoModRuleEventType, data['event_type'])\n self.trigger: AutoModTrigger = AutoModTrigger.from_data(data['trigger_type'], data=data.get('trigger_metadata'))\n self.enabled: bool = data['enabled']\n self.exempt_role_ids: Set[int] = {int(role_id) for role_id in data['exempt_roles']}\n self.exempt_channel_ids: Set[int] = {int(channel_id) for channel_id in data['exempt_channels']}\n self._actions: List[AutoModerationActionPayload] = data['actions']\n\n def __repr__(self) -> str:\n return f''\n\n def to_dict(self) -> AutoModerationRulePayload:\n ret: AutoModerationRulePayload = {\n 'id': str(self.id),\n 'guild_id': str(self.guild.id),\n 'name': self.name,\n 'creator_id': str(self.creator_id),\n 'event_type': self.event_type.value,\n 'trigger_type': self.trigger.type.value,\n 'trigger_metadata': self.trigger.to_metadata_dict(),\n 'actions': [action.to_dict() for action in self.actions],\n 'enabled': self.enabled,\n 'exempt_roles': [str(role_id) for role_id in self.exempt_role_ids],\n 'exempt_channels': [str(channel_id) for channel_id in self.exempt_channel_ids],\n } # type: ignore # trigger types break the flow here.\n\n return ret\n\n @property\n def creator(self) -> Optional[Member]:\n \"\"\"Optional[:class:`Member`]: The member that created this rule.\"\"\"\n return self.guild.get_member(self.creator_id)\n\n @cached_slot_property('_cs_exempt_roles')\n def exempt_roles(self) -> List[Role]:\n \"\"\"List[:class:`Role`]: The roles that are exempt from this rule.\"\"\"\n result = []\n get_role = self.guild.get_role\n for role_id in self.exempt_role_ids:\n role = get_role(role_id)\n if role is not None:\n result.append(role)\n\n return utils._unique(result)\n\n @cached_slot_property('_cs_exempt_channels')\n def exempt_channels(self) -> List[Union[GuildChannel, Thread]]:\n \"\"\"List[Union[:class:`abc.GuildChannel`, :class:`Thread`]]: The channels that are exempt from this rule.\"\"\"\n it = filter(None, map(self.guild._resolve_channel, self.exempt_channel_ids))\n return utils._unique(it)\n\n @cached_slot_property('_cs_actions')\n def actions(self) -> List[AutoModRuleAction]:\n \"\"\"List[:class:`AutoModRuleAction`]: The actions that are taken when this rule is triggered.\"\"\"\n return [AutoModRuleAction.from_data(action) for action in self._actions]\n\n def is_exempt(self, obj: Snowflake, /) -> bool:\n \"\"\"Check if an object is exempt from the automod rule.\n\n Parameters\n -----------\n obj: :class:`abc.Snowflake`\n The role, channel, or thread to check.\n\n Returns\n --------\n :class:`bool`\n Whether the object is exempt from the automod rule.\n \"\"\"\n return obj.id in self.exempt_channel_ids or obj.id in self.exempt_role_ids\n\n async def edit(\n self,\n *,\n name: str = MISSING,\n event_type: AutoModRuleEventType = MISSING,\n actions: List[AutoModRuleAction] = MISSING,\n trigger: AutoModTrigger = MISSING,\n enabled: bool = MISSING,\n exempt_roles: Sequence[Snowflake] = MISSING,\n exempt_channels: Sequence[Snowflake] = MISSING,\n reason: str = MISSING,\n ) -> Self:\n \"\"\"|coro|\n\n Edits this auto moderation rule.\n\n You must have :attr:`Permissions.manage_guild` to edit rules.\n\n Parameters\n -----------\n name: :class:`str`\n The new name to change to.\n event_type: :class:`AutoModRuleEventType`\n The new event type to change to.\n actions: List[:class:`AutoModRuleAction`]\n The new rule actions to update.\n trigger: :class:`AutoModTrigger`\n The new trigger to update.\n You can only change the trigger metadata, not the type.\n enabled: :class:`bool`\n Whether the rule should be enabled or not.\n exempt_roles: Sequence[:class:`abc.Snowflake`]\n The new roles to exempt from the rule.\n exempt_channels: Sequence[:class:`abc.Snowflake`]\n The new channels to exempt from the rule.\n reason: :class:`str`\n The reason for updating this rule. Shows up on the audit log.\n\n Raises\n -------\n Forbidden\n You do not have permission to edit this rule.\n HTTPException\n Editing the rule failed.\n\n Returns\n --------\n :class:`AutoModRule`\n The updated auto moderation rule.\n \"\"\"\n payload = {}\n if actions is not MISSING:\n payload['actions'] = [action.to_dict() for action in actions]\n\n if name is not MISSING:\n payload['name'] = name\n\n if event_type is not MISSING:\n payload['event_type'] = event_type\n\n if trigger is not MISSING:\n trigger_metadata = trigger.to_metadata_dict()\n if trigger_metadata is not None:\n payload['trigger_metadata'] = trigger_metadata\n\n if enabled is not MISSING:\n payload['enabled'] = enabled\n\n if exempt_roles is not MISSING:\n payload['exempt_roles'] = [x.id for x in exempt_roles]\n\n if exempt_channels is not MISSING:\n payload['exempt_channels'] = [x.id for x in exempt_channels]\n\n data = await self._state.http.edit_auto_moderation_rule(\n self.guild.id,\n self.id,\n reason=reason,\n **payload,\n )\n\n return AutoModRule(data=data, guild=self.guild, state=self._state)\n\n async def delete(self, *, reason: str = MISSING) -> None:\n \"\"\"|coro|\n\n Deletes the auto moderation rule.\n\n You must have :attr:`Permissions.manage_guild` to delete rules.\n\n Parameters\n -----------\n reason: :class:`str`\n The reason for deleting this rule. Shows up on the audit log.\n\n Raises\n -------\n Forbidden\n You do not have permissions to delete the rule.\n HTTPException\n Deleting the rule failed.\n \"\"\"\n await self._state.http.delete_auto_moderation_rule(self.guild.id, self.id, reason=reason)\n\n\nclass AutoModAction:\n \"\"\"Represents an action that was taken as the result of a moderation rule.\n\n .. versionadded:: 2.0\n\n Attributes\n -----------\n action: :class:`AutoModRuleAction`\n The action that was taken.\n message_id: Optional[:class:`int`]\n The message ID that triggered the action. This is only available if the\n action is done on an edited message.\n rule_id: :class:`int`\n The ID of the rule that was triggered.\n rule_trigger_type: :class:`AutoModRuleTriggerType`\n The trigger type of the rule that was triggered.\n guild_id: :class:`int`\n The ID of the guild where the rule was triggered.\n user_id: :class:`int`\n The ID of the user that triggered the rule.\n channel_id: :class:`int`\n The ID of the channel where the rule was triggered.\n alert_system_message_id: Optional[:class:`int`]\n The ID of the system message that was sent to the predefined alert channel.\n content: :class:`str`\n The content of the message that triggered the rule.\n Requires the :attr:`Intents.message_content` or it will always return an empty string.\n matched_keyword: Optional[:class:`str`]\n The matched keyword from the triggering message.\n matched_content: Optional[:class:`str`]\n The matched content from the triggering message.\n Requires the :attr:`Intents.message_content` or it will always return ``None``.\n \"\"\"\n\n __slots__ = (\n '_state',\n 'action',\n 'rule_id',\n 'rule_trigger_type',\n 'guild_id',\n 'user_id',\n 'channel_id',\n 'message_id',\n 'alert_system_message_id',\n 'content',\n 'matched_keyword',\n 'matched_content',\n )\n\n def __init__(self, *, data: AutoModerationActionExecutionPayload, state: ConnectionState) -> None:\n self._state: ConnectionState = state\n self.message_id: Optional[int] = utils._get_as_snowflake(data, 'message_id')\n self.action: AutoModRuleAction = AutoModRuleAction.from_data(data['action'])\n self.rule_id: int = int(data['rule_id'])\n self.rule_trigger_type: AutoModRuleTriggerType = try_enum(AutoModRuleTriggerType, data['rule_trigger_type'])\n self.guild_id: int = int(data['guild_id'])\n self.channel_id: Optional[int] = utils._get_as_snowflake(data, 'channel_id')\n self.user_id: int = int(data['user_id'])\n self.alert_system_message_id: Optional[int] = utils._get_as_snowflake(data, 'alert_system_message_id')\n self.content: str = data.get('content', '')\n self.matched_keyword: Optional[str] = data['matched_keyword']\n self.matched_content: Optional[str] = data.get('matched_content')\n\n def __repr__(self) -> str:\n return f''\n\n @property\n def guild(self) -> Guild:\n \"\"\":class:`Guild`: The guild this action was taken in.\"\"\"\n return self._state._get_or_create_unavailable_guild(self.guild_id)\n\n @property\n def channel(self) -> Optional[Union[GuildChannel, Thread]]:\n \"\"\"Optional[Union[:class:`abc.GuildChannel`, :class:`Thread`]]: The channel this action was taken in.\"\"\"\n if self.channel_id:\n return self.guild.get_channel_or_thread(self.channel_id)\n return None\n\n @property\n def member(self) -> Optional[Member]:\n \"\"\"Optional[:class:`Member`]: The member this action was taken against /who triggered this rule.\"\"\"\n return self.guild.get_member(self.user_id)\n\n async def fetch_rule(self) -> AutoModRule:\n \"\"\"|coro|\n\n Fetch the rule whose action was taken.\n\n You must have :attr:`Permissions.manage_guild` to do this.\n\n Raises\n -------\n Forbidden\n You do not have permissions to view the rule.\n HTTPException\n Fetching the rule failed.\n\n Returns\n --------\n :class:`AutoModRule`\n The rule that was executed.\n \"\"\"\n\n data = await self._state.http.get_auto_moderation_rule(self.guild.id, self.rule_id)\n return AutoModRule(data=data, guild=self.guild, state=self._state)\n" } ], "language": "python" }, { "id": "10_5", "repo_url": "https://github.com/teamqurrent/discord.py", "instruction": "In `app_commands/commands.py`, modify the `Group` class's `__init__` method to include validation checks that ensure both name and description parameters are provided when creating a command group. Implement conditional logic to raise a TypeError if either of these essential attributes is missing, thereby enforcing the requirement for command groups to have both a name and a description before any further processing.", "base_commit": "576ab26", "test_script": "import unittest\nimport sys\n\n\n\nclass TestCommandGroupInitialization(unittest.TestCase):\n def test_group_initialization_without_name(self):\n from discord.app_commands import Group\n with self.assertRaises(TypeError):\n Group(description=\"Test Description\", parent=None)\n\n def test_group_initialization_without_description(self):\n from discord.app_commands import Group\n\n with self.assertRaises(TypeError):\n Group(name=\"test\", parent=None)\n\n def test_group_initialization_with_name_and_description(self):\n from discord.app_commands import Group\n try:\n Group(name=\"test\", description=\"Test Description\", parent=None)\n except TypeError:\n self.fail(\"Group initialization raised TypeError unexpectedly.\")\n\ndef main():\n\n\n suite = unittest.TestSuite()\n suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestCommandGroupInitialization))\n runner = unittest.TextTestRunner()\n\n if runner.run(suite).wasSuccessful():\n sys.exit(0)\n else:\n sys.exit(1)\n\nif __name__ == '__main__':\n\n main()\n", "testbed_environment": "python3.9", "requirements_txt": "discord", "solution_commit": "55594035", "solution_patch": "diff --git a/discord/app_commands/commands.py b/discord/app_commands/commands.py\n--- a/discord/app_commands/commands.py\n+++ b/discord/app_commands/commands.py\n@@ -1548,6 +1548,9 @@ class Group:\n if not self.description:\n raise TypeError('groups must have a description')\n \n+ if not self.name:\n+ raise TypeError('groups must have a name')\n+\n self.parent: Optional[Group] = parent\n self.module: Optional[str]\n if cls.__discord_app_commands_has_module__:\n", "modified_files": [ { "path": "discord/app_commands/commands.py", "content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\n\nfrom __future__ import annotations\nimport inspect\n\nfrom typing import (\n Any,\n Callable,\n ClassVar,\n Coroutine,\n Dict,\n Generator,\n Generic,\n List,\n MutableMapping,\n Optional,\n Set,\n TYPE_CHECKING,\n Tuple,\n Type,\n TypeVar,\n Union,\n overload,\n)\n\nimport re\nfrom copy import copy as shallow_copy\n\nfrom ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale\nfrom .models import Choice\nfrom .transformers import annotation_to_parameter, CommandParameter, NoneType\nfrom .errors import AppCommandError, CheckFailure, CommandInvokeError, CommandSignatureMismatch, CommandAlreadyRegistered\nfrom .translator import TranslationContextLocation, TranslationContext, Translator, locale_str\nfrom ..message import Message\nfrom ..user import User\nfrom ..member import Member\nfrom ..permissions import Permissions\nfrom ..utils import resolve_annotation, MISSING, is_inside_class, maybe_coroutine, async_all, _shorten, _to_kebab_case\n\nif TYPE_CHECKING:\n from typing_extensions import ParamSpec, Concatenate\n from ..interactions import Interaction\n from ..abc import Snowflake\n from .namespace import Namespace\n from .models import ChoiceT\n\n # Generally, these two libraries are supposed to be separate from each other.\n # However, for type hinting purposes it's unfortunately necessary for one to\n # reference the other to prevent type checking errors in callbacks\n from discord.ext import commands\n\n ErrorFunc = Callable[[Interaction, AppCommandError], Coroutine[Any, Any, None]]\n\n__all__ = (\n 'Command',\n 'ContextMenu',\n 'Group',\n 'Parameter',\n 'context_menu',\n 'command',\n 'describe',\n 'check',\n 'rename',\n 'choices',\n 'autocomplete',\n 'guilds',\n 'guild_only',\n 'default_permissions',\n)\n\nif TYPE_CHECKING:\n P = ParamSpec('P')\nelse:\n P = TypeVar('P')\n\nT = TypeVar('T')\nF = TypeVar('F', bound=Callable[..., Any])\nGroupT = TypeVar('GroupT', bound='Binding')\nCoro = Coroutine[Any, Any, T]\nUnboundError = Callable[['Interaction[Any]', AppCommandError], Coro[Any]]\nError = Union[\n Callable[[GroupT, 'Interaction[Any]', AppCommandError], Coro[Any]],\n UnboundError,\n]\nCheck = Callable[['Interaction[Any]'], Union[bool, Coro[bool]]]\nBinding = Union['Group', 'commands.Cog']\n\n\nif TYPE_CHECKING:\n CommandCallback = Union[\n Callable[Concatenate[GroupT, 'Interaction[Any]', P], Coro[T]],\n Callable[Concatenate['Interaction[Any]', P], Coro[T]],\n ]\n\n ContextMenuCallback = Union[\n # If groups end up support context menus these would be uncommented\n # Callable[[GroupT, 'Interaction', Member], Coro[Any]],\n # Callable[[GroupT, 'Interaction', User], Coro[Any]],\n # Callable[[GroupT, 'Interaction', Message], Coro[Any]],\n # Callable[[GroupT, 'Interaction', Union[Member, User]], Coro[Any]],\n Callable[['Interaction[Any]', Member], Coro[Any]],\n Callable[['Interaction[Any]', User], Coro[Any]],\n Callable[['Interaction[Any]', Message], Coro[Any]],\n Callable[['Interaction[Any]', Union[Member, User]], Coro[Any]],\n ]\n\n AutocompleteCallback = Union[\n Callable[[GroupT, 'Interaction[Any]', str], Coro[List[Choice[ChoiceT]]]],\n Callable[['Interaction[Any]', str], Coro[List[Choice[ChoiceT]]]],\n ]\nelse:\n CommandCallback = Callable[..., Coro[T]]\n ContextMenuCallback = Callable[..., Coro[T]]\n AutocompleteCallback = Callable[..., Coro[T]]\n\n\nCheckInputParameter = Union['Command[Any, ..., Any]', 'ContextMenu', 'CommandCallback[Any, ..., Any]', ContextMenuCallback]\n\n# The re module doesn't support \\p{} so we have to list characters from Thai and Devanagari manually.\nTHAI_COMBINING = r'\\u0e31-\\u0e3a\\u0e47-\\u0e4e'\nDEVANAGARI_COMBINING = r'\\u0900-\\u0903\\u093a\\u093b\\u093c\\u093e\\u093f\\u0940-\\u094f\\u0955\\u0956\\u0957\\u0962\\u0963'\nVALID_SLASH_COMMAND_NAME = re.compile(r'^[-_\\w' + THAI_COMBINING + DEVANAGARI_COMBINING + r']{1,32}$')\n\nARG_NAME_SUBREGEX = r'(?:\\\\?\\*){0,2}(?P\\w+)'\n\nARG_DESCRIPTION_SUBREGEX = r'(?P(?:.|\\n)+?(?:\\Z|\\r?\\n(?=[\\S\\r\\n])))'\n\nARG_TYPE_SUBREGEX = r'(?:.+)'\n\nGOOGLE_DOCSTRING_ARG_REGEX = re.compile(\n rf'^{ARG_NAME_SUBREGEX}[ \\t]*(?:\\({ARG_TYPE_SUBREGEX}\\))?[ \\t]*:[ \\t]*{ARG_DESCRIPTION_SUBREGEX}',\n re.MULTILINE,\n)\n\nSPHINX_DOCSTRING_ARG_REGEX = re.compile(\n rf'^:param {ARG_NAME_SUBREGEX}:[ \\t]+{ARG_DESCRIPTION_SUBREGEX}',\n re.MULTILINE,\n)\n\nNUMPY_DOCSTRING_ARG_REGEX = re.compile(\n rf'^{ARG_NAME_SUBREGEX}(?:[ \\t]*:)?(?:[ \\t]+{ARG_TYPE_SUBREGEX})?[ \\t]*\\r?\\n[ \\t]+{ARG_DESCRIPTION_SUBREGEX}',\n re.MULTILINE,\n)\n\n\ndef _parse_args_from_docstring(func: Callable[..., Any], params: Dict[str, CommandParameter]) -> Dict[str, str]:\n docstring = inspect.getdoc(func)\n\n if docstring is None:\n return {}\n\n # Extract the arguments\n # Note: These are loose regexes, but they are good enough for our purposes\n # For Google-style, look only at the lines that are indented\n section_lines = inspect.cleandoc('\\n'.join(line for line in docstring.splitlines() if line.startswith(' ')))\n docstring_styles = (\n GOOGLE_DOCSTRING_ARG_REGEX.finditer(section_lines),\n SPHINX_DOCSTRING_ARG_REGEX.finditer(docstring),\n NUMPY_DOCSTRING_ARG_REGEX.finditer(docstring),\n )\n\n return {\n m.group('name'): m.group('description') for matches in docstring_styles for m in matches if m.group('name') in params\n }\n\n\ndef validate_name(name: str) -> str:\n match = VALID_SLASH_COMMAND_NAME.match(name)\n if match is None:\n raise ValueError(\n f'{name!r} must be between 1-32 characters and contain only lower-case letters, numbers, hyphens, or underscores.'\n )\n\n # Ideally, name.islower() would work instead but since certain characters\n # are Lo (e.g. CJK) those don't pass the test. I'd use `casefold` instead as\n # well, but chances are the server-side check is probably something similar to\n # this code anyway.\n if name.lower() != name:\n raise ValueError(f'{name!r} must be all lower-case')\n return name\n\n\ndef validate_context_menu_name(name: str) -> str:\n if not name or len(name) > 32:\n raise ValueError('context menu names must be between 1-32 characters')\n return name\n\n\ndef validate_auto_complete_callback(\n callback: AutocompleteCallback[GroupT, ChoiceT]\n) -> AutocompleteCallback[GroupT, ChoiceT]:\n # This function needs to ensure the following is true:\n # If self.foo is passed then don't pass command.binding to the callback\n # If Class.foo is passed then it is assumed command.binding has to be passed\n # If free_function_foo is passed then no binding should be passed at all\n # Passing command.binding is mandated by pass_command_binding\n\n binding = getattr(callback, '__self__', None)\n pass_command_binding = binding is None and is_inside_class(callback)\n\n # 'method' objects can't have dynamic attributes\n if binding is None:\n callback.pass_command_binding = pass_command_binding\n\n required_parameters = 2 + pass_command_binding\n params = inspect.signature(callback).parameters\n if len(params) != required_parameters:\n raise TypeError(f'autocomplete callback {callback.__qualname__!r} requires either 2 or 3 parameters to be passed')\n\n return callback\n\n\ndef _context_menu_annotation(annotation: Any, *, _none: type = NoneType) -> AppCommandType:\n if annotation is Message:\n return AppCommandType.message\n\n supported_types: Set[Any] = {Member, User}\n if annotation in supported_types:\n return AppCommandType.user\n\n # Check if there's an origin\n origin = getattr(annotation, '__origin__', None)\n if origin is not Union:\n # Only Union is supported so bail early\n msg = (\n f'unsupported type annotation {annotation!r}, must be either discord.Member, '\n 'discord.User, discord.Message, or a typing.Union of discord.Member and discord.User'\n )\n raise TypeError(msg)\n\n # Only Union[Member, User] is supported\n if not all(arg in supported_types for arg in annotation.__args__):\n raise TypeError(f'unsupported types given inside {annotation!r}')\n\n return AppCommandType.user\n\n\ndef _populate_descriptions(params: Dict[str, CommandParameter], descriptions: Dict[str, Any]) -> None:\n for name, param in params.items():\n description = descriptions.pop(name, MISSING)\n if description is MISSING:\n param.description = '\u2026'\n continue\n\n if not isinstance(description, (str, locale_str)):\n raise TypeError('description must be a string')\n\n if isinstance(description, str):\n param.description = _shorten(description)\n else:\n param.description = description\n\n if descriptions:\n first = next(iter(descriptions))\n raise TypeError(f'unknown parameter given: {first}')\n\n\ndef _populate_renames(params: Dict[str, CommandParameter], renames: Dict[str, Union[str, locale_str]]) -> None:\n rename_map: Dict[str, Union[str, locale_str]] = {}\n\n # original name to renamed name\n\n for name in params.keys():\n new_name = renames.pop(name, MISSING)\n\n if new_name is MISSING:\n rename_map[name] = name\n continue\n\n if name in rename_map:\n raise ValueError(f'{new_name} is already used')\n\n if isinstance(new_name, str):\n new_name = validate_name(new_name)\n else:\n validate_name(new_name.message)\n\n rename_map[name] = new_name\n params[name]._rename = new_name\n\n if renames:\n first = next(iter(renames))\n raise ValueError(f'unknown parameter given: {first}')\n\n\ndef _populate_choices(params: Dict[str, CommandParameter], all_choices: Dict[str, List[Choice]]) -> None:\n for name, param in params.items():\n choices = all_choices.pop(name, MISSING)\n if choices is MISSING:\n continue\n\n if not isinstance(choices, list):\n raise TypeError('choices must be a list of Choice')\n\n if not all(isinstance(choice, Choice) for choice in choices):\n raise TypeError('choices must be a list of Choice')\n\n if param.type not in (AppCommandOptionType.string, AppCommandOptionType.number, AppCommandOptionType.integer):\n raise TypeError('choices are only supported for integer, string, or number option types')\n\n if not all(param.type == choice._option_type for choice in choices):\n raise TypeError('choices must all have the same inner option type as the parameter choice type')\n\n param.choices = choices\n\n if all_choices:\n first = next(iter(all_choices))\n raise TypeError(f'unknown parameter given: {first}')\n\n\ndef _populate_autocomplete(params: Dict[str, CommandParameter], autocomplete: Dict[str, Any]) -> None:\n for name, param in params.items():\n callback = autocomplete.pop(name, MISSING)\n if callback is MISSING:\n continue\n\n if not inspect.iscoroutinefunction(callback):\n raise TypeError('autocomplete callback must be a coroutine function')\n\n if param.type not in (AppCommandOptionType.string, AppCommandOptionType.number, AppCommandOptionType.integer):\n raise TypeError('autocomplete is only supported for integer, string, or number option types')\n\n if param.is_choice_annotation():\n raise TypeError(\n 'Choice annotation unsupported for autocomplete parameters, consider using a regular annotation instead'\n )\n\n param.autocomplete = validate_auto_complete_callback(callback)\n\n if autocomplete:\n first = next(iter(autocomplete))\n raise TypeError(f'unknown parameter given: {first}')\n\n\ndef _extract_parameters_from_callback(func: Callable[..., Any], globalns: Dict[str, Any]) -> Dict[str, CommandParameter]:\n params = inspect.signature(func).parameters\n cache = {}\n required_params = is_inside_class(func) + 1\n if len(params) < required_params:\n raise TypeError(f'callback {func.__qualname__!r} must have more than {required_params - 1} parameter(s)')\n\n iterator = iter(params.values())\n for _ in range(0, required_params):\n next(iterator)\n\n parameters: List[CommandParameter] = []\n for parameter in iterator:\n if parameter.annotation is parameter.empty:\n raise TypeError(f'parameter {parameter.name!r} is missing a type annotation in callback {func.__qualname__!r}')\n\n resolved = resolve_annotation(parameter.annotation, globalns, globalns, cache)\n param = annotation_to_parameter(resolved, parameter)\n parameters.append(param)\n\n values = sorted(parameters, key=lambda a: a.required, reverse=True)\n result = {v.name: v for v in values}\n\n descriptions = _parse_args_from_docstring(func, result)\n\n try:\n descriptions.update(func.__discord_app_commands_param_description__)\n except AttributeError:\n for param in values:\n if param.description is MISSING:\n param.description = '\u2026'\n if descriptions:\n _populate_descriptions(result, descriptions)\n\n try:\n renames = func.__discord_app_commands_param_rename__\n except AttributeError:\n pass\n else:\n _populate_renames(result, renames.copy())\n\n try:\n choices = func.__discord_app_commands_param_choices__\n except AttributeError:\n pass\n else:\n _populate_choices(result, choices.copy())\n\n try:\n autocomplete = func.__discord_app_commands_param_autocomplete__\n except AttributeError:\n pass\n else:\n _populate_autocomplete(result, autocomplete.copy())\n\n return result\n\n\ndef _get_context_menu_parameter(func: ContextMenuCallback) -> Tuple[str, Any, AppCommandType]:\n params = inspect.signature(func).parameters\n if is_inside_class(func) and not hasattr(func, '__self__'):\n raise TypeError('context menus cannot be defined inside a class')\n\n if len(params) != 2:\n msg = (\n f'context menu callback {func.__qualname__!r} requires 2 parameters, '\n 'the first one being the interaction and the other one explicitly '\n 'annotated with either discord.Message, discord.User, discord.Member, '\n 'or a typing.Union of discord.Member and discord.User'\n )\n raise TypeError(msg)\n\n iterator = iter(params.values())\n next(iterator) # skip interaction\n parameter = next(iterator)\n if parameter.annotation is parameter.empty:\n msg = (\n f'second parameter of context menu callback {func.__qualname__!r} must be explicitly '\n 'annotated with either discord.Message, discord.User, discord.Member, or '\n 'a typing.Union of discord.Member and discord.User'\n )\n raise TypeError(msg)\n\n resolved = resolve_annotation(parameter.annotation, func.__globals__, func.__globals__, {})\n type = _context_menu_annotation(resolved)\n return (parameter.name, resolved, type)\n\n\ndef mark_overrideable(func: F) -> F:\n func.__discord_app_commands_base_function__ = None\n return func\n\n\nclass Parameter:\n \"\"\"A class that contains the parameter information of a :class:`Command` callback.\n\n .. versionadded:: 2.0\n\n Attributes\n -----------\n name: :class:`str`\n The name of the parameter. This is the Python identifier for the parameter.\n display_name: :class:`str`\n The displayed name of the parameter on Discord.\n description: :class:`str`\n The description of the parameter.\n autocomplete: :class:`bool`\n Whether the parameter has an autocomplete handler.\n locale_name: Optional[:class:`locale_str`]\n The display name's locale string, if available.\n locale_description: Optional[:class:`locale_str`]\n The description's locale string, if available.\n required: :class:`bool`\n Whether the parameter is required\n choices: List[:class:`~discord.app_commands.Choice`]\n A list of choices this parameter takes, if any.\n type: :class:`~discord.AppCommandOptionType`\n The underlying type of this parameter.\n channel_types: List[:class:`~discord.ChannelType`]\n The channel types that are allowed for this parameter.\n min_value: Optional[Union[:class:`int`, :class:`float`]]\n The minimum supported value for this parameter.\n max_value: Optional[Union[:class:`int`, :class:`float`]]\n The maximum supported value for this parameter.\n default: Any\n The default value of the parameter, if given.\n If not given then this is :data:`~discord.utils.MISSING`.\n command: :class:`Command`\n The command this parameter is attached to.\n \"\"\"\n\n def __init__(self, parent: CommandParameter, command: Command[Any, ..., Any]) -> None:\n self.__parent: CommandParameter = parent\n self.__command: Command[Any, ..., Any] = command\n\n @property\n def command(self) -> Command[Any, ..., Any]:\n return self.__command\n\n @property\n def name(self) -> str:\n return self.__parent.name\n\n @property\n def display_name(self) -> str:\n return self.__parent.display_name\n\n @property\n def required(self) -> bool:\n return self.__parent.required\n\n @property\n def description(self) -> str:\n return str(self.__parent.description)\n\n @property\n def locale_name(self) -> Optional[locale_str]:\n if isinstance(self.__parent._rename, locale_str):\n return self.__parent._rename\n return None\n\n @property\n def locale_description(self) -> Optional[locale_str]:\n if isinstance(self.__parent.description, locale_str):\n return self.__parent.description\n return None\n\n @property\n def autocomplete(self) -> bool:\n return self.__parent.autocomplete is not None\n\n @property\n def default(self) -> Any:\n return self.__parent.default\n\n @property\n def type(self) -> AppCommandOptionType:\n return self.__parent.type\n\n @property\n def choices(self) -> List[Choice[Union[int, float, str]]]:\n choices = self.__parent.choices\n if choices is MISSING:\n return []\n return choices.copy()\n\n @property\n def channel_types(self) -> List[ChannelType]:\n channel_types = self.__parent.channel_types\n if channel_types is MISSING:\n return []\n return channel_types.copy()\n\n @property\n def min_value(self) -> Optional[Union[int, float]]:\n return self.__parent.min_value\n\n @property\n def max_value(self) -> Optional[Union[int, float]]:\n return self.__parent.max_value\n\n\nclass Command(Generic[GroupT, P, T]):\n \"\"\"A class that implements an application command.\n\n These are usually not created manually, instead they are created using\n one of the following decorators:\n\n - :func:`~discord.app_commands.command`\n - :meth:`Group.command `\n - :meth:`CommandTree.command `\n\n .. versionadded:: 2.0\n\n Parameters\n -----------\n name: Union[:class:`str`, :class:`locale_str`]\n The name of the application command.\n description: Union[:class:`str`, :class:`locale_str`]\n The description of the application command. This shows up in the UI to describe\n the application command.\n callback: :ref:`coroutine `\n The coroutine that is executed when the command is called.\n auto_locale_strings: :class:`bool`\n If this is set to ``True``, then all translatable strings will implicitly\n be wrapped into :class:`locale_str` rather than :class:`str`. This could\n avoid some repetition and be more ergonomic for certain defaults such\n as default command names, command descriptions, and parameter names.\n Defaults to ``True``.\n nsfw: :class:`bool`\n Whether the command is NSFW and should only work in NSFW channels.\n Defaults to ``False``.\n\n Due to a Discord limitation, this does not work on subcommands.\n parent: Optional[:class:`Group`]\n The parent application command. ``None`` if there isn't one.\n extras: :class:`dict`\n A dictionary that can be used to store extraneous data.\n The library will not touch any values or keys within this dictionary.\n\n Attributes\n ------------\n name: :class:`str`\n The name of the application command.\n description: :class:`str`\n The description of the application command. This shows up in the UI to describe\n the application command.\n checks\n A list of predicates that take a :class:`~discord.Interaction` parameter\n to indicate whether the command callback should be executed. If an exception\n is necessary to be thrown to signal failure, then one inherited from\n :exc:`AppCommandError` should be used. If all the checks fail without\n propagating an exception, :exc:`CheckFailure` is raised.\n default_permissions: Optional[:class:`~discord.Permissions`]\n The default permissions that can execute this command on Discord. Note\n that server administrators can override this value in the client.\n Setting an empty permissions field will disallow anyone except server\n administrators from using the command in a guild.\n\n Due to a Discord limitation, this does not work on subcommands.\n guild_only: :class:`bool`\n Whether the command should only be usable in guild contexts.\n\n Due to a Discord limitation, this does not work on subcommands.\n nsfw: :class:`bool`\n Whether the command is NSFW and should only work in NSFW channels.\n\n Due to a Discord limitation, this does not work on subcommands.\n parent: Optional[:class:`Group`]\n The parent application command. ``None`` if there isn't one.\n extras: :class:`dict`\n A dictionary that can be used to store extraneous data.\n The library will not touch any values or keys within this dictionary.\n \"\"\"\n\n def __init__(\n self,\n *,\n name: Union[str, locale_str],\n description: Union[str, locale_str],\n callback: CommandCallback[GroupT, P, T],\n nsfw: bool = False,\n parent: Optional[Group] = None,\n guild_ids: Optional[List[int]] = None,\n auto_locale_strings: bool = True,\n extras: Dict[Any, Any] = MISSING,\n ):\n name, locale = (name.message, name) if isinstance(name, locale_str) else (name, None)\n self.name: str = validate_name(name)\n self._locale_name: Optional[locale_str] = locale\n description, locale = (\n (description.message, description) if isinstance(description, locale_str) else (description, None)\n )\n self.description: str = description\n self._locale_description: Optional[locale_str] = locale\n self._attr: Optional[str] = None\n self._callback: CommandCallback[GroupT, P, T] = callback\n self.parent: Optional[Group] = parent\n self.binding: Optional[GroupT] = None\n self.on_error: Optional[Error[GroupT]] = None\n self.module: Optional[str] = callback.__module__\n\n # Unwrap __self__ for bound methods\n try:\n self.binding = callback.__self__\n self._callback = callback = callback.__func__\n except AttributeError:\n pass\n\n self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)\n self.checks: List[Check] = getattr(callback, '__discord_app_commands_checks__', [])\n self._guild_ids: Optional[List[int]] = guild_ids or getattr(\n callback, '__discord_app_commands_default_guilds__', None\n )\n self.default_permissions: Optional[Permissions] = getattr(\n callback, '__discord_app_commands_default_permissions__', None\n )\n self.guild_only: bool = getattr(callback, '__discord_app_commands_guild_only__', False)\n self.nsfw: bool = nsfw\n self.extras: Dict[Any, Any] = extras or {}\n\n if self._guild_ids is not None and self.parent is not None:\n raise ValueError('child commands cannot have default guilds set, consider setting them in the parent instead')\n\n if auto_locale_strings:\n self._convert_to_locale_strings()\n\n def _convert_to_locale_strings(self) -> None:\n if self._locale_name is None:\n self._locale_name = locale_str(self.name)\n if self._locale_description is None:\n self._locale_description = locale_str(self.description)\n\n for param in self._params.values():\n param._convert_to_locale_strings()\n\n def __set_name__(self, owner: Type[Any], name: str) -> None:\n self._attr = name\n\n @property\n def callback(self) -> CommandCallback[GroupT, P, T]:\n \"\"\":ref:`coroutine `: The coroutine that is executed when the command is called.\"\"\"\n return self._callback\n\n def _copy_with(\n self,\n *,\n parent: Optional[Group],\n binding: GroupT,\n bindings: MutableMapping[GroupT, GroupT] = MISSING,\n set_on_binding: bool = True,\n ) -> Command:\n bindings = {} if bindings is MISSING else bindings\n\n copy = shallow_copy(self)\n copy._params = self._params.copy()\n copy.parent = parent\n copy.binding = bindings.get(self.binding) if self.binding is not None else binding\n\n if copy._attr and set_on_binding:\n setattr(copy.binding, copy._attr, copy)\n\n return copy\n\n async def get_translated_payload(self, translator: Translator) -> Dict[str, Any]:\n base = self.to_dict()\n name_localizations: Dict[str, str] = {}\n description_localizations: Dict[str, str] = {}\n\n # Prevent creating these objects in a heavy loop\n name_context = TranslationContext(location=TranslationContextLocation.command_name, data=self)\n description_context = TranslationContext(location=TranslationContextLocation.command_description, data=self)\n\n for locale in Locale:\n if self._locale_name:\n translation = await translator._checked_translate(self._locale_name, locale, name_context)\n if translation is not None:\n name_localizations[locale.value] = translation\n\n if self._locale_description:\n translation = await translator._checked_translate(self._locale_description, locale, description_context)\n if translation is not None:\n description_localizations[locale.value] = translation\n\n base['name_localizations'] = name_localizations\n base['description_localizations'] = description_localizations\n base['options'] = [\n await param.get_translated_payload(translator, Parameter(param, self)) for param in self._params.values()\n ]\n return base\n\n def to_dict(self) -> Dict[str, Any]:\n # If we have a parent then our type is a subcommand\n # Otherwise, the type falls back to the specific command type (e.g. slash command or context menu)\n option_type = AppCommandType.chat_input.value if self.parent is None else AppCommandOptionType.subcommand.value\n base: Dict[str, Any] = {\n 'name': self.name,\n 'description': self.description,\n 'type': option_type,\n 'options': [param.to_dict() for param in self._params.values()],\n }\n\n if self.parent is None:\n base['nsfw'] = self.nsfw\n base['dm_permission'] = not self.guild_only\n base['default_member_permissions'] = None if self.default_permissions is None else self.default_permissions.value\n\n return base\n\n async def _invoke_error_handlers(self, interaction: Interaction, error: AppCommandError) -> None:\n # These type ignores are because the type checker can't narrow this type properly.\n if self.on_error is not None:\n if self.binding is not None:\n await self.on_error(self.binding, interaction, error) # type: ignore\n else:\n await self.on_error(interaction, error) # type: ignore\n\n parent = self.parent\n if parent is not None:\n await parent.on_error(interaction, error)\n\n if parent.parent is not None:\n await parent.parent.on_error(interaction, error)\n\n binding_error_handler = getattr(self.binding, '__discord_app_commands_error_handler__', None)\n if binding_error_handler is not None:\n await binding_error_handler(interaction, error)\n\n def _has_any_error_handlers(self) -> bool:\n if self.on_error is not None:\n return True\n\n parent = self.parent\n if parent is not None:\n # Check if the on_error is overridden\n if not hasattr(parent.on_error, '__discord_app_commands_base_function__'):\n return True\n\n if parent.parent is not None:\n if not hasattr(parent.parent.on_error, '__discord_app_commands_base_function__'):\n return True\n\n # Check if we have a bound error handler\n if getattr(self.binding, '__discord_app_commands_error_handler__', None) is not None:\n return True\n\n return False\n\n async def _transform_arguments(self, interaction: Interaction, namespace: Namespace) -> Dict[str, Any]:\n values = namespace.__dict__\n transformed_values = {}\n\n for param in self._params.values():\n try:\n value = values[param.display_name]\n except KeyError:\n if not param.required:\n transformed_values[param.name] = param.default\n else:\n raise CommandSignatureMismatch(self) from None\n else:\n transformed_values[param.name] = await param.transform(interaction, value)\n\n return transformed_values\n\n async def _do_call(self, interaction: Interaction, params: Dict[str, Any]) -> T:\n # These type ignores are because the type checker doesn't quite understand the narrowing here\n # Likewise, it thinks we're missing positional arguments when there aren't any.\n try:\n if self.binding is not None:\n return await self._callback(self.binding, interaction, **params) # type: ignore\n return await self._callback(interaction, **params) # type: ignore\n except TypeError as e:\n # In order to detect mismatch from the provided signature and the Discord data,\n # there are many ways it can go wrong yet all of them eventually lead to a TypeError\n # from the Python compiler showcasing that the signature is incorrect. This lovely\n # piece of code essentially checks the last frame of the caller and checks if the\n # locals contains our `self` reference.\n #\n # This is because there is a possibility that a TypeError is raised within the body\n # of the function, and in that case the locals wouldn't contain a reference to\n # the command object under the name `self`.\n frame = inspect.trace()[-1].frame\n if frame.f_locals.get('self') is self:\n raise CommandSignatureMismatch(self) from None\n raise CommandInvokeError(self, e) from e\n except AppCommandError:\n raise\n except Exception as e:\n raise CommandInvokeError(self, e) from e\n\n async def _invoke_with_namespace(self, interaction: Interaction, namespace: Namespace) -> T:\n if not await self._check_can_run(interaction):\n raise CheckFailure(f'The check functions for command {self.name!r} failed.')\n\n transformed_values = await self._transform_arguments(interaction, namespace)\n return await self._do_call(interaction, transformed_values)\n\n async def _invoke_autocomplete(self, interaction: Interaction, name: str, namespace: Namespace):\n # The namespace contains the Discord provided names so this will be fine\n # even if the name is renamed\n value = namespace.__dict__[name]\n\n try:\n param = self._params[name]\n except KeyError:\n # Slow case, it might be a rename\n params = {param.display_name: param for param in self._params.values()}\n try:\n param = params[name]\n except KeyError:\n raise CommandSignatureMismatch(self) from None\n\n if param.autocomplete is None:\n raise CommandSignatureMismatch(self)\n\n predicates = getattr(param.autocomplete, '__discord_app_commands_checks__', [])\n if predicates:\n try:\n passed = await async_all(f(interaction) for f in predicates)\n except Exception:\n passed = False\n\n if not passed:\n if not interaction.response.is_done():\n await interaction.response.autocomplete([])\n return\n\n if getattr(param.autocomplete, 'pass_command_binding', False):\n binding = self.binding\n if binding is not None:\n choices = await param.autocomplete(binding, interaction, value)\n else:\n raise TypeError('autocomplete parameter expected a bound self parameter but one was not provided')\n else:\n choices = await param.autocomplete(interaction, value)\n\n if interaction.response.is_done():\n return\n\n await interaction.response.autocomplete(choices)\n\n def _get_internal_command(self, name: str) -> Optional[Union[Command, Group]]:\n return None\n\n @property\n def parameters(self) -> List[Parameter]:\n \"\"\"Returns a list of parameters for this command.\n\n This does not include the ``self`` or ``interaction`` parameters.\n\n Returns\n --------\n List[:class:`Parameter`]\n The parameters of this command.\n \"\"\"\n return [Parameter(p, self) for p in self._params.values()]\n\n def get_parameter(self, name: str) -> Optional[Parameter]:\n \"\"\"Retrieves a parameter by its name.\n\n The name must be the Python identifier rather than the renamed\n one for display on Discord.\n\n Parameters\n -----------\n name: :class:`str`\n The parameter name in the callback function.\n\n Returns\n --------\n Optional[:class:`Parameter`]\n The parameter or ``None`` if not found.\n \"\"\"\n\n parent = self._params.get(name)\n if parent is not None:\n return Parameter(parent, self)\n return None\n\n @property\n def root_parent(self) -> Optional[Group]:\n \"\"\"Optional[:class:`Group`]: The root parent of this command.\"\"\"\n if self.parent is None:\n return None\n parent = self.parent\n return parent.parent or parent\n\n @property\n def qualified_name(self) -> str:\n \"\"\":class:`str`: Returns the fully qualified command name.\n\n The qualified name includes the parent name as well. For example,\n in a command like ``/foo bar`` the qualified name is ``foo bar``.\n \"\"\"\n # A B C\n # ^ self\n # ^ parent\n # ^ grandparent\n if self.parent is None:\n return self.name\n\n names = [self.name, self.parent.name]\n grandparent = self.parent.parent\n if grandparent is not None:\n names.append(grandparent.name)\n\n return ' '.join(reversed(names))\n\n async def _check_can_run(self, interaction: Interaction) -> bool:\n if self.parent is not None and self.parent is not self.binding:\n # For commands with a parent which isn't the binding, i.e.\n # \n # \n # \n # The parent check needs to be called first\n if not await maybe_coroutine(self.parent.interaction_check, interaction):\n return False\n\n if self.binding is not None:\n check: Optional[Check] = getattr(self.binding, 'interaction_check', None)\n if check:\n ret = await maybe_coroutine(check, interaction)\n if not ret:\n return False\n\n predicates = self.checks\n if not predicates:\n return True\n\n return await async_all(f(interaction) for f in predicates)\n\n def error(self, coro: Error[GroupT]) -> Error[GroupT]:\n \"\"\"A decorator that registers a coroutine as a local error handler.\n\n The local error handler is called whenever an exception is raised in the body\n of the command or during handling of the command. The error handler must take\n 2 parameters, the interaction and the error.\n\n The error passed will be derived from :exc:`AppCommandError`.\n\n Parameters\n -----------\n coro: :ref:`coroutine `\n The coroutine to register as the local error handler.\n\n Raises\n -------\n TypeError\n The coroutine passed is not actually a coroutine.\n \"\"\"\n\n if not inspect.iscoroutinefunction(coro):\n raise TypeError('The error handler must be a coroutine.')\n\n self.on_error = coro\n return coro\n\n def autocomplete(\n self, name: str\n ) -> Callable[[AutocompleteCallback[GroupT, ChoiceT]], AutocompleteCallback[GroupT, ChoiceT]]:\n \"\"\"A decorator that registers a coroutine as an autocomplete prompt for a parameter.\n\n The coroutine callback must have 2 parameters, the :class:`~discord.Interaction`,\n and the current value by the user (the string currently being typed by the user).\n\n To get the values from other parameters that may be filled in, accessing\n :attr:`.Interaction.namespace` will give a :class:`Namespace` object with those\n values.\n\n Parent :func:`checks ` are ignored within an autocomplete. However, checks can be added\n to the autocomplete callback and the ones added will be called. If the checks fail for any reason\n then an empty list is sent as the interaction response.\n\n The coroutine decorator **must** return a list of :class:`~discord.app_commands.Choice` objects.\n Only up to 25 objects are supported.\n\n .. warning::\n The choices returned from this coroutine are suggestions. The user may ignore them and input their own value.\n\n Example:\n\n .. code-block:: python3\n\n @app_commands.command()\n async def fruits(interaction: discord.Interaction, fruit: str):\n await interaction.response.send_message(f'Your favourite fruit seems to be {fruit}')\n\n @fruits.autocomplete('fruit')\n async def fruits_autocomplete(\n interaction: discord.Interaction,\n current: str,\n ) -> List[app_commands.Choice[str]]:\n fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']\n return [\n app_commands.Choice(name=fruit, value=fruit)\n for fruit in fruits if current.lower() in fruit.lower()\n ]\n\n\n Parameters\n -----------\n name: :class:`str`\n The parameter name to register as autocomplete.\n\n Raises\n -------\n TypeError\n The coroutine passed is not actually a coroutine or\n the parameter is not found or of an invalid type.\n \"\"\"\n\n def decorator(coro: AutocompleteCallback[GroupT, ChoiceT]) -> AutocompleteCallback[GroupT, ChoiceT]:\n if not inspect.iscoroutinefunction(coro):\n raise TypeError('The error handler must be a coroutine.')\n\n try:\n param = self._params[name]\n except KeyError:\n raise TypeError(f'unknown parameter: {name!r}') from None\n\n if param.type not in (AppCommandOptionType.string, AppCommandOptionType.number, AppCommandOptionType.integer):\n raise TypeError('autocomplete is only supported for integer, string, or number option types')\n\n if param.is_choice_annotation():\n raise TypeError(\n 'Choice annotation unsupported for autocomplete parameters, consider using a regular annotation instead'\n )\n\n param.autocomplete = validate_auto_complete_callback(coro)\n return coro\n\n return decorator\n\n def add_check(self, func: Check, /) -> None:\n \"\"\"Adds a check to the command.\n\n This is the non-decorator interface to :func:`check`.\n\n Parameters\n -----------\n func\n The function that will be used as a check.\n \"\"\"\n\n self.checks.append(func)\n\n def remove_check(self, func: Check, /) -> None:\n \"\"\"Removes a check from the command.\n\n This function is idempotent and will not raise an exception\n if the function is not in the command's checks.\n\n Parameters\n -----------\n func\n The function to remove from the checks.\n \"\"\"\n\n try:\n self.checks.remove(func)\n except ValueError:\n pass\n\n\nclass ContextMenu:\n \"\"\"A class that implements a context menu application command.\n\n These are usually not created manually, instead they are created using\n one of the following decorators:\n\n - :func:`~discord.app_commands.context_menu`\n - :meth:`CommandTree.context_menu `\n\n .. versionadded:: 2.0\n\n Parameters\n -----------\n name: Union[:class:`str`, :class:`locale_str`]\n The name of the context menu.\n callback: :ref:`coroutine `\n The coroutine that is executed when the command is called.\n type: :class:`.AppCommandType`\n The type of context menu application command. By default, this is inferred\n by the parameter of the callback.\n auto_locale_strings: :class:`bool`\n If this is set to ``True``, then all translatable strings will implicitly\n be wrapped into :class:`locale_str` rather than :class:`str`. This could\n avoid some repetition and be more ergonomic for certain defaults such\n as default command names, command descriptions, and parameter names.\n Defaults to ``True``.\n nsfw: :class:`bool`\n Whether the command is NSFW and should only work in NSFW channels.\n Defaults to ``False``.\n extras: :class:`dict`\n A dictionary that can be used to store extraneous data.\n The library will not touch any values or keys within this dictionary.\n\n Attributes\n ------------\n name: :class:`str`\n The name of the context menu.\n type: :class:`.AppCommandType`\n The type of context menu application command. By default, this is inferred\n by the parameter of the callback.\n default_permissions: Optional[:class:`~discord.Permissions`]\n The default permissions that can execute this command on Discord. Note\n that server administrators can override this value in the client.\n Setting an empty permissions field will disallow anyone except server\n administrators from using the command in a guild.\n guild_only: :class:`bool`\n Whether the command should only be usable in guild contexts.\n Defaults to ``False``.\n nsfw: :class:`bool`\n Whether the command is NSFW and should only work in NSFW channels.\n Defaults to ``False``.\n checks\n A list of predicates that take a :class:`~discord.Interaction` parameter\n to indicate whether the command callback should be executed. If an exception\n is necessary to be thrown to signal failure, then one inherited from\n :exc:`AppCommandError` should be used. If all the checks fail without\n propagating an exception, :exc:`CheckFailure` is raised.\n extras: :class:`dict`\n A dictionary that can be used to store extraneous data.\n The library will not touch any values or keys within this dictionary.\n \"\"\"\n\n def __init__(\n self,\n *,\n name: Union[str, locale_str],\n callback: ContextMenuCallback,\n type: AppCommandType = MISSING,\n nsfw: bool = False,\n guild_ids: Optional[List[int]] = None,\n auto_locale_strings: bool = True,\n extras: Dict[Any, Any] = MISSING,\n ):\n name, locale = (name.message, name) if isinstance(name, locale_str) else (name, None)\n self.name: str = validate_context_menu_name(name)\n self._locale_name: Optional[locale_str] = locale\n self._callback: ContextMenuCallback = callback\n (param, annotation, actual_type) = _get_context_menu_parameter(callback)\n if type is MISSING:\n type = actual_type\n\n if actual_type != type:\n raise ValueError(f'context menu callback implies a type of {actual_type} but {type} was passed.')\n\n self.type: AppCommandType = type\n self._param_name = param\n self._annotation = annotation\n self.module: Optional[str] = callback.__module__\n self._guild_ids = guild_ids or getattr(callback, '__discord_app_commands_default_guilds__', None)\n self.on_error: Optional[UnboundError] = None\n self.default_permissions: Optional[Permissions] = getattr(\n callback, '__discord_app_commands_default_permissions__', None\n )\n self.nsfw: bool = nsfw\n self.guild_only: bool = getattr(callback, '__discord_app_commands_guild_only__', False)\n self.checks: List[Check] = getattr(callback, '__discord_app_commands_checks__', [])\n self.extras: Dict[Any, Any] = extras or {}\n\n if auto_locale_strings:\n if self._locale_name is None:\n self._locale_name = locale_str(self.name)\n\n @property\n def callback(self) -> ContextMenuCallback:\n \"\"\":ref:`coroutine `: The coroutine that is executed when the context menu is called.\"\"\"\n return self._callback\n\n @property\n def qualified_name(self) -> str:\n \"\"\":class:`str`: Returns the fully qualified command name.\"\"\"\n return self.name\n\n async def get_translated_payload(self, translator: Translator) -> Dict[str, Any]:\n base = self.to_dict()\n context = TranslationContext(location=TranslationContextLocation.command_name, data=self)\n if self._locale_name:\n name_localizations: Dict[str, str] = {}\n for locale in Locale:\n translation = await translator._checked_translate(self._locale_name, locale, context)\n if translation is not None:\n name_localizations[locale.value] = translation\n\n base['name_localizations'] = name_localizations\n return base\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n 'name': self.name,\n 'type': self.type.value,\n 'dm_permission': not self.guild_only,\n 'default_member_permissions': None if self.default_permissions is None else self.default_permissions.value,\n 'nsfw': self.nsfw,\n }\n\n async def _check_can_run(self, interaction: Interaction) -> bool:\n predicates = self.checks\n if not predicates:\n return True\n\n return await async_all(f(interaction) for f in predicates)\n\n def _has_any_error_handlers(self) -> bool:\n return self.on_error is not None\n\n async def _invoke(self, interaction: Interaction, arg: Any):\n try:\n if not await self._check_can_run(interaction):\n raise CheckFailure(f'The check functions for context menu {self.name!r} failed.')\n\n await self._callback(interaction, arg)\n except AppCommandError:\n raise\n except Exception as e:\n raise CommandInvokeError(self, e) from e\n\n def error(self, coro: UnboundError) -> UnboundError:\n \"\"\"A decorator that registers a coroutine as a local error handler.\n\n The local error handler is called whenever an exception is raised in the body\n of the command or during handling of the command. The error handler must take\n 2 parameters, the interaction and the error.\n\n The error passed will be derived from :exc:`AppCommandError`.\n\n Parameters\n -----------\n coro: :ref:`coroutine `\n The coroutine to register as the local error handler.\n\n Raises\n -------\n TypeError\n The coroutine passed is not actually a coroutine.\n \"\"\"\n\n if not inspect.iscoroutinefunction(coro):\n raise TypeError('The error handler must be a coroutine.')\n\n self.on_error = coro\n return coro\n\n def add_check(self, func: Check, /) -> None:\n \"\"\"Adds a check to the command.\n\n This is the non-decorator interface to :func:`check`.\n\n Parameters\n -----------\n func\n The function that will be used as a check.\n \"\"\"\n\n self.checks.append(func)\n\n def remove_check(self, func: Check, /) -> None:\n \"\"\"Removes a check from the command.\n\n This function is idempotent and will not raise an exception\n if the function is not in the command's checks.\n\n Parameters\n -----------\n func\n The function to remove from the checks.\n \"\"\"\n\n try:\n self.checks.remove(func)\n except ValueError:\n pass\n\n\nclass Group:\n \"\"\"A class that implements an application command group.\n\n These are usually inherited rather than created manually.\n\n Decorators such as :func:`guild_only`, :func:`guilds`, and :func:`default_permissions`\n will apply to the group if used on top of a subclass. For example:\n\n .. code-block:: python3\n\n from discord import app_commands\n\n @app_commands.guild_only()\n class MyGroup(app_commands.Group):\n pass\n\n .. versionadded:: 2.0\n\n Parameters\n -----------\n name: Union[:class:`str`, :class:`locale_str`]\n The name of the group. If not given, it defaults to a lower-case\n kebab-case version of the class name.\n description: Union[:class:`str`, :class:`locale_str`]\n The description of the group. This shows up in the UI to describe\n the group. If not given, it defaults to the docstring of the\n class shortened to 100 characters.\n auto_locale_strings: :class:`bool`\n If this is set to ``True``, then all translatable strings will implicitly\n be wrapped into :class:`locale_str` rather than :class:`str`. This could\n avoid some repetition and be more ergonomic for certain defaults such\n as default command names, command descriptions, and parameter names.\n Defaults to ``True``.\n default_permissions: Optional[:class:`~discord.Permissions`]\n The default permissions that can execute this group on Discord. Note\n that server administrators can override this value in the client.\n Setting an empty permissions field will disallow anyone except server\n administrators from using the command in a guild.\n\n Due to a Discord limitation, this does not work on subcommands.\n guild_only: :class:`bool`\n Whether the group should only be usable in guild contexts.\n Defaults to ``False``.\n\n Due to a Discord limitation, this does not work on subcommands.\n nsfw: :class:`bool`\n Whether the command is NSFW and should only work in NSFW channels.\n Defaults to ``False``.\n\n Due to a Discord limitation, this does not work on subcommands.\n parent: Optional[:class:`Group`]\n The parent application command. ``None`` if there isn't one.\n extras: :class:`dict`\n A dictionary that can be used to store extraneous data.\n The library will not touch any values or keys within this dictionary.\n\n Attributes\n ------------\n name: :class:`str`\n The name of the group.\n description: :class:`str`\n The description of the group. This shows up in the UI to describe\n the group.\n default_permissions: Optional[:class:`~discord.Permissions`]\n The default permissions that can execute this group on Discord. Note\n that server administrators can override this value in the client.\n Setting an empty permissions field will disallow anyone except server\n administrators from using the command in a guild.\n\n Due to a Discord limitation, this does not work on subcommands.\n guild_only: :class:`bool`\n Whether the group should only be usable in guild contexts.\n\n Due to a Discord limitation, this does not work on subcommands.\n nsfw: :class:`bool`\n Whether the command is NSFW and should only work in NSFW channels.\n\n Due to a Discord limitation, this does not work on subcommands.\n parent: Optional[:class:`Group`]\n The parent group. ``None`` if there isn't one.\n extras: :class:`dict`\n A dictionary that can be used to store extraneous data.\n The library will not touch any values or keys within this dictionary.\n \"\"\"\n\n __discord_app_commands_group_children__: ClassVar[List[Union[Command[Any, ..., Any], Group]]] = []\n __discord_app_commands_skip_init_binding__: bool = False\n __discord_app_commands_group_name__: str = MISSING\n __discord_app_commands_group_description__: str = MISSING\n __discord_app_commands_group_locale_name__: Optional[locale_str] = None\n __discord_app_commands_group_locale_description__: Optional[locale_str] = None\n __discord_app_commands_group_nsfw__: bool = False\n __discord_app_commands_guild_only__: bool = MISSING\n __discord_app_commands_default_permissions__: Optional[Permissions] = MISSING\n __discord_app_commands_has_module__: bool = False\n __discord_app_commands_error_handler__: Optional[\n Callable[[Interaction, AppCommandError], Coroutine[Any, Any, None]]\n ] = None\n\n def __init_subclass__(\n cls,\n *,\n name: Union[str, locale_str] = MISSING,\n description: Union[str, locale_str] = MISSING,\n guild_only: bool = MISSING,\n nsfw: bool = False,\n default_permissions: Optional[Permissions] = MISSING,\n ) -> None:\n if not cls.__discord_app_commands_group_children__:\n children: List[Union[Command[Any, ..., Any], Group]] = [\n member for member in cls.__dict__.values() if isinstance(member, (Group, Command)) and member.parent is None\n ]\n\n cls.__discord_app_commands_group_children__ = children\n\n found = set()\n for child in children:\n if child.name in found:\n raise TypeError(f'Command {child.name!r} is a duplicate')\n found.add(child.name)\n\n if len(children) > 25:\n raise TypeError('groups cannot have more than 25 commands')\n\n if name is MISSING:\n cls.__discord_app_commands_group_name__ = validate_name(_to_kebab_case(cls.__name__))\n elif isinstance(name, str):\n cls.__discord_app_commands_group_name__ = validate_name(name)\n else:\n cls.__discord_app_commands_group_name__ = validate_name(name.message)\n cls.__discord_app_commands_group_locale_name__ = name\n\n if description is MISSING:\n if cls.__doc__ is None:\n cls.__discord_app_commands_group_description__ = '\u2026'\n else:\n cls.__discord_app_commands_group_description__ = _shorten(cls.__doc__)\n elif isinstance(description, str):\n cls.__discord_app_commands_group_description__ = description\n else:\n cls.__discord_app_commands_group_description__ = description.message\n cls.__discord_app_commands_group_locale_description__ = description\n\n if guild_only is not MISSING:\n cls.__discord_app_commands_guild_only__ = guild_only\n\n if default_permissions is not MISSING:\n cls.__discord_app_commands_default_permissions__ = default_permissions\n\n if cls.__module__ != __name__:\n cls.__discord_app_commands_has_module__ = True\n cls.__discord_app_commands_group_nsfw__ = nsfw\n\n def __init__(\n self,\n *,\n name: Union[str, locale_str] = MISSING,\n description: Union[str, locale_str] = MISSING,\n parent: Optional[Group] = None,\n guild_ids: Optional[List[int]] = None,\n guild_only: bool = MISSING,\n nsfw: bool = MISSING,\n auto_locale_strings: bool = True,\n default_permissions: Optional[Permissions] = MISSING,\n extras: Dict[Any, Any] = MISSING,\n ):\n cls = self.__class__\n\n if name is MISSING:\n name, locale = cls.__discord_app_commands_group_name__, cls.__discord_app_commands_group_locale_name__\n elif isinstance(name, str):\n name, locale = validate_name(name), None\n else:\n name, locale = validate_name(name.message), name\n self.name: str = name\n self._locale_name: Optional[locale_str] = locale\n\n if description is MISSING:\n description, locale = (\n cls.__discord_app_commands_group_description__,\n cls.__discord_app_commands_group_locale_description__,\n )\n elif isinstance(description, str):\n description, locale = description, None\n else:\n description, locale = description.message, description\n self.description: str = description\n self._locale_description: Optional[locale_str] = locale\n\n self._attr: Optional[str] = None\n self._owner_cls: Optional[Type[Any]] = None\n self._guild_ids: Optional[List[int]] = guild_ids or getattr(cls, '__discord_app_commands_default_guilds__', None)\n\n if default_permissions is MISSING:\n if cls.__discord_app_commands_default_permissions__ is MISSING:\n default_permissions = None\n else:\n default_permissions = cls.__discord_app_commands_default_permissions__\n\n self.default_permissions: Optional[Permissions] = default_permissions\n\n if guild_only is MISSING:\n if cls.__discord_app_commands_guild_only__ is MISSING:\n guild_only = False\n else:\n guild_only = cls.__discord_app_commands_guild_only__\n\n self.guild_only: bool = guild_only\n\n if nsfw is MISSING:\n nsfw = cls.__discord_app_commands_group_nsfw__\n\n self.nsfw: bool = nsfw\n\n if not self.description:\n raise TypeError('groups must have a description')\n\n self.parent: Optional[Group] = parent\n self.module: Optional[str]\n if cls.__discord_app_commands_has_module__:\n self.module = cls.__module__\n else:\n try:\n # This is pretty hacky\n # It allows the module to be fetched if someone just constructs a bare Group object though.\n self.module = inspect.currentframe().f_back.f_globals['__name__'] # type: ignore\n except (AttributeError, IndexError, KeyError):\n self.module = None\n\n self._children: Dict[str, Union[Command, Group]] = {}\n self.extras: Dict[Any, Any] = extras or {}\n\n bindings: Dict[Group, Group] = {}\n\n for child in self.__discord_app_commands_group_children__:\n # commands and groups created directly in this class (no parent)\n copy = (\n child._copy_with(parent=self, binding=self, bindings=bindings, set_on_binding=False)\n if not cls.__discord_app_commands_skip_init_binding__\n else child\n )\n\n self._children[copy.name] = copy\n if copy._attr and not cls.__discord_app_commands_skip_init_binding__:\n setattr(self, copy._attr, copy)\n\n if parent is not None:\n if parent.parent is not None:\n raise ValueError('groups can only be nested at most one level')\n parent.add_command(self)\n\n if auto_locale_strings:\n self._convert_to_locale_strings()\n\n def _convert_to_locale_strings(self) -> None:\n if self._locale_name is None:\n self._locale_name = locale_str(self.name)\n if self._locale_description is None:\n self._locale_description = locale_str(self.description)\n\n # I don't know if propagating to the children is the right behaviour here.\n\n def __set_name__(self, owner: Type[Any], name: str) -> None:\n self._attr = name\n self.module = owner.__module__\n self._owner_cls = owner\n\n def _copy_with(\n self,\n *,\n parent: Optional[Group],\n binding: Binding,\n bindings: MutableMapping[Group, Group] = MISSING,\n set_on_binding: bool = True,\n ) -> Group:\n bindings = {} if bindings is MISSING else bindings\n\n copy = shallow_copy(self)\n copy.parent = parent\n copy._children = {}\n\n bindings[self] = copy\n\n for child in self._children.values():\n child_copy = child._copy_with(parent=copy, binding=binding, bindings=bindings)\n child_copy.parent = copy\n copy._children[child_copy.name] = child_copy\n\n if isinstance(child_copy, Group) and child_copy._attr and set_on_binding:\n if binding.__class__ is child_copy._owner_cls:\n setattr(binding, child_copy._attr, child_copy)\n elif child_copy._owner_cls is copy.__class__:\n setattr(copy, child_copy._attr, child_copy)\n\n if copy._attr and set_on_binding:\n setattr(parent or binding, copy._attr, copy)\n\n return copy\n\n async def get_translated_payload(self, translator: Translator) -> Dict[str, Any]:\n base = self.to_dict()\n name_localizations: Dict[str, str] = {}\n description_localizations: Dict[str, str] = {}\n\n # Prevent creating these objects in a heavy loop\n name_context = TranslationContext(location=TranslationContextLocation.group_name, data=self)\n description_context = TranslationContext(location=TranslationContextLocation.group_description, data=self)\n for locale in Locale:\n if self._locale_name:\n translation = await translator._checked_translate(self._locale_name, locale, name_context)\n if translation is not None:\n name_localizations[locale.value] = translation\n\n if self._locale_description:\n translation = await translator._checked_translate(self._locale_description, locale, description_context)\n if translation is not None:\n description_localizations[locale.value] = translation\n\n base['name_localizations'] = name_localizations\n base['description_localizations'] = description_localizations\n base['options'] = [await child.get_translated_payload(translator) for child in self._children.values()]\n return base\n\n def to_dict(self) -> Dict[str, Any]:\n # If this has a parent command then it's part of a subcommand group\n # Otherwise, it's just a regular command\n option_type = 1 if self.parent is None else AppCommandOptionType.subcommand_group.value\n base: Dict[str, Any] = {\n 'name': self.name,\n 'description': self.description,\n 'type': option_type,\n 'options': [child.to_dict() for child in self._children.values()],\n }\n\n if self.parent is None:\n base['nsfw'] = self.nsfw\n base['dm_permission'] = not self.guild_only\n base['default_member_permissions'] = None if self.default_permissions is None else self.default_permissions.value\n\n return base\n\n @property\n def root_parent(self) -> Optional[Group]:\n \"\"\"Optional[:class:`Group`]: The parent of this group.\"\"\"\n return self.parent\n\n @property\n def qualified_name(self) -> str:\n \"\"\":class:`str`: Returns the fully qualified group name.\n\n The qualified name includes the parent name as well. For example,\n in a group like ``/foo bar`` the qualified name is ``foo bar``.\n \"\"\"\n\n if self.parent is None:\n return self.name\n return f'{self.parent.name} {self.name}'\n\n def _get_internal_command(self, name: str) -> Optional[Union[Command[Any, ..., Any], Group]]:\n return self._children.get(name)\n\n @property\n def commands(self) -> List[Union[Command[Any, ..., Any], Group]]:\n \"\"\"List[Union[:class:`Command`, :class:`Group`]]: The commands that this group contains.\"\"\"\n return list(self._children.values())\n\n def walk_commands(self) -> Generator[Union[Command[Any, ..., Any], Group], None, None]:\n \"\"\"An iterator that recursively walks through all commands that this group contains.\n\n Yields\n ---------\n Union[:class:`Command`, :class:`Group`]\n The commands in this group.\n \"\"\"\n\n for command in self._children.values():\n yield command\n if isinstance(command, Group):\n yield from command.walk_commands()\n\n @mark_overrideable\n async def on_error(self, interaction: Interaction, error: AppCommandError, /) -> None:\n \"\"\"|coro|\n\n A callback that is called when a child's command raises an :exc:`AppCommandError`.\n\n To get the command that failed, :attr:`discord.Interaction.command` should be used.\n\n The default implementation does nothing.\n\n Parameters\n -----------\n interaction: :class:`~discord.Interaction`\n The interaction that is being handled.\n error: :exc:`AppCommandError`\n The exception that was raised.\n \"\"\"\n\n pass\n\n def error(self, coro: ErrorFunc) -> ErrorFunc:\n \"\"\"A decorator that registers a coroutine as a local error handler.\n\n The local error handler is called whenever an exception is raised in a child command.\n The error handler must take 2 parameters, the interaction and the error.\n\n The error passed will be derived from :exc:`AppCommandError`.\n\n Parameters\n -----------\n coro: :ref:`coroutine `\n The coroutine to register as the local error handler.\n\n Raises\n -------\n TypeError\n The coroutine passed is not actually a coroutine, or is an invalid coroutine.\n \"\"\"\n\n if not inspect.iscoroutinefunction(coro):\n raise TypeError('The error handler must be a coroutine.')\n\n params = inspect.signature(coro).parameters\n if len(params) != 2:\n raise TypeError('The error handler must have 2 parameters.')\n\n self.on_error = coro\n return coro\n\n async def interaction_check(self, interaction: Interaction, /) -> bool:\n \"\"\"|coro|\n\n A callback that is called when an interaction happens within the group\n that checks whether a command inside the group should be executed.\n\n This is useful to override if, for example, you want to ensure that the\n interaction author is a given user.\n\n The default implementation of this returns ``True``.\n\n .. note::\n\n If an exception occurs within the body then the check\n is considered a failure and error handlers such as\n :meth:`on_error` is called. See :exc:`AppCommandError`\n for more information.\n\n Parameters\n -----------\n interaction: :class:`~discord.Interaction`\n The interaction that occurred.\n\n Returns\n ---------\n :class:`bool`\n Whether the view children's callbacks should be called.\n \"\"\"\n\n return True\n\n def add_command(self, command: Union[Command[Any, ..., Any], Group], /, *, override: bool = False) -> None:\n \"\"\"Adds a command or group to this group's internal list of commands.\n\n Parameters\n -----------\n command: Union[:class:`Command`, :class:`Group`]\n The command or group to add.\n override: :class:`bool`\n Whether to override a pre-existing command or group with the same name.\n If ``False`` then an exception is raised.\n\n Raises\n -------\n CommandAlreadyRegistered\n The command or group is already registered. Note that the :attr:`CommandAlreadyRegistered.guild_id`\n attribute will always be ``None`` in this case.\n ValueError\n There are too many commands already registered or the group is too\n deeply nested.\n TypeError\n The wrong command type was passed.\n \"\"\"\n\n if not isinstance(command, (Command, Group)):\n raise TypeError(f'expected Command or Group not {command.__class__.__name__}')\n\n if isinstance(command, Group) and self.parent is not None:\n # In a tree like so:\n # \n # \n # \n # this needs to be forbidden\n raise ValueError(f'{command.name!r} is too nested, groups can only be nested at most one level')\n\n if not override and command.name in self._children:\n raise CommandAlreadyRegistered(command.name, guild_id=None)\n\n self._children[command.name] = command\n command.parent = self\n if len(self._children) > 25:\n raise ValueError('maximum number of child commands exceeded')\n\n def remove_command(self, name: str, /) -> Optional[Union[Command[Any, ..., Any], Group]]:\n \"\"\"Removes a command or group from the internal list of commands.\n\n Parameters\n -----------\n name: :class:`str`\n The name of the command or group to remove.\n\n Returns\n --------\n Optional[Union[:class:`~discord.app_commands.Command`, :class:`~discord.app_commands.Group`]]\n The command that was removed. If nothing was removed\n then ``None`` is returned instead.\n \"\"\"\n\n self._children.pop(name, None)\n\n def get_command(self, name: str, /) -> Optional[Union[Command[Any, ..., Any], Group]]:\n \"\"\"Retrieves a command or group from its name.\n\n Parameters\n -----------\n name: :class:`str`\n The name of the command or group to retrieve.\n\n Returns\n --------\n Optional[Union[:class:`~discord.app_commands.Command`, :class:`~discord.app_commands.Group`]]\n The command or group that was retrieved. If nothing was found\n then ``None`` is returned instead.\n \"\"\"\n return self._children.get(name)\n\n def command(\n self,\n *,\n name: Union[str, locale_str] = MISSING,\n description: Union[str, locale_str] = MISSING,\n nsfw: bool = False,\n auto_locale_strings: bool = True,\n extras: Dict[Any, Any] = MISSING,\n ) -> Callable[[CommandCallback[GroupT, P, T]], Command[GroupT, P, T]]:\n \"\"\"A decorator that creates an application command from a regular function under this group.\n\n Parameters\n ------------\n name: Union[:class:`str`, :class:`locale_str`]\n The name of the application command. If not given, it defaults to a lower-case\n version of the callback name.\n description: Union[:class:`str`, :class:`locale_str`]\n The description of the application command. This shows up in the UI to describe\n the application command. If not given, it defaults to the first line of the docstring\n of the callback shortened to 100 characters.\n nsfw: :class:`bool`\n Whether the command is NSFW and should only work in NSFW channels. Defaults to ``False``.\n auto_locale_strings: :class:`bool`\n If this is set to ``True``, then all translatable strings will implicitly\n be wrapped into :class:`locale_str` rather than :class:`str`. This could\n avoid some repetition and be more ergonomic for certain defaults such\n as default command names, command descriptions, and parameter names.\n Defaults to ``True``.\n extras: :class:`dict`\n A dictionary that can be used to store extraneous data.\n The library will not touch any values or keys within this dictionary.\n \"\"\"\n\n def decorator(func: CommandCallback[GroupT, P, T]) -> Command[GroupT, P, T]:\n if not inspect.iscoroutinefunction(func):\n raise TypeError('command function must be a coroutine function')\n\n if description is MISSING:\n if func.__doc__ is None:\n desc = '\u2026'\n else:\n desc = _shorten(func.__doc__)\n else:\n desc = description\n\n command = Command(\n name=name if name is not MISSING else func.__name__,\n description=desc,\n callback=func,\n nsfw=nsfw,\n parent=self,\n auto_locale_strings=auto_locale_strings,\n extras=extras,\n )\n self.add_command(command)\n return command\n\n return decorator\n\n\ndef command(\n *,\n name: Union[str, locale_str] = MISSING,\n description: Union[str, locale_str] = MISSING,\n nsfw: bool = False,\n auto_locale_strings: bool = True,\n extras: Dict[Any, Any] = MISSING,\n) -> Callable[[CommandCallback[GroupT, P, T]], Command[GroupT, P, T]]:\n \"\"\"Creates an application command from a regular function.\n\n Parameters\n ------------\n name: :class:`str`\n The name of the application command. If not given, it defaults to a lower-case\n version of the callback name.\n description: :class:`str`\n The description of the application command. This shows up in the UI to describe\n the application command. If not given, it defaults to the first line of the docstring\n of the callback shortened to 100 characters.\n nsfw: :class:`bool`\n Whether the command is NSFW and should only work in NSFW channels. Defaults to ``False``.\n\n Due to a Discord limitation, this does not work on subcommands.\n auto_locale_strings: :class:`bool`\n If this is set to ``True``, then all translatable strings will implicitly\n be wrapped into :class:`locale_str` rather than :class:`str`. This could\n avoid some repetition and be more ergonomic for certain defaults such\n as default command names, command descriptions, and parameter names.\n Defaults to ``True``.\n extras: :class:`dict`\n A dictionary that can be used to store extraneous data.\n The library will not touch any values or keys within this dictionary.\n \"\"\"\n\n def decorator(func: CommandCallback[GroupT, P, T]) -> Command[GroupT, P, T]:\n if not inspect.iscoroutinefunction(func):\n raise TypeError('command function must be a coroutine function')\n\n if description is MISSING:\n if func.__doc__ is None:\n desc = '\u2026'\n else:\n desc = _shorten(func.__doc__)\n else:\n desc = description\n\n return Command(\n name=name if name is not MISSING else func.__name__,\n description=desc,\n callback=func,\n parent=None,\n nsfw=nsfw,\n auto_locale_strings=auto_locale_strings,\n extras=extras,\n )\n\n return decorator\n\n\ndef context_menu(\n *,\n name: Union[str, locale_str] = MISSING,\n nsfw: bool = False,\n auto_locale_strings: bool = True,\n extras: Dict[Any, Any] = MISSING,\n) -> Callable[[ContextMenuCallback], ContextMenu]:\n \"\"\"Creates an application command context menu from a regular function.\n\n This function must have a signature of :class:`~discord.Interaction` as its first parameter\n and taking either a :class:`~discord.Member`, :class:`~discord.User`, or :class:`~discord.Message`,\n or a :obj:`typing.Union` of ``Member`` and ``User`` as its second parameter.\n\n Examples\n ---------\n\n .. code-block:: python3\n\n @app_commands.context_menu()\n async def react(interaction: discord.Interaction, message: discord.Message):\n await interaction.response.send_message('Very cool message!', ephemeral=True)\n\n @app_commands.context_menu()\n async def ban(interaction: discord.Interaction, user: discord.Member):\n await interaction.response.send_message(f'Should I actually ban {user}...', ephemeral=True)\n\n Parameters\n ------------\n name: Union[:class:`str`, :class:`locale_str`]\n The name of the context menu command. If not given, it defaults to a title-case\n version of the callback name. Note that unlike regular slash commands this can\n have spaces and upper case characters in the name.\n nsfw: :class:`bool`\n Whether the command is NSFW and should only work in NSFW channels. Defaults to ``False``.\n\n Due to a Discord limitation, this does not work on subcommands.\n auto_locale_strings: :class:`bool`\n If this is set to ``True``, then all translatable strings will implicitly\n be wrapped into :class:`locale_str` rather than :class:`str`. This could\n avoid some repetition and be more ergonomic for certain defaults such\n as default command names, command descriptions, and parameter names.\n Defaults to ``True``.\n extras: :class:`dict`\n A dictionary that can be used to store extraneous data.\n The library will not touch any values or keys within this dictionary.\n \"\"\"\n\n def decorator(func: ContextMenuCallback) -> ContextMenu:\n if not inspect.iscoroutinefunction(func):\n raise TypeError('context menu function must be a coroutine function')\n\n actual_name = func.__name__.title() if name is MISSING else name\n return ContextMenu(\n name=actual_name,\n nsfw=nsfw,\n callback=func,\n auto_locale_strings=auto_locale_strings,\n extras=extras,\n )\n\n return decorator\n\n\ndef describe(**parameters: Union[str, locale_str]) -> Callable[[T], T]:\n r'''Describes the given parameters by their name using the key of the keyword argument\n as the name.\n\n Example:\n\n .. code-block:: python3\n\n @app_commands.command(description='Bans a member')\n @app_commands.describe(member='the member to ban')\n async def ban(interaction: discord.Interaction, member: discord.Member):\n await interaction.response.send_message(f'Banned {member}')\n\n Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings.\n\n Example:\n\n .. code-block:: python3\n\n @app_commands.command()\n async def ban(interaction: discord.Interaction, member: discord.Member):\n \"\"\"Bans a member\n\n Parameters\n -----------\n member: discord.Member\n the member to ban\n \"\"\"\n await interaction.response.send_message(f'Banned {member}')\n\n Parameters\n -----------\n \\*\\*parameters: Union[:class:`str`, :class:`locale_str`]\n The description of the parameters.\n\n Raises\n --------\n TypeError\n The parameter name is not found.\n '''\n\n def decorator(inner: T) -> T:\n if isinstance(inner, Command):\n _populate_descriptions(inner._params, parameters)\n else:\n try:\n inner.__discord_app_commands_param_description__.update(parameters) # type: ignore # Runtime attribute access\n except AttributeError:\n inner.__discord_app_commands_param_description__ = parameters # type: ignore # Runtime attribute assignment\n\n return inner\n\n return decorator\n\n\ndef rename(**parameters: Union[str, locale_str]) -> Callable[[T], T]:\n r\"\"\"Renames the given parameters by their name using the key of the keyword argument\n as the name.\n\n This renames the parameter within the Discord UI. When referring to the parameter in other\n decorators, the parameter name used in the function is used instead of the renamed one.\n\n Example:\n\n .. code-block:: python3\n\n @app_commands.command()\n @app_commands.rename(the_member_to_ban='member')\n async def ban(interaction: discord.Interaction, the_member_to_ban: discord.Member):\n await interaction.response.send_message(f'Banned {the_member_to_ban}')\n\n Parameters\n -----------\n \\*\\*parameters: Union[:class:`str`, :class:`locale_str`]\n The name of the parameters.\n\n Raises\n --------\n ValueError\n The parameter name is already used by another parameter.\n TypeError\n The parameter name is not found.\n \"\"\"\n\n def decorator(inner: T) -> T:\n if isinstance(inner, Command):\n _populate_renames(inner._params, parameters)\n else:\n try:\n inner.__discord_app_commands_param_rename__.update(parameters) # type: ignore # Runtime attribute access\n except AttributeError:\n inner.__discord_app_commands_param_rename__ = parameters # type: ignore # Runtime attribute assignment\n\n return inner\n\n return decorator\n\n\ndef choices(**parameters: List[Choice[ChoiceT]]) -> Callable[[T], T]:\n r\"\"\"Instructs the given parameters by their name to use the given choices for their choices.\n\n Example:\n\n .. code-block:: python3\n\n @app_commands.command()\n @app_commands.describe(fruits='fruits to choose from')\n @app_commands.choices(fruits=[\n Choice(name='apple', value=1),\n Choice(name='banana', value=2),\n Choice(name='cherry', value=3),\n ])\n async def fruit(interaction: discord.Interaction, fruits: Choice[int]):\n await interaction.response.send_message(f'Your favourite fruit is {fruits.name}.')\n\n .. note::\n\n This is not the only way to provide choices to a command. There are two more ergonomic ways\n of doing this. The first one is to use a :obj:`typing.Literal` annotation:\n\n .. code-block:: python3\n\n @app_commands.command()\n @app_commands.describe(fruits='fruits to choose from')\n async def fruit(interaction: discord.Interaction, fruits: Literal['apple', 'banana', 'cherry']):\n await interaction.response.send_message(f'Your favourite fruit is {fruits}.')\n\n The second way is to use an :class:`enum.Enum`:\n\n .. code-block:: python3\n\n class Fruits(enum.Enum):\n apple = 1\n banana = 2\n cherry = 3\n\n @app_commands.command()\n @app_commands.describe(fruits='fruits to choose from')\n async def fruit(interaction: discord.Interaction, fruits: Fruits):\n await interaction.response.send_message(f'Your favourite fruit is {fruits}.')\n\n\n Parameters\n -----------\n \\*\\*parameters\n The choices of the parameters.\n\n Raises\n --------\n TypeError\n The parameter name is not found or the parameter type was incorrect.\n \"\"\"\n\n def decorator(inner: T) -> T:\n if isinstance(inner, Command):\n _populate_choices(inner._params, parameters)\n else:\n try:\n inner.__discord_app_commands_param_choices__.update(parameters) # type: ignore # Runtime attribute access\n except AttributeError:\n inner.__discord_app_commands_param_choices__ = parameters # type: ignore # Runtime attribute assignment\n\n return inner\n\n return decorator\n\n\ndef autocomplete(**parameters: AutocompleteCallback[GroupT, ChoiceT]) -> Callable[[T], T]:\n r\"\"\"Associates the given parameters with the given autocomplete callback.\n\n Autocomplete is only supported on types that have :class:`str`, :class:`int`, or :class:`float`\n values.\n\n :func:`Checks ` are supported, however they must be attached to the autocomplete\n callback in order to work. Checks attached to the command are ignored when invoking the autocomplete\n callback.\n\n For more information, see the :meth:`Command.autocomplete` documentation.\n\n .. warning::\n The choices returned from this coroutine are suggestions. The user may ignore them and input their own value.\n\n Example:\n\n .. code-block:: python3\n\n async def fruit_autocomplete(\n interaction: discord.Interaction,\n current: str,\n ) -> List[app_commands.Choice[str]]:\n fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']\n return [\n app_commands.Choice(name=fruit, value=fruit)\n for fruit in fruits if current.lower() in fruit.lower()\n ]\n\n @app_commands.command()\n @app_commands.autocomplete(fruit=fruit_autocomplete)\n async def fruits(interaction: discord.Interaction, fruit: str):\n await interaction.response.send_message(f'Your favourite fruit seems to be {fruit}')\n\n Parameters\n -----------\n \\*\\*parameters\n The parameters to mark as autocomplete.\n\n Raises\n --------\n TypeError\n The parameter name is not found or the parameter type was incorrect.\n \"\"\"\n\n def decorator(inner: T) -> T:\n if isinstance(inner, Command):\n _populate_autocomplete(inner._params, parameters)\n else:\n try:\n inner.__discord_app_commands_param_autocomplete__.update(parameters) # type: ignore # Runtime attribute access\n except AttributeError:\n inner.__discord_app_commands_param_autocomplete__ = parameters # type: ignore # Runtime attribute assignment\n\n return inner\n\n return decorator\n\n\ndef guilds(*guild_ids: Union[Snowflake, int]) -> Callable[[T], T]:\n r\"\"\"Associates the given guilds with the command.\n\n When the command instance is added to a :class:`CommandTree`, the guilds that are\n specified by this decorator become the default guilds that it's added to rather\n than being a global command.\n\n .. note::\n\n Due to an implementation quirk and Python limitation, if this is used in conjunction\n with the :meth:`CommandTree.command` or :meth:`CommandTree.context_menu` decorator\n then this must go below that decorator.\n\n Example:\n\n .. code-block:: python3\n\n MY_GUILD_ID = discord.Object(...) # Guild ID here\n\n @app_commands.command()\n @app_commands.guilds(MY_GUILD_ID)\n async def bonk(interaction: discord.Interaction):\n await interaction.response.send_message('Bonk', ephemeral=True)\n\n Parameters\n -----------\n \\*guild_ids: Union[:class:`int`, :class:`~discord.abc.Snowflake`]\n The guilds to associate this command with. The command tree will\n use this as the default when added rather than adding it as a global\n command.\n \"\"\"\n\n defaults: List[int] = [g if isinstance(g, int) else g.id for g in guild_ids]\n\n def decorator(inner: T) -> T:\n if isinstance(inner, (Group, ContextMenu)):\n inner._guild_ids = defaults\n elif isinstance(inner, Command):\n if inner.parent is not None:\n raise ValueError('child commands of a group cannot have default guilds set')\n\n inner._guild_ids = defaults\n else:\n # Runtime attribute assignment\n inner.__discord_app_commands_default_guilds__ = defaults # type: ignore\n\n return inner\n\n return decorator\n\n\ndef check(predicate: Check) -> Callable[[T], T]:\n r\"\"\"A decorator that adds a check to an application command.\n\n These checks should be predicates that take in a single parameter taking\n a :class:`~discord.Interaction`. If the check returns a ``False``\\-like value then\n during invocation a :exc:`CheckFailure` exception is raised and sent to\n the appropriate error handlers.\n\n These checks can be either a coroutine or not.\n\n Examples\n ---------\n\n Creating a basic check to see if the command invoker is you.\n\n .. code-block:: python3\n\n def check_if_it_is_me(interaction: discord.Interaction) -> bool:\n return interaction.user.id == 85309593344815104\n\n @tree.command()\n @app_commands.check(check_if_it_is_me)\n async def only_for_me(interaction: discord.Interaction):\n await interaction.response.send_message('I know you!', ephemeral=True)\n\n Transforming common checks into its own decorator:\n\n .. code-block:: python3\n\n def is_me():\n def predicate(interaction: discord.Interaction) -> bool:\n return interaction.user.id == 85309593344815104\n return app_commands.check(predicate)\n\n @tree.command()\n @is_me()\n async def only_me(interaction: discord.Interaction):\n await interaction.response.send_message('Only you!')\n\n Parameters\n -----------\n predicate: Callable[[:class:`~discord.Interaction`], :class:`bool`]\n The predicate to check if the command should be invoked.\n \"\"\"\n\n def decorator(func: CheckInputParameter) -> CheckInputParameter:\n if isinstance(func, (Command, ContextMenu)):\n func.checks.append(predicate)\n else:\n if not hasattr(func, '__discord_app_commands_checks__'):\n func.__discord_app_commands_checks__ = []\n\n func.__discord_app_commands_checks__.append(predicate)\n\n return func\n\n return decorator # type: ignore\n\n\n@overload\ndef guild_only(func: None = ...) -> Callable[[T], T]:\n ...\n\n\n@overload\ndef guild_only(func: T) -> T:\n ...\n\n\ndef guild_only(func: Optional[T] = None) -> Union[T, Callable[[T], T]]:\n \"\"\"A decorator that indicates this command can only be used in a guild context.\n\n This is **not** implemented as a :func:`check`, and is instead verified by Discord server side.\n Therefore, there is no error handler called when a command is used within a private message.\n\n This decorator can be called with or without parentheses.\n\n Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.\n\n Examples\n ---------\n\n .. code-block:: python3\n\n @app_commands.command()\n @app_commands.guild_only()\n async def my_guild_only_command(interaction: discord.Interaction) -> None:\n await interaction.response.send_message('I am only available in guilds!')\n \"\"\"\n\n def inner(f: T) -> T:\n if isinstance(f, (Command, Group, ContextMenu)):\n f.guild_only = True\n else:\n f.__discord_app_commands_guild_only__ = True # type: ignore # Runtime attribute assignment\n return f\n\n # Check if called with parentheses or not\n if func is None:\n # Called with parentheses\n return inner\n else:\n return inner(func)\n\n\ndef default_permissions(**perms: bool) -> Callable[[T], T]:\n r\"\"\"A decorator that sets the default permissions needed to execute this command.\n\n When this decorator is used, by default users must have these permissions to execute the command.\n However, an administrator can change the permissions needed to execute this command using the official\n client. Therefore, this only serves as a hint.\n\n Setting an empty permissions field, including via calling this with no arguments, will disallow anyone\n except server administrators from using the command in a guild.\n\n This is sent to Discord server side, and is not a :func:`check`. Therefore, error handlers are not called.\n\n Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.\n\n .. warning::\n\n This serves as a *hint* and members are *not* required to have the permissions given to actually\n execute this command. If you want to ensure that members have the permissions needed, consider using\n :func:`~discord.app_commands.checks.has_permissions` instead.\n\n Parameters\n -----------\n \\*\\*perms: :class:`bool`\n Keyword arguments denoting the permissions to set as the default.\n\n Example\n ---------\n\n .. code-block:: python3\n\n @app_commands.command()\n @app_commands.default_permissions(manage_messages=True)\n async def test(interaction: discord.Interaction):\n await interaction.response.send_message('You may or may not have manage messages.')\n \"\"\"\n\n permissions = Permissions(**perms)\n\n def decorator(func: T) -> T:\n if isinstance(func, (Command, Group, ContextMenu)):\n func.default_permissions = permissions\n else:\n func.__discord_app_commands_default_permissions__ = permissions # type: ignore # Runtime attribute assignment\n\n return func\n\n return decorator\n" } ], "language": "python" }, { "id": "10_6", "repo_url": "https://github.com/teamqurrent/discord.py", "instruction": "Enhance the discord.py library by adding a remove_dynamic_items method to the `Client`, `ConnectionState`, and `ViewStore` classes, enabling the removal of registered DynamicItem classes from persistent listening. In `client.py`, implement remove_dynamic_items in the `Client` class to validate and pass dynamic item classes to the _connection object's similar method. In `state.py`, add a corresponding remove_dynamic_items method to the `ConnectionState` class, which should forward the request to the ViewStore. Finally, in `view.py`, update the `ViewStore` class with a remove_dynamic_items method that actually removes the specified dynamic items from its internal storage. This series of methods across different classes will ensure that dynamic items can be effectively unregistered from the system.", "base_commit": "4182306", "test_script": "import unittest\nimport sys\n\n\nfrom discord.ui import DynamicItem, Item\n\nclass MockDynamicItem(DynamicItem, Item, template='mock_template'):\n pass\n\nclass TestClientDynamicItems(unittest.TestCase):\n def setUp(self):\n from discord import Client, Intents\n from unittest.mock import MagicMock\n\n intents = Intents.default() # Use default intents for the test\n self.client = Client(intents=intents)\n self.client._connection = MagicMock()\n\n def test_remove_dynamic_items_method_exists(self):\n self.assertTrue(hasattr(self.client, 'remove_dynamic_items'))\n\n def test_remove_dynamic_items_functionality(self): \n self.client.add_dynamic_items(MockDynamicItem)\n self.client.remove_dynamic_items(MockDynamicItem)\n # Check if remove_dynamic_items was called on the _connection object\n self.client._connection.remove_dynamic_items.assert_called_with(MockDynamicItem)\n\n def test_remove_dynamic_items_with_invalid_type(self):\n with self.assertRaises(TypeError):\n self.client.remove_dynamic_items(str)\n\ndef main():\n\n \n suite = unittest.TestSuite()\n suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestClientDynamicItems))\n runner = unittest.TextTestRunner()\n\n if runner.run(suite).wasSuccessful():\n sys.exit(0)\n else:\n sys.exit(1)\n\nif __name__ == '__main__':\n\n main()\n", "testbed_environment": "python3.9", "requirements_txt": "discord", "solution_commit": "7c3868ef", "solution_patch": "diff --git a/discord/client.py b/discord/client.py\n--- a/discord/client.py\n+++ b/discord/client.py\n@@ -2681,7 +2681,7 @@ class Client:\n return state.add_dm_channel(data)\n \n def add_dynamic_items(self, *items: Type[DynamicItem[Item[Any]]]) -> None:\n- r\"\"\"Registers a :class:`~discord.ui.DynamicItem` class for persistent listening.\n+ r\"\"\"Registers :class:`~discord.ui.DynamicItem` classes for persistent listening.\n \n This method accepts *class types* rather than instances.\n \n@@ -2695,7 +2695,7 @@ class Client:\n Raises\n -------\n TypeError\n- The class is not a subclass of :class:`~discord.ui.DynamicItem`.\n+ A class is not a subclass of :class:`~discord.ui.DynamicItem`.\n \"\"\"\n \n for item in items:\n@@ -2704,6 +2704,30 @@ class Client:\n \n self._connection.store_dynamic_items(*items)\n \n+ def remove_dynamic_items(self, *items: Type[DynamicItem[Item[Any]]]) -> None:\n+ r\"\"\"Removes :class:`~discord.ui.DynamicItem` classes from persistent listening.\n+\n+ This method accepts *class types* rather than instances.\n+\n+ .. versionadded:: 2.4\n+\n+ Parameters\n+ -----------\n+ \\*items: Type[:class:`~discord.ui.DynamicItem`]\n+ The classes of dynamic items to remove.\n+\n+ Raises\n+ -------\n+ TypeError\n+ A class is not a subclass of :class:`~discord.ui.DynamicItem`.\n+ \"\"\"\n+\n+ for item in items:\n+ if not issubclass(item, DynamicItem):\n+ raise TypeError(f'expected subclass of DynamicItem not {item.__name__}')\n+\n+ self._connection.remove_dynamic_items(*items)\n+\n def add_view(self, view: View, *, message_id: Optional[int] = None) -> None:\n \"\"\"Registers a :class:`~discord.ui.View` for persistent listening.\n \ndiff --git a/discord/state.py b/discord/state.py\n--- a/discord/state.py\n+++ b/discord/state.py\n@@ -401,6 +401,9 @@ class ConnectionState(Generic[ClientT]):\n def store_dynamic_items(self, *items: Type[DynamicItem[Item[Any]]]) -> None:\n self._view_store.add_dynamic_items(*items)\n \n+ def remove_dynamic_items(self, *items: Type[DynamicItem[Item[Any]]]) -> None:\n+ self._view_store.remove_dynamic_items(*items)\n+\n @property\n def persistent_views(self) -> Sequence[View]:\n return self._view_store.persistent_views\ndiff --git a/discord/ui/view.py b/discord/ui/view.py\n--- a/discord/ui/view.py\n+++ b/discord/ui/view.py\n@@ -557,6 +557,11 @@ class ViewStore:\n pattern = item.__discord_ui_compiled_template__\n self._dynamic_items[pattern] = item\n \n+ def remove_dynamic_items(self, *items: Type[DynamicItem[Item[Any]]]) -> None:\n+ for item in items:\n+ pattern = item.__discord_ui_compiled_template__\n+ self._dynamic_items.pop(pattern, None)\n+\n def add_view(self, view: View, message_id: Optional[int] = None) -> None:\n view._start_listening_from_store(self)\n if view.__discord_ui_modal__:\n", "modified_files": [ { "path": "discord/client.py", "content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\nimport datetime\nimport logging\nfrom typing import (\n TYPE_CHECKING,\n Any,\n AsyncIterator,\n Callable,\n Coroutine,\n Dict,\n Generator,\n List,\n Literal,\n Optional,\n Sequence,\n Tuple,\n Type,\n TypeVar,\n Union,\n overload,\n)\n\nimport aiohttp\n\nfrom .user import User, ClientUser\nfrom .invite import Invite\nfrom .template import Template\nfrom .widget import Widget\nfrom .guild import Guild\nfrom .emoji import Emoji\nfrom .channel import _threaded_channel_factory, PartialMessageable\nfrom .enums import ChannelType\nfrom .mentions import AllowedMentions\nfrom .errors import *\nfrom .enums import Status\nfrom .flags import ApplicationFlags, Intents\nfrom .gateway import *\nfrom .activity import ActivityTypes, BaseActivity, create_activity\nfrom .voice_client import VoiceClient\nfrom .http import HTTPClient\nfrom .state import ConnectionState\nfrom . import utils\nfrom .utils import MISSING, time_snowflake\nfrom .object import Object\nfrom .backoff import ExponentialBackoff\nfrom .webhook import Webhook\nfrom .appinfo import AppInfo\nfrom .ui.view import View\nfrom .ui.dynamic import DynamicItem\nfrom .stage_instance import StageInstance\nfrom .threads import Thread\nfrom .sticker import GuildSticker, StandardSticker, StickerPack, _sticker_factory\n\nif TYPE_CHECKING:\n from types import TracebackType\n\n from typing_extensions import Self\n\n from .abc import Messageable, PrivateChannel, Snowflake, SnowflakeTime\n from .app_commands import Command, ContextMenu\n from .automod import AutoModAction, AutoModRule\n from .channel import DMChannel, GroupChannel\n from .ext.commands import AutoShardedBot, Bot, Context, CommandError\n from .guild import GuildChannel\n from .integrations import Integration\n from .interactions import Interaction\n from .member import Member, VoiceState\n from .message import Message\n from .raw_models import (\n RawAppCommandPermissionsUpdateEvent,\n RawBulkMessageDeleteEvent,\n RawIntegrationDeleteEvent,\n RawMemberRemoveEvent,\n RawMessageDeleteEvent,\n RawMessageUpdateEvent,\n RawReactionActionEvent,\n RawReactionClearEmojiEvent,\n RawReactionClearEvent,\n RawThreadDeleteEvent,\n RawThreadMembersUpdate,\n RawThreadUpdateEvent,\n RawTypingEvent,\n )\n from .reaction import Reaction\n from .role import Role\n from .scheduled_event import ScheduledEvent\n from .threads import ThreadMember\n from .types.guild import Guild as GuildPayload\n from .ui.item import Item\n from .voice_client import VoiceProtocol\n from .audit_logs import AuditLogEntry\n\n\n# fmt: off\n__all__ = (\n 'Client',\n)\n# fmt: on\n\nT = TypeVar('T')\nCoro = Coroutine[Any, Any, T]\nCoroT = TypeVar('CoroT', bound=Callable[..., Coro[Any]])\n\n_log = logging.getLogger(__name__)\n\n\nclass _LoopSentinel:\n __slots__ = ()\n\n def __getattr__(self, attr: str) -> None:\n msg = (\n 'loop attribute cannot be accessed in non-async contexts. '\n 'Consider using either an asynchronous main function and passing it to asyncio.run or '\n 'using asynchronous initialisation hooks such as Client.setup_hook'\n )\n raise AttributeError(msg)\n\n\n_loop: Any = _LoopSentinel()\n\n\nclass Client:\n r\"\"\"Represents a client connection that connects to Discord.\n This class is used to interact with the Discord WebSocket and API.\n\n .. container:: operations\n\n .. describe:: async with x\n\n Asynchronously initialises the client and automatically cleans up.\n\n .. versionadded:: 2.0\n\n A number of options can be passed to the :class:`Client`.\n\n Parameters\n -----------\n max_messages: Optional[:class:`int`]\n The maximum number of messages to store in the internal message cache.\n This defaults to ``1000``. Passing in ``None`` disables the message cache.\n\n .. versionchanged:: 1.3\n Allow disabling the message cache and change the default size to ``1000``.\n proxy: Optional[:class:`str`]\n Proxy URL.\n proxy_auth: Optional[:class:`aiohttp.BasicAuth`]\n An object that represents proxy HTTP Basic Authorization.\n shard_id: Optional[:class:`int`]\n Integer starting at ``0`` and less than :attr:`.shard_count`.\n shard_count: Optional[:class:`int`]\n The total number of shards.\n application_id: :class:`int`\n The client's application ID.\n intents: :class:`Intents`\n The intents that you want to enable for the session. This is a way of\n disabling and enabling certain gateway events from triggering and being sent.\n\n .. versionadded:: 1.5\n\n .. versionchanged:: 2.0\n Parameter is now required.\n member_cache_flags: :class:`MemberCacheFlags`\n Allows for finer control over how the library caches members.\n If not given, defaults to cache as much as possible with the\n currently selected intents.\n\n .. versionadded:: 1.5\n chunk_guilds_at_startup: :class:`bool`\n Indicates if :func:`.on_ready` should be delayed to chunk all guilds\n at start-up if necessary. This operation is incredibly slow for large\n amounts of guilds. The default is ``True`` if :attr:`Intents.members`\n is ``True``.\n\n .. versionadded:: 1.5\n status: Optional[:class:`.Status`]\n A status to start your presence with upon logging on to Discord.\n activity: Optional[:class:`.BaseActivity`]\n An activity to start your presence with upon logging on to Discord.\n allowed_mentions: Optional[:class:`AllowedMentions`]\n Control how the client handles mentions by default on every message sent.\n\n .. versionadded:: 1.4\n heartbeat_timeout: :class:`float`\n The maximum numbers of seconds before timing out and restarting the\n WebSocket in the case of not receiving a HEARTBEAT_ACK. Useful if\n processing the initial packets take too long to the point of disconnecting\n you. The default timeout is 60 seconds.\n guild_ready_timeout: :class:`float`\n The maximum number of seconds to wait for the GUILD_CREATE stream to end before\n preparing the member cache and firing READY. The default timeout is 2 seconds.\n\n .. versionadded:: 1.4\n assume_unsync_clock: :class:`bool`\n Whether to assume the system clock is unsynced. This applies to the ratelimit handling\n code. If this is set to ``True``, the default, then the library uses the time to reset\n a rate limit bucket given by Discord. If this is ``False`` then your system clock is\n used to calculate how long to sleep for. If this is set to ``False`` it is recommended to\n sync your system clock to Google's NTP server.\n\n .. versionadded:: 1.3\n enable_debug_events: :class:`bool`\n Whether to enable events that are useful only for debugging gateway related information.\n\n Right now this involves :func:`on_socket_raw_receive` and :func:`on_socket_raw_send`. If\n this is ``False`` then those events will not be dispatched (due to performance considerations).\n To enable these events, this must be set to ``True``. Defaults to ``False``.\n\n .. versionadded:: 2.0\n http_trace: :class:`aiohttp.TraceConfig`\n The trace configuration to use for tracking HTTP requests the library does using ``aiohttp``.\n This allows you to check requests the library is using. For more information, check the\n `aiohttp documentation `_.\n\n .. versionadded:: 2.0\n max_ratelimit_timeout: Optional[:class:`float`]\n The maximum number of seconds to wait when a non-global rate limit is encountered.\n If a request requires sleeping for more than the seconds passed in, then\n :exc:`~discord.RateLimited` will be raised. By default, there is no timeout limit.\n In order to prevent misuse and unnecessary bans, the minimum value this can be\n set to is ``30.0`` seconds.\n\n .. versionadded:: 2.0\n\n Attributes\n -----------\n ws\n The websocket gateway the client is currently connected to. Could be ``None``.\n \"\"\"\n\n def __init__(self, *, intents: Intents, **options: Any) -> None:\n self.loop: asyncio.AbstractEventLoop = _loop\n # self.ws is set in the connect method\n self.ws: DiscordWebSocket = None # type: ignore\n self._listeners: Dict[str, List[Tuple[asyncio.Future, Callable[..., bool]]]] = {}\n self.shard_id: Optional[int] = options.get('shard_id')\n self.shard_count: Optional[int] = options.get('shard_count')\n\n proxy: Optional[str] = options.pop('proxy', None)\n proxy_auth: Optional[aiohttp.BasicAuth] = options.pop('proxy_auth', None)\n unsync_clock: bool = options.pop('assume_unsync_clock', True)\n http_trace: Optional[aiohttp.TraceConfig] = options.pop('http_trace', None)\n max_ratelimit_timeout: Optional[float] = options.pop('max_ratelimit_timeout', None)\n self.http: HTTPClient = HTTPClient(\n self.loop,\n proxy=proxy,\n proxy_auth=proxy_auth,\n unsync_clock=unsync_clock,\n http_trace=http_trace,\n max_ratelimit_timeout=max_ratelimit_timeout,\n )\n\n self._handlers: Dict[str, Callable[..., None]] = {\n 'ready': self._handle_ready,\n }\n\n self._hooks: Dict[str, Callable[..., Coroutine[Any, Any, Any]]] = {\n 'before_identify': self._call_before_identify_hook,\n }\n\n self._enable_debug_events: bool = options.pop('enable_debug_events', False)\n self._connection: ConnectionState[Self] = self._get_state(intents=intents, **options)\n self._connection.shard_count = self.shard_count\n self._closed: bool = False\n self._ready: asyncio.Event = MISSING\n self._application: Optional[AppInfo] = None\n self._connection._get_websocket = self._get_websocket\n self._connection._get_client = lambda: self\n\n if VoiceClient.warn_nacl:\n VoiceClient.warn_nacl = False\n _log.warning(\"PyNaCl is not installed, voice will NOT be supported\")\n\n async def __aenter__(self) -> Self:\n await self._async_setup_hook()\n return self\n\n async def __aexit__(\n self,\n exc_type: Optional[Type[BaseException]],\n exc_value: Optional[BaseException],\n traceback: Optional[TracebackType],\n ) -> None:\n if not self.is_closed():\n await self.close()\n\n # internals\n\n def _get_websocket(self, guild_id: Optional[int] = None, *, shard_id: Optional[int] = None) -> DiscordWebSocket:\n return self.ws\n\n def _get_state(self, **options: Any) -> ConnectionState:\n return ConnectionState(dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, http=self.http, **options)\n\n def _handle_ready(self) -> None:\n self._ready.set()\n\n @property\n def latency(self) -> float:\n \"\"\":class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.\n\n This could be referred to as the Discord WebSocket protocol latency.\n \"\"\"\n ws = self.ws\n return float('nan') if not ws else ws.latency\n\n def is_ws_ratelimited(self) -> bool:\n \"\"\":class:`bool`: Whether the websocket is currently rate limited.\n\n This can be useful to know when deciding whether you should query members\n using HTTP or via the gateway.\n\n .. versionadded:: 1.6\n \"\"\"\n if self.ws:\n return self.ws.is_ratelimited()\n return False\n\n @property\n def user(self) -> Optional[ClientUser]:\n \"\"\"Optional[:class:`.ClientUser`]: Represents the connected client. ``None`` if not logged in.\"\"\"\n return self._connection.user\n\n @property\n def guilds(self) -> Sequence[Guild]:\n \"\"\"Sequence[:class:`.Guild`]: The guilds that the connected client is a member of.\"\"\"\n return self._connection.guilds\n\n @property\n def emojis(self) -> Sequence[Emoji]:\n \"\"\"Sequence[:class:`.Emoji`]: The emojis that the connected client has.\"\"\"\n return self._connection.emojis\n\n @property\n def stickers(self) -> Sequence[GuildSticker]:\n \"\"\"Sequence[:class:`.GuildSticker`]: The stickers that the connected client has.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._connection.stickers\n\n @property\n def cached_messages(self) -> Sequence[Message]:\n \"\"\"Sequence[:class:`.Message`]: Read-only list of messages the connected client has cached.\n\n .. versionadded:: 1.1\n \"\"\"\n return utils.SequenceProxy(self._connection._messages or [])\n\n @property\n def private_channels(self) -> Sequence[PrivateChannel]:\n \"\"\"Sequence[:class:`.abc.PrivateChannel`]: The private channels that the connected client is participating on.\n\n .. note::\n\n This returns only up to 128 most recent private channels due to an internal working\n on how Discord deals with private channels.\n \"\"\"\n return self._connection.private_channels\n\n @property\n def voice_clients(self) -> List[VoiceProtocol]:\n \"\"\"List[:class:`.VoiceProtocol`]: Represents a list of voice connections.\n\n These are usually :class:`.VoiceClient` instances.\n \"\"\"\n return self._connection.voice_clients\n\n @property\n def application_id(self) -> Optional[int]:\n \"\"\"Optional[:class:`int`]: The client's application ID.\n\n If this is not passed via ``__init__`` then this is retrieved\n through the gateway when an event contains the data or after a call\n to :meth:`~discord.Client.login`. Usually after :func:`~discord.on_connect`\n is called.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._connection.application_id\n\n @property\n def application_flags(self) -> ApplicationFlags:\n \"\"\":class:`~discord.ApplicationFlags`: The client's application flags.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._connection.application_flags\n\n @property\n def application(self) -> Optional[AppInfo]:\n \"\"\"Optional[:class:`~discord.AppInfo`]: The client's application info.\n\n This is retrieved on :meth:`~discord.Client.login` and is not updated\n afterwards. This allows populating the application_id without requiring a\n gateway connection.\n\n This is ``None`` if accessed before :meth:`~discord.Client.login` is called.\n\n .. seealso:: The :meth:`~discord.Client.application_info` API call\n\n .. versionadded:: 2.0\n \"\"\"\n return self._application\n\n def is_ready(self) -> bool:\n \"\"\":class:`bool`: Specifies if the client's internal cache is ready for use.\"\"\"\n return self._ready is not MISSING and self._ready.is_set()\n\n async def _run_event(\n self,\n coro: Callable[..., Coroutine[Any, Any, Any]],\n event_name: str,\n *args: Any,\n **kwargs: Any,\n ) -> None:\n try:\n await coro(*args, **kwargs)\n except asyncio.CancelledError:\n pass\n except Exception:\n try:\n await self.on_error(event_name, *args, **kwargs)\n except asyncio.CancelledError:\n pass\n\n def _schedule_event(\n self,\n coro: Callable[..., Coroutine[Any, Any, Any]],\n event_name: str,\n *args: Any,\n **kwargs: Any,\n ) -> asyncio.Task:\n wrapped = self._run_event(coro, event_name, *args, **kwargs)\n # Schedules the task\n return self.loop.create_task(wrapped, name=f'discord.py: {event_name}')\n\n def dispatch(self, event: str, /, *args: Any, **kwargs: Any) -> None:\n _log.debug('Dispatching event %s', event)\n method = 'on_' + event\n\n listeners = self._listeners.get(event)\n if listeners:\n removed = []\n for i, (future, condition) in enumerate(listeners):\n if future.cancelled():\n removed.append(i)\n continue\n\n try:\n result = condition(*args)\n except Exception as exc:\n future.set_exception(exc)\n removed.append(i)\n else:\n if result:\n if len(args) == 0:\n future.set_result(None)\n elif len(args) == 1:\n future.set_result(args[0])\n else:\n future.set_result(args)\n removed.append(i)\n\n if len(removed) == len(listeners):\n self._listeners.pop(event)\n else:\n for idx in reversed(removed):\n del listeners[idx]\n\n try:\n coro = getattr(self, method)\n except AttributeError:\n pass\n else:\n self._schedule_event(coro, method, *args, **kwargs)\n\n async def on_error(self, event_method: str, /, *args: Any, **kwargs: Any) -> None:\n \"\"\"|coro|\n\n The default error handler provided by the client.\n\n By default this logs to the library logger however it could be\n overridden to have a different implementation.\n Check :func:`~discord.on_error` for more details.\n\n .. versionchanged:: 2.0\n\n ``event_method`` parameter is now positional-only\n and instead of writing to ``sys.stderr`` it logs instead.\n \"\"\"\n _log.exception('Ignoring exception in %s', event_method)\n\n # hooks\n\n async def _call_before_identify_hook(self, shard_id: Optional[int], *, initial: bool = False) -> None:\n # This hook is an internal hook that actually calls the public one.\n # It allows the library to have its own hook without stepping on the\n # toes of those who need to override their own hook.\n await self.before_identify_hook(shard_id, initial=initial)\n\n async def before_identify_hook(self, shard_id: Optional[int], *, initial: bool = False) -> None:\n \"\"\"|coro|\n\n A hook that is called before IDENTIFYing a session. This is useful\n if you wish to have more control over the synchronization of multiple\n IDENTIFYing clients.\n\n The default implementation sleeps for 5 seconds.\n\n .. versionadded:: 1.4\n\n Parameters\n ------------\n shard_id: :class:`int`\n The shard ID that requested being IDENTIFY'd\n initial: :class:`bool`\n Whether this IDENTIFY is the first initial IDENTIFY.\n \"\"\"\n\n if not initial:\n await asyncio.sleep(5.0)\n\n async def _async_setup_hook(self) -> None:\n # Called whenever the client needs to initialise asyncio objects with a running loop\n loop = asyncio.get_running_loop()\n self.loop = loop\n self.http.loop = loop\n self._connection.loop = loop\n\n self._ready = asyncio.Event()\n\n async def setup_hook(self) -> None:\n \"\"\"|coro|\n\n A coroutine to be called to setup the bot, by default this is blank.\n\n To perform asynchronous setup after the bot is logged in but before\n it has connected to the Websocket, overwrite this coroutine.\n\n This is only called once, in :meth:`login`, and will be called before\n any events are dispatched, making it a better solution than doing such\n setup in the :func:`~discord.on_ready` event.\n\n .. warning::\n\n Since this is called *before* the websocket connection is made therefore\n anything that waits for the websocket will deadlock, this includes things\n like :meth:`wait_for` and :meth:`wait_until_ready`.\n\n .. versionadded:: 2.0\n \"\"\"\n pass\n\n # login state management\n\n async def login(self, token: str) -> None:\n \"\"\"|coro|\n\n Logs in the client with the specified credentials and\n calls the :meth:`setup_hook`.\n\n\n Parameters\n -----------\n token: :class:`str`\n The authentication token. Do not prefix this token with\n anything as the library will do it for you.\n\n Raises\n ------\n LoginFailure\n The wrong credentials are passed.\n HTTPException\n An unknown HTTP related error occurred,\n usually when it isn't 200 or the known incorrect credentials\n passing status code.\n \"\"\"\n\n _log.info('logging in using static token')\n\n if self.loop is _loop:\n await self._async_setup_hook()\n\n if not isinstance(token, str):\n raise TypeError(f'expected token to be a str, received {token.__class__.__name__} instead')\n token = token.strip()\n\n data = await self.http.static_login(token)\n self._connection.user = ClientUser(state=self._connection, data=data)\n self._application = await self.application_info()\n if self._connection.application_id is None:\n self._connection.application_id = self._application.id\n\n if not self._connection.application_flags:\n self._connection.application_flags = self._application.flags\n\n await self.setup_hook()\n\n async def connect(self, *, reconnect: bool = True) -> None:\n \"\"\"|coro|\n\n Creates a websocket connection and lets the websocket listen\n to messages from Discord. This is a loop that runs the entire\n event system and miscellaneous aspects of the library. Control\n is not resumed until the WebSocket connection is terminated.\n\n Parameters\n -----------\n reconnect: :class:`bool`\n If we should attempt reconnecting, either due to internet\n failure or a specific failure on Discord's part. Certain\n disconnects that lead to bad state will not be handled (such as\n invalid sharding payloads or bad tokens).\n\n Raises\n -------\n GatewayNotFound\n If the gateway to connect to Discord is not found. Usually if this\n is thrown then there is a Discord API outage.\n ConnectionClosed\n The websocket connection has been terminated.\n \"\"\"\n\n backoff = ExponentialBackoff()\n ws_params = {\n 'initial': True,\n 'shard_id': self.shard_id,\n }\n while not self.is_closed():\n try:\n coro = DiscordWebSocket.from_client(self, **ws_params)\n self.ws = await asyncio.wait_for(coro, timeout=60.0)\n ws_params['initial'] = False\n while True:\n await self.ws.poll_event()\n except ReconnectWebSocket as e:\n _log.debug('Got a request to %s the websocket.', e.op)\n self.dispatch('disconnect')\n ws_params.update(sequence=self.ws.sequence, resume=e.resume, session=self.ws.session_id)\n if e.resume:\n ws_params['gateway'] = self.ws.gateway\n continue\n except (\n OSError,\n HTTPException,\n GatewayNotFound,\n ConnectionClosed,\n aiohttp.ClientError,\n asyncio.TimeoutError,\n ) as exc:\n\n self.dispatch('disconnect')\n if not reconnect:\n await self.close()\n if isinstance(exc, ConnectionClosed) and exc.code == 1000:\n # clean close, don't re-raise this\n return\n raise\n\n if self.is_closed():\n return\n\n # If we get connection reset by peer then try to RESUME\n if isinstance(exc, OSError) and exc.errno in (54, 10054):\n ws_params.update(\n sequence=self.ws.sequence,\n gateway=self.ws.gateway,\n initial=False,\n resume=True,\n session=self.ws.session_id,\n )\n continue\n\n # We should only get this when an unhandled close code happens,\n # such as a clean disconnect (1000) or a bad state (bad token, no sharding, etc)\n # sometimes, discord sends us 1000 for unknown reasons so we should reconnect\n # regardless and rely on is_closed instead\n if isinstance(exc, ConnectionClosed):\n if exc.code == 4014:\n raise PrivilegedIntentsRequired(exc.shard_id) from None\n if exc.code != 1000:\n await self.close()\n raise\n\n retry = backoff.delay()\n _log.exception(\"Attempting a reconnect in %.2fs\", retry)\n await asyncio.sleep(retry)\n # Always try to RESUME the connection\n # If the connection is not RESUME-able then the gateway will invalidate the session.\n # This is apparently what the official Discord client does.\n ws_params.update(\n sequence=self.ws.sequence,\n gateway=self.ws.gateway,\n resume=True,\n session=self.ws.session_id,\n )\n\n async def close(self) -> None:\n \"\"\"|coro|\n\n Closes the connection to Discord.\n \"\"\"\n if self._closed:\n return\n\n self._closed = True\n\n await self._connection.close()\n\n if self.ws is not None and self.ws.open:\n await self.ws.close(code=1000)\n\n await self.http.close()\n\n if self._ready is not MISSING:\n self._ready.clear()\n\n self.loop = MISSING\n\n def clear(self) -> None:\n \"\"\"Clears the internal state of the bot.\n\n After this, the bot can be considered \"re-opened\", i.e. :meth:`is_closed`\n and :meth:`is_ready` both return ``False`` along with the bot's internal\n cache cleared.\n \"\"\"\n self._closed = False\n self._ready.clear()\n self._connection.clear()\n self.http.clear()\n\n async def start(self, token: str, *, reconnect: bool = True) -> None:\n \"\"\"|coro|\n\n A shorthand coroutine for :meth:`login` + :meth:`connect`.\n\n Parameters\n -----------\n token: :class:`str`\n The authentication token. Do not prefix this token with\n anything as the library will do it for you.\n reconnect: :class:`bool`\n If we should attempt reconnecting, either due to internet\n failure or a specific failure on Discord's part. Certain\n disconnects that lead to bad state will not be handled (such as\n invalid sharding payloads or bad tokens).\n\n Raises\n -------\n TypeError\n An unexpected keyword argument was received.\n \"\"\"\n await self.login(token)\n await self.connect(reconnect=reconnect)\n\n def run(\n self,\n token: str,\n *,\n reconnect: bool = True,\n log_handler: Optional[logging.Handler] = MISSING,\n log_formatter: logging.Formatter = MISSING,\n log_level: int = MISSING,\n root_logger: bool = False,\n ) -> None:\n \"\"\"A blocking call that abstracts away the event loop\n initialisation from you.\n\n If you want more control over the event loop then this\n function should not be used. Use :meth:`start` coroutine\n or :meth:`connect` + :meth:`login`.\n\n This function also sets up the logging library to make it easier\n for beginners to know what is going on with the library. For more\n advanced users, this can be disabled by passing ``None`` to\n the ``log_handler`` parameter.\n\n .. warning::\n\n This function must be the last function to call due to the fact that it\n is blocking. That means that registration of events or anything being\n called after this function call will not execute until it returns.\n\n Parameters\n -----------\n token: :class:`str`\n The authentication token. Do not prefix this token with\n anything as the library will do it for you.\n reconnect: :class:`bool`\n If we should attempt reconnecting, either due to internet\n failure or a specific failure on Discord's part. Certain\n disconnects that lead to bad state will not be handled (such as\n invalid sharding payloads or bad tokens).\n log_handler: Optional[:class:`logging.Handler`]\n The log handler to use for the library's logger. If this is ``None``\n then the library will not set up anything logging related. Logging\n will still work if ``None`` is passed, though it is your responsibility\n to set it up.\n\n The default log handler if not provided is :class:`logging.StreamHandler`.\n\n .. versionadded:: 2.0\n log_formatter: :class:`logging.Formatter`\n The formatter to use with the given log handler. If not provided then it\n defaults to a colour based logging formatter (if available).\n\n .. versionadded:: 2.0\n log_level: :class:`int`\n The default log level for the library's logger. This is only applied if the\n ``log_handler`` parameter is not ``None``. Defaults to ``logging.INFO``.\n\n .. versionadded:: 2.0\n root_logger: :class:`bool`\n Whether to set up the root logger rather than the library logger.\n By default, only the library logger (``'discord'``) is set up. If this\n is set to ``True`` then the root logger is set up as well.\n\n Defaults to ``False``.\n\n .. versionadded:: 2.0\n \"\"\"\n\n async def runner():\n async with self:\n await self.start(token, reconnect=reconnect)\n\n if log_handler is not None:\n utils.setup_logging(\n handler=log_handler,\n formatter=log_formatter,\n level=log_level,\n root=root_logger,\n )\n\n try:\n asyncio.run(runner())\n except KeyboardInterrupt:\n # nothing to do here\n # `asyncio.run` handles the loop cleanup\n # and `self.start` closes all sockets and the HTTPClient instance.\n return\n\n # properties\n\n def is_closed(self) -> bool:\n \"\"\":class:`bool`: Indicates if the websocket connection is closed.\"\"\"\n return self._closed\n\n @property\n def activity(self) -> Optional[ActivityTypes]:\n \"\"\"Optional[:class:`.BaseActivity`]: The activity being used upon\n logging in.\n \"\"\"\n return create_activity(self._connection._activity, self._connection)\n\n @activity.setter\n def activity(self, value: Optional[ActivityTypes]) -> None:\n if value is None:\n self._connection._activity = None\n elif isinstance(value, BaseActivity):\n # ConnectionState._activity is typehinted as ActivityPayload, we're passing Dict[str, Any]\n self._connection._activity = value.to_dict() # type: ignore\n else:\n raise TypeError('activity must derive from BaseActivity.')\n\n @property\n def status(self) -> Status:\n \"\"\":class:`.Status`:\n The status being used upon logging on to Discord.\n\n .. versionadded: 2.0\n \"\"\"\n if self._connection._status in set(state.value for state in Status):\n return Status(self._connection._status)\n return Status.online\n\n @status.setter\n def status(self, value: Status) -> None:\n if value is Status.offline:\n self._connection._status = 'invisible'\n elif isinstance(value, Status):\n self._connection._status = str(value)\n else:\n raise TypeError('status must derive from Status.')\n\n @property\n def allowed_mentions(self) -> Optional[AllowedMentions]:\n \"\"\"Optional[:class:`~discord.AllowedMentions`]: The allowed mention configuration.\n\n .. versionadded:: 1.4\n \"\"\"\n return self._connection.allowed_mentions\n\n @allowed_mentions.setter\n def allowed_mentions(self, value: Optional[AllowedMentions]) -> None:\n if value is None or isinstance(value, AllowedMentions):\n self._connection.allowed_mentions = value\n else:\n raise TypeError(f'allowed_mentions must be AllowedMentions not {value.__class__.__name__}')\n\n @property\n def intents(self) -> Intents:\n \"\"\":class:`~discord.Intents`: The intents configured for this connection.\n\n .. versionadded:: 1.5\n \"\"\"\n return self._connection.intents\n\n # helpers/getters\n\n @property\n def users(self) -> List[User]:\n \"\"\"List[:class:`~discord.User`]: Returns a list of all the users the bot can see.\"\"\"\n return list(self._connection._users.values())\n\n def get_channel(self, id: int, /) -> Optional[Union[GuildChannel, Thread, PrivateChannel]]:\n \"\"\"Returns a channel or thread with the given ID.\n\n .. versionchanged:: 2.0\n\n ``id`` parameter is now positional-only.\n\n Parameters\n -----------\n id: :class:`int`\n The ID to search for.\n\n Returns\n --------\n Optional[Union[:class:`.abc.GuildChannel`, :class:`.Thread`, :class:`.abc.PrivateChannel`]]\n The returned channel or ``None`` if not found.\n \"\"\"\n return self._connection.get_channel(id) # type: ignore # The cache contains all channel types\n\n def get_partial_messageable(\n self, id: int, *, guild_id: Optional[int] = None, type: Optional[ChannelType] = None\n ) -> PartialMessageable:\n \"\"\"Returns a partial messageable with the given channel ID.\n\n This is useful if you have a channel_id but don't want to do an API call\n to send messages to it.\n\n .. versionadded:: 2.0\n\n Parameters\n -----------\n id: :class:`int`\n The channel ID to create a partial messageable for.\n guild_id: Optional[:class:`int`]\n The optional guild ID to create a partial messageable for.\n\n This is not required to actually send messages, but it does allow the\n :meth:`~discord.PartialMessageable.jump_url` and\n :attr:`~discord.PartialMessageable.guild` properties to function properly.\n type: Optional[:class:`.ChannelType`]\n The underlying channel type for the partial messageable.\n\n Returns\n --------\n :class:`.PartialMessageable`\n The partial messageable\n \"\"\"\n return PartialMessageable(state=self._connection, id=id, guild_id=guild_id, type=type)\n\n def get_stage_instance(self, id: int, /) -> Optional[StageInstance]:\n \"\"\"Returns a stage instance with the given stage channel ID.\n\n .. versionadded:: 2.0\n\n Parameters\n -----------\n id: :class:`int`\n The ID to search for.\n\n Returns\n --------\n Optional[:class:`.StageInstance`]\n The stage instance or ``None`` if not found.\n \"\"\"\n from .channel import StageChannel\n\n channel = self._connection.get_channel(id)\n\n if isinstance(channel, StageChannel):\n return channel.instance\n\n def get_guild(self, id: int, /) -> Optional[Guild]:\n \"\"\"Returns a guild with the given ID.\n\n .. versionchanged:: 2.0\n\n ``id`` parameter is now positional-only.\n\n Parameters\n -----------\n id: :class:`int`\n The ID to search for.\n\n Returns\n --------\n Optional[:class:`.Guild`]\n The guild or ``None`` if not found.\n \"\"\"\n return self._connection._get_guild(id)\n\n def get_user(self, id: int, /) -> Optional[User]:\n \"\"\"Returns a user with the given ID.\n\n .. versionchanged:: 2.0\n\n ``id`` parameter is now positional-only.\n\n Parameters\n -----------\n id: :class:`int`\n The ID to search for.\n\n Returns\n --------\n Optional[:class:`~discord.User`]\n The user or ``None`` if not found.\n \"\"\"\n return self._connection.get_user(id)\n\n def get_emoji(self, id: int, /) -> Optional[Emoji]:\n \"\"\"Returns an emoji with the given ID.\n\n .. versionchanged:: 2.0\n\n ``id`` parameter is now positional-only.\n\n Parameters\n -----------\n id: :class:`int`\n The ID to search for.\n\n Returns\n --------\n Optional[:class:`.Emoji`]\n The custom emoji or ``None`` if not found.\n \"\"\"\n return self._connection.get_emoji(id)\n\n def get_sticker(self, id: int, /) -> Optional[GuildSticker]:\n \"\"\"Returns a guild sticker with the given ID.\n\n .. versionadded:: 2.0\n\n .. note::\n\n To retrieve standard stickers, use :meth:`.fetch_sticker`.\n or :meth:`.fetch_premium_sticker_packs`.\n\n Returns\n --------\n Optional[:class:`.GuildSticker`]\n The sticker or ``None`` if not found.\n \"\"\"\n return self._connection.get_sticker(id)\n\n def get_all_channels(self) -> Generator[GuildChannel, None, None]:\n \"\"\"A generator that retrieves every :class:`.abc.GuildChannel` the client can 'access'.\n\n This is equivalent to: ::\n\n for guild in client.guilds:\n for channel in guild.channels:\n yield channel\n\n .. note::\n\n Just because you receive a :class:`.abc.GuildChannel` does not mean that\n you can communicate in said channel. :meth:`.abc.GuildChannel.permissions_for` should\n be used for that.\n\n Yields\n ------\n :class:`.abc.GuildChannel`\n A channel the client can 'access'.\n \"\"\"\n\n for guild in self.guilds:\n yield from guild.channels\n\n def get_all_members(self) -> Generator[Member, None, None]:\n \"\"\"Returns a generator with every :class:`.Member` the client can see.\n\n This is equivalent to: ::\n\n for guild in client.guilds:\n for member in guild.members:\n yield member\n\n Yields\n ------\n :class:`.Member`\n A member the client can see.\n \"\"\"\n for guild in self.guilds:\n yield from guild.members\n\n # listeners/waiters\n\n async def wait_until_ready(self) -> None:\n \"\"\"|coro|\n\n Waits until the client's internal cache is all ready.\n\n .. warning::\n\n Calling this inside :meth:`setup_hook` can lead to a deadlock.\n \"\"\"\n if self._ready is not MISSING:\n await self._ready.wait()\n else:\n raise RuntimeError(\n 'Client has not been properly initialised. '\n 'Please use the login method or asynchronous context manager before calling this method'\n )\n\n # App Commands\n\n @overload\n async def wait_for(\n self,\n event: Literal['raw_app_command_permissions_update'],\n /,\n *,\n check: Optional[Callable[[RawAppCommandPermissionsUpdateEvent], bool]],\n timeout: Optional[float] = None,\n ) -> RawAppCommandPermissionsUpdateEvent:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['app_command_completion'],\n /,\n *,\n check: Optional[Callable[[Interaction[Self], Union[Command[Any, ..., Any], ContextMenu]], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[Interaction[Self], Union[Command[Any, ..., Any], ContextMenu]]:\n ...\n\n # AutoMod\n\n @overload\n async def wait_for(\n self,\n event: Literal['automod_rule_create', 'automod_rule_update', 'automod_rule_delete'],\n /,\n *,\n check: Optional[Callable[[AutoModRule], bool]],\n timeout: Optional[float] = None,\n ) -> AutoModRule:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['automod_action'],\n /,\n *,\n check: Optional[Callable[[AutoModAction], bool]],\n timeout: Optional[float] = None,\n ) -> AutoModAction:\n ...\n\n # Channels\n\n @overload\n async def wait_for(\n self,\n event: Literal['private_channel_update'],\n /,\n *,\n check: Optional[Callable[[GroupChannel, GroupChannel], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[GroupChannel, GroupChannel]:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['private_channel_pins_update'],\n /,\n *,\n check: Optional[Callable[[PrivateChannel, datetime.datetime], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[PrivateChannel, datetime.datetime]:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['guild_channel_delete', 'guild_channel_create'],\n /,\n *,\n check: Optional[Callable[[GuildChannel], bool]],\n timeout: Optional[float] = None,\n ) -> GuildChannel:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['guild_channel_update'],\n /,\n *,\n check: Optional[Callable[[GuildChannel, GuildChannel], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[GuildChannel, GuildChannel]:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['guild_channel_pins_update'],\n /,\n *,\n check: Optional[\n Callable[\n [Union[GuildChannel, Thread], Optional[datetime.datetime]],\n bool,\n ]\n ],\n timeout: Optional[float] = None,\n ) -> Tuple[Union[GuildChannel, Thread], Optional[datetime.datetime]]:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['typing'],\n /,\n *,\n check: Optional[Callable[[Messageable, Union[User, Member], datetime.datetime], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[Messageable, Union[User, Member], datetime.datetime]:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['raw_typing'],\n /,\n *,\n check: Optional[Callable[[RawTypingEvent], bool]],\n timeout: Optional[float] = None,\n ) -> RawTypingEvent:\n ...\n\n # Debug & Gateway events\n\n @overload\n async def wait_for(\n self,\n event: Literal['connect', 'disconnect', 'ready', 'resumed'],\n /,\n *,\n check: Optional[Callable[[], bool]],\n timeout: Optional[float] = None,\n ) -> None:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['shard_connect', 'shard_disconnect', 'shard_ready', 'shard_resumed'],\n /,\n *,\n check: Optional[Callable[[int], bool]],\n timeout: Optional[float] = None,\n ) -> int:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['socket_event_type', 'socket_raw_receive'],\n /,\n *,\n check: Optional[Callable[[str], bool]],\n timeout: Optional[float] = None,\n ) -> str:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['socket_raw_send'],\n /,\n *,\n check: Optional[Callable[[Union[str, bytes]], bool]],\n timeout: Optional[float] = None,\n ) -> Union[str, bytes]:\n ...\n\n # Guilds\n\n @overload\n async def wait_for(\n self,\n event: Literal[\n 'guild_available',\n 'guild_unavailable',\n 'guild_join',\n 'guild_remove',\n ],\n /,\n *,\n check: Optional[Callable[[Guild], bool]],\n timeout: Optional[float] = None,\n ) -> Guild:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['guild_update'],\n /,\n *,\n check: Optional[Callable[[Guild, Guild], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[Guild, Guild]:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['guild_emojis_update'],\n /,\n *,\n check: Optional[Callable[[Guild, Sequence[Emoji], Sequence[Emoji]], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[Guild, Sequence[Emoji], Sequence[Emoji]]:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['guild_stickers_update'],\n /,\n *,\n check: Optional[Callable[[Guild, Sequence[GuildSticker], Sequence[GuildSticker]], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[Guild, Sequence[GuildSticker], Sequence[GuildSticker]]:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['invite_create', 'invite_delete'],\n /,\n *,\n check: Optional[Callable[[Invite], bool]],\n timeout: Optional[float] = None,\n ) -> Invite:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['audit_log_entry_create'],\n /,\n *,\n check: Optional[Callable[[AuditLogEntry], bool]],\n timeout: Optional[float] = None,\n ) -> AuditLogEntry:\n ...\n\n # Integrations\n\n @overload\n async def wait_for(\n self,\n event: Literal['integration_create', 'integration_update'],\n /,\n *,\n check: Optional[Callable[[Integration], bool]],\n timeout: Optional[float] = None,\n ) -> Integration:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['guild_integrations_update'],\n /,\n *,\n check: Optional[Callable[[Guild], bool]],\n timeout: Optional[float] = None,\n ) -> Guild:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['webhooks_update'],\n /,\n *,\n check: Optional[Callable[[GuildChannel], bool]],\n timeout: Optional[float] = None,\n ) -> GuildChannel:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['raw_integration_delete'],\n /,\n *,\n check: Optional[Callable[[RawIntegrationDeleteEvent], bool]],\n timeout: Optional[float] = None,\n ) -> RawIntegrationDeleteEvent:\n ...\n\n # Interactions\n\n @overload\n async def wait_for(\n self,\n event: Literal['interaction'],\n /,\n *,\n check: Optional[Callable[[Interaction[Self]], bool]],\n timeout: Optional[float] = None,\n ) -> Interaction[Self]:\n ...\n\n # Members\n\n @overload\n async def wait_for(\n self,\n event: Literal['member_join', 'member_remove'],\n /,\n *,\n check: Optional[Callable[[Member], bool]],\n timeout: Optional[float] = None,\n ) -> Member:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['raw_member_remove'],\n /,\n *,\n check: Optional[Callable[[RawMemberRemoveEvent], bool]],\n timeout: Optional[float] = None,\n ) -> RawMemberRemoveEvent:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['member_update', 'presence_update'],\n /,\n *,\n check: Optional[Callable[[Member, Member], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[Member, Member]:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['user_update'],\n /,\n *,\n check: Optional[Callable[[User, User], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[User, User]:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['member_ban'],\n /,\n *,\n check: Optional[Callable[[Guild, Union[User, Member]], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[Guild, Union[User, Member]]:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['member_unban'],\n /,\n *,\n check: Optional[Callable[[Guild, User], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[Guild, User]:\n ...\n\n # Messages\n\n @overload\n async def wait_for(\n self,\n event: Literal['message', 'message_delete'],\n /,\n *,\n check: Optional[Callable[[Message], bool]],\n timeout: Optional[float] = None,\n ) -> Message:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['message_edit'],\n /,\n *,\n check: Optional[Callable[[Message, Message], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[Message, Message]:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['bulk_message_delete'],\n /,\n *,\n check: Optional[Callable[[List[Message]], bool]],\n timeout: Optional[float] = None,\n ) -> List[Message]:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['raw_message_edit'],\n /,\n *,\n check: Optional[Callable[[RawMessageUpdateEvent], bool]],\n timeout: Optional[float] = None,\n ) -> RawMessageUpdateEvent:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['raw_message_delete'],\n /,\n *,\n check: Optional[Callable[[RawMessageDeleteEvent], bool]],\n timeout: Optional[float] = None,\n ) -> RawMessageDeleteEvent:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['raw_bulk_message_delete'],\n /,\n *,\n check: Optional[Callable[[RawBulkMessageDeleteEvent], bool]],\n timeout: Optional[float] = None,\n ) -> RawBulkMessageDeleteEvent:\n ...\n\n # Reactions\n\n @overload\n async def wait_for(\n self,\n event: Literal['reaction_add', 'reaction_remove'],\n /,\n *,\n check: Optional[Callable[[Reaction, Union[Member, User]], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[Reaction, Union[Member, User]]:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['reaction_clear'],\n /,\n *,\n check: Optional[Callable[[Message, List[Reaction]], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[Message, List[Reaction]]:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['reaction_clear_emoji'],\n /,\n *,\n check: Optional[Callable[[Reaction], bool]],\n timeout: Optional[float] = None,\n ) -> Reaction:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['raw_reaction_add', 'raw_reaction_remove'],\n /,\n *,\n check: Optional[Callable[[RawReactionActionEvent], bool]],\n timeout: Optional[float] = None,\n ) -> RawReactionActionEvent:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['raw_reaction_clear'],\n /,\n *,\n check: Optional[Callable[[RawReactionClearEvent], bool]],\n timeout: Optional[float] = None,\n ) -> RawReactionClearEvent:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['raw_reaction_clear_emoji'],\n /,\n *,\n check: Optional[Callable[[RawReactionClearEmojiEvent], bool]],\n timeout: Optional[float] = None,\n ) -> RawReactionClearEmojiEvent:\n ...\n\n # Roles\n\n @overload\n async def wait_for(\n self,\n event: Literal['guild_role_create', 'guild_role_delete'],\n /,\n *,\n check: Optional[Callable[[Role], bool]],\n timeout: Optional[float] = None,\n ) -> Role:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['guild_role_update'],\n /,\n *,\n check: Optional[Callable[[Role, Role], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[Role, Role]:\n ...\n\n # Scheduled Events\n\n @overload\n async def wait_for(\n self,\n event: Literal['scheduled_event_create', 'scheduled_event_delete'],\n /,\n *,\n check: Optional[Callable[[ScheduledEvent], bool]],\n timeout: Optional[float] = None,\n ) -> ScheduledEvent:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['scheduled_event_user_add', 'scheduled_event_user_remove'],\n /,\n *,\n check: Optional[Callable[[ScheduledEvent, User], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[ScheduledEvent, User]:\n ...\n\n # Stages\n\n @overload\n async def wait_for(\n self,\n event: Literal['stage_instance_create', 'stage_instance_delete'],\n /,\n *,\n check: Optional[Callable[[StageInstance], bool]],\n timeout: Optional[float] = None,\n ) -> StageInstance:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['stage_instance_update'],\n /,\n *,\n check: Optional[Callable[[StageInstance, StageInstance], bool]],\n timeout: Optional[float] = None,\n ) -> Coroutine[Any, Any, Tuple[StageInstance, StageInstance]]:\n ...\n\n # Threads\n @overload\n async def wait_for(\n self,\n event: Literal['thread_create', 'thread_join', 'thread_remove', 'thread_delete'],\n /,\n *,\n check: Optional[Callable[[Thread], bool]],\n timeout: Optional[float] = None,\n ) -> Thread:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['thread_update'],\n /,\n *,\n check: Optional[Callable[[Thread, Thread], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[Thread, Thread]:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['raw_thread_update'],\n /,\n *,\n check: Optional[Callable[[RawThreadUpdateEvent], bool]],\n timeout: Optional[float] = None,\n ) -> RawThreadUpdateEvent:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['raw_thread_delete'],\n /,\n *,\n check: Optional[Callable[[RawThreadDeleteEvent], bool]],\n timeout: Optional[float] = None,\n ) -> RawThreadDeleteEvent:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['thread_member_join', 'thread_member_remove'],\n /,\n *,\n check: Optional[Callable[[ThreadMember], bool]],\n timeout: Optional[float] = None,\n ) -> ThreadMember:\n ...\n\n @overload\n async def wait_for(\n self,\n event: Literal['raw_thread_member_remove'],\n /,\n *,\n check: Optional[Callable[[RawThreadMembersUpdate], bool]],\n timeout: Optional[float] = None,\n ) -> RawThreadMembersUpdate:\n ...\n\n # Voice\n\n @overload\n async def wait_for(\n self,\n event: Literal['voice_state_update'],\n /,\n *,\n check: Optional[Callable[[Member, VoiceState, VoiceState], bool]],\n timeout: Optional[float] = None,\n ) -> Tuple[Member, VoiceState, VoiceState]:\n ...\n\n # Commands\n\n @overload\n async def wait_for(\n self: Union[Bot, AutoShardedBot],\n event: Literal[\"command\", \"command_completion\"],\n /,\n *,\n check: Optional[Callable[[Context[Any]], bool]] = None,\n timeout: Optional[float] = None,\n ) -> Context[Any]:\n ...\n\n @overload\n async def wait_for(\n self: Union[Bot, AutoShardedBot],\n event: Literal[\"command_error\"],\n /,\n *,\n check: Optional[Callable[[Context[Any], CommandError], bool]] = None,\n timeout: Optional[float] = None,\n ) -> Tuple[Context[Any], CommandError]:\n ...\n\n @overload\n async def wait_for(\n self,\n event: str,\n /,\n *,\n check: Optional[Callable[..., bool]] = None,\n timeout: Optional[float] = None,\n ) -> Any:\n ...\n\n def wait_for(\n self,\n event: str,\n /,\n *,\n check: Optional[Callable[..., bool]] = None,\n timeout: Optional[float] = None,\n ) -> Coro[Any]:\n \"\"\"|coro|\n\n Waits for a WebSocket event to be dispatched.\n\n This could be used to wait for a user to reply to a message,\n or to react to a message, or to edit a message in a self-contained\n way.\n\n The ``timeout`` parameter is passed onto :func:`asyncio.wait_for`. By default,\n it does not timeout. Note that this does propagate the\n :exc:`asyncio.TimeoutError` for you in case of timeout and is provided for\n ease of use.\n\n In case the event returns multiple arguments, a :class:`tuple` containing those\n arguments is returned instead. Please check the\n :ref:`documentation ` for a list of events and their\n parameters.\n\n This function returns the **first event that meets the requirements**.\n\n Examples\n ---------\n\n Waiting for a user reply: ::\n\n @client.event\n async def on_message(message):\n if message.content.startswith('$greet'):\n channel = message.channel\n await channel.send('Say hello!')\n\n def check(m):\n return m.content == 'hello' and m.channel == channel\n\n msg = await client.wait_for('message', check=check)\n await channel.send(f'Hello {msg.author}!')\n\n Waiting for a thumbs up reaction from the message author: ::\n\n @client.event\n async def on_message(message):\n if message.content.startswith('$thumb'):\n channel = message.channel\n await channel.send('Send me that \\N{THUMBS UP SIGN} reaction, mate')\n\n def check(reaction, user):\n return user == message.author and str(reaction.emoji) == '\\N{THUMBS UP SIGN}'\n\n try:\n reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)\n except asyncio.TimeoutError:\n await channel.send('\\N{THUMBS DOWN SIGN}')\n else:\n await channel.send('\\N{THUMBS UP SIGN}')\n\n .. versionchanged:: 2.0\n\n ``event`` parameter is now positional-only.\n\n\n Parameters\n ------------\n event: :class:`str`\n The event name, similar to the :ref:`event reference `,\n but without the ``on_`` prefix, to wait for.\n check: Optional[Callable[..., :class:`bool`]]\n A predicate to check what to wait for. The arguments must meet the\n parameters of the event being waited for.\n timeout: Optional[:class:`float`]\n The number of seconds to wait before timing out and raising\n :exc:`asyncio.TimeoutError`.\n\n Raises\n -------\n asyncio.TimeoutError\n If a timeout is provided and it was reached.\n\n Returns\n --------\n Any\n Returns no arguments, a single argument, or a :class:`tuple` of multiple\n arguments that mirrors the parameters passed in the\n :ref:`event reference `.\n \"\"\"\n\n future = self.loop.create_future()\n if check is None:\n\n def _check(*args):\n return True\n\n check = _check\n\n ev = event.lower()\n try:\n listeners = self._listeners[ev]\n except KeyError:\n listeners = []\n self._listeners[ev] = listeners\n\n listeners.append((future, check))\n return asyncio.wait_for(future, timeout)\n\n # event registration\n\n def event(self, coro: CoroT, /) -> CoroT:\n \"\"\"A decorator that registers an event to listen to.\n\n You can find more info about the events on the :ref:`documentation below `.\n\n The events must be a :ref:`coroutine `, if not, :exc:`TypeError` is raised.\n\n Example\n ---------\n\n .. code-block:: python3\n\n @client.event\n async def on_ready():\n print('Ready!')\n\n .. versionchanged:: 2.0\n\n ``coro`` parameter is now positional-only.\n\n Raises\n --------\n TypeError\n The coroutine passed is not actually a coroutine.\n \"\"\"\n\n if not asyncio.iscoroutinefunction(coro):\n raise TypeError('event registered must be a coroutine function')\n\n setattr(self, coro.__name__, coro)\n _log.debug('%s has successfully been registered as an event', coro.__name__)\n return coro\n\n async def change_presence(\n self,\n *,\n activity: Optional[BaseActivity] = None,\n status: Optional[Status] = None,\n ) -> None:\n \"\"\"|coro|\n\n Changes the client's presence.\n\n Example\n ---------\n\n .. code-block:: python3\n\n game = discord.Game(\"with the API\")\n await client.change_presence(status=discord.Status.idle, activity=game)\n\n .. versionchanged:: 2.0\n Removed the ``afk`` keyword-only parameter.\n\n .. versionchanged:: 2.0\n This function will now raise :exc:`TypeError` instead of\n ``InvalidArgument``.\n\n Parameters\n ----------\n activity: Optional[:class:`.BaseActivity`]\n The activity being done. ``None`` if no currently active activity is done.\n status: Optional[:class:`.Status`]\n Indicates what status to change to. If ``None``, then\n :attr:`.Status.online` is used.\n\n Raises\n ------\n TypeError\n If the ``activity`` parameter is not the proper type.\n \"\"\"\n\n if status is None:\n status_str = 'online'\n status = Status.online\n elif status is Status.offline:\n status_str = 'invisible'\n status = Status.offline\n else:\n status_str = str(status)\n\n await self.ws.change_presence(activity=activity, status=status_str)\n\n for guild in self._connection.guilds:\n me = guild.me\n if me is None:\n continue\n\n if activity is not None:\n me.activities = (activity,) # type: ignore # Type checker does not understand the downcast here\n else:\n me.activities = ()\n\n me.status = status\n\n # Guild stuff\n\n async def fetch_guilds(\n self,\n *,\n limit: Optional[int] = 200,\n before: Optional[SnowflakeTime] = None,\n after: Optional[SnowflakeTime] = None,\n with_counts: bool = True,\n ) -> AsyncIterator[Guild]:\n \"\"\"Retrieves an :term:`asynchronous iterator` that enables receiving your guilds.\n\n .. note::\n\n Using this, you will only receive :attr:`.Guild.owner`, :attr:`.Guild.icon`,\n :attr:`.Guild.id`, :attr:`.Guild.name`, :attr:`.Guild.approximate_member_count`,\n and :attr:`.Guild.approximate_presence_count` per :class:`.Guild`.\n\n .. note::\n\n This method is an API call. For general usage, consider :attr:`guilds` instead.\n\n Examples\n ---------\n\n Usage ::\n\n async for guild in client.fetch_guilds(limit=150):\n print(guild.name)\n\n Flattening into a list ::\n\n guilds = [guild async for guild in client.fetch_guilds(limit=150)]\n # guilds is now a list of Guild...\n\n All parameters are optional.\n\n Parameters\n -----------\n limit: Optional[:class:`int`]\n The number of guilds to retrieve.\n If ``None``, it retrieves every guild you have access to. Note, however,\n that this would make it a slow operation.\n Defaults to ``200``.\n\n .. versionchanged:: 2.0\n\n The default has been changed to 200.\n\n before: Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`]\n Retrieves guilds before this date or object.\n If a datetime is provided, it is recommended to use a UTC aware datetime.\n If the datetime is naive, it is assumed to be local time.\n after: Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`]\n Retrieve guilds after this date or object.\n If a datetime is provided, it is recommended to use a UTC aware datetime.\n If the datetime is naive, it is assumed to be local time.\n with_counts: :class:`bool`\n Whether to include count information in the guilds. This fills the\n :attr:`.Guild.approximate_member_count` and :attr:`.Guild.approximate_presence_count`\n attributes without needing any privileged intents. Defaults to ``True``.\n\n .. versionadded:: 2.3\n\n Raises\n ------\n HTTPException\n Getting the guilds failed.\n\n Yields\n --------\n :class:`.Guild`\n The guild with the guild data parsed.\n \"\"\"\n\n async def _before_strategy(retrieve: int, before: Optional[Snowflake], limit: Optional[int]):\n before_id = before.id if before else None\n data = await self.http.get_guilds(retrieve, before=before_id, with_counts=with_counts)\n\n if data:\n if limit is not None:\n limit -= len(data)\n\n before = Object(id=int(data[0]['id']))\n\n return data, before, limit\n\n async def _after_strategy(retrieve: int, after: Optional[Snowflake], limit: Optional[int]):\n after_id = after.id if after else None\n data = await self.http.get_guilds(retrieve, after=after_id, with_counts=with_counts)\n\n if data:\n if limit is not None:\n limit -= len(data)\n\n after = Object(id=int(data[-1]['id']))\n\n return data, after, limit\n\n if isinstance(before, datetime.datetime):\n before = Object(id=time_snowflake(before, high=False))\n if isinstance(after, datetime.datetime):\n after = Object(id=time_snowflake(after, high=True))\n\n predicate: Optional[Callable[[GuildPayload], bool]] = None\n strategy, state = _after_strategy, after\n\n if before:\n strategy, state = _before_strategy, before\n\n if before and after:\n predicate = lambda m: int(m['id']) > after.id\n\n while True:\n retrieve = 200 if limit is None else min(limit, 200)\n if retrieve < 1:\n return\n\n data, state, limit = await strategy(retrieve, state, limit)\n\n if predicate:\n data = filter(predicate, data)\n\n count = 0\n\n for count, raw_guild in enumerate(data, 1):\n yield Guild(state=self._connection, data=raw_guild)\n\n if count < 200:\n # There's no data left after this\n break\n\n async def fetch_template(self, code: Union[Template, str]) -> Template:\n \"\"\"|coro|\n\n Gets a :class:`.Template` from a discord.new URL or code.\n\n Parameters\n -----------\n code: Union[:class:`.Template`, :class:`str`]\n The Discord Template Code or URL (must be a discord.new URL).\n\n Raises\n -------\n NotFound\n The template is invalid.\n HTTPException\n Getting the template failed.\n\n Returns\n --------\n :class:`.Template`\n The template from the URL/code.\n \"\"\"\n code = utils.resolve_template(code)\n data = await self.http.get_template(code)\n return Template(data=data, state=self._connection)\n\n async def fetch_guild(self, guild_id: int, /, *, with_counts: bool = True) -> Guild:\n \"\"\"|coro|\n\n Retrieves a :class:`.Guild` from an ID.\n\n .. note::\n\n Using this, you will **not** receive :attr:`.Guild.channels`, :attr:`.Guild.members`,\n :attr:`.Member.activity` and :attr:`.Member.voice` per :class:`.Member`.\n\n .. note::\n\n This method is an API call. For general usage, consider :meth:`get_guild` instead.\n\n .. versionchanged:: 2.0\n\n ``guild_id`` parameter is now positional-only.\n\n\n Parameters\n -----------\n guild_id: :class:`int`\n The guild's ID to fetch from.\n with_counts: :class:`bool`\n Whether to include count information in the guild. This fills the\n :attr:`.Guild.approximate_member_count` and :attr:`.Guild.approximate_presence_count`\n attributes without needing any privileged intents. Defaults to ``True``.\n\n .. versionadded:: 2.0\n\n Raises\n ------\n Forbidden\n You do not have access to the guild.\n HTTPException\n Getting the guild failed.\n\n Returns\n --------\n :class:`.Guild`\n The guild from the ID.\n \"\"\"\n data = await self.http.get_guild(guild_id, with_counts=with_counts)\n return Guild(data=data, state=self._connection)\n\n async def create_guild(\n self,\n *,\n name: str,\n icon: bytes = MISSING,\n code: str = MISSING,\n ) -> Guild:\n \"\"\"|coro|\n\n Creates a :class:`.Guild`.\n\n Bot accounts in more than 10 guilds are not allowed to create guilds.\n\n .. versionchanged:: 2.0\n ``name`` and ``icon`` parameters are now keyword-only. The ``region`` parameter has been removed.\n\n .. versionchanged:: 2.0\n This function will now raise :exc:`ValueError` instead of\n ``InvalidArgument``.\n\n Parameters\n ----------\n name: :class:`str`\n The name of the guild.\n icon: Optional[:class:`bytes`]\n The :term:`py:bytes-like object` representing the icon. See :meth:`.ClientUser.edit`\n for more details on what is expected.\n code: :class:`str`\n The code for a template to create the guild with.\n\n .. versionadded:: 1.4\n\n Raises\n ------\n HTTPException\n Guild creation failed.\n ValueError\n Invalid icon image format given. Must be PNG or JPG.\n\n Returns\n -------\n :class:`.Guild`\n The guild created. This is not the same guild that is\n added to cache.\n \"\"\"\n if icon is not MISSING:\n icon_base64 = utils._bytes_to_base64_data(icon)\n else:\n icon_base64 = None\n\n if code:\n data = await self.http.create_from_template(code, name, icon_base64)\n else:\n data = await self.http.create_guild(name, icon_base64)\n return Guild(data=data, state=self._connection)\n\n async def fetch_stage_instance(self, channel_id: int, /) -> StageInstance:\n \"\"\"|coro|\n\n Gets a :class:`.StageInstance` for a stage channel id.\n\n .. versionadded:: 2.0\n\n Parameters\n -----------\n channel_id: :class:`int`\n The stage channel ID.\n\n Raises\n -------\n NotFound\n The stage instance or channel could not be found.\n HTTPException\n Getting the stage instance failed.\n\n Returns\n --------\n :class:`.StageInstance`\n The stage instance from the stage channel ID.\n \"\"\"\n data = await self.http.get_stage_instance(channel_id)\n guild = self.get_guild(int(data['guild_id']))\n # Guild can technically be None here but this is being explicitly silenced right now.\n return StageInstance(guild=guild, state=self._connection, data=data) # type: ignore\n\n # Invite management\n\n async def fetch_invite(\n self,\n url: Union[Invite, str],\n *,\n with_counts: bool = True,\n with_expiration: bool = True,\n scheduled_event_id: Optional[int] = None,\n ) -> Invite:\n \"\"\"|coro|\n\n Gets an :class:`.Invite` from a discord.gg URL or ID.\n\n .. note::\n\n If the invite is for a guild you have not joined, the guild and channel\n attributes of the returned :class:`.Invite` will be :class:`.PartialInviteGuild` and\n :class:`.PartialInviteChannel` respectively.\n\n Parameters\n -----------\n url: Union[:class:`.Invite`, :class:`str`]\n The Discord invite ID or URL (must be a discord.gg URL).\n with_counts: :class:`bool`\n Whether to include count information in the invite. This fills the\n :attr:`.Invite.approximate_member_count` and :attr:`.Invite.approximate_presence_count`\n fields.\n with_expiration: :class:`bool`\n Whether to include the expiration date of the invite. This fills the\n :attr:`.Invite.expires_at` field.\n\n .. versionadded:: 2.0\n scheduled_event_id: Optional[:class:`int`]\n The ID of the scheduled event this invite is for.\n\n .. note::\n\n It is not possible to provide a url that contains an ``event_id`` parameter\n when using this parameter.\n\n .. versionadded:: 2.0\n\n Raises\n -------\n ValueError\n The url contains an ``event_id``, but ``scheduled_event_id`` has also been provided.\n NotFound\n The invite has expired or is invalid.\n HTTPException\n Getting the invite failed.\n\n Returns\n --------\n :class:`.Invite`\n The invite from the URL/ID.\n \"\"\"\n\n resolved = utils.resolve_invite(url)\n\n if scheduled_event_id and resolved.event:\n raise ValueError('Cannot specify scheduled_event_id and contain an event_id in the url.')\n\n scheduled_event_id = scheduled_event_id or resolved.event\n\n data = await self.http.get_invite(\n resolved.code,\n with_counts=with_counts,\n with_expiration=with_expiration,\n guild_scheduled_event_id=scheduled_event_id,\n )\n return Invite.from_incomplete(state=self._connection, data=data)\n\n async def delete_invite(self, invite: Union[Invite, str], /) -> None:\n \"\"\"|coro|\n\n Revokes an :class:`.Invite`, URL, or ID to an invite.\n\n You must have :attr:`~.Permissions.manage_channels` in\n the associated guild to do this.\n\n .. versionchanged:: 2.0\n\n ``invite`` parameter is now positional-only.\n\n Parameters\n ----------\n invite: Union[:class:`.Invite`, :class:`str`]\n The invite to revoke.\n\n Raises\n -------\n Forbidden\n You do not have permissions to revoke invites.\n NotFound\n The invite is invalid or expired.\n HTTPException\n Revoking the invite failed.\n \"\"\"\n\n resolved = utils.resolve_invite(invite)\n await self.http.delete_invite(resolved.code)\n\n # Miscellaneous stuff\n\n async def fetch_widget(self, guild_id: int, /) -> Widget:\n \"\"\"|coro|\n\n Gets a :class:`.Widget` from a guild ID.\n\n .. note::\n\n The guild must have the widget enabled to get this information.\n\n .. versionchanged:: 2.0\n\n ``guild_id`` parameter is now positional-only.\n\n Parameters\n -----------\n guild_id: :class:`int`\n The ID of the guild.\n\n Raises\n -------\n Forbidden\n The widget for this guild is disabled.\n HTTPException\n Retrieving the widget failed.\n\n Returns\n --------\n :class:`.Widget`\n The guild's widget.\n \"\"\"\n data = await self.http.get_widget(guild_id)\n\n return Widget(state=self._connection, data=data)\n\n async def application_info(self) -> AppInfo:\n \"\"\"|coro|\n\n Retrieves the bot's application information.\n\n Raises\n -------\n HTTPException\n Retrieving the information failed somehow.\n\n Returns\n --------\n :class:`.AppInfo`\n The bot's application information.\n \"\"\"\n data = await self.http.application_info()\n return AppInfo(self._connection, data)\n\n async def fetch_user(self, user_id: int, /) -> User:\n \"\"\"|coro|\n\n Retrieves a :class:`~discord.User` based on their ID.\n You do not have to share any guilds with the user to get this information,\n however many operations do require that you do.\n\n .. note::\n\n This method is an API call. If you have :attr:`discord.Intents.members` and member cache enabled, consider :meth:`get_user` instead.\n\n .. versionchanged:: 2.0\n\n ``user_id`` parameter is now positional-only.\n\n Parameters\n -----------\n user_id: :class:`int`\n The user's ID to fetch from.\n\n Raises\n -------\n NotFound\n A user with this ID does not exist.\n HTTPException\n Fetching the user failed.\n\n Returns\n --------\n :class:`~discord.User`\n The user you requested.\n \"\"\"\n data = await self.http.get_user(user_id)\n return User(state=self._connection, data=data)\n\n async def fetch_channel(self, channel_id: int, /) -> Union[GuildChannel, PrivateChannel, Thread]:\n \"\"\"|coro|\n\n Retrieves a :class:`.abc.GuildChannel`, :class:`.abc.PrivateChannel`, or :class:`.Thread` with the specified ID.\n\n .. note::\n\n This method is an API call. For general usage, consider :meth:`get_channel` instead.\n\n .. versionadded:: 1.2\n\n .. versionchanged:: 2.0\n\n ``channel_id`` parameter is now positional-only.\n\n Raises\n -------\n InvalidData\n An unknown channel type was received from Discord.\n HTTPException\n Retrieving the channel failed.\n NotFound\n Invalid Channel ID.\n Forbidden\n You do not have permission to fetch this channel.\n\n Returns\n --------\n Union[:class:`.abc.GuildChannel`, :class:`.abc.PrivateChannel`, :class:`.Thread`]\n The channel from the ID.\n \"\"\"\n data = await self.http.get_channel(channel_id)\n\n factory, ch_type = _threaded_channel_factory(data['type'])\n if factory is None:\n raise InvalidData('Unknown channel type {type} for channel ID {id}.'.format_map(data))\n\n if ch_type in (ChannelType.group, ChannelType.private):\n # the factory will be a DMChannel or GroupChannel here\n channel = factory(me=self.user, data=data, state=self._connection) # type: ignore\n else:\n # the factory can't be a DMChannel or GroupChannel here\n guild_id = int(data['guild_id']) # type: ignore\n guild = self._connection._get_or_create_unavailable_guild(guild_id)\n # the factory should be a GuildChannel or Thread\n channel = factory(guild=guild, state=self._connection, data=data) # type: ignore\n\n return channel\n\n async def fetch_webhook(self, webhook_id: int, /) -> Webhook:\n \"\"\"|coro|\n\n Retrieves a :class:`.Webhook` with the specified ID.\n\n .. versionchanged:: 2.0\n\n ``webhook_id`` parameter is now positional-only.\n\n Raises\n --------\n HTTPException\n Retrieving the webhook failed.\n NotFound\n Invalid webhook ID.\n Forbidden\n You do not have permission to fetch this webhook.\n\n Returns\n ---------\n :class:`.Webhook`\n The webhook you requested.\n \"\"\"\n data = await self.http.get_webhook(webhook_id)\n return Webhook.from_state(data, state=self._connection)\n\n async def fetch_sticker(self, sticker_id: int, /) -> Union[StandardSticker, GuildSticker]:\n \"\"\"|coro|\n\n Retrieves a :class:`.Sticker` with the specified ID.\n\n .. versionadded:: 2.0\n\n Raises\n --------\n HTTPException\n Retrieving the sticker failed.\n NotFound\n Invalid sticker ID.\n\n Returns\n --------\n Union[:class:`.StandardSticker`, :class:`.GuildSticker`]\n The sticker you requested.\n \"\"\"\n data = await self.http.get_sticker(sticker_id)\n cls, _ = _sticker_factory(data['type'])\n # The type checker is not smart enough to figure out the constructor is correct\n return cls(state=self._connection, data=data) # type: ignore\n\n async def fetch_premium_sticker_packs(self) -> List[StickerPack]:\n \"\"\"|coro|\n\n Retrieves all available premium sticker packs.\n\n .. versionadded:: 2.0\n\n Raises\n -------\n HTTPException\n Retrieving the sticker packs failed.\n\n Returns\n ---------\n List[:class:`.StickerPack`]\n All available premium sticker packs.\n \"\"\"\n data = await self.http.list_premium_sticker_packs()\n return [StickerPack(state=self._connection, data=pack) for pack in data['sticker_packs']]\n\n async def create_dm(self, user: Snowflake) -> DMChannel:\n \"\"\"|coro|\n\n Creates a :class:`.DMChannel` with this user.\n\n This should be rarely called, as this is done transparently for most\n people.\n\n .. versionadded:: 2.0\n\n Parameters\n -----------\n user: :class:`~discord.abc.Snowflake`\n The user to create a DM with.\n\n Returns\n -------\n :class:`.DMChannel`\n The channel that was created.\n \"\"\"\n state = self._connection\n found = state._get_private_channel_by_user(user.id)\n if found:\n return found\n\n data = await state.http.start_private_message(user.id)\n return state.add_dm_channel(data)\n\n def add_dynamic_items(self, *items: Type[DynamicItem[Item[Any]]]) -> None:\n r\"\"\"Registers a :class:`~discord.ui.DynamicItem` class for persistent listening.\n\n This method accepts *class types* rather than instances.\n\n .. versionadded:: 2.4\n\n Parameters\n -----------\n \\*items: Type[:class:`~discord.ui.DynamicItem`]\n The classes of dynamic items to add.\n\n Raises\n -------\n TypeError\n The class is not a subclass of :class:`~discord.ui.DynamicItem`.\n \"\"\"\n\n for item in items:\n if not issubclass(item, DynamicItem):\n raise TypeError(f'expected subclass of DynamicItem not {item.__name__}')\n\n self._connection.store_dynamic_items(*items)\n\n def add_view(self, view: View, *, message_id: Optional[int] = None) -> None:\n \"\"\"Registers a :class:`~discord.ui.View` for persistent listening.\n\n This method should be used for when a view is comprised of components\n that last longer than the lifecycle of the program.\n\n .. versionadded:: 2.0\n\n Parameters\n ------------\n view: :class:`discord.ui.View`\n The view to register for dispatching.\n message_id: Optional[:class:`int`]\n The message ID that the view is attached to. This is currently used to\n refresh the view's state during message update events. If not given\n then message update events are not propagated for the view.\n\n Raises\n -------\n TypeError\n A view was not passed.\n ValueError\n The view is not persistent or is already finished. A persistent view has no timeout\n and all their components have an explicitly provided custom_id.\n \"\"\"\n\n if not isinstance(view, View):\n raise TypeError(f'expected an instance of View not {view.__class__.__name__}')\n\n if not view.is_persistent():\n raise ValueError('View is not persistent. Items need to have a custom_id set and View must have no timeout')\n\n if view.is_finished():\n raise ValueError('View is already finished.')\n\n self._connection.store_view(view, message_id)\n\n @property\n def persistent_views(self) -> Sequence[View]:\n \"\"\"Sequence[:class:`.View`]: A sequence of persistent views added to the client.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._connection.persistent_views\n" }, { "path": "discord/state.py", "content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\nfrom collections import deque, OrderedDict\nimport copy\nimport logging\nfrom typing import (\n Dict,\n Optional,\n TYPE_CHECKING,\n Type,\n Union,\n Callable,\n Any,\n List,\n TypeVar,\n Coroutine,\n Sequence,\n Generic,\n Tuple,\n Deque,\n Literal,\n overload,\n)\nimport weakref\nimport inspect\n\nimport os\n\nfrom .guild import Guild\nfrom .activity import BaseActivity\nfrom .user import User, ClientUser\nfrom .emoji import Emoji\nfrom .mentions import AllowedMentions\nfrom .partial_emoji import PartialEmoji\nfrom .message import Message\nfrom .channel import *\nfrom .channel import _channel_factory\nfrom .raw_models import *\nfrom .member import Member\nfrom .role import Role\nfrom .enums import ChannelType, try_enum, Status\nfrom . import utils\nfrom .flags import ApplicationFlags, Intents, MemberCacheFlags\nfrom .invite import Invite\nfrom .integrations import _integration_factory\nfrom .interactions import Interaction\nfrom .ui.view import ViewStore, View\nfrom .scheduled_event import ScheduledEvent\nfrom .stage_instance import StageInstance\nfrom .threads import Thread, ThreadMember\nfrom .sticker import GuildSticker\nfrom .automod import AutoModRule, AutoModAction\nfrom .audit_logs import AuditLogEntry\nfrom ._types import ClientT\n\nif TYPE_CHECKING:\n from .abc import PrivateChannel\n from .message import MessageableChannel\n from .guild import GuildChannel\n from .http import HTTPClient\n from .voice_client import VoiceProtocol\n from .gateway import DiscordWebSocket\n from .ui.item import Item\n from .ui.dynamic import DynamicItem\n from .app_commands import CommandTree, Translator\n\n from .types.automod import AutoModerationRule, AutoModerationActionExecution\n from .types.snowflake import Snowflake\n from .types.activity import Activity as ActivityPayload\n from .types.channel import DMChannel as DMChannelPayload\n from .types.user import User as UserPayload, PartialUser as PartialUserPayload\n from .types.emoji import Emoji as EmojiPayload, PartialEmoji as PartialEmojiPayload\n from .types.sticker import GuildSticker as GuildStickerPayload\n from .types.guild import Guild as GuildPayload\n from .types.message import Message as MessagePayload, PartialMessage as PartialMessagePayload\n from .types import gateway as gw\n from .types.command import GuildApplicationCommandPermissions as GuildApplicationCommandPermissionsPayload\n\n T = TypeVar('T')\n Channel = Union[GuildChannel, PrivateChannel, PartialMessageable]\n\n\nclass ChunkRequest:\n def __init__(\n self,\n guild_id: int,\n loop: asyncio.AbstractEventLoop,\n resolver: Callable[[int], Any],\n *,\n cache: bool = True,\n ) -> None:\n self.guild_id: int = guild_id\n self.resolver: Callable[[int], Any] = resolver\n self.loop: asyncio.AbstractEventLoop = loop\n self.cache: bool = cache\n self.nonce: str = os.urandom(16).hex()\n self.buffer: List[Member] = []\n self.waiters: List[asyncio.Future[List[Member]]] = []\n\n def add_members(self, members: List[Member]) -> None:\n self.buffer.extend(members)\n if self.cache:\n guild = self.resolver(self.guild_id)\n if guild is None:\n return\n\n for member in members:\n existing = guild.get_member(member.id)\n if existing is None or existing.joined_at is None:\n guild._add_member(member)\n\n async def wait(self) -> List[Member]:\n future = self.loop.create_future()\n self.waiters.append(future)\n try:\n return await future\n finally:\n self.waiters.remove(future)\n\n def get_future(self) -> asyncio.Future[List[Member]]:\n future = self.loop.create_future()\n self.waiters.append(future)\n return future\n\n def done(self) -> None:\n for future in self.waiters:\n if not future.done():\n future.set_result(self.buffer)\n\n\n_log = logging.getLogger(__name__)\n\n\nasync def logging_coroutine(coroutine: Coroutine[Any, Any, T], *, info: str) -> Optional[T]:\n try:\n await coroutine\n except Exception:\n _log.exception('Exception occurred during %s', info)\n\n\nclass ConnectionState(Generic[ClientT]):\n if TYPE_CHECKING:\n _get_websocket: Callable[..., DiscordWebSocket]\n _get_client: Callable[..., ClientT]\n _parsers: Dict[str, Callable[[Dict[str, Any]], None]]\n\n def __init__(\n self,\n *,\n dispatch: Callable[..., Any],\n handlers: Dict[str, Callable[..., Any]],\n hooks: Dict[str, Callable[..., Coroutine[Any, Any, Any]]],\n http: HTTPClient,\n **options: Any,\n ) -> None:\n # Set later, after Client.login\n self.loop: asyncio.AbstractEventLoop = utils.MISSING\n self.http: HTTPClient = http\n self.max_messages: Optional[int] = options.get('max_messages', 1000)\n if self.max_messages is not None and self.max_messages <= 0:\n self.max_messages = 1000\n\n self.dispatch: Callable[..., Any] = dispatch\n self.handlers: Dict[str, Callable[..., Any]] = handlers\n self.hooks: Dict[str, Callable[..., Coroutine[Any, Any, Any]]] = hooks\n self.shard_count: Optional[int] = None\n self._ready_task: Optional[asyncio.Task] = None\n self.application_id: Optional[int] = utils._get_as_snowflake(options, 'application_id')\n self.application_flags: ApplicationFlags = utils.MISSING\n self.heartbeat_timeout: float = options.get('heartbeat_timeout', 60.0)\n self.guild_ready_timeout: float = options.get('guild_ready_timeout', 2.0)\n if self.guild_ready_timeout < 0:\n raise ValueError('guild_ready_timeout cannot be negative')\n\n allowed_mentions = options.get('allowed_mentions')\n\n if allowed_mentions is not None and not isinstance(allowed_mentions, AllowedMentions):\n raise TypeError('allowed_mentions parameter must be AllowedMentions')\n\n self.allowed_mentions: Optional[AllowedMentions] = allowed_mentions\n self._chunk_requests: Dict[Union[int, str], ChunkRequest] = {}\n\n activity = options.get('activity', None)\n if activity:\n if not isinstance(activity, BaseActivity):\n raise TypeError('activity parameter must derive from BaseActivity.')\n\n activity = activity.to_dict()\n\n status = options.get('status', None)\n if status:\n if status is Status.offline:\n status = 'invisible'\n else:\n status = str(status)\n\n intents = options.get('intents', None)\n if intents is not None:\n if not isinstance(intents, Intents):\n raise TypeError(f'intents parameter must be Intent not {type(intents)!r}')\n else:\n intents = Intents.default()\n\n if not intents.guilds:\n _log.warning('Guilds intent seems to be disabled. This may cause state related issues.')\n\n self._chunk_guilds: bool = options.get('chunk_guilds_at_startup', intents.members)\n\n # Ensure these two are set properly\n if not intents.members and self._chunk_guilds:\n raise ValueError('Intents.members must be enabled to chunk guilds at startup.')\n\n cache_flags = options.get('member_cache_flags', None)\n if cache_flags is None:\n cache_flags = MemberCacheFlags.from_intents(intents)\n else:\n if not isinstance(cache_flags, MemberCacheFlags):\n raise TypeError(f'member_cache_flags parameter must be MemberCacheFlags not {type(cache_flags)!r}')\n\n cache_flags._verify_intents(intents)\n\n self.member_cache_flags: MemberCacheFlags = cache_flags\n self._activity: Optional[ActivityPayload] = activity\n self._status: Optional[str] = status\n self._intents: Intents = intents\n self._command_tree: Optional[CommandTree] = None\n self._translator: Optional[Translator] = None\n\n if not intents.members or cache_flags._empty:\n self.store_user = self.store_user_no_intents\n\n self.parsers: Dict[str, Callable[[Any], None]]\n self.parsers = parsers = {}\n for attr, func in inspect.getmembers(self):\n if attr.startswith('parse_'):\n parsers[attr[6:].upper()] = func\n\n self.clear()\n\n # For some reason Discord still sends emoji/sticker data in payloads\n # This makes it hard to actually swap out the appropriate store methods\n # So this is checked instead, it's a small penalty to pay\n @property\n def cache_guild_expressions(self) -> bool:\n return self._intents.emojis_and_stickers\n\n async def close(self) -> None:\n for voice in self.voice_clients:\n try:\n await voice.disconnect(force=True)\n except Exception:\n # if an error happens during disconnects, disregard it.\n pass\n\n if self._translator:\n await self._translator.unload()\n\n # Purposefully don't call `clear` because users rely on cache being available post-close\n\n def clear(self, *, views: bool = True) -> None:\n self.user: Optional[ClientUser] = None\n self._users: weakref.WeakValueDictionary[int, User] = weakref.WeakValueDictionary()\n self._emojis: Dict[int, Emoji] = {}\n self._stickers: Dict[int, GuildSticker] = {}\n self._guilds: Dict[int, Guild] = {}\n if views:\n self._view_store: ViewStore = ViewStore(self)\n\n self._voice_clients: Dict[int, VoiceProtocol] = {}\n\n # LRU of max size 128\n self._private_channels: OrderedDict[int, PrivateChannel] = OrderedDict()\n # extra dict to look up private channels by user id\n self._private_channels_by_user: Dict[int, DMChannel] = {}\n if self.max_messages is not None:\n self._messages: Optional[Deque[Message]] = deque(maxlen=self.max_messages)\n else:\n self._messages: Optional[Deque[Message]] = None\n\n def process_chunk_requests(self, guild_id: int, nonce: Optional[str], members: List[Member], complete: bool) -> None:\n removed = []\n for key, request in self._chunk_requests.items():\n if request.guild_id == guild_id and request.nonce == nonce:\n request.add_members(members)\n if complete:\n request.done()\n removed.append(key)\n\n for key in removed:\n del self._chunk_requests[key]\n\n def call_handlers(self, key: str, *args: Any, **kwargs: Any) -> None:\n try:\n func = self.handlers[key]\n except KeyError:\n pass\n else:\n func(*args, **kwargs)\n\n async def call_hooks(self, key: str, *args: Any, **kwargs: Any) -> None:\n try:\n coro = self.hooks[key]\n except KeyError:\n pass\n else:\n await coro(*args, **kwargs)\n\n @property\n def self_id(self) -> Optional[int]:\n u = self.user\n return u.id if u else None\n\n @property\n def intents(self) -> Intents:\n ret = Intents.none()\n ret.value = self._intents.value\n return ret\n\n @property\n def voice_clients(self) -> List[VoiceProtocol]:\n return list(self._voice_clients.values())\n\n def _get_voice_client(self, guild_id: Optional[int]) -> Optional[VoiceProtocol]:\n # the keys of self._voice_clients are ints\n return self._voice_clients.get(guild_id) # type: ignore\n\n def _add_voice_client(self, guild_id: int, voice: VoiceProtocol) -> None:\n self._voice_clients[guild_id] = voice\n\n def _remove_voice_client(self, guild_id: int) -> None:\n self._voice_clients.pop(guild_id, None)\n\n def _update_references(self, ws: DiscordWebSocket) -> None:\n for vc in self.voice_clients:\n vc.main_ws = ws # type: ignore # Silencing the unknown attribute (ok at runtime).\n\n def store_user(self, data: Union[UserPayload, PartialUserPayload], *, cache: bool = True) -> User:\n # this way is 300% faster than `dict.setdefault`.\n user_id = int(data['id'])\n try:\n return self._users[user_id]\n except KeyError:\n user = User(state=self, data=data)\n if cache:\n self._users[user_id] = user\n return user\n\n def store_user_no_intents(self, data: Union[UserPayload, PartialUserPayload], *, cache: bool = True) -> User:\n return User(state=self, data=data)\n\n def create_user(self, data: Union[UserPayload, PartialUserPayload]) -> User:\n return User(state=self, data=data)\n\n def get_user(self, id: int) -> Optional[User]:\n return self._users.get(id)\n\n def store_emoji(self, guild: Guild, data: EmojiPayload) -> Emoji:\n # the id will be present here\n emoji_id = int(data['id']) # type: ignore\n self._emojis[emoji_id] = emoji = Emoji(guild=guild, state=self, data=data)\n return emoji\n\n def store_sticker(self, guild: Guild, data: GuildStickerPayload) -> GuildSticker:\n sticker_id = int(data['id'])\n self._stickers[sticker_id] = sticker = GuildSticker(state=self, data=data)\n return sticker\n\n def store_view(self, view: View, message_id: Optional[int] = None, interaction_id: Optional[int] = None) -> None:\n if interaction_id is not None:\n self._view_store.remove_interaction_mapping(interaction_id)\n self._view_store.add_view(view, message_id)\n\n def prevent_view_updates_for(self, message_id: int) -> Optional[View]:\n return self._view_store.remove_message_tracking(message_id)\n\n def store_dynamic_items(self, *items: Type[DynamicItem[Item[Any]]]) -> None:\n self._view_store.add_dynamic_items(*items)\n\n @property\n def persistent_views(self) -> Sequence[View]:\n return self._view_store.persistent_views\n\n @property\n def guilds(self) -> Sequence[Guild]:\n return utils.SequenceProxy(self._guilds.values())\n\n def _get_guild(self, guild_id: Optional[int]) -> Optional[Guild]:\n # the keys of self._guilds are ints\n return self._guilds.get(guild_id) # type: ignore\n\n def _get_or_create_unavailable_guild(self, guild_id: int) -> Guild:\n return self._guilds.get(guild_id) or Guild._create_unavailable(state=self, guild_id=guild_id)\n\n def _add_guild(self, guild: Guild) -> None:\n self._guilds[guild.id] = guild\n\n def _remove_guild(self, guild: Guild) -> None:\n self._guilds.pop(guild.id, None)\n\n for emoji in guild.emojis:\n self._emojis.pop(emoji.id, None)\n\n for sticker in guild.stickers:\n self._stickers.pop(sticker.id, None)\n\n del guild\n\n @property\n def emojis(self) -> Sequence[Emoji]:\n return utils.SequenceProxy(self._emojis.values())\n\n @property\n def stickers(self) -> Sequence[GuildSticker]:\n return utils.SequenceProxy(self._stickers.values())\n\n def get_emoji(self, emoji_id: Optional[int]) -> Optional[Emoji]:\n # the keys of self._emojis are ints\n return self._emojis.get(emoji_id) # type: ignore\n\n def get_sticker(self, sticker_id: Optional[int]) -> Optional[GuildSticker]:\n # the keys of self._stickers are ints\n return self._stickers.get(sticker_id) # type: ignore\n\n @property\n def private_channels(self) -> Sequence[PrivateChannel]:\n return utils.SequenceProxy(self._private_channels.values())\n\n def _get_private_channel(self, channel_id: Optional[int]) -> Optional[PrivateChannel]:\n try:\n # the keys of self._private_channels are ints\n value = self._private_channels[channel_id] # type: ignore\n except KeyError:\n return None\n else:\n # Type narrowing can't figure out that channel_id isn't None here\n self._private_channels.move_to_end(channel_id) # type: ignore\n return value\n\n def _get_private_channel_by_user(self, user_id: Optional[int]) -> Optional[DMChannel]:\n # the keys of self._private_channels are ints\n return self._private_channels_by_user.get(user_id) # type: ignore\n\n def _add_private_channel(self, channel: PrivateChannel) -> None:\n channel_id = channel.id\n self._private_channels[channel_id] = channel\n\n if len(self._private_channels) > 128:\n _, to_remove = self._private_channels.popitem(last=False)\n if isinstance(to_remove, DMChannel) and to_remove.recipient:\n self._private_channels_by_user.pop(to_remove.recipient.id, None)\n\n if isinstance(channel, DMChannel) and channel.recipient:\n self._private_channels_by_user[channel.recipient.id] = channel\n\n def add_dm_channel(self, data: DMChannelPayload) -> DMChannel:\n # self.user is *always* cached when this is called\n channel = DMChannel(me=self.user, state=self, data=data) # type: ignore\n self._add_private_channel(channel)\n return channel\n\n def _remove_private_channel(self, channel: PrivateChannel) -> None:\n self._private_channels.pop(channel.id, None)\n if isinstance(channel, DMChannel):\n recipient = channel.recipient\n if recipient is not None:\n self._private_channels_by_user.pop(recipient.id, None)\n\n def _get_message(self, msg_id: Optional[int]) -> Optional[Message]:\n return utils.find(lambda m: m.id == msg_id, reversed(self._messages)) if self._messages else None\n\n def _add_guild_from_data(self, data: GuildPayload) -> Guild:\n guild = Guild(data=data, state=self)\n self._add_guild(guild)\n return guild\n\n def _guild_needs_chunking(self, guild: Guild) -> bool:\n # If presences are enabled then we get back the old guild.large behaviour\n return self._chunk_guilds and not guild.chunked and not (self._intents.presences and not guild.large)\n\n def _get_guild_channel(\n self, data: PartialMessagePayload, guild_id: Optional[int] = None\n ) -> Tuple[Union[Channel, Thread], Optional[Guild]]:\n channel_id = int(data['channel_id'])\n try:\n guild_id = guild_id or int(data['guild_id'])\n guild = self._get_guild(guild_id)\n except KeyError:\n channel = DMChannel._from_message(self, channel_id)\n guild = None\n else:\n channel = guild and guild._resolve_channel(channel_id)\n\n return channel or PartialMessageable(state=self, guild_id=guild_id, id=channel_id), guild\n\n async def chunker(\n self, guild_id: int, query: str = '', limit: int = 0, presences: bool = False, *, nonce: Optional[str] = None\n ) -> None:\n ws = self._get_websocket(guild_id) # This is ignored upstream\n await ws.request_chunks(guild_id, query=query, limit=limit, presences=presences, nonce=nonce)\n\n async def query_members(\n self, guild: Guild, query: Optional[str], limit: int, user_ids: Optional[List[int]], cache: bool, presences: bool\n ) -> List[Member]:\n guild_id = guild.id\n ws = self._get_websocket(guild_id)\n if ws is None:\n raise RuntimeError('Somehow do not have a websocket for this guild_id')\n\n request = ChunkRequest(guild.id, self.loop, self._get_guild, cache=cache)\n self._chunk_requests[request.nonce] = request\n\n try:\n # start the query operation\n await ws.request_chunks(\n guild_id, query=query, limit=limit, user_ids=user_ids, presences=presences, nonce=request.nonce\n )\n return await asyncio.wait_for(request.wait(), timeout=30.0)\n except asyncio.TimeoutError:\n _log.warning('Timed out waiting for chunks with query %r and limit %d for guild_id %d', query, limit, guild_id)\n raise\n\n async def _delay_ready(self) -> None:\n try:\n states = []\n while True:\n # this snippet of code is basically waiting N seconds\n # until the last GUILD_CREATE was sent\n try:\n guild = await asyncio.wait_for(self._ready_state.get(), timeout=self.guild_ready_timeout)\n except asyncio.TimeoutError:\n break\n else:\n if self._guild_needs_chunking(guild):\n future = await self.chunk_guild(guild, wait=False)\n states.append((guild, future))\n else:\n if guild.unavailable is False:\n self.dispatch('guild_available', guild)\n else:\n self.dispatch('guild_join', guild)\n\n for guild, future in states:\n timeout = self._chunk_timeout(guild)\n\n try:\n await asyncio.wait_for(future, timeout=timeout)\n except asyncio.TimeoutError:\n _log.warning('Shard ID %s timed out waiting for chunks for guild_id %s.', guild.shard_id, guild.id)\n\n if guild.unavailable is False:\n self.dispatch('guild_available', guild)\n else:\n self.dispatch('guild_join', guild)\n\n # remove the state\n try:\n del self._ready_state\n except AttributeError:\n pass # already been deleted somehow\n\n except asyncio.CancelledError:\n pass\n else:\n # dispatch the event\n self.call_handlers('ready')\n self.dispatch('ready')\n finally:\n self._ready_task = None\n\n def parse_ready(self, data: gw.ReadyEvent) -> None:\n if self._ready_task is not None:\n self._ready_task.cancel()\n\n self._ready_state: asyncio.Queue[Guild] = asyncio.Queue()\n self.clear(views=False)\n self.user = user = ClientUser(state=self, data=data['user'])\n self._users[user.id] = user # type: ignore\n\n if self.application_id is None:\n try:\n application = data['application']\n except KeyError:\n pass\n else:\n self.application_id = utils._get_as_snowflake(application, 'id')\n self.application_flags: ApplicationFlags = ApplicationFlags._from_value(application['flags'])\n\n for guild_data in data['guilds']:\n self._add_guild_from_data(guild_data) # type: ignore\n\n self.dispatch('connect')\n self._ready_task = asyncio.create_task(self._delay_ready())\n\n def parse_resumed(self, data: gw.ResumedEvent) -> None:\n self.dispatch('resumed')\n\n def parse_message_create(self, data: gw.MessageCreateEvent) -> None:\n channel, _ = self._get_guild_channel(data)\n # channel would be the correct type here\n message = Message(channel=channel, data=data, state=self) # type: ignore\n self.dispatch('message', message)\n if self._messages is not None:\n self._messages.append(message)\n # we ensure that the channel is either a TextChannel, VoiceChannel, or Thread\n if channel and channel.__class__ in (TextChannel, VoiceChannel, Thread, StageChannel):\n channel.last_message_id = message.id # type: ignore\n\n def parse_message_delete(self, data: gw.MessageDeleteEvent) -> None:\n raw = RawMessageDeleteEvent(data)\n found = self._get_message(raw.message_id)\n raw.cached_message = found\n self.dispatch('raw_message_delete', raw)\n if self._messages is not None and found is not None:\n self.dispatch('message_delete', found)\n self._messages.remove(found)\n\n def parse_message_delete_bulk(self, data: gw.MessageDeleteBulkEvent) -> None:\n raw = RawBulkMessageDeleteEvent(data)\n if self._messages:\n found_messages = [message for message in self._messages if message.id in raw.message_ids]\n else:\n found_messages = []\n raw.cached_messages = found_messages\n self.dispatch('raw_bulk_message_delete', raw)\n if found_messages:\n self.dispatch('bulk_message_delete', found_messages)\n for msg in found_messages:\n # self._messages won't be None here\n self._messages.remove(msg) # type: ignore\n\n def parse_message_update(self, data: gw.MessageUpdateEvent) -> None:\n raw = RawMessageUpdateEvent(data)\n message = self._get_message(raw.message_id)\n if message is not None:\n older_message = copy.copy(message)\n raw.cached_message = older_message\n self.dispatch('raw_message_edit', raw)\n message._update(data)\n # Coerce the `after` parameter to take the new updated Member\n # ref: #5999\n older_message.author = message.author\n self.dispatch('message_edit', older_message, message)\n else:\n self.dispatch('raw_message_edit', raw)\n\n if 'components' in data:\n try:\n entity_id = int(data['interaction']['id'])\n except (KeyError, ValueError):\n entity_id = raw.message_id\n\n if self._view_store.is_message_tracked(entity_id):\n self._view_store.update_from_message(entity_id, data['components'])\n\n def parse_message_reaction_add(self, data: gw.MessageReactionAddEvent) -> None:\n emoji = PartialEmoji.from_dict(data['emoji'])\n emoji._state = self\n raw = RawReactionActionEvent(data, emoji, 'REACTION_ADD')\n\n member_data = data.get('member')\n if member_data:\n guild = self._get_guild(raw.guild_id)\n if guild is not None:\n raw.member = Member(data=member_data, guild=guild, state=self)\n else:\n raw.member = None\n else:\n raw.member = None\n self.dispatch('raw_reaction_add', raw)\n\n # rich interface here\n message = self._get_message(raw.message_id)\n if message is not None:\n emoji = self._upgrade_partial_emoji(emoji)\n reaction = message._add_reaction(data, emoji, raw.user_id)\n user = raw.member or self._get_reaction_user(message.channel, raw.user_id)\n\n if user:\n self.dispatch('reaction_add', reaction, user)\n\n def parse_message_reaction_remove_all(self, data: gw.MessageReactionRemoveAllEvent) -> None:\n raw = RawReactionClearEvent(data)\n self.dispatch('raw_reaction_clear', raw)\n\n message = self._get_message(raw.message_id)\n if message is not None:\n old_reactions = message.reactions.copy()\n message.reactions.clear()\n self.dispatch('reaction_clear', message, old_reactions)\n\n def parse_message_reaction_remove(self, data: gw.MessageReactionRemoveEvent) -> None:\n emoji = PartialEmoji.from_dict(data['emoji'])\n emoji._state = self\n raw = RawReactionActionEvent(data, emoji, 'REACTION_REMOVE')\n self.dispatch('raw_reaction_remove', raw)\n\n message = self._get_message(raw.message_id)\n if message is not None:\n emoji = self._upgrade_partial_emoji(emoji)\n try:\n reaction = message._remove_reaction(data, emoji, raw.user_id)\n except (AttributeError, ValueError): # eventual consistency lol\n pass\n else:\n user = self._get_reaction_user(message.channel, raw.user_id)\n if user:\n self.dispatch('reaction_remove', reaction, user)\n\n def parse_message_reaction_remove_emoji(self, data: gw.MessageReactionRemoveEmojiEvent) -> None:\n emoji = PartialEmoji.from_dict(data['emoji'])\n emoji._state = self\n raw = RawReactionClearEmojiEvent(data, emoji)\n self.dispatch('raw_reaction_clear_emoji', raw)\n\n message = self._get_message(raw.message_id)\n if message is not None:\n try:\n reaction = message._clear_emoji(emoji)\n except (AttributeError, ValueError): # eventual consistency lol\n pass\n else:\n if reaction:\n self.dispatch('reaction_clear_emoji', reaction)\n\n def parse_interaction_create(self, data: gw.InteractionCreateEvent) -> None:\n interaction = Interaction(data=data, state=self)\n if data['type'] in (2, 4) and self._command_tree: # application command and auto complete\n self._command_tree._from_interaction(interaction)\n elif data['type'] == 3: # interaction component\n # These keys are always there for this interaction type\n inner_data = data['data']\n custom_id = inner_data['custom_id']\n component_type = inner_data['component_type']\n self._view_store.dispatch_view(component_type, custom_id, interaction)\n elif data['type'] == 5: # modal submit\n # These keys are always there for this interaction type\n inner_data = data['data']\n custom_id = inner_data['custom_id']\n components = inner_data['components']\n self._view_store.dispatch_modal(custom_id, interaction, components)\n self.dispatch('interaction', interaction)\n\n def parse_presence_update(self, data: gw.PresenceUpdateEvent) -> None:\n guild_id = utils._get_as_snowflake(data, 'guild_id')\n # guild_id won't be None here\n guild = self._get_guild(guild_id)\n if guild is None:\n _log.debug('PRESENCE_UPDATE referencing an unknown guild ID: %s. Discarding.', guild_id)\n return\n\n user = data['user']\n member_id = int(user['id'])\n member = guild.get_member(member_id)\n if member is None:\n _log.debug('PRESENCE_UPDATE referencing an unknown member ID: %s. Discarding', member_id)\n return\n\n old_member = Member._copy(member)\n user_update = member._presence_update(data=data, user=user)\n if user_update:\n self.dispatch('user_update', user_update[0], user_update[1])\n\n self.dispatch('presence_update', old_member, member)\n\n def parse_user_update(self, data: gw.UserUpdateEvent) -> None:\n if self.user:\n self.user._update(data)\n\n def parse_invite_create(self, data: gw.InviteCreateEvent) -> None:\n invite = Invite.from_gateway(state=self, data=data)\n self.dispatch('invite_create', invite)\n\n def parse_invite_delete(self, data: gw.InviteDeleteEvent) -> None:\n invite = Invite.from_gateway(state=self, data=data)\n self.dispatch('invite_delete', invite)\n\n def parse_channel_delete(self, data: gw.ChannelDeleteEvent) -> None:\n guild = self._get_guild(utils._get_as_snowflake(data, 'guild_id'))\n channel_id = int(data['id'])\n if guild is not None:\n channel = guild.get_channel(channel_id)\n if channel is not None:\n guild._remove_channel(channel)\n self.dispatch('guild_channel_delete', channel)\n\n if channel.type in (ChannelType.voice, ChannelType.stage_voice):\n for s in guild.scheduled_events:\n if s.channel_id == channel.id:\n guild._scheduled_events.pop(s.id)\n self.dispatch('scheduled_event_delete', s)\n\n def parse_channel_update(self, data: gw.ChannelUpdateEvent) -> None:\n channel_type = try_enum(ChannelType, data.get('type'))\n channel_id = int(data['id'])\n if channel_type is ChannelType.group:\n channel = self._get_private_channel(channel_id)\n if channel is not None:\n old_channel = copy.copy(channel)\n # the channel is a GroupChannel rather than PrivateChannel\n channel._update_group(data) # type: ignore\n self.dispatch('private_channel_update', old_channel, channel)\n return\n else:\n _log.debug('CHANNEL_UPDATE referencing an unknown channel ID: %s. Discarding.', channel_id)\n\n guild_id = utils._get_as_snowflake(data, 'guild_id')\n guild = self._get_guild(guild_id)\n if guild is not None:\n channel = guild.get_channel(channel_id)\n if channel is not None:\n old_channel = copy.copy(channel)\n channel._update(guild, data) # type: ignore # the data payload varies based on the channel type.\n self.dispatch('guild_channel_update', old_channel, channel)\n else:\n _log.debug('CHANNEL_UPDATE referencing an unknown channel ID: %s. Discarding.', channel_id)\n else:\n _log.debug('CHANNEL_UPDATE referencing an unknown guild ID: %s. Discarding.', guild_id)\n\n def parse_channel_create(self, data: gw.ChannelCreateEvent) -> None:\n factory, ch_type = _channel_factory(data['type'])\n if factory is None:\n _log.debug('CHANNEL_CREATE referencing an unknown channel type %s. Discarding.', data['type'])\n return\n\n guild_id = utils._get_as_snowflake(data, 'guild_id')\n guild = self._get_guild(guild_id)\n if guild is not None:\n # the factory can't be a DMChannel or GroupChannel here\n channel = factory(guild=guild, state=self, data=data) # type: ignore\n guild._add_channel(channel) # type: ignore\n self.dispatch('guild_channel_create', channel)\n else:\n _log.debug('CHANNEL_CREATE referencing an unknown guild ID: %s. Discarding.', guild_id)\n return\n\n def parse_channel_pins_update(self, data: gw.ChannelPinsUpdateEvent) -> None:\n channel_id = int(data['channel_id'])\n try:\n guild = self._get_guild(int(data['guild_id']))\n except KeyError:\n guild = None\n channel = self._get_private_channel(channel_id)\n else:\n channel = guild and guild._resolve_channel(channel_id)\n\n if channel is None:\n _log.debug('CHANNEL_PINS_UPDATE referencing an unknown channel ID: %s. Discarding.', channel_id)\n return\n\n last_pin = utils.parse_time(data.get('last_pin_timestamp'))\n\n if guild is None:\n self.dispatch('private_channel_pins_update', channel, last_pin)\n else:\n self.dispatch('guild_channel_pins_update', channel, last_pin)\n\n def parse_thread_create(self, data: gw.ThreadCreateEvent) -> None:\n guild_id = int(data['guild_id'])\n guild: Optional[Guild] = self._get_guild(guild_id)\n if guild is None:\n _log.debug('THREAD_CREATE referencing an unknown guild ID: %s. Discarding', guild_id)\n return\n\n thread = Thread(guild=guild, state=guild._state, data=data)\n has_thread = guild.get_thread(thread.id)\n guild._add_thread(thread)\n if not has_thread:\n if data.get('newly_created'):\n if thread.parent.__class__ is ForumChannel:\n thread.parent.last_message_id = thread.id # type: ignore\n\n self.dispatch('thread_create', thread)\n else:\n self.dispatch('thread_join', thread)\n\n def parse_thread_update(self, data: gw.ThreadUpdateEvent) -> None:\n guild_id = int(data['guild_id'])\n guild = self._get_guild(guild_id)\n if guild is None:\n _log.debug('THREAD_UPDATE referencing an unknown guild ID: %s. Discarding', guild_id)\n return\n\n raw = RawThreadUpdateEvent(data)\n raw.thread = thread = guild.get_thread(raw.thread_id)\n self.dispatch('raw_thread_update', raw)\n if thread is not None:\n old = copy.copy(thread)\n thread._update(data)\n if thread.archived:\n guild._remove_thread(thread)\n self.dispatch('thread_update', old, thread)\n else:\n thread = Thread(guild=guild, state=guild._state, data=data)\n if not thread.archived:\n guild._add_thread(thread)\n self.dispatch('thread_join', thread)\n\n def parse_thread_delete(self, data: gw.ThreadDeleteEvent) -> None:\n guild_id = int(data['guild_id'])\n guild = self._get_guild(guild_id)\n if guild is None:\n _log.debug('THREAD_DELETE referencing an unknown guild ID: %s. Discarding', guild_id)\n return\n\n raw = RawThreadDeleteEvent(data)\n raw.thread = thread = guild.get_thread(raw.thread_id)\n self.dispatch('raw_thread_delete', raw)\n\n if thread is not None:\n guild._remove_thread(thread)\n self.dispatch('thread_delete', thread)\n\n def parse_thread_list_sync(self, data: gw.ThreadListSyncEvent) -> None:\n guild_id = int(data['guild_id'])\n guild: Optional[Guild] = self._get_guild(guild_id)\n if guild is None:\n _log.debug('THREAD_LIST_SYNC referencing an unknown guild ID: %s. Discarding', guild_id)\n return\n\n try:\n channel_ids = {int(i) for i in data['channel_ids']}\n except KeyError:\n # If not provided, then the entire guild is being synced\n # So all previous thread data should be overwritten\n previous_threads = guild._threads.copy()\n guild._clear_threads()\n else:\n previous_threads = guild._filter_threads(channel_ids)\n\n threads = {d['id']: guild._store_thread(d) for d in data.get('threads', [])}\n\n for member in data.get('members', []):\n try:\n # note: member['id'] is the thread_id\n thread = threads[member['id']]\n except KeyError:\n continue\n else:\n thread._add_member(ThreadMember(thread, member))\n\n for thread in threads.values():\n old = previous_threads.pop(thread.id, None)\n if old is None:\n self.dispatch('thread_join', thread)\n\n for thread in previous_threads.values():\n self.dispatch('thread_remove', thread)\n\n def parse_thread_member_update(self, data: gw.ThreadMemberUpdate) -> None:\n guild_id = int(data['guild_id'])\n guild: Optional[Guild] = self._get_guild(guild_id)\n if guild is None:\n _log.debug('THREAD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding', guild_id)\n return\n\n thread_id = int(data['id'])\n thread: Optional[Thread] = guild.get_thread(thread_id)\n if thread is None:\n _log.debug('THREAD_MEMBER_UPDATE referencing an unknown thread ID: %s. Discarding', thread_id)\n return\n\n member = ThreadMember(thread, data)\n thread.me = member\n\n def parse_thread_members_update(self, data: gw.ThreadMembersUpdate) -> None:\n guild_id = int(data['guild_id'])\n guild: Optional[Guild] = self._get_guild(guild_id)\n if guild is None:\n _log.debug('THREAD_MEMBERS_UPDATE referencing an unknown guild ID: %s. Discarding', guild_id)\n return\n\n thread_id = int(data['id'])\n thread: Optional[Thread] = guild.get_thread(thread_id)\n raw = RawThreadMembersUpdate(data)\n if thread is None:\n _log.debug('THREAD_MEMBERS_UPDATE referencing an unknown thread ID: %s. Discarding', thread_id)\n return\n\n added_members = [ThreadMember(thread, d) for d in data.get('added_members', [])]\n removed_member_ids = [int(x) for x in data.get('removed_member_ids', [])]\n self_id = self.self_id\n for member in added_members:\n if member.id != self_id:\n thread._add_member(member)\n self.dispatch('thread_member_join', member)\n else:\n thread.me = member\n self.dispatch('thread_join', thread)\n\n for member_id in removed_member_ids:\n if member_id != self_id:\n member = thread._pop_member(member_id)\n self.dispatch('raw_thread_member_remove', raw)\n if member is not None:\n self.dispatch('thread_member_remove', member)\n else:\n self.dispatch('thread_remove', thread)\n\n def parse_guild_member_add(self, data: gw.GuildMemberAddEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('GUILD_MEMBER_ADD referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n member = Member(guild=guild, data=data, state=self)\n if self.member_cache_flags.joined:\n guild._add_member(member)\n\n if guild._member_count is not None:\n guild._member_count += 1\n\n self.dispatch('member_join', member)\n\n def parse_guild_member_remove(self, data: gw.GuildMemberRemoveEvent) -> None:\n user = self.store_user(data['user'])\n raw = RawMemberRemoveEvent(data, user)\n\n guild = self._get_guild(raw.guild_id)\n if guild is not None:\n if guild._member_count is not None:\n guild._member_count -= 1\n\n member = guild.get_member(user.id)\n if member is not None:\n raw.user = member\n guild._remove_member(member)\n self.dispatch('member_remove', member)\n else:\n _log.debug('GUILD_MEMBER_REMOVE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n\n self.dispatch('raw_member_remove', raw)\n\n def parse_guild_member_update(self, data: gw.GuildMemberUpdateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n user = data['user']\n user_id = int(user['id'])\n if guild is None:\n _log.debug('GUILD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n member = guild.get_member(user_id)\n if member is not None:\n old_member = Member._copy(member)\n member._update(data)\n user_update = member._update_inner_user(user)\n if user_update:\n self.dispatch('user_update', user_update[0], user_update[1])\n\n self.dispatch('member_update', old_member, member)\n else:\n if self.member_cache_flags.joined:\n member = Member(data=data, guild=guild, state=self) # type: ignore # the data is not complete, contains a delta of values\n\n # Force an update on the inner user if necessary\n user_update = member._update_inner_user(user)\n if user_update:\n self.dispatch('user_update', user_update[0], user_update[1])\n\n guild._add_member(member)\n _log.debug('GUILD_MEMBER_UPDATE referencing an unknown member ID: %s. Discarding.', user_id)\n\n def parse_guild_emojis_update(self, data: gw.GuildEmojisUpdateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('GUILD_EMOJIS_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n before_emojis = guild.emojis\n for emoji in before_emojis:\n self._emojis.pop(emoji.id, None)\n # guild won't be None here\n guild.emojis = tuple(map(lambda d: self.store_emoji(guild, d), data['emojis']))\n self.dispatch('guild_emojis_update', guild, before_emojis, guild.emojis)\n\n def parse_guild_stickers_update(self, data: gw.GuildStickersUpdateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('GUILD_STICKERS_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n before_stickers = guild.stickers\n for emoji in before_stickers:\n self._stickers.pop(emoji.id, None)\n\n guild.stickers = tuple(map(lambda d: self.store_sticker(guild, d), data['stickers']))\n self.dispatch('guild_stickers_update', guild, before_stickers, guild.stickers)\n\n def parse_guild_audit_log_entry_create(self, data: gw.GuildAuditLogEntryCreate) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('GUILD_AUDIT_LOG_ENTRY_CREATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n entry = AuditLogEntry(\n users=self._users,\n integrations={},\n app_commands={},\n automod_rules={},\n webhooks={},\n data=data,\n guild=guild,\n )\n\n self.dispatch('audit_log_entry_create', entry)\n\n def parse_auto_moderation_rule_create(self, data: AutoModerationRule) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('AUTO_MODERATION_RULE_CREATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n rule = AutoModRule(data=data, guild=guild, state=self)\n\n self.dispatch('automod_rule_create', rule)\n\n def parse_auto_moderation_rule_update(self, data: AutoModerationRule) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('AUTO_MODERATION_RULE_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n rule = AutoModRule(data=data, guild=guild, state=self)\n\n self.dispatch('automod_rule_update', rule)\n\n def parse_auto_moderation_rule_delete(self, data: AutoModerationRule) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('AUTO_MODERATION_RULE_DELETE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n rule = AutoModRule(data=data, guild=guild, state=self)\n\n self.dispatch('automod_rule_delete', rule)\n\n def parse_auto_moderation_action_execution(self, data: AutoModerationActionExecution) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('AUTO_MODERATION_ACTION_EXECUTION referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n execution = AutoModAction(data=data, state=self)\n\n self.dispatch('automod_action', execution)\n\n def _get_create_guild(self, data: gw.GuildCreateEvent) -> Guild:\n if data.get('unavailable') is False:\n # GUILD_CREATE with unavailable in the response\n # usually means that the guild has become available\n # and is therefore in the cache\n guild = self._get_guild(int(data['id']))\n if guild is not None:\n guild.unavailable = False\n guild._from_data(data)\n return guild\n\n return self._add_guild_from_data(data)\n\n def is_guild_evicted(self, guild: Guild) -> bool:\n return guild.id not in self._guilds\n\n @overload\n async def chunk_guild(self, guild: Guild, *, wait: Literal[True] = ..., cache: Optional[bool] = ...) -> List[Member]:\n ...\n\n @overload\n async def chunk_guild(\n self, guild: Guild, *, wait: Literal[False] = ..., cache: Optional[bool] = ...\n ) -> asyncio.Future[List[Member]]:\n ...\n\n async def chunk_guild(\n self, guild: Guild, *, wait: bool = True, cache: Optional[bool] = None\n ) -> Union[List[Member], asyncio.Future[List[Member]]]:\n cache = cache or self.member_cache_flags.joined\n request = self._chunk_requests.get(guild.id)\n if request is None:\n self._chunk_requests[guild.id] = request = ChunkRequest(guild.id, self.loop, self._get_guild, cache=cache)\n await self.chunker(guild.id, nonce=request.nonce)\n\n if wait:\n return await request.wait()\n return request.get_future()\n\n def _chunk_timeout(self, guild: Guild) -> float:\n return max(5.0, (guild.member_count or 0) / 10000)\n\n async def _chunk_and_dispatch(self, guild, unavailable):\n timeout = self._chunk_timeout(guild)\n\n try:\n await asyncio.wait_for(self.chunk_guild(guild), timeout=timeout)\n except asyncio.TimeoutError:\n _log.warning('Somehow timed out waiting for chunks for guild ID %s.', guild.id)\n\n if unavailable is False:\n self.dispatch('guild_available', guild)\n else:\n self.dispatch('guild_join', guild)\n\n def _add_ready_state(self, guild: Guild) -> bool:\n try:\n # Notify the on_ready state, if any, that this guild is complete.\n self._ready_state.put_nowait(guild)\n except AttributeError:\n return False\n else:\n return True\n\n def parse_guild_create(self, data: gw.GuildCreateEvent) -> None:\n unavailable = data.get('unavailable')\n if unavailable is True:\n # joined a guild with unavailable == True so..\n return\n\n guild = self._get_create_guild(data)\n\n if self._add_ready_state(guild):\n return # We're waiting for the ready event, put the rest on hold\n\n # check if it requires chunking\n if self._guild_needs_chunking(guild):\n asyncio.create_task(self._chunk_and_dispatch(guild, unavailable))\n return\n\n # Dispatch available if newly available\n if unavailable is False:\n self.dispatch('guild_available', guild)\n else:\n self.dispatch('guild_join', guild)\n\n def parse_guild_update(self, data: gw.GuildUpdateEvent) -> None:\n guild = self._get_guild(int(data['id']))\n if guild is not None:\n old_guild = copy.copy(guild)\n guild._from_data(data)\n self.dispatch('guild_update', old_guild, guild)\n else:\n _log.debug('GUILD_UPDATE referencing an unknown guild ID: %s. Discarding.', data['id'])\n\n def parse_guild_delete(self, data: gw.GuildDeleteEvent) -> None:\n guild = self._get_guild(int(data['id']))\n if guild is None:\n _log.debug('GUILD_DELETE referencing an unknown guild ID: %s. Discarding.', data['id'])\n return\n\n if data.get('unavailable', False):\n # GUILD_DELETE with unavailable being True means that the\n # guild that was available is now currently unavailable\n guild.unavailable = True\n self.dispatch('guild_unavailable', guild)\n return\n\n # do a cleanup of the messages cache\n if self._messages is not None:\n self._messages: Optional[Deque[Message]] = deque(\n (msg for msg in self._messages if msg.guild != guild), maxlen=self.max_messages\n )\n\n self._remove_guild(guild)\n self.dispatch('guild_remove', guild)\n\n def parse_guild_ban_add(self, data: gw.GuildBanAddEvent) -> None:\n # we make the assumption that GUILD_BAN_ADD is done\n # before GUILD_MEMBER_REMOVE is called\n # hence we don't remove it from cache or do anything\n # strange with it, the main purpose of this event\n # is mainly to dispatch to another event worth listening to for logging\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n try:\n user = User(data=data['user'], state=self)\n except KeyError:\n pass\n else:\n member = guild.get_member(user.id) or user\n self.dispatch('member_ban', guild, member)\n\n def parse_guild_ban_remove(self, data: gw.GuildBanRemoveEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None and 'user' in data:\n user = self.store_user(data['user'])\n self.dispatch('member_unban', guild, user)\n\n def parse_guild_role_create(self, data: gw.GuildRoleCreateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('GUILD_ROLE_CREATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n return\n\n role_data = data['role']\n role = Role(guild=guild, data=role_data, state=self)\n guild._add_role(role)\n self.dispatch('guild_role_create', role)\n\n def parse_guild_role_delete(self, data: gw.GuildRoleDeleteEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n role_id = int(data['role_id'])\n try:\n role = guild._remove_role(role_id)\n except KeyError:\n return\n else:\n self.dispatch('guild_role_delete', role)\n else:\n _log.debug('GUILD_ROLE_DELETE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_guild_role_update(self, data: gw.GuildRoleUpdateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n role_data = data['role']\n role_id = int(role_data['id'])\n role = guild.get_role(role_id)\n if role is not None:\n old_role = copy.copy(role)\n role._update(role_data)\n self.dispatch('guild_role_update', old_role, role)\n else:\n _log.debug('GUILD_ROLE_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_guild_members_chunk(self, data: gw.GuildMembersChunkEvent) -> None:\n guild_id = int(data['guild_id'])\n guild = self._get_guild(guild_id)\n presences = data.get('presences', [])\n\n if guild is None:\n return\n\n members = [Member(guild=guild, data=member, state=self) for member in data.get('members', [])]\n _log.debug('Processed a chunk for %s members in guild ID %s.', len(members), guild_id)\n\n if presences:\n member_dict: Dict[Snowflake, Member] = {str(member.id): member for member in members}\n for presence in presences:\n user = presence['user']\n member_id = user['id']\n member = member_dict.get(member_id)\n if member is not None:\n member._presence_update(presence, user)\n\n complete = data.get('chunk_index', 0) + 1 == data.get('chunk_count')\n self.process_chunk_requests(guild_id, data.get('nonce'), members, complete)\n\n def parse_guild_integrations_update(self, data: gw.GuildIntegrationsUpdateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n self.dispatch('guild_integrations_update', guild)\n else:\n _log.debug('GUILD_INTEGRATIONS_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_integration_create(self, data: gw.IntegrationCreateEvent) -> None:\n guild_id = int(data['guild_id'])\n guild = self._get_guild(guild_id)\n if guild is not None:\n cls, _ = _integration_factory(data['type'])\n integration = cls(data=data, guild=guild)\n self.dispatch('integration_create', integration)\n else:\n _log.debug('INTEGRATION_CREATE referencing an unknown guild ID: %s. Discarding.', guild_id)\n\n def parse_integration_update(self, data: gw.IntegrationUpdateEvent) -> None:\n guild_id = int(data['guild_id'])\n guild = self._get_guild(guild_id)\n if guild is not None:\n cls, _ = _integration_factory(data['type'])\n integration = cls(data=data, guild=guild)\n self.dispatch('integration_update', integration)\n else:\n _log.debug('INTEGRATION_UPDATE referencing an unknown guild ID: %s. Discarding.', guild_id)\n\n def parse_integration_delete(self, data: gw.IntegrationDeleteEvent) -> None:\n guild_id = int(data['guild_id'])\n guild = self._get_guild(guild_id)\n if guild is not None:\n raw = RawIntegrationDeleteEvent(data)\n self.dispatch('raw_integration_delete', raw)\n else:\n _log.debug('INTEGRATION_DELETE referencing an unknown guild ID: %s. Discarding.', guild_id)\n\n def parse_webhooks_update(self, data: gw.WebhooksUpdateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is None:\n _log.debug('WEBHOOKS_UPDATE referencing an unknown guild ID: %s. Discarding', data['guild_id'])\n return\n\n channel_id = utils._get_as_snowflake(data, 'channel_id')\n channel = guild.get_channel(channel_id) # type: ignore # None is okay here\n if channel is not None:\n self.dispatch('webhooks_update', channel)\n else:\n _log.debug('WEBHOOKS_UPDATE referencing an unknown channel ID: %s. Discarding.', data['channel_id'])\n\n def parse_stage_instance_create(self, data: gw.StageInstanceCreateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n stage_instance = StageInstance(guild=guild, state=self, data=data)\n guild._stage_instances[stage_instance.id] = stage_instance\n self.dispatch('stage_instance_create', stage_instance)\n else:\n _log.debug('STAGE_INSTANCE_CREATE referencing unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_stage_instance_update(self, data: gw.StageInstanceUpdateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n stage_instance = guild._stage_instances.get(int(data['id']))\n if stage_instance is not None:\n old_stage_instance = copy.copy(stage_instance)\n stage_instance._update(data)\n self.dispatch('stage_instance_update', old_stage_instance, stage_instance)\n else:\n _log.debug('STAGE_INSTANCE_UPDATE referencing unknown stage instance ID: %s. Discarding.', data['id'])\n else:\n _log.debug('STAGE_INSTANCE_UPDATE referencing unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_stage_instance_delete(self, data: gw.StageInstanceDeleteEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n try:\n stage_instance = guild._stage_instances.pop(int(data['id']))\n except KeyError:\n pass\n else:\n self.dispatch('stage_instance_delete', stage_instance)\n else:\n _log.debug('STAGE_INSTANCE_DELETE referencing unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_guild_scheduled_event_create(self, data: gw.GuildScheduledEventCreateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n scheduled_event = ScheduledEvent(state=self, data=data)\n guild._scheduled_events[scheduled_event.id] = scheduled_event\n self.dispatch('scheduled_event_create', scheduled_event)\n else:\n _log.debug('SCHEDULED_EVENT_CREATE referencing unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_guild_scheduled_event_update(self, data: gw.GuildScheduledEventUpdateEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n scheduled_event = guild._scheduled_events.get(int(data['id']))\n if scheduled_event is not None:\n old_scheduled_event = copy.copy(scheduled_event)\n scheduled_event._update(data)\n self.dispatch('scheduled_event_update', old_scheduled_event, scheduled_event)\n else:\n _log.debug('SCHEDULED_EVENT_UPDATE referencing unknown scheduled event ID: %s. Discarding.', data['id'])\n else:\n _log.debug('SCHEDULED_EVENT_UPDATE referencing unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_guild_scheduled_event_delete(self, data: gw.GuildScheduledEventDeleteEvent) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n try:\n scheduled_event = guild._scheduled_events.pop(int(data['id']))\n except KeyError:\n pass\n else:\n self.dispatch('scheduled_event_delete', scheduled_event)\n else:\n _log.debug('SCHEDULED_EVENT_DELETE referencing unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_guild_scheduled_event_user_add(self, data: gw.GuildScheduledEventUserAdd) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n scheduled_event = guild._scheduled_events.get(int(data['guild_scheduled_event_id']))\n if scheduled_event is not None:\n user = self.get_user(int(data['user_id']))\n if user is not None:\n scheduled_event._add_user(user)\n self.dispatch('scheduled_event_user_add', scheduled_event, user)\n else:\n _log.debug('SCHEDULED_EVENT_USER_ADD referencing unknown user ID: %s. Discarding.', data['user_id'])\n else:\n _log.debug(\n 'SCHEDULED_EVENT_USER_ADD referencing unknown scheduled event ID: %s. Discarding.',\n data['guild_scheduled_event_id'],\n )\n else:\n _log.debug('SCHEDULED_EVENT_USER_ADD referencing unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_guild_scheduled_event_user_remove(self, data: gw.GuildScheduledEventUserRemove) -> None:\n guild = self._get_guild(int(data['guild_id']))\n if guild is not None:\n scheduled_event = guild._scheduled_events.get(int(data['guild_scheduled_event_id']))\n if scheduled_event is not None:\n user = self.get_user(int(data['user_id']))\n if user is not None:\n scheduled_event._pop_user(user.id)\n self.dispatch('scheduled_event_user_remove', scheduled_event, user)\n else:\n _log.debug('SCHEDULED_EVENT_USER_REMOVE referencing unknown user ID: %s. Discarding.', data['user_id'])\n else:\n _log.debug(\n 'SCHEDULED_EVENT_USER_REMOVE referencing unknown scheduled event ID: %s. Discarding.',\n data['guild_scheduled_event_id'],\n )\n else:\n _log.debug('SCHEDULED_EVENT_USER_REMOVE referencing unknown guild ID: %s. Discarding.', data['guild_id'])\n\n def parse_application_command_permissions_update(self, data: GuildApplicationCommandPermissionsPayload):\n raw = RawAppCommandPermissionsUpdateEvent(data=data, state=self)\n self.dispatch('raw_app_command_permissions_update', raw)\n\n def parse_voice_state_update(self, data: gw.VoiceStateUpdateEvent) -> None:\n guild = self._get_guild(utils._get_as_snowflake(data, 'guild_id'))\n channel_id = utils._get_as_snowflake(data, 'channel_id')\n flags = self.member_cache_flags\n # self.user is *always* cached when this is called\n self_id = self.user.id # type: ignore\n if guild is not None:\n if int(data['user_id']) == self_id:\n voice = self._get_voice_client(guild.id)\n if voice is not None:\n coro = voice.on_voice_state_update(data)\n asyncio.create_task(logging_coroutine(coro, info='Voice Protocol voice state update handler'))\n\n member, before, after = guild._update_voice_state(data, channel_id) # type: ignore\n if member is not None:\n if flags.voice:\n if channel_id is None and flags._voice_only and member.id != self_id:\n # Only remove from cache if we only have the voice flag enabled\n guild._remove_member(member)\n elif channel_id is not None:\n guild._add_member(member)\n\n self.dispatch('voice_state_update', member, before, after)\n else:\n _log.debug('VOICE_STATE_UPDATE referencing an unknown member ID: %s. Discarding.', data['user_id'])\n\n def parse_voice_server_update(self, data: gw.VoiceServerUpdateEvent) -> None:\n key_id = int(data['guild_id'])\n\n vc = self._get_voice_client(key_id)\n if vc is not None:\n coro = vc.on_voice_server_update(data)\n asyncio.create_task(logging_coroutine(coro, info='Voice Protocol voice server update handler'))\n\n def parse_typing_start(self, data: gw.TypingStartEvent) -> None:\n raw = RawTypingEvent(data)\n raw.user = self.get_user(raw.user_id)\n channel, guild = self._get_guild_channel(data)\n\n if channel is not None:\n if isinstance(channel, DMChannel):\n channel.recipient = raw.user\n elif guild is not None:\n raw.user = guild.get_member(raw.user_id)\n\n if raw.user is None:\n member_data = data.get('member')\n if member_data:\n raw.user = Member(data=member_data, state=self, guild=guild)\n\n if raw.user is not None:\n self.dispatch('typing', channel, raw.user, raw.timestamp)\n\n self.dispatch('raw_typing', raw)\n\n def _get_reaction_user(self, channel: MessageableChannel, user_id: int) -> Optional[Union[User, Member]]:\n if isinstance(channel, (TextChannel, Thread, VoiceChannel)):\n return channel.guild.get_member(user_id)\n return self.get_user(user_id)\n\n def get_reaction_emoji(self, data: PartialEmojiPayload) -> Union[Emoji, PartialEmoji, str]:\n emoji_id = utils._get_as_snowflake(data, 'id')\n\n if not emoji_id:\n # the name key will be a str\n return data['name'] # type: ignore\n\n try:\n return self._emojis[emoji_id]\n except KeyError:\n return PartialEmoji.with_state(\n self, animated=data.get('animated', False), id=emoji_id, name=data['name'] # type: ignore\n )\n\n def _upgrade_partial_emoji(self, emoji: PartialEmoji) -> Union[Emoji, PartialEmoji, str]:\n emoji_id = emoji.id\n if not emoji_id:\n return emoji.name\n try:\n return self._emojis[emoji_id]\n except KeyError:\n return emoji\n\n def get_channel(self, id: Optional[int]) -> Optional[Union[Channel, Thread]]:\n if id is None:\n return None\n\n pm = self._get_private_channel(id)\n if pm is not None:\n return pm\n\n for guild in self.guilds:\n channel = guild._resolve_channel(id)\n if channel is not None:\n return channel\n\n def create_message(self, *, channel: MessageableChannel, data: MessagePayload) -> Message:\n return Message(state=self, channel=channel, data=data)\n\n\nclass AutoShardedConnectionState(ConnectionState[ClientT]):\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n super().__init__(*args, **kwargs)\n\n self.shard_ids: Union[List[int], range] = []\n\n self._ready_tasks: Dict[int, asyncio.Task[None]] = {}\n self._ready_states: Dict[int, asyncio.Queue[Guild]] = {}\n\n def _update_message_references(self) -> None:\n # self._messages won't be None when this is called\n for msg in self._messages: # type: ignore\n if not msg.guild:\n continue\n\n new_guild = self._get_guild(msg.guild.id)\n if new_guild is not None and new_guild is not msg.guild:\n channel_id = msg.channel.id\n channel = new_guild._resolve_channel(channel_id) or PartialMessageable(\n state=self, id=channel_id, guild_id=new_guild.id\n )\n msg._rebind_cached_references(new_guild, channel)\n\n async def chunker(\n self,\n guild_id: int,\n query: str = '',\n limit: int = 0,\n presences: bool = False,\n *,\n shard_id: Optional[int] = None,\n nonce: Optional[str] = None,\n ) -> None:\n ws = self._get_websocket(guild_id, shard_id=shard_id)\n await ws.request_chunks(guild_id, query=query, limit=limit, presences=presences, nonce=nonce)\n\n def _add_ready_state(self, guild: Guild) -> bool:\n try:\n # Notify the on_ready state, if any, that this guild is complete.\n self._ready_states[guild.shard_id].put_nowait(guild)\n except KeyError:\n return False\n else:\n return True\n\n async def _delay_ready(self) -> None:\n await asyncio.gather(*self._ready_tasks.values())\n\n # clear the current tasks\n self._ready_task = None\n self._ready_tasks = {}\n\n # dispatch the event\n self.call_handlers('ready')\n self.dispatch('ready')\n\n async def _delay_shard_ready(self, shard_id: int) -> None:\n try:\n states = []\n while True:\n # this snippet of code is basically waiting N seconds\n # until the last GUILD_CREATE was sent\n try:\n guild = await asyncio.wait_for(self._ready_states[shard_id].get(), timeout=self.guild_ready_timeout)\n except asyncio.TimeoutError:\n break\n else:\n if self._guild_needs_chunking(guild):\n future = await self.chunk_guild(guild, wait=False)\n states.append((guild, future))\n else:\n if guild.unavailable is False:\n self.dispatch('guild_available', guild)\n else:\n self.dispatch('guild_join', guild)\n\n for guild, future in states:\n timeout = self._chunk_timeout(guild)\n\n try:\n await asyncio.wait_for(future, timeout=timeout)\n except asyncio.TimeoutError:\n _log.warning('Shard ID %s timed out waiting for chunks for guild_id %s.', guild.shard_id, guild.id)\n\n if guild.unavailable is False:\n self.dispatch('guild_available', guild)\n else:\n self.dispatch('guild_join', guild)\n\n # remove the state\n try:\n del self._ready_states[shard_id]\n except KeyError:\n pass # already been deleted somehow\n\n except asyncio.CancelledError:\n pass\n else:\n # dispatch the event\n self.dispatch('shard_ready', shard_id)\n\n def parse_ready(self, data: gw.ReadyEvent) -> None:\n if self._ready_task is not None:\n self._ready_task.cancel()\n\n shard_id = data['shard'][0] # shard_id, num_shards\n\n if shard_id in self._ready_tasks:\n self._ready_tasks[shard_id].cancel()\n\n if shard_id not in self._ready_states:\n self._ready_states[shard_id] = asyncio.Queue()\n\n self.user: Optional[ClientUser]\n self.user = user = ClientUser(state=self, data=data['user'])\n # self._users is a list of Users, we're setting a ClientUser\n self._users[user.id] = user # type: ignore\n\n if self.application_id is None:\n try:\n application = data['application']\n except KeyError:\n pass\n else:\n self.application_id: Optional[int] = utils._get_as_snowflake(application, 'id')\n self.application_flags: ApplicationFlags = ApplicationFlags._from_value(application['flags'])\n\n for guild_data in data['guilds']:\n self._add_guild_from_data(guild_data) # type: ignore # _add_guild_from_data requires a complete Guild payload\n\n if self._messages:\n self._update_message_references()\n\n self.dispatch('connect')\n self.dispatch('shard_connect', shard_id)\n\n self._ready_tasks[shard_id] = asyncio.create_task(self._delay_shard_ready(shard_id))\n\n # The delay task for every shard has been started\n if len(self._ready_tasks) == len(self.shard_ids):\n self._ready_task = asyncio.create_task(self._delay_ready())\n\n def parse_resumed(self, data: gw.ResumedEvent) -> None:\n self.dispatch('resumed')\n self.dispatch('shard_resumed', data['__shard_id__']) # type: ignore # This is an internal discord.py key\n" }, { "path": "discord/ui/view.py", "content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\n\nfrom __future__ import annotations\nfrom typing import Any, Callable, ClassVar, Coroutine, Dict, Iterator, List, Optional, Sequence, TYPE_CHECKING, Tuple, Type\nfrom functools import partial\nfrom itertools import groupby\n\nimport asyncio\nimport logging\nimport sys\nimport time\nimport os\nfrom .item import Item, ItemCallbackType\nfrom .dynamic import DynamicItem\nfrom ..components import (\n Component,\n ActionRow as ActionRowComponent,\n _component_factory,\n Button as ButtonComponent,\n SelectMenu as SelectComponent,\n)\n\n# fmt: off\n__all__ = (\n 'View',\n)\n# fmt: on\n\n\nif TYPE_CHECKING:\n from typing_extensions import Self\n import re\n\n from ..interactions import Interaction\n from ..message import Message\n from ..types.components import Component as ComponentPayload\n from ..types.interactions import ModalSubmitComponentInteractionData as ModalSubmitComponentInteractionDataPayload\n from ..state import ConnectionState\n from .modal import Modal\n\n\n_log = logging.getLogger(__name__)\n\n\ndef _walk_all_components(components: List[Component]) -> Iterator[Component]:\n for item in components:\n if isinstance(item, ActionRowComponent):\n yield from item.children\n else:\n yield item\n\n\ndef _component_to_item(component: Component) -> Item:\n if isinstance(component, ButtonComponent):\n from .button import Button\n\n return Button.from_component(component)\n if isinstance(component, SelectComponent):\n from .select import Select\n\n return Select.from_component(component)\n return Item.from_component(component)\n\n\nclass _ViewWeights:\n # fmt: off\n __slots__ = (\n 'weights',\n )\n # fmt: on\n\n def __init__(self, children: List[Item]):\n self.weights: List[int] = [0, 0, 0, 0, 0]\n\n key = lambda i: sys.maxsize if i.row is None else i.row\n children = sorted(children, key=key)\n for row, group in groupby(children, key=key):\n for item in group:\n self.add_item(item)\n\n def find_open_space(self, item: Item) -> int:\n for index, weight in enumerate(self.weights):\n if weight + item.width <= 5:\n return index\n\n raise ValueError('could not find open space for item')\n\n def add_item(self, item: Item) -> None:\n if item.row is not None:\n total = self.weights[item.row] + item.width\n if total > 5:\n raise ValueError(f'item would not fit at row {item.row} ({total} > 5 width)')\n self.weights[item.row] = total\n item._rendered_row = item.row\n else:\n index = self.find_open_space(item)\n self.weights[index] += item.width\n item._rendered_row = index\n\n def remove_item(self, item: Item) -> None:\n if item._rendered_row is not None:\n self.weights[item._rendered_row] -= item.width\n item._rendered_row = None\n\n def clear(self) -> None:\n self.weights = [0, 0, 0, 0, 0]\n\n\nclass _ViewCallback:\n __slots__ = ('view', 'callback', 'item')\n\n def __init__(self, callback: ItemCallbackType[Any, Any], view: View, item: Item[View]) -> None:\n self.callback: ItemCallbackType[Any, Any] = callback\n self.view: View = view\n self.item: Item[View] = item\n\n def __call__(self, interaction: Interaction) -> Coroutine[Any, Any, Any]:\n return self.callback(self.view, interaction, self.item)\n\n\nclass View:\n \"\"\"Represents a UI view.\n\n This object must be inherited to create a UI within Discord.\n\n .. versionadded:: 2.0\n\n Parameters\n -----------\n timeout: Optional[:class:`float`]\n Timeout in seconds from last interaction with the UI before no longer accepting input.\n If ``None`` then there is no timeout.\n \"\"\"\n\n __discord_ui_view__: ClassVar[bool] = True\n __discord_ui_modal__: ClassVar[bool] = False\n __view_children_items__: ClassVar[List[ItemCallbackType[Any, Any]]] = []\n\n def __init_subclass__(cls) -> None:\n super().__init_subclass__()\n\n children: Dict[str, ItemCallbackType[Any, Any]] = {}\n for base in reversed(cls.__mro__):\n for name, member in base.__dict__.items():\n if hasattr(member, '__discord_ui_model_type__'):\n children[name] = member\n\n if len(children) > 25:\n raise TypeError('View cannot have more than 25 children')\n\n cls.__view_children_items__ = list(children.values())\n\n def _init_children(self) -> List[Item[Self]]:\n children = []\n for func in self.__view_children_items__:\n item: Item = func.__discord_ui_model_type__(**func.__discord_ui_model_kwargs__)\n item.callback = _ViewCallback(func, self, item)\n item._view = self\n setattr(self, func.__name__, item)\n children.append(item)\n return children\n\n def __init__(self, *, timeout: Optional[float] = 180.0):\n self.__timeout = timeout\n self._children: List[Item[Self]] = self._init_children()\n self.__weights = _ViewWeights(self._children)\n self.id: str = os.urandom(16).hex()\n self._cache_key: Optional[int] = None\n self.__cancel_callback: Optional[Callable[[View], None]] = None\n self.__timeout_expiry: Optional[float] = None\n self.__timeout_task: Optional[asyncio.Task[None]] = None\n self.__stopped: asyncio.Future[bool] = asyncio.get_running_loop().create_future()\n\n def __repr__(self) -> str:\n return f'<{self.__class__.__name__} timeout={self.timeout} children={len(self._children)}>'\n\n async def __timeout_task_impl(self) -> None:\n while True:\n # Guard just in case someone changes the value of the timeout at runtime\n if self.timeout is None:\n return\n\n if self.__timeout_expiry is None:\n return self._dispatch_timeout()\n\n # Check if we've elapsed our currently set timeout\n now = time.monotonic()\n if now >= self.__timeout_expiry:\n return self._dispatch_timeout()\n\n # Wait N seconds to see if timeout data has been refreshed\n await asyncio.sleep(self.__timeout_expiry - now)\n\n def to_components(self) -> List[Dict[str, Any]]:\n def key(item: Item) -> int:\n return item._rendered_row or 0\n\n children = sorted(self._children, key=key)\n components: List[Dict[str, Any]] = []\n for _, group in groupby(children, key=key):\n children = [item.to_component_dict() for item in group]\n if not children:\n continue\n\n components.append(\n {\n 'type': 1,\n 'components': children,\n }\n )\n\n return components\n\n def _refresh_timeout(self) -> None:\n if self.__timeout:\n self.__timeout_expiry = time.monotonic() + self.__timeout\n\n @property\n def timeout(self) -> Optional[float]:\n \"\"\"Optional[:class:`float`]: The timeout in seconds from last interaction with the UI before no longer accepting input.\n If ``None`` then there is no timeout.\n \"\"\"\n return self.__timeout\n\n @timeout.setter\n def timeout(self, value: Optional[float]) -> None:\n # If the timeout task is already running this allows it to update\n # the expiry while it's running\n if self.__timeout_task is not None:\n if value is not None:\n self.__timeout_expiry = time.monotonic() + value\n else:\n self.__timeout_expiry = None\n\n self.__timeout = value\n\n @property\n def children(self) -> List[Item[Self]]:\n \"\"\"List[:class:`Item`]: The list of children attached to this view.\"\"\"\n return self._children.copy()\n\n @classmethod\n def from_message(cls, message: Message, /, *, timeout: Optional[float] = 180.0) -> View:\n \"\"\"Converts a message's components into a :class:`View`.\n\n The :attr:`.Message.components` of a message are read-only\n and separate types from those in the ``discord.ui`` namespace.\n In order to modify and edit message components they must be\n converted into a :class:`View` first.\n\n Parameters\n -----------\n message: :class:`discord.Message`\n The message with components to convert into a view.\n timeout: Optional[:class:`float`]\n The timeout of the converted view.\n\n Returns\n --------\n :class:`View`\n The converted view. This always returns a :class:`View` and not\n one of its subclasses.\n \"\"\"\n view = View(timeout=timeout)\n row = 0\n for component in message.components:\n if isinstance(component, ActionRowComponent):\n for child in component.children:\n item = _component_to_item(child)\n item.row = row\n view.add_item(item)\n row += 1\n else:\n item = _component_to_item(component)\n item.row = row\n view.add_item(item)\n\n return view\n\n def add_item(self, item: Item[Any]) -> Self:\n \"\"\"Adds an item to the view.\n\n This function returns the class instance to allow for fluent-style\n chaining.\n\n Parameters\n -----------\n item: :class:`Item`\n The item to add to the view.\n\n Raises\n --------\n TypeError\n An :class:`Item` was not passed.\n ValueError\n Maximum number of children has been exceeded (25)\n or the row the item is trying to be added to is full.\n \"\"\"\n\n if len(self._children) > 25:\n raise ValueError('maximum number of children exceeded')\n\n if not isinstance(item, Item):\n raise TypeError(f'expected Item not {item.__class__.__name__}')\n\n self.__weights.add_item(item)\n\n item._view = self\n self._children.append(item)\n return self\n\n def remove_item(self, item: Item[Any]) -> Self:\n \"\"\"Removes an item from the view.\n\n This function returns the class instance to allow for fluent-style\n chaining.\n\n Parameters\n -----------\n item: :class:`Item`\n The item to remove from the view.\n \"\"\"\n\n try:\n self._children.remove(item)\n except ValueError:\n pass\n else:\n self.__weights.remove_item(item)\n return self\n\n def clear_items(self) -> Self:\n \"\"\"Removes all items from the view.\n\n This function returns the class instance to allow for fluent-style\n chaining.\n \"\"\"\n self._children.clear()\n self.__weights.clear()\n return self\n\n async def interaction_check(self, interaction: Interaction, /) -> bool:\n \"\"\"|coro|\n\n A callback that is called when an interaction happens within the view\n that checks whether the view should process item callbacks for the interaction.\n\n This is useful to override if, for example, you want to ensure that the\n interaction author is a given user.\n\n The default implementation of this returns ``True``.\n\n .. note::\n\n If an exception occurs within the body then the check\n is considered a failure and :meth:`on_error` is called.\n\n Parameters\n -----------\n interaction: :class:`~discord.Interaction`\n The interaction that occurred.\n\n Returns\n ---------\n :class:`bool`\n Whether the view children's callbacks should be called.\n \"\"\"\n return True\n\n async def on_timeout(self) -> None:\n \"\"\"|coro|\n\n A callback that is called when a view's timeout elapses without being explicitly stopped.\n \"\"\"\n pass\n\n async def on_error(self, interaction: Interaction, error: Exception, item: Item[Any], /) -> None:\n \"\"\"|coro|\n\n A callback that is called when an item's callback or :meth:`interaction_check`\n fails with an error.\n\n The default implementation logs to the library logger.\n\n Parameters\n -----------\n interaction: :class:`~discord.Interaction`\n The interaction that led to the failure.\n error: :class:`Exception`\n The exception that was raised.\n item: :class:`Item`\n The item that failed the dispatch.\n \"\"\"\n _log.error('Ignoring exception in view %r for item %r', self, item, exc_info=error)\n\n async def _scheduled_task(self, item: Item, interaction: Interaction):\n try:\n item._refresh_state(interaction, interaction.data) # type: ignore\n\n allow = await item.interaction_check(interaction) and await self.interaction_check(interaction)\n if not allow:\n return\n\n if self.timeout:\n self.__timeout_expiry = time.monotonic() + self.timeout\n\n await item.callback(interaction)\n except Exception as e:\n return await self.on_error(interaction, e, item)\n\n def _start_listening_from_store(self, store: ViewStore) -> None:\n self.__cancel_callback = partial(store.remove_view)\n if self.timeout:\n if self.__timeout_task is not None:\n self.__timeout_task.cancel()\n\n self.__timeout_expiry = time.monotonic() + self.timeout\n self.__timeout_task = asyncio.create_task(self.__timeout_task_impl())\n\n def _dispatch_timeout(self):\n if self.__stopped.done():\n return\n\n if self.__cancel_callback:\n self.__cancel_callback(self)\n self.__cancel_callback = None\n\n self.__stopped.set_result(True)\n asyncio.create_task(self.on_timeout(), name=f'discord-ui-view-timeout-{self.id}')\n\n def _dispatch_item(self, item: Item, interaction: Interaction):\n if self.__stopped.done():\n return\n\n asyncio.create_task(self._scheduled_task(item, interaction), name=f'discord-ui-view-dispatch-{self.id}')\n\n def _refresh(self, components: List[Component]) -> None:\n # fmt: off\n old_state: Dict[str, Item[Any]] = {\n item.custom_id: item # type: ignore\n for item in self._children\n if item.is_dispatchable()\n }\n # fmt: on\n\n for component in _walk_all_components(components):\n custom_id = getattr(component, 'custom_id', None)\n if custom_id is None:\n continue\n\n try:\n older = old_state[custom_id]\n except KeyError:\n _log.debug('View interaction referenced an unknown item custom_id %s. Discarding', custom_id)\n continue\n else:\n older._refresh_component(component)\n\n def stop(self) -> None:\n \"\"\"Stops listening to interaction events from this view.\n\n This operation cannot be undone.\n \"\"\"\n if not self.__stopped.done():\n self.__stopped.set_result(False)\n\n self.__timeout_expiry = None\n if self.__timeout_task is not None:\n self.__timeout_task.cancel()\n self.__timeout_task = None\n\n if self.__cancel_callback:\n self.__cancel_callback(self)\n self.__cancel_callback = None\n\n def is_finished(self) -> bool:\n \"\"\":class:`bool`: Whether the view has finished interacting.\"\"\"\n return self.__stopped.done()\n\n def is_dispatching(self) -> bool:\n \"\"\":class:`bool`: Whether the view has been added for dispatching purposes.\"\"\"\n return self.__cancel_callback is not None\n\n def is_persistent(self) -> bool:\n \"\"\":class:`bool`: Whether the view is set up as persistent.\n\n A persistent view has all their components with a set ``custom_id`` and\n a :attr:`timeout` set to ``None``.\n \"\"\"\n return self.timeout is None and all(item.is_persistent() for item in self._children)\n\n async def wait(self) -> bool:\n \"\"\"|coro|\n\n Waits until the view has finished interacting.\n\n A view is considered finished when :meth:`stop` is called\n or it times out.\n\n Returns\n --------\n :class:`bool`\n If ``True``, then the view timed out. If ``False`` then\n the view finished normally.\n \"\"\"\n return await self.__stopped\n\n\nclass ViewStore:\n def __init__(self, state: ConnectionState):\n # entity_id: {(component_type, custom_id): Item}\n self._views: Dict[Optional[int], Dict[Tuple[int, str], Item[View]]] = {}\n # message_id: View\n self._synced_message_views: Dict[int, View] = {}\n # custom_id: Modal\n self._modals: Dict[str, Modal] = {}\n # component_type is the key\n self._dynamic_items: Dict[re.Pattern[str], Type[DynamicItem[Item[Any]]]] = {}\n self._state: ConnectionState = state\n\n @property\n def persistent_views(self) -> Sequence[View]:\n # fmt: off\n views = {\n item.view.id: item.view\n for items in self._views.values()\n for item in items.values()\n if item.view and item.view.is_persistent()\n }\n # fmt: on\n return list(views.values())\n\n def add_dynamic_items(self, *items: Type[DynamicItem[Item[Any]]]) -> None:\n for item in items:\n pattern = item.__discord_ui_compiled_template__\n self._dynamic_items[pattern] = item\n\n def add_view(self, view: View, message_id: Optional[int] = None) -> None:\n view._start_listening_from_store(self)\n if view.__discord_ui_modal__:\n self._modals[view.custom_id] = view # type: ignore\n return\n\n dispatch_info = self._views.setdefault(message_id, {})\n for item in view._children:\n if isinstance(item, DynamicItem):\n pattern = item.__discord_ui_compiled_template__\n self._dynamic_items[pattern] = item.__class__\n elif item.is_dispatchable():\n dispatch_info[(item.type.value, item.custom_id)] = item # type: ignore\n\n view._cache_key = message_id\n if message_id is not None:\n self._synced_message_views[message_id] = view\n\n def remove_view(self, view: View) -> None:\n if view.__discord_ui_modal__:\n self._modals.pop(view.custom_id, None) # type: ignore\n return\n\n dispatch_info = self._views.get(view._cache_key)\n if dispatch_info:\n for item in view._children:\n if isinstance(item, DynamicItem):\n pattern = item.__discord_ui_compiled_template__\n self._dynamic_items.pop(pattern, None)\n elif item.is_dispatchable():\n dispatch_info.pop((item.type.value, item.custom_id), None) # type: ignore\n\n if len(dispatch_info) == 0:\n self._views.pop(view._cache_key, None)\n\n self._synced_message_views.pop(view._cache_key, None) # type: ignore\n\n async def schedule_dynamic_item_call(\n self,\n component_type: int,\n factory: Type[DynamicItem[Item[Any]]],\n interaction: Interaction,\n match: re.Match[str],\n ) -> None:\n try:\n item = await factory.from_custom_id(interaction, match)\n except Exception:\n _log.exception('Ignoring exception in dynamic item creation for %r', factory)\n return\n\n # Unfortunately cannot set Item.view here...\n item._refresh_state(interaction, interaction.data) # type: ignore\n\n try:\n allow = await item.interaction_check(interaction)\n except Exception:\n allow = False\n\n if not allow:\n return\n\n if interaction.message is None:\n item._view = None\n else:\n item._view = view = View.from_message(interaction.message)\n\n # Find the original item and replace it with the dynamic item\n for index, child in enumerate(view._children):\n if child.type.value == component_type and getattr(child, 'custom_id', None) == item.custom_id:\n view._children[index] = item\n break\n\n try:\n await item.callback(interaction)\n except Exception:\n _log.exception('Ignoring exception in dynamic item callback for %r', item)\n\n def dispatch_dynamic_items(self, component_type: int, custom_id: str, interaction: Interaction) -> None:\n for pattern, item in self._dynamic_items.items():\n match = pattern.fullmatch(custom_id)\n if match is not None:\n asyncio.create_task(\n self.schedule_dynamic_item_call(component_type, item, interaction, match),\n name=f'discord-ui-dynamic-item-{item.__name__}-{custom_id}',\n )\n\n def dispatch_view(self, component_type: int, custom_id: str, interaction: Interaction) -> None:\n self.dispatch_dynamic_items(component_type, custom_id, interaction)\n interaction_id: Optional[int] = None\n message_id: Optional[int] = None\n # Realistically, in a component based interaction the Interaction.message will never be None\n # However, this guard is just in case Discord screws up somehow\n msg = interaction.message\n if msg is not None:\n message_id = msg.id\n if msg.interaction:\n interaction_id = msg.interaction.id\n\n key = (component_type, custom_id)\n\n # The entity_id can either be message_id, interaction_id, or None in that priority order.\n item: Optional[Item[View]] = None\n if message_id is not None:\n item = self._views.get(message_id, {}).get(key)\n\n if item is None and interaction_id is not None:\n try:\n items = self._views.pop(interaction_id)\n except KeyError:\n item = None\n else:\n item = items.get(key)\n # If we actually got the items, then these keys should probably be moved\n # to the proper message_id instead of the interaction_id as they are now.\n # An interaction_id is only used as a temporary stop gap for\n # InteractionResponse.send_message so multiple view instances do not\n # override each other.\n # NOTE: Fix this mess if /callback endpoint ever gets proper return types\n self._views.setdefault(message_id, {}).update(items)\n\n if item is None:\n # Fallback to None message_id searches in case a persistent view\n # was added without an associated message_id\n item = self._views.get(None, {}).get(key)\n\n # If 3 lookups failed at this point then just discard it\n if item is None:\n return\n\n # Note, at this point the View is *not* None\n item.view._dispatch_item(item, interaction) # type: ignore\n\n def dispatch_modal(\n self,\n custom_id: str,\n interaction: Interaction,\n components: List[ModalSubmitComponentInteractionDataPayload],\n ) -> None:\n modal = self._modals.get(custom_id)\n if modal is None:\n _log.debug(\"Modal interaction referencing unknown custom_id %s. Discarding\", custom_id)\n return\n\n modal._dispatch_submit(interaction, components)\n\n def remove_interaction_mapping(self, interaction_id: int) -> None:\n # This is called before re-adding the view\n self._views.pop(interaction_id, None)\n self._synced_message_views.pop(interaction_id, None)\n\n def is_message_tracked(self, message_id: int) -> bool:\n return message_id in self._synced_message_views\n\n def remove_message_tracking(self, message_id: int) -> Optional[View]:\n return self._synced_message_views.pop(message_id, None)\n\n def update_from_message(self, message_id: int, data: List[ComponentPayload]) -> None:\n components: List[Component] = []\n\n for component_data in data:\n component = _component_factory(component_data)\n\n if component is not None:\n components.append(component)\n\n # pre-req: is_message_tracked == true\n view = self._synced_message_views[message_id]\n view._refresh(components)\n" } ], "language": "python" }, { "id": "10_7", "repo_url": "https://github.com/teamqurrent/discord.py", "instruction": "In the discord.py repository, refactor the `Template` class in `template.py` to streamline the initialization of the source_guild attribute. Remove the conditional logic that checks for an existing guild and instead always initialize source_guild from the serialized guild data. Additionally, add a cache_guild_expressions property to the `_PartialTemplateState` class that returns False.", "base_commit": "8b8ce55", "test_script": "import unittest\nimport sys\nimport os\n\n\n\n# Mocking _PartialTemplateState as it is not importable easily\nclass MockPartialTemplateState:\n def __init__(self, state):\n from unittest.mock import MagicMock\n \n self.__state = state\n self.user = state.user\n self.member_cache_flags = MagicMock()\n\n def create_user(self, data):\n from unittest.mock import MagicMock\n return MagicMock()\n\n def _get_guild(self, guild_id):\n from unittest.mock import MagicMock\n return MagicMock() \n\n\nclass TestTemplateSourceGuild(unittest.TestCase):\n def setUp(self):\n from unittest.mock import MagicMock\n self.mock_state = MagicMock()\n self.mock_state.user.id = 123456\n self.partial_state = MockPartialTemplateState(state=self.mock_state)\n\n def test_source_guild_initialization(self):\n from discord.template import Template\n\n template_data = {\n 'code': 'template_code',\n 'usage_count': 1,\n 'name': 'Template Name',\n 'description': 'Template Description',\n 'creator': {'id': '123', 'username': 'creator', 'discriminator': '0001'},\n 'created_at': '2020-01-01T00:00:00.000000+00:00',\n 'updated_at': '2020-01-01T00:00:00.000000+00:00',\n 'source_guild_id': '1234567890',\n 'serialized_source_guild': {'id': '1234567890', 'name': 'Test Guild'}\n }\n template = Template(state=self.partial_state, data=template_data)\n self.assertEqual(template.source_guild.id, 1234567890)\n self.assertEqual(template.source_guild.name, 'Test Guild')\n \n def test_cache_guild_expressions_in_partial_template_state(self):\n discord_py_directory = \"\" \n template_file_path = os.path.join(discord_py_directory, \"discord\", \"template.py\")\n\n with open(template_file_path, 'r') as file:\n template_content = file.read()\n\n # Check if the specific line is in the file content... Such a small addition means a source code check is viable\n self.assertIn(\"def cache_guild_expressions(self):\", template_content)\n self.assertIn(\"return False\", template_content)\n\ndef main():\n\n\n suite = unittest.TestSuite()\n suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestTemplateSourceGuild))\n runner = unittest.TextTestRunner()\n\n if runner.run(suite).wasSuccessful():\n sys.exit(0)\n else:\n sys.exit(1)\n\nif __name__ == '__main__':\n\n main()\n", "testbed_environment": "python3.9", "requirements_txt": "discord", "solution_commit": "16f6466d", "solution_patch": "diff --git a/discord/template.py b/discord/template.py\n--- a/discord/template.py\n+++ b/discord/template.py\n@@ -69,6 +69,10 @@ class _PartialTemplateState:\n def member_cache_flags(self):\n return self.__state.member_cache_flags\n \n+ @property\n+ def cache_guild_expressions(self):\n+ return False\n+\n def store_emoji(self, guild, packet) -> None:\n return None\n \n@@ -146,18 +150,11 @@ class Template:\n self.created_at: Optional[datetime.datetime] = parse_time(data.get('created_at'))\n self.updated_at: Optional[datetime.datetime] = parse_time(data.get('updated_at'))\n \n- guild_id = int(data['source_guild_id'])\n- guild: Optional[Guild] = self._state._get_guild(guild_id)\n-\n- self.source_guild: Guild\n- if guild is None:\n- source_serialised = data['serialized_source_guild']\n- source_serialised['id'] = guild_id\n- state = _PartialTemplateState(state=self._state)\n- # Guild expects a ConnectionState, we're passing a _PartialTemplateState\n- self.source_guild = Guild(data=source_serialised, state=state) # type: ignore\n- else:\n- self.source_guild = guild\n+ source_serialised = data['serialized_source_guild']\n+ source_serialised['id'] = int(data['source_guild_id'])\n+ state = _PartialTemplateState(state=self._state)\n+ # Guild expects a ConnectionState, we're passing a _PartialTemplateState\n+ self.source_guild = Guild(data=source_serialised, state=state) # type: ignore\n \n self.is_dirty: Optional[bool] = data.get('is_dirty', None)\n \n", "modified_files": [ { "path": "discord/template.py", "content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Any, Optional, TYPE_CHECKING, List\nfrom .utils import parse_time, _bytes_to_base64_data, MISSING\nfrom .guild import Guild\n\n# fmt: off\n__all__ = (\n 'Template',\n)\n# fmt: on\n\nif TYPE_CHECKING:\n import datetime\n from .types.template import Template as TemplatePayload\n from .state import ConnectionState\n from .user import User\n\n\nclass _FriendlyHttpAttributeErrorHelper:\n __slots__ = ()\n\n def __getattr__(self, attr):\n raise AttributeError('PartialTemplateState does not support http methods.')\n\n\nclass _PartialTemplateState:\n def __init__(self, *, state) -> None:\n self.__state = state\n self.http = _FriendlyHttpAttributeErrorHelper()\n\n @property\n def shard_count(self):\n return self.__state.shard_count\n\n @property\n def user(self):\n return self.__state.user\n\n @property\n def self_id(self):\n return self.__state.user.id\n\n @property\n def member_cache_flags(self):\n return self.__state.member_cache_flags\n\n def store_emoji(self, guild, packet) -> None:\n return None\n\n def _get_voice_client(self, id) -> None:\n return None\n\n def _get_message(self, id) -> None:\n return None\n\n def _get_guild(self, id):\n return self.__state._get_guild(id)\n\n async def query_members(self, **kwargs: Any) -> List[Any]:\n return []\n\n def __getattr__(self, attr):\n raise AttributeError(f'PartialTemplateState does not support {attr!r}.')\n\n\nclass Template:\n \"\"\"Represents a Discord template.\n\n .. versionadded:: 1.4\n\n Attributes\n -----------\n code: :class:`str`\n The template code.\n uses: :class:`int`\n How many times the template has been used.\n name: :class:`str`\n The name of the template.\n description: :class:`str`\n The description of the template.\n creator: :class:`User`\n The creator of the template.\n created_at: :class:`datetime.datetime`\n An aware datetime in UTC representing when the template was created.\n updated_at: :class:`datetime.datetime`\n An aware datetime in UTC representing when the template was last updated.\n This is referred to as \"last synced\" in the official Discord client.\n source_guild: :class:`Guild`\n The guild snapshot that represents the data that this template currently holds.\n is_dirty: Optional[:class:`bool`]\n Whether the template has unsynced changes.\n\n .. versionadded:: 2.0\n \"\"\"\n\n __slots__ = (\n 'code',\n 'uses',\n 'name',\n 'description',\n 'creator',\n 'created_at',\n 'updated_at',\n 'source_guild',\n 'is_dirty',\n '_state',\n )\n\n def __init__(self, *, state: ConnectionState, data: TemplatePayload) -> None:\n self._state = state\n self._store(data)\n\n def _store(self, data: TemplatePayload) -> None:\n self.code: str = data['code']\n self.uses: int = data['usage_count']\n self.name: str = data['name']\n self.description: Optional[str] = data['description']\n creator_data = data.get('creator')\n self.creator: Optional[User] = None if creator_data is None else self._state.create_user(creator_data)\n\n self.created_at: Optional[datetime.datetime] = parse_time(data.get('created_at'))\n self.updated_at: Optional[datetime.datetime] = parse_time(data.get('updated_at'))\n\n guild_id = int(data['source_guild_id'])\n guild: Optional[Guild] = self._state._get_guild(guild_id)\n\n self.source_guild: Guild\n if guild is None:\n source_serialised = data['serialized_source_guild']\n source_serialised['id'] = guild_id\n state = _PartialTemplateState(state=self._state)\n # Guild expects a ConnectionState, we're passing a _PartialTemplateState\n self.source_guild = Guild(data=source_serialised, state=state) # type: ignore\n else:\n self.source_guild = guild\n\n self.is_dirty: Optional[bool] = data.get('is_dirty', None)\n\n def __repr__(self) -> str:\n return (\n f'